From a5f8e43d3641b98fce08356e99bb24ca47c00d46 Mon Sep 17 00:00:00 2001 From: Sunjay Cauligi Date: Wed, 1 Jun 2022 18:51:01 -0700 Subject: [PATCH] generate .pyc files from .hy files on install (and include them in wheel distributions) --- setup.py | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 60 insertions(+), 4 deletions(-) diff --git a/setup.py b/setup.py index b71667410..301365cd9 100755 --- a/setup.py +++ b/setup.py @@ -5,6 +5,31 @@ import fastentrypoints # Monkey-patches setuptools. from get_version import __version__ from setuptools import find_packages, setup +from setuptools.command.install import install as _install + +cmdclass = {} + +try: + from wheel.bdist_wheel import bdist_wheel as _bdist_wheel + + class bdist_wheel(_bdist_wheel): + def get_tag(self): + from wheel.vendored.packaging import tags + + impl_name = tags.interpreter_name() + impl_ver = tags.interpreter_version() + impl = impl_name + impl_ver + return (impl, "none", "any") + + def finalize_options(self): + if self.plat_name is None: + self.plat_name = "any" + super().finalize_options() + self.root_is_pure = False + + cmdclass["bdist_wheel"] = bdist_wheel +except ModuleNotFoundError: + pass os.chdir(os.path.split(os.path.abspath(__file__))[0]) @@ -14,6 +39,39 @@ make things work nicer, and lets Python and the Hy lisp variant play nice together. """ + +class install(_install): + def run(self): + super().run() + import contextlib + import importlib.util + import py_compile + from glob import glob + + import hy # for compile hooks + + mode = py_compile.PycInvalidationMode.CHECKED_HASH + + # use timestamp mode if we detect the python files have been compiled that way + init_file = os.path.join(self.install_lib, "hy", "__init__.py") + init_pyc = importlib.util.cache_from_source(init_file) + with contextlib.suppress(FileNotFoundError), open(init_pyc, "rb") as fp: + fp.seek(4) + flags = int.from_bytes(fp.read(4), "little") + + mode = ( + py_compile.PycInvalidationMode.CHECKED_HASH + if flags & 0b1 + else py_compile.PycInvalidationMode.TIMESTAMP + ) + + for path in glob(os.path.join(self.install_lib, "**/*.hy"), recursive=True): + py_compile.compile(path, invalidation_mode=mode) + + +cmdclass["install"] = install + + setup( name=PKG, version=__version__, @@ -35,10 +93,7 @@ }, packages=find_packages(exclude=["tests*"]), package_data={ - "hy": ["*.hy", "__pycache__/*"], - "hy.contrib": ["*.hy", "__pycache__/*"], - "hy.core": ["*.hy", "__pycache__/*"], - "hy.extra": ["*.hy", "__pycache__/*"], + "": ["*.hy"], }, data_files=[("get_version", ["get_version.py"])], author="Paul Tagliamonte", @@ -69,4 +124,5 @@ "Documentation": "https://docs.hylang.org/", "Source": "https://github.com/hylang/hy", }, + cmdclass=cmdclass, )