| 1 |
# This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
# License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
# file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 4 |
|
| 5 |
import math |
| 6 |
import os |
| 7 |
import shutil |
| 8 |
import sys |
| 9 |
from importlib.abc import MetaPathFinder |
| 10 |
from pathlib import Path |
| 11 |
|
| 12 |
STATE_DIR_FIRST_RUN = """ |
| 13 |
Mach and the build system store shared state in a common directory |
| 14 |
on the filesystem. The following directory will be created: |
| 15 |
|
| 16 |
{} |
| 17 |
|
| 18 |
If you would like to use a different directory, rename or move it to your |
| 19 |
desired location, and set the MOZBUILD_STATE_PATH environment variable |
| 20 |
accordingly. |
| 21 |
""".strip() |
| 22 |
|
| 23 |
|
| 24 |
CATEGORIES = { |
| 25 |
"build": { |
| 26 |
"short": "Build Commands", |
| 27 |
"long": "Interact with the build system", |
| 28 |
"priority": 80, |
| 29 |
}, |
| 30 |
"post-build": { |
| 31 |
"short": "Post-build Commands", |
| 32 |
"long": "Common actions performed after completing a build.", |
| 33 |
"priority": 70, |
| 34 |
}, |
| 35 |
"testing": { |
| 36 |
"short": "Testing", |
| 37 |
"long": "Run tests.", |
| 38 |
"priority": 60, |
| 39 |
}, |
| 40 |
"ci": { |
| 41 |
"short": "CI", |
| 42 |
"long": "Taskcluster commands", |
| 43 |
"priority": 59, |
| 44 |
}, |
| 45 |
"devenv": { |
| 46 |
"short": "Development Environment", |
| 47 |
"long": "Set up and configure your development environment.", |
| 48 |
"priority": 50, |
| 49 |
}, |
| 50 |
"build-dev": { |
| 51 |
"short": "Low-level Build System Interaction", |
| 52 |
"long": "Interact with specific parts of the build system.", |
| 53 |
"priority": 20, |
| 54 |
}, |
| 55 |
"misc": { |
| 56 |
"short": "Potpourri", |
| 57 |
"long": "Potent potables and assorted snacks.", |
| 58 |
"priority": 10, |
| 59 |
}, |
| 60 |
"release": { |
| 61 |
"short": "Release automation", |
| 62 |
"long": "Commands for used in release automation.", |
| 63 |
"priority": 5, |
| 64 |
}, |
| 65 |
"disabled": { |
| 66 |
"short": "Disabled", |
| 67 |
"long": "The disabled commands are hidden by default. Use -v to display them. " |
| 68 |
"These commands are unavailable for your current context, " |
| 69 |
'run "mach <command>" to see why.', |
| 70 |
"priority": 0, |
| 71 |
}, |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
def _activate_python_environment(topsrcdir, get_state_dir, quiet): |
| 76 |
from mach.site import MachSiteManager |
| 77 |
|
| 78 |
mach_environment = MachSiteManager.from_environment( |
| 79 |
topsrcdir, get_state_dir, quiet=quiet |
| 80 |
) |
| 81 |
mach_environment.activate() |
| 82 |
|
| 83 |
|
| 84 |
def _maybe_activate_mozillabuild_environment(): |
| 85 |
if sys.platform != "win32": |
| 86 |
return |
| 87 |
|
| 88 |
mozillabuild = Path(os.environ.get("MOZILLABUILD", r"C:\mozilla-build")) |
| 89 |
os.environ.setdefault("MOZILLABUILD", str(mozillabuild)) |
| 90 |
assert mozillabuild.exists(), ( |
| 91 |
f'MozillaBuild was not found at "{mozillabuild}".\n' |
| 92 |
"If it's installed in a different location, please " |
| 93 |
'set the "MOZILLABUILD" environment variable ' |
| 94 |
"accordingly." |
| 95 |
) |
| 96 |
|
| 97 |
use_msys2 = (mozillabuild / "msys2").exists() |
| 98 |
if use_msys2: |
| 99 |
mozillabuild_msys_tools_path = mozillabuild / "msys2" / "usr" / "bin" |
| 100 |
else: |
| 101 |
mozillabuild_msys_tools_path = mozillabuild / "msys" / "bin" |
| 102 |
|
| 103 |
paths_to_add = [mozillabuild_msys_tools_path, mozillabuild / "bin"] |
| 104 |
existing_paths = [Path(p) for p in os.environ.get("PATH", "").split(os.pathsep)] |
| 105 |
for new_path in paths_to_add: |
| 106 |
if new_path not in existing_paths: |
| 107 |
os.environ["PATH"] += f"{os.pathsep}{new_path}" |
| 108 |
|
| 109 |
|
| 110 |
def check_for_spaces(topsrcdir): |
| 111 |
if " " in topsrcdir: |
| 112 |
raise Exception( |
| 113 |
f"Your checkout at path '{topsrcdir}' contains a space, which " |
| 114 |
f"is not supported. Please move it to somewhere that does not " |
| 115 |
f"have a space in the path before rerunning mach." |
| 116 |
) |
| 117 |
|
| 118 |
mozillabuild_dir = os.environ.get("MOZILLABUILD", "") |
| 119 |
if sys.platform == "win32" and " " in mozillabuild_dir: |
| 120 |
raise Exception( |
| 121 |
f"Your installation of MozillaBuild appears to be installed on a path that " |
| 122 |
f"contains a space ('{mozillabuild_dir}') which is not supported. Please " |
| 123 |
f"reinstall MozillaBuild on a path without a space and restart your shell" |
| 124 |
f"from the new installation." |
| 125 |
) |
| 126 |
|
| 127 |
|
| 128 |
def initialize(topsrcdir, args=()): |
| 129 |
# This directory was deleted in bug 1666345, but there may be some ignored |
| 130 |
# files here. We can safely just delete it for the user so they don't have |
| 131 |
# to clean the repo themselves. |
| 132 |
deleted_dir = os.path.join(topsrcdir, "third_party", "python", "psutil") |
| 133 |
if os.path.exists(deleted_dir): |
| 134 |
shutil.rmtree(deleted_dir, ignore_errors=True) |
| 135 |
|
| 136 |
# We need the "mach" module to access the logic to parse virtualenv |
| 137 |
# requirements. Since that depends on "packaging", we add it to the path too. |
| 138 |
# We need filelock for solving a virtualenv race condition |
| 139 |
sys.path[0:0] = [ |
| 140 |
os.path.join(topsrcdir, module) |
| 141 |
for module in ( |
| 142 |
os.path.join("python", "mach"), |
| 143 |
os.path.join("third_party", "python", "packaging"), |
| 144 |
os.path.join("third_party", "python", "filelock"), |
| 145 |
) |
| 146 |
] |
| 147 |
|
| 148 |
from mach.util import get_state_dir, get_virtualenv_base_dir, setenv |
| 149 |
|
| 150 |
state_dir = _create_state_dir() |
| 151 |
|
| 152 |
check_for_spaces(topsrcdir) |
| 153 |
|
| 154 |
# See bug 1874208: |
| 155 |
# Status messages from site.py break usages of `./mach environment`. |
| 156 |
# We pass `quiet` only for it to work around this, so that all other |
| 157 |
# commands can still write status messages. |
| 158 |
if args and (args[0] == "environment" or "--quiet" in args): |
| 159 |
quiet = True |
| 160 |
else: |
| 161 |
quiet = False |
| 162 |
|
| 163 |
# normpath state_dir to normalize msys-style slashes. |
| 164 |
_activate_python_environment( |
| 165 |
topsrcdir, |
| 166 |
lambda: os.path.normpath(get_state_dir(True, topsrcdir=topsrcdir)), |
| 167 |
quiet=quiet, |
| 168 |
) |
| 169 |
_maybe_activate_mozillabuild_environment() |
| 170 |
|
| 171 |
import mach.main |
| 172 |
from mach.command_util import ( |
| 173 |
MACH_COMMANDS, |
| 174 |
DetermineCommandVenvAction, |
| 175 |
load_commands_from_spec, |
| 176 |
) |
| 177 |
from mach.main import get_argument_parser |
| 178 |
|
| 179 |
# Set a reasonable limit to the number of open files. |
| 180 |
# |
| 181 |
# Some linux systems set `ulimit -n` to a very high number, which works |
| 182 |
# well for systems that run servers, but this setting causes performance |
| 183 |
# problems when programs close file descriptors before forking, like |
| 184 |
# Python's `subprocess.Popen(..., close_fds=True)` (close_fds=True is the |
| 185 |
# default in Python 3), or Rust's stdlib. In some cases, Firefox does the |
| 186 |
# same thing when spawning processes. We would prefer to lower this limit |
| 187 |
# to avoid such performance problems; processes spawned by `mach` will |
| 188 |
# inherit the limit set here. |
| 189 |
# |
| 190 |
# The Firefox build defaults the soft limit to 1024, except for builds that |
| 191 |
# do LTO, where the soft limit is 8192. We're going to default to the |
| 192 |
# latter, since people do occasionally do LTO builds on their local |
| 193 |
# machines, and requiring them to discover another magical setting after |
| 194 |
# setting up an LTO build in the first place doesn't seem good. |
| 195 |
# |
| 196 |
# This code mimics the code in taskcluster/scripts/run-task. |
| 197 |
try: |
| 198 |
import resource |
| 199 |
|
| 200 |
# Keep the hard limit the same, though, allowing processes to change |
| 201 |
# their soft limit if they need to (Firefox does, for instance). |
| 202 |
(soft, hard) = resource.getrlimit(resource.RLIMIT_NOFILE) |
| 203 |
# Permit people to override our default limit if necessary via |
| 204 |
# MOZ_LIMIT_NOFILE, which is the same variable `run-task` uses. |
| 205 |
limit = os.environ.get("MOZ_LIMIT_NOFILE") |
| 206 |
if limit: |
| 207 |
limit = int(limit) |
| 208 |
else: |
| 209 |
# If no explicit limit is given, use our default if it's less than |
| 210 |
# the current soft limit. For instance, the default on macOS is |
| 211 |
# 256, so we'd pick that rather than our default. |
| 212 |
limit = min(soft, 8192) |
| 213 |
# Now apply the limit, if it's different from the original one. |
| 214 |
if limit != soft: |
| 215 |
resource.setrlimit(resource.RLIMIT_NOFILE, (limit, hard)) |
| 216 |
except ImportError: |
| 217 |
# The resource module is UNIX only. |
| 218 |
pass |
| 219 |
|
| 220 |
def resolve_repository(): |
| 221 |
import mozversioncontrol |
| 222 |
|
| 223 |
try: |
| 224 |
# This API doesn't respect the vcs binary choices from configure. |
| 225 |
# If we ever need to use the VCS binary here, consider something |
| 226 |
# more robust. |
| 227 |
return mozversioncontrol.get_repository_object(path=topsrcdir) |
| 228 |
except (mozversioncontrol.InvalidRepoPath, mozversioncontrol.MissingVCSTool): |
| 229 |
return None |
| 230 |
|
| 231 |
def pre_dispatch_handler(context, handler, args): |
| 232 |
# If --disable-tests flag was enabled in the mozconfig used to compile |
| 233 |
# the build, tests will be disabled. Instead of trying to run |
| 234 |
# nonexistent tests then reporting a failure, this will prevent mach |
| 235 |
# from progressing beyond this point. |
| 236 |
if handler.category == "testing" and not handler.ok_if_tests_disabled: |
| 237 |
from mozbuild.base import BuildEnvironmentNotFoundException |
| 238 |
|
| 239 |
try: |
| 240 |
from mozbuild.base import MozbuildObject |
| 241 |
|
| 242 |
# all environments should have an instance of build object. |
| 243 |
build = MozbuildObject.from_environment() |
| 244 |
if build is not None and not getattr( |
| 245 |
build, "substs", {"ENABLE_TESTS": True} |
| 246 |
).get("ENABLE_TESTS"): |
| 247 |
print( |
| 248 |
"Tests have been disabled with --disable-tests.\n" |
| 249 |
+ "Remove the flag, and re-compile to enable tests." |
| 250 |
) |
| 251 |
sys.exit(1) |
| 252 |
except BuildEnvironmentNotFoundException: |
| 253 |
# likely automation environment, so do nothing. |
| 254 |
pass |
| 255 |
|
| 256 |
def post_dispatch_handler( |
| 257 |
context, handler, instance, success, start_time, end_time, depth, args |
| 258 |
): |
| 259 |
"""Perform global operations after command dispatch. |
| 260 |
|
| 261 |
|
| 262 |
For now, we will use this to handle build system telemetry. |
| 263 |
""" |
| 264 |
|
| 265 |
# Don't finalize telemetry data if this mach command was invoked as part of |
| 266 |
# another mach command. |
| 267 |
if depth != 1: |
| 268 |
return |
| 269 |
|
| 270 |
_finalize_telemetry_glean( |
| 271 |
context.telemetry, handler.name == "bootstrap", success |
| 272 |
) |
| 273 |
|
| 274 |
def populate_context(key=None): |
| 275 |
if key is None: |
| 276 |
return |
| 277 |
if key == "state_dir": |
| 278 |
return state_dir |
| 279 |
|
| 280 |
if key == "local_state_dir": |
| 281 |
return get_state_dir(specific_to_topsrcdir=True) |
| 282 |
|
| 283 |
if key == "topdir": |
| 284 |
return topsrcdir |
| 285 |
|
| 286 |
if key == "pre_dispatch_handler": |
| 287 |
return pre_dispatch_handler |
| 288 |
|
| 289 |
if key == "post_dispatch_handler": |
| 290 |
return post_dispatch_handler |
| 291 |
|
| 292 |
if key == "repository": |
| 293 |
return resolve_repository() |
| 294 |
|
| 295 |
raise AttributeError(key) |
| 296 |
|
| 297 |
# Note which process is top-level so that recursive mach invocations can avoid writing |
| 298 |
# telemetry data. |
| 299 |
if "MACH_MAIN_PID" not in os.environ: |
| 300 |
setenv("MACH_MAIN_PID", str(os.getpid())) |
| 301 |
|
| 302 |
driver = mach.main.Mach(os.getcwd()) |
| 303 |
driver.populate_context_handler = populate_context |
| 304 |
|
| 305 |
if not driver.settings_paths: |
| 306 |
# default global machrc location |
| 307 |
driver.settings_paths.append(state_dir) |
| 308 |
# always load local repository configuration |
| 309 |
driver.settings_paths.append(topsrcdir) |
| 310 |
driver.load_settings() |
| 311 |
|
| 312 |
aliases = driver.settings.alias |
| 313 |
|
| 314 |
parser = get_argument_parser( |
| 315 |
action=DetermineCommandVenvAction, |
| 316 |
topsrcdir=topsrcdir, |
| 317 |
) |
| 318 |
from argparse import Namespace |
| 319 |
|
| 320 |
from mach.main import ( |
| 321 |
SUGGESTED_COMMANDS_MESSAGE, |
| 322 |
UNKNOWN_COMMAND_ERROR, |
| 323 |
UnknownCommandError, |
| 324 |
) |
| 325 |
|
| 326 |
namespace_in = Namespace() |
| 327 |
setattr(namespace_in, "mach_command_aliases", aliases) |
| 328 |
|
| 329 |
try: |
| 330 |
namespace = parser.parse_args(args, namespace_in) |
| 331 |
except UnknownCommandError as e: |
| 332 |
suggestion_message = ( |
| 333 |
SUGGESTED_COMMANDS_MESSAGE % (e.verb, ", ".join(e.suggested_commands)) |
| 334 |
if e.suggested_commands |
| 335 |
else "" |
| 336 |
) |
| 337 |
print(UNKNOWN_COMMAND_ERROR % (e.verb, e.command, suggestion_message)) |
| 338 |
sys.exit(1) |
| 339 |
|
| 340 |
command_name = getattr(namespace, "command_name", None) |
| 341 |
site_name = getattr(namespace, "site_name", "common") |
| 342 |
command_site_manager = None |
| 343 |
|
| 344 |
# the 'clobber' command needs to run in the 'mach' venv, so we |
| 345 |
# don't want to activate any other virtualenv for it. |
| 346 |
if command_name != "clobber": |
| 347 |
from mach.site import CommandSiteManager |
| 348 |
|
| 349 |
command_site_manager = CommandSiteManager.from_environment( |
| 350 |
topsrcdir, |
| 351 |
lambda: os.path.normpath(get_state_dir(True, topsrcdir=topsrcdir)), |
| 352 |
site_name, |
| 353 |
get_virtualenv_base_dir(topsrcdir), |
| 354 |
quiet=quiet, |
| 355 |
) |
| 356 |
|
| 357 |
command_site_manager.activate() |
| 358 |
|
| 359 |
for category, meta in CATEGORIES.items(): |
| 360 |
driver.define_category(category, meta["short"], meta["long"], meta["priority"]) |
| 361 |
|
| 362 |
# Sparse checkouts may not have all mach_commands.py files. Ignore |
| 363 |
# errors from missing files. Same for spidermonkey tarballs. |
| 364 |
repo = resolve_repository() |
| 365 |
if repo != "SOURCE": |
| 366 |
missing_ok = ( |
| 367 |
repo is not None and repo.sparse_checkout_present() |
| 368 |
) or os.path.exists(os.path.join(topsrcdir, "INSTALL")) |
| 369 |
else: |
| 370 |
missing_ok = () |
| 371 |
|
| 372 |
commands_that_need_all_modules_loaded = [ |
| 373 |
"busted", |
| 374 |
"help", |
| 375 |
"mach-commands", |
| 376 |
"mach-completion", |
| 377 |
"mach-debug-commands", |
| 378 |
] |
| 379 |
|
| 380 |
def commands_to_load(top_level_command: str): |
| 381 |
visited = set() |
| 382 |
|
| 383 |
def find_downstream_commands_recursively(command: str): |
| 384 |
if not MACH_COMMANDS.get(command): |
| 385 |
return |
| 386 |
|
| 387 |
if command in visited: |
| 388 |
return |
| 389 |
|
| 390 |
visited.add(command) |
| 391 |
|
| 392 |
for command_dependency in MACH_COMMANDS[command].command_dependencies: |
| 393 |
find_downstream_commands_recursively(command_dependency) |
| 394 |
|
| 395 |
find_downstream_commands_recursively(top_level_command) |
| 396 |
|
| 397 |
return list(visited) |
| 398 |
|
| 399 |
if ( |
| 400 |
command_name not in MACH_COMMANDS |
| 401 |
or command_name in commands_that_need_all_modules_loaded |
| 402 |
): |
| 403 |
command_modules_to_load = MACH_COMMANDS |
| 404 |
else: |
| 405 |
command_names_to_load = commands_to_load(command_name) |
| 406 |
command_modules_to_load = { |
| 407 |
command_name: MACH_COMMANDS[command_name] |
| 408 |
for command_name in command_names_to_load |
| 409 |
} |
| 410 |
|
| 411 |
driver.command_site_manager = command_site_manager |
| 412 |
load_commands_from_spec(command_modules_to_load, topsrcdir, missing_ok=missing_ok) |
| 413 |
|
| 414 |
return driver |
| 415 |
|
| 416 |
|
| 417 |
def _finalize_telemetry_glean(telemetry, is_bootstrap, success): |
| 418 |
"""Submit telemetry collected by Glean. |
| 419 |
|
| 420 |
Finalizes some metrics (command success state and duration, system information) and |
| 421 |
requests Glean to send the collected data. |
| 422 |
""" |
| 423 |
|
| 424 |
from mach.telemetry import MACH_METRICS_PATH |
| 425 |
from mozbuild.telemetry import ( |
| 426 |
get_cpu_brand, |
| 427 |
get_distro_and_version, |
| 428 |
get_psutil_stats, |
| 429 |
get_shell_info, |
| 430 |
get_vscode_running, |
| 431 |
) |
| 432 |
|
| 433 |
moz_automation = any(e in os.environ for e in ("MOZ_AUTOMATION", "TASK_ID")) |
| 434 |
|
| 435 |
mach_metrics = telemetry.metrics(MACH_METRICS_PATH) |
| 436 |
mach_metrics.mach.duration.stop() |
| 437 |
mach_metrics.mach.success.set(success) |
| 438 |
mach_metrics.mach.moz_automation.set(moz_automation) |
| 439 |
|
| 440 |
system_metrics = mach_metrics.mach.system |
| 441 |
cpu_brand = get_cpu_brand() |
| 442 |
if cpu_brand: |
| 443 |
system_metrics.cpu_brand.set(cpu_brand) |
| 444 |
distro, version = get_distro_and_version() |
| 445 |
system_metrics.distro.set(distro) |
| 446 |
system_metrics.distro_version.set(version) |
| 447 |
|
| 448 |
vscode_terminal, ssh_connection = get_shell_info() |
| 449 |
system_metrics.vscode_terminal.set(vscode_terminal) |
| 450 |
system_metrics.ssh_connection.set(ssh_connection) |
| 451 |
system_metrics.vscode_running.set(get_vscode_running()) |
| 452 |
|
| 453 |
has_psutil, logical_cores, physical_cores, memory_total = get_psutil_stats() |
| 454 |
if has_psutil: |
| 455 |
# psutil may not be available (we may not have been able to download |
| 456 |
# a wheel or build it from source). |
| 457 |
system_metrics.logical_cores.add(logical_cores) |
| 458 |
if physical_cores is not None: |
| 459 |
system_metrics.physical_cores.add(physical_cores) |
| 460 |
if memory_total is not None: |
| 461 |
system_metrics.memory.accumulate( |
| 462 |
int(math.ceil(float(memory_total) / (1024 * 1024 * 1024))) |
| 463 |
) |
| 464 |
telemetry.submit(is_bootstrap) |
| 465 |
|
| 466 |
|
| 467 |
def _create_state_dir(): |
| 468 |
# Global build system and mach state is stored in a central directory. By |
| 469 |
# default, this is ~/.mozbuild. However, it can be defined via an |
| 470 |
# environment variable. We detect first run (by lack of this directory |
| 471 |
# existing) and notify the user that it will be created. The logic for |
| 472 |
# creation is much simpler for the "advanced" environment variable use |
| 473 |
# case. For default behavior, we educate users and give them an opportunity |
| 474 |
# to react. |
| 475 |
state_dir = os.environ.get("MOZBUILD_STATE_PATH") |
| 476 |
if state_dir: |
| 477 |
if not os.path.exists(state_dir): |
| 478 |
print( |
| 479 |
f"Creating global state directory from environment variable: {state_dir}" |
| 480 |
) |
| 481 |
else: |
| 482 |
state_dir = os.path.expanduser("~/.mozbuild") |
| 483 |
if not os.path.exists(state_dir): |
| 484 |
if not os.environ.get("MOZ_AUTOMATION"): |
| 485 |
print(STATE_DIR_FIRST_RUN.format(state_dir)) |
| 486 |
|
| 487 |
print(f"Creating default state directory: {state_dir}") |
| 488 |
|
| 489 |
os.makedirs(state_dir, mode=0o770, exist_ok=True) |
| 490 |
return state_dir |
| 491 |
|
| 492 |
|
| 493 |
# Hook import such that .pyc/.pyo files without a corresponding .py file in |
| 494 |
# the source directory are essentially ignored. See further below for details |
| 495 |
# and caveats. |
| 496 |
# Objdirs outside the source directory are ignored because in most cases, if |
| 497 |
# a .pyc/.pyo file exists there, a .py file will be next to it anyways. |
| 498 |
class FinderHook(MetaPathFinder): |
| 499 |
def __init__(self, klass): |
| 500 |
# Assume the source directory is the parent directory of the one |
| 501 |
# containing this file. |
| 502 |
self._source_dir = ( |
| 503 |
os.path.normcase( |
| 504 |
os.path.abspath(os.path.dirname(os.path.dirname(__file__))) |
| 505 |
) |
| 506 |
+ os.sep |
| 507 |
) |
| 508 |
self.finder_class = klass |
| 509 |
|
| 510 |
def find_spec(self, full_name, paths=None, target=None): |
| 511 |
spec = self.finder_class.find_spec(full_name, paths, target) |
| 512 |
|
| 513 |
# Some modules don't have an origin. |
| 514 |
if spec is None or spec.origin is None: |
| 515 |
return spec |
| 516 |
|
| 517 |
# Normalize the origin path. |
| 518 |
path = os.path.normcase(os.path.abspath(spec.origin)) |
| 519 |
# Note: we could avoid normcase and abspath above for non pyc/pyo |
| 520 |
# files, but those are actually rare, so it doesn't really matter. |
| 521 |
if not path.endswith((".pyc", ".pyo")): |
| 522 |
return spec |
| 523 |
|
| 524 |
# Ignore modules outside our source directory |
| 525 |
if not path.startswith(self._source_dir): |
| 526 |
return spec |
| 527 |
|
| 528 |
# If there is no .py corresponding to the .pyc/.pyo module we're |
| 529 |
# resolving, remove the .pyc/.pyo file, and try again. |
| 530 |
if not os.path.exists(spec.origin[:-1]): |
| 531 |
if os.path.exists(spec.origin): |
| 532 |
os.remove(spec.origin) |
| 533 |
spec = self.finder_class.find_spec(full_name, paths, target) |
| 534 |
|
| 535 |
return spec |
| 536 |
|
| 537 |
|
| 538 |
# Additional hook for python >= 3.8's importlib.metadata. |
| 539 |
class MetadataHook(FinderHook): |
| 540 |
def find_distributions(self, *args, **kwargs): |
| 541 |
return self.finder_class.find_distributions(*args, **kwargs) |
| 542 |
|
| 543 |
|
| 544 |
def hook(finder): |
| 545 |
has_find_spec = hasattr(finder, "find_spec") |
| 546 |
has_find_distributions = hasattr(finder, "find_distributions") |
| 547 |
if has_find_spec and has_find_distributions: |
| 548 |
return MetadataHook(finder) |
| 549 |
elif has_find_spec: |
| 550 |
return FinderHook(finder) |
| 551 |
return finder |
| 552 |
|
| 553 |
|
| 554 |
sys.meta_path = [hook(c) for c in sys.meta_path] |