| 1 |
# SPDX-FileCopyrightText: 2021-present Ofek Lev <[email protected]> |
| 2 |
# |
| 3 |
# SPDX-License-Identifier: MIT |
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import os |
| 7 |
import platform |
| 8 |
import subprocess |
| 9 |
import sys |
| 10 |
from contextlib import contextmanager |
| 11 |
from tempfile import TemporaryDirectory |
| 12 |
|
| 13 |
import pathspec |
| 14 |
from hatchling.builders.hooks.plugin.interface import BuildHookInterface |
| 15 |
|
| 16 |
from hatch_mypyc.utils import construct_setup_file, installed_in_prefix |
| 17 |
|
| 18 |
|
| 19 |
class MypycBuildHook(BuildHookInterface): |
| 20 |
PLUGIN_NAME = 'mypyc' |
| 21 |
|
| 22 |
def __init__(self, *args, **kwargs): |
| 23 |
super().__init__(*args, **kwargs) |
| 24 |
|
| 25 |
self.__config_mypy_args = None |
| 26 |
self.__config_options = None |
| 27 |
self.__config_separation = None |
| 28 |
self.__config_build_dir = None |
| 29 |
self.__config_include = None |
| 30 |
self.__config_exclude = None |
| 31 |
self.__package_source = None |
| 32 |
self.__include_spec = None |
| 33 |
self.__exclude_spec = None |
| 34 |
self.__included_files = None |
| 35 |
self.__normalized_included_files = None |
| 36 |
self.__artifact_globs = None |
| 37 |
self.__normalized_artifact_globs = None |
| 38 |
self.__artifact_patterns = None |
| 39 |
|
| 40 |
self._on_windows = platform.system() == 'Windows' |
| 41 |
self.__compiled_extension = '.pyd' if self._on_windows else '.so' |
| 42 |
|
| 43 |
@property |
| 44 |
def compiled_extension(self): |
| 45 |
return self.__compiled_extension |
| 46 |
|
| 47 |
@property |
| 48 |
def config_mypy_args(self): |
| 49 |
if self.__config_mypy_args is None: |
| 50 |
mypy_args = self.config.get('mypy-args', []) |
| 51 |
if isinstance(mypy_args, list): |
| 52 |
for i, argument in enumerate(mypy_args, 1): |
| 53 |
if not isinstance(argument, str): |
| 54 |
raise TypeError( |
| 55 |
f'Argument #{i} of option `mypy-args` for build hook `{self.PLUGIN_NAME}` must be a string' |
| 56 |
) |
| 57 |
elif not argument: |
| 58 |
raise ValueError( |
| 59 |
f'Argument #{i} of option `mypy-args` for build hook `{self.PLUGIN_NAME}` ' |
| 60 |
f'cannot be an empty string' |
| 61 |
) |
| 62 |
else: |
| 63 |
raise TypeError(f'Option `mypy-args` for build hook `{self.PLUGIN_NAME}` must be an array') |
| 64 |
|
| 65 |
self.__config_mypy_args = mypy_args |
| 66 |
|
| 67 |
return self.__config_mypy_args |
| 68 |
|
| 69 |
@property |
| 70 |
def config_options(self): |
| 71 |
if self.__config_options is None: |
| 72 |
options = self.config.get('options', {}) |
| 73 |
if not isinstance(options, dict): |
| 74 |
raise TypeError(f'Option `options` for build hook `{self.PLUGIN_NAME}` must be a table') |
| 75 |
|
| 76 |
self.__config_options = options |
| 77 |
|
| 78 |
return self.__config_options |
| 79 |
|
| 80 |
@property |
| 81 |
def config_separation(self): |
| 82 |
if self.__config_separation is None: |
| 83 |
self.__config_separation = self.config_options.get('separate', False) is not False |
| 84 |
|
| 85 |
return self.__config_separation |
| 86 |
|
| 87 |
@property |
| 88 |
def config_build_dir(self): |
| 89 |
if self.__config_build_dir is None: |
| 90 |
build_dir = os.environ.get('HATCH_MYPYC_BUILD_DIR', self.config_options.get('build-dir', '')) |
| 91 |
if build_dir and not os.path.isabs(build_dir): |
| 92 |
build_dir = os.path.join(self.root, build_dir) |
| 93 |
|
| 94 |
self.__config_build_dir = build_dir |
| 95 |
|
| 96 |
return self.__config_build_dir |
| 97 |
|
| 98 |
@property |
| 99 |
def config_include(self): |
| 100 |
if self.__config_include is None: |
| 101 |
patterns = self.config.get('include', []) |
| 102 |
if isinstance(patterns, list): |
| 103 |
for i, pattern in enumerate(patterns, 1): |
| 104 |
if not isinstance(pattern, str): |
| 105 |
raise TypeError( |
| 106 |
f'Pattern #{i} of option `include` for build hook `{self.PLUGIN_NAME}` must be a string' |
| 107 |
) |
| 108 |
elif not pattern: |
| 109 |
raise ValueError( |
| 110 |
f'Pattern #{i} of option `include` for build hook `{self.PLUGIN_NAME}` ' |
| 111 |
f'cannot be an empty string' |
| 112 |
) |
| 113 |
else: |
| 114 |
raise TypeError(f'Option `include` for build hook `{self.PLUGIN_NAME}` must be an array') |
| 115 |
|
| 116 |
self.__config_include = patterns |
| 117 |
|
| 118 |
return self.__config_include |
| 119 |
|
| 120 |
@property |
| 121 |
def config_exclude(self): |
| 122 |
if self.__config_exclude is None: |
| 123 |
patterns = self.config.get('exclude', []) |
| 124 |
if isinstance(patterns, list): |
| 125 |
for i, pattern in enumerate(patterns, 1): |
| 126 |
if not isinstance(pattern, str): |
| 127 |
raise TypeError( |
| 128 |
f'Pattern #{i} of option `exclude` for build hook `{self.PLUGIN_NAME}` must be a string' |
| 129 |
) |
| 130 |
elif not pattern: |
| 131 |
raise ValueError( |
| 132 |
f'Pattern #{i} of option `exclude` for build hook `{self.PLUGIN_NAME}` ' |
| 133 |
f'cannot be an empty string' |
| 134 |
) |
| 135 |
else: |
| 136 |
raise TypeError(f'Option `exclude` for build hook `{self.PLUGIN_NAME}` must be an array') |
| 137 |
|
| 138 |
self.__config_exclude = patterns |
| 139 |
|
| 140 |
return self.__config_exclude |
| 141 |
|
| 142 |
@property |
| 143 |
def package_source(self): |
| 144 |
if self.__package_source is None: |
| 145 |
if self.build_config.sources: |
| 146 |
# Just support one source for now |
| 147 |
self.__package_source = list(self.build_config.sources)[0][:-1] |
| 148 |
else: |
| 149 |
self.__package_source = '' |
| 150 |
|
| 151 |
return self.__package_source |
| 152 |
|
| 153 |
@property |
| 154 |
def include_spec(self): |
| 155 |
if self.__config_include is None and self.config_include: |
| 156 |
self.__include_spec = pathspec.PathSpec.from_lines( |
| 157 |
pathspec.patterns.GitWildMatchPattern, self.config_include |
| 158 |
) |
| 159 |
|
| 160 |
return self.__include_spec |
| 161 |
|
| 162 |
@property |
| 163 |
def exclude_spec(self): |
| 164 |
if self.__exclude_spec is None and self.config_exclude: |
| 165 |
self.__exclude_spec = pathspec.PathSpec.from_lines( |
| 166 |
pathspec.patterns.GitWildMatchPattern, self.config_exclude |
| 167 |
) |
| 168 |
|
| 169 |
return self.__exclude_spec |
| 170 |
|
| 171 |
def include_path(self, relative_path): |
| 172 |
return self.path_is_included(relative_path) and not self.path_is_excluded(relative_path) |
| 173 |
|
| 174 |
def path_is_included(self, relative_path): |
| 175 |
if self.include_spec is None: # no cov |
| 176 |
return True |
| 177 |
|
| 178 |
return self.include_spec.match_file(relative_path) |
| 179 |
|
| 180 |
def path_is_excluded(self, relative_path): |
| 181 |
if self.exclude_spec is None: # no cov |
| 182 |
return False |
| 183 |
|
| 184 |
return self.exclude_spec.match_file(relative_path) |
| 185 |
|
| 186 |
@property |
| 187 |
def included_files(self): |
| 188 |
if self.__included_files is None: |
| 189 |
included_files = [] |
| 190 |
|
| 191 |
for included_file in self.build_config.builder.recurse_included_files(): |
| 192 |
relative_path = included_file.relative_path |
| 193 |
if relative_path.endswith('.py') and self.include_path(relative_path): |
| 194 |
included_files.append(relative_path) |
| 195 |
|
| 196 |
self.__included_files = included_files |
| 197 |
|
| 198 |
return self.__included_files |
| 199 |
|
| 200 |
@property |
| 201 |
def normalized_included_files(self): |
| 202 |
if self.__normalized_included_files is None: |
| 203 |
if self._on_windows: |
| 204 |
self.__normalized_included_files = [f.replace('\\', '/') for f in self.included_files] |
| 205 |
else: |
| 206 |
self.__normalized_included_files = self.included_files |
| 207 |
|
| 208 |
return self.__normalized_included_files |
| 209 |
|
| 210 |
@property |
| 211 |
def artifact_globs(self): |
| 212 |
if self.__artifact_globs is None: |
| 213 |
artifact_globs = [] |
| 214 |
|
| 215 |
# TODO: investigate using more specific patterns to avoid having to clean everything before each run |
| 216 |
for included_file in self.included_files: |
| 217 |
root, _ = os.path.splitext(included_file) |
| 218 |
artifact_globs.append(f'{root}.*{self.compiled_extension}') |
| 219 |
|
| 220 |
if self.config_separation: |
| 221 |
artifact_globs.append(f'{root}__mypyc.*{self.compiled_extension}') |
| 222 |
|
| 223 |
self.__artifact_globs = artifact_globs |
| 224 |
|
| 225 |
return self.__artifact_globs |
| 226 |
|
| 227 |
@property |
| 228 |
def normalized_artifact_globs(self): |
| 229 |
if self.__normalized_artifact_globs is None: |
| 230 |
if self._on_windows: |
| 231 |
self.__normalized_artifact_globs = [f.replace('\\', '/') for f in self.artifact_globs] |
| 232 |
else: |
| 233 |
self.__normalized_artifact_globs = self.artifact_globs |
| 234 |
|
| 235 |
return self.__normalized_artifact_globs |
| 236 |
|
| 237 |
@property |
| 238 |
def artifact_patterns(self): |
| 239 |
if self.__artifact_patterns is None: |
| 240 |
# Match the exact path starting at the project root |
| 241 |
self.__artifact_patterns = [f'/{artifact_glob}' for artifact_glob in self.normalized_artifact_globs] |
| 242 |
|
| 243 |
return self.__artifact_patterns |
| 244 |
|
| 245 |
def get_forced_inclusion_map(self): |
| 246 |
inclusion_map = {} |
| 247 |
if not self.config_separation: |
| 248 |
from glob import iglob |
| 249 |
|
| 250 |
pattern = f'*__mypyc.*{self.compiled_extension}' |
| 251 |
if self.package_source: |
| 252 |
pattern = os.path.join(self.package_source, pattern) |
| 253 |
|
| 254 |
for path in iglob(os.path.join(self.root, pattern)): |
| 255 |
inclusion_map[path] = os.path.relpath(path, self.root) |
| 256 |
|
| 257 |
return inclusion_map |
| 258 |
|
| 259 |
def clean(self, versions): |
| 260 |
from glob import iglob |
| 261 |
|
| 262 |
for path in self.get_forced_inclusion_map(): |
| 263 |
os.remove(path) |
| 264 |
|
| 265 |
for artifact_glob in self.artifact_globs: |
| 266 |
absolute_glob = os.path.join(self.root, artifact_glob) |
| 267 |
for artifact in iglob(absolute_glob): |
| 268 |
os.remove(artifact) |
| 269 |
|
| 270 |
@contextmanager |
| 271 |
def hide_project_file(self): |
| 272 |
# TODO: remove this and bump setuptools when it supports PEP 639 |
| 273 |
project_file = os.path.join(self.root, 'pyproject.toml') |
| 274 |
project_file_backup = os.path.join(self.root, 'pyproject.toml.bak') |
| 275 |
|
| 276 |
os.replace(project_file, project_file_backup) |
| 277 |
try: |
| 278 |
yield |
| 279 |
finally: |
| 280 |
os.replace(project_file_backup, project_file) |
| 281 |
|
| 282 |
@contextmanager |
| 283 |
def get_build_dirs(self): |
| 284 |
with TemporaryDirectory() as temp_dir: |
| 285 |
temp_dir = os.path.realpath(temp_dir) |
| 286 |
if self.config_build_dir: |
| 287 |
yield self.config_build_dir, temp_dir |
| 288 |
# Prevent temporary files from being written inside the project by both Mypy and setuptools |
| 289 |
else: |
| 290 |
yield temp_dir, temp_dir |
| 291 |
|
| 292 |
def initialize(self, version, build_data): |
| 293 |
if self.target_name != 'wheel': |
| 294 |
return |
| 295 |
|
| 296 |
# Hopefully there will be an API for this soon: |
| 297 |
# https://github.com/python/mypy/blob/v0.961/mypyc/__main__.py |
| 298 |
with self.get_build_dirs() as (intermediate_build_dir, temp_dir): |
| 299 |
shared_temp_build_dir = os.path.join(intermediate_build_dir, 'build') |
| 300 |
temp_build_dir = os.path.join(intermediate_build_dir, 'tmp') |
| 301 |
os.mkdir(shared_temp_build_dir) |
| 302 |
os.mkdir(temp_build_dir) |
| 303 |
|
| 304 |
options = self.config_options.copy() |
| 305 |
options['target_dir'] = shared_temp_build_dir |
| 306 |
|
| 307 |
mypy_args = list(self.config_mypy_args) |
| 308 |
# Prevent horribly breaking users' global environments |
| 309 |
if installed_in_prefix() and '--install-types' in mypy_args: # no cov |
| 310 |
mypy_args.remove('--install-types') |
| 311 |
|
| 312 |
setup_file = os.path.join(temp_dir, 'setup.py') |
| 313 |
with open(setup_file, 'w', encoding='utf-8') as f: |
| 314 |
f.write( |
| 315 |
construct_setup_file(self.package_source, *mypy_args, *self.normalized_included_files, **options) |
| 316 |
) |
| 317 |
|
| 318 |
# We don't know the exact naming scheme of the files produced using this interpreter, |
| 319 |
# so always clean to prevent including files from other runs |
| 320 |
self.clean([version]) |
| 321 |
|
| 322 |
with self.hide_project_file(): |
| 323 |
process = subprocess.run( |
| 324 |
[ |
| 325 |
sys.executable, |
| 326 |
setup_file, |
| 327 |
'build_ext', |
| 328 |
'--inplace', |
| 329 |
'--build-lib', |
| 330 |
shared_temp_build_dir, |
| 331 |
'--build-temp', |
| 332 |
temp_build_dir, |
| 333 |
], |
| 334 |
stdout=subprocess.PIPE, |
| 335 |
stderr=subprocess.STDOUT, |
| 336 |
) |
| 337 |
if process.returncode: # no cov |
| 338 |
raise Exception(f'Error while invoking Mypyc:\n{process.stdout.decode("utf-8")}') |
| 339 |
|
| 340 |
# Success, now finalize build data |
| 341 |
build_data['infer_tag'] = True |
| 342 |
build_data['pure_python'] = False |
| 343 |
build_data['artifacts'].extend(self.artifact_patterns) |
| 344 |
build_data['force_include'].update(self.get_forced_inclusion_map()) |