GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — csspin-python/src/csspin_python/python.py at master · cslab/csspin-python Expand file tree/ Copy pathpython.pyMore file actions 1319 lines (1146 loc) · 43.4 KB / Copy pathpython.pyFile metadata and controls1319 lines (1146 loc) · 43.4 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 # -*- mode: python; coding: utf-8 -*- # # Copyright (C) 2020 CONTACT Software GmbH # https://www.contact-software.com/ # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # pylint: disable=too-few-public-methods,missing-class-docstring,too-many-lines """``python`` ========== This plugin provisions the requested version of the Python programming languages. On Linux and macOS, Python is installed by compiling from source (implying, that Python's build requirements must be installed). On Windows, pre-built binaries are downloaded using `nuget`. If a user has `pyenv <https://github.com/pyenv/pyenv>`_ installed it can be activated by setting ``python.user_pyenv`` in :file:`global.yaml`. To skip provisioning of Python and use an already installed version, :py:data:`python.use` can be set to the name or the full path of an interpreter: .. code-block:: console spin -p python.use=/usr/local/bin/python ... Note: `spin` will install or update certain packages of that interpreter, thus write access is required. Tasks ----- .. click:: csspin_python:python :prog: spin python .. click:: csspin_python:python:wheel :prog: spin python:wheel .. click:: csspin_python:env :prog: spin env Properties ---------- * :py:data:`python.version` -- must be set to choose the required Python version * :py:data:`python.interpreter` -- path to the Python interpreter Note: don't use these properties when using `virtualenv`, they will point to the base installation. """ import abc import configparser import contextlib import hashlib import inspect import json import logging import os import re import shutil import subprocess import sys from contextlib import contextmanager from functools import cache from subprocess import CalledProcessError, check_output from textwrap import dedent, indent from typing import Generator, Iterable, Type, Union from urllib.error import HTTPError from urllib.parse import urljoin, urlsplit try: from typing import Self # type: ignore[attr-defined] except ImportError: from typing import TypeVar Self = TypeVar("Self") # type: ignore[misc] from click.exceptions import Abort from csspin import ( CONFIG, EXPORTS, Command, Memoizer, Path, Verbosity, argument, backtick, cd, config, die, download, echo, error, exists, get_requires, info, interpolate1, memoizer, mkdir, namespaces, normpath, readtext, rmtree, setenv, sh, task, warn, writetext, ) from csspin.tree import ConfigTree # csspin's plugin development guide, for warnings pointing to its sections _PLUGIN_GUIDE_URL = "https://csspin.readthedocs.io/en/stable/howtoplugins.html" defaults = config( build_wheels=["{spin.project_root}"], pyenv=config( url="https://github.com/pyenv/pyenv.git", path="{spin.data}/pyenv", cache="{spin.data}/pyenv_cache", python_build="{python.pyenv.path}/plugins/python-build/bin/python-build", ), user_pyenv=False, nuget=config( url="https://dist.nuget.org/win-x86-commandline/latest/nuget.exe", exe="{spin.data}/nuget.exe", source="https://api.nuget.org/v3/index.json", ), version=None, use=None, inst_dir=( "{spin.data}/python/{python.version}" if sys.platform != "win32" else "{spin.data}/python/python.{python.version}/tools" ), interpreter=( "{python.inst_dir}/bin/python{platform.exe}" if sys.platform != "win32" else "{python.inst_dir}/python{platform.exe}" ), venv="{spin.spin_dir}/venv", memo="{python.venv}/spininfo.memo", bindir="{python.venv}/bin" if sys.platform != "win32" else "{python.venv}", scriptdir=( "{python.venv}/bin" if sys.platform != "win32" else "{python.venv}/Scripts" ), python="{python.scriptdir}/python{platform.exe}", provisioner=None, provisioner_memo="{spin.spin_dir}/python_provisioner.memo", aws_auth=config( enabled=False, memo="{spin.spin_dir}/aws_auth.memo", key_duration=3600 * 10, # 10 hours ), index_url="https://pypi.org/simple", skip_js_build=None, requires=config(python=["build", "wheel"]), ) @task() def python(args: Iterable[object]) -> None: """Run the Python interpreter used for this projects.""" sh("python", *args) @task("python:wheel", when="package") def wheel( cfg: ConfigTree, paths: argument(type=str, nargs=-1, required=False), # type: ignore[valid-type] ) -> None: """Build a wheel of the current project and any additional wheels.""" setenv(PIP_INDEX_URL=cfg.python.index_url) if cfg.python.extra_index_urls: setenv(PIP_EXTRA_INDEX_URL=" ".join(cfg.python.extra_index_urls)) search_paths = paths or cfg.python.build_wheels for build_path in {Path(path).absolute() for path in search_paths}: try: echo("Building PEP 517-like wheel") cmd = [ "python", "-m", "build", "-w", build_path, "-o", "{spin.project_root}/dist", ] if cfg.verbosity <= Verbosity.NORMAL: cmd.append("--config-setting=quiet=true") sh(*cmd) except Abort: echo("Building does not seem to work, use legacy setup.py style") with cd(build_path): cmd = [ "python", "setup.py", ] if cfg.verbosity <= Verbosity.NORMAL: cmd.append("-q") cmd += [ "build", "-b", "{spin.project_root}/build", "bdist_wheel", "-d", "{spin.project_root}/dist", ] sh(*cmd) @task() def env() -> None: """ Generate command to activate the virtual environment NOTE: spin itself should not be run from within the activated virtual environment! """ if sys.platform == "win32": # Don't care about cmd print(normpath("{python.scriptdir}", "activate.ps1")) else: print(f". {normpath('{python.scriptdir}', 'activate')}") def pyenv_install(cfg: ConfigTree) -> None: """Install and setup the virtual environment using pyenv""" with namespaces(cfg.python): if cfg.python.user_pyenv: info("Using your existing pyenv installation ...") sh("pyenv", "install", "--skip-existing", {cfg.python.version}) cfg.python.interpreter = backtick("pyenv which python --nosystem").strip() else: info("Installing Python {version} to {inst_dir}") # For Linux/macOS using the 'python-build' plugin from # pyenv is by far the most robust way to install a # version of Python. if not exists("{pyenv.path}"): sh("git", "clone", cfg.python.pyenv.url, cfg.python.pyenv.path) else: with cd(cfg.python.pyenv.path): sh("git", "pull") # we should set setenv(PYTHON_BUILD_CACHE_PATH=mkdir(cfg.python.pyenv.cache)) if cfg.python.pyenv.mirror: setenv(PYTHON_BUILD_MIRROR_URL=cfg.python.pyenv.mirror) setenv(PYTHON_CFLAGS="-DOPENSSL_NO_COMP") try: sh( cfg.python.pyenv.python_build, cfg.python.version, cfg.python.inst_dir, ) except Abort: error("Failed to build the Python interpreter - removing it") rmtree(cfg.python.inst_dir) raise def nuget_install(cfg: ConfigTree) -> None: """Install the virtual environment using nuget""" if not exists(cfg.python.nuget.exe): download(cfg.python.nuget.url, cfg.python.nuget.exe) setenv(NUGET_HTTP_CACHE_PATH=cfg.spin.data / "nugetcache") sh( cfg.python.nuget.exe, "install", "-verbosity", "quiet", "-o", cfg.spin.data / "python", "python", "-version", cfg.python.version, "-source", cfg.python.nuget.source, ) sh(cfg.python.interpreter, "-m", "ensurepip", "--upgrade") sh( cfg.python.interpreter, "-mpip", None if cfg.verbosity > Verbosity.NORMAL else "-q", "install", f"--index-url={cfg.python.index_url}", *[f"--extra-index-url={url}" for url in cfg.python.extra_index_urls], "-U", "pip", "wheel", "packaging", ) def _check_venv( # pylint: disable=too-many-return-statements cfg: ConfigTree, ) -> bool: """ Checks whether the venv is actually a venv compatible with our configuration and not just some dir. Uses absolute interpreter paths and runs *outside* the subprocess environment on purpose: it must work while inspecting an existing venv to decide whether a ``python.version`` change requires rebuilding it -- i.e. before the new interpreter is provisioned. """ try: python_version = ( check_output([cfg.python.python, "--version"]) .decode() .strip() .replace("Python ", "") ) except CalledProcessError: return False if not cfg.python.version and not cfg.python.use: return False if cfg.python.use: try: use_python_version = ( check_output([cfg.python.use, "--version"]) .decode() .strip() .replace("Python ", "") ) except CalledProcessError: return False if use_python_version == python_version: return True else: warn( "The cfg.python.use version does not match the cfg.python.python " "version set in the venv. If you want to update the python version " "used in the venv, you have to manually remove it." ) return True if python_version.startswith(cfg.python.version): return True return False def provision(cfg: ConfigTree) -> None: """Provision the python plugin""" info("Checking venv '{python.venv}'") fresh_venv = False if exists("{python.venv}"): if not _check_venv(cfg): _cleanup_memoed_provisioners(cfg) rmtree(cfg.python.provisioner_memo) rmtree(cfg.python.aws_auth.memo) rmtree(cfg.python.venv) fresh_venv = True else: fresh_venv = True with memoizer(cfg.python.provisioner_memo) as memo: if cfg.python.provisioner is None: cfg.python.provisioner = SimpleProvisioner(cfg) if not memo.check(cfg.python.provisioner): memo.add(cfg.python.provisioner) if not shutil.which(cfg.python.interpreter): cfg.python.provisioner.provision_python(cfg) venv_provision(cfg, fresh_venv) cfg.python.site_packages = get_site_packages(interpreter=cfg.python.python) def configure(cfg: ConfigTree) -> None: """Configure the python plugin""" if not cfg.python.version and not cfg.python.use: die( "Please choose a version in spinfile.yaml by setting python.version" " or pass a local interpreter via python.use." ) if cfg.python.use: if cfg.python.version: warn("python.version will be ignored, using '{python.use}' instead.") cfg.python.interpreter = cfg.python.use elif cfg.python.user_pyenv: setenv(PYENV_VERSION="{python.version}") try: cfg.python.interpreter = backtick( "pyenv which python --nosystem", check=False, silent=not cfg.verbosity > Verbosity.NORMAL, ).strip() except Exception: # pylint: disable=broad-exception-caught # nosec warn( "The desired interpreter is not available within the" " user's pyenv installation." ) if exists(cfg.python.python): cfg.python.site_packages = get_site_packages(interpreter=cfg.python.python) # Built JS should still be available in this case # Skip only if users hasn't explicitly set it to False if cfg.python.skip_js_build is None: cfg.python.skip_js_build = True if cfg.python.aws_auth.enabled: _check_aws_token_validity(cfg) def init(cfg: ConfigTree) -> None: """Initialize the python plugin and activate the virtual environment. Runs before spin executes tasks, and during 'spin provision' as soon as the virtual environment has been created (see venv_provision). """ if not cfg.python.use: logging.debug("Checking for %s", cfg.python.interpreter) if not exists(cfg.python.interpreter): die( f"Python {cfg.python.version} has not been provisioned for this" " project. You might want to run spin with the 'provision'" " task." ) activate(cfg) def activate(cfg: ConfigTree) -> None: """Activate the virtual environment for the processes spin starts, like its 'activate' script does in a shell. This only sets environment variables. It must never change spin's own sys.path or sys.prefix (e.g. by executing 'activate_this.py'): plugin code must not import from the project's virtual environment, which may use another Python version (see "Outer and inner interpreter" in csspin's plugin development guide). """ venv = str(cfg.python.venv) if os.environ.get("VIRTUAL_ENV") == venv: return if not exists(cfg.python.scriptdir): die( f"{cfg.python.venv} does not exist. You may want to provision" " it using 'spin provision'" ) if sys.platform == "win32": echo(f"{cfg.python.scriptdir}\\activate.ps1") else: echo(f". {cfg.python.scriptdir}/activate") os.environ["PATH"] = os.pathsep.join( (str(cfg.python.scriptdir), os.environ.get("PATH", "")) ) os.environ["VIRTUAL_ENV"] = venv os.environ.pop("PYTHONHOME", None) def venv_init(cfg: ConfigTree) -> None: """Activate the virtual environment""" activate_this = cfg.python.scriptdir / "activate_this.py" if not exists(activate_this): die( f"{cfg.python.venv} does not exist. You may want to provision" " it using 'spin provision'" ) if sys.platform == "win32": echo(f"{cfg.python.scriptdir}\\activate.ps1") else: echo(f". {cfg.python.scriptdir}/activate") with open(activate_this, encoding="utf-8") as file: exec( # pylint: disable=exec-used # nosec file.read(), {"__file__": activate_this} ) def _caller_location() -> str: """Return 'file:line' of the innermost caller outside this module and contextlib, i.e. the plugin code using one of our functions.""" skip = {os.path.normcase(__file__), os.path.normcase(contextlib.__file__)} frame = inspect.currentframe() try: while frame is not None: filename = frame.f_code.co_filename if os.path.normcase(filename) not in skip: return f"{filename}:{frame.f_lineno}" frame = frame.f_back return "<unknown>" finally: del frame @contextmanager def python_env(cfg: ConfigTree) -> Generator: """ Context manager activating the virtual environment *in spin's process*, including its sys.path, and deactivating it once done. .. deprecated:: Plugin code must not import from the project's virtual environment, which may use another Python version than spin (see "Outer and inner interpreter" in csspin's plugin development guide). The virtual environment is activated for the processes spin starts by :py:func:`activate` already. Make modules a plugin imports dependencies of its plugin package, or run the tools from the virtual environment as subprocesses. This function will be removed in a future release. Saving and restoring ``os.environ``, ``sys.path`` and the ``sys`` prefix attributes makes nesting safe. """ warn( f"{_caller_location()} uses csspin_python.python.python_env(), which is" " deprecated and will be removed: plugin code must not import from the" " project's virtual environment." f" See {_PLUGIN_GUIDE_URL}#outer-and-inner-interpreter." ) if not exists(cfg.python.scriptdir / "activate_this.py"): # The virtual environment has not been provisioned (yet); run the command # in spin's in-process environment instead of activating. yield else: def interpolate_environ_value(value: str) -> str: if not value: return "" value = str(value) keys = re.findall(r"{(?P<key>\w+?)}", value) for key in keys: if key in os.environ: value = value.replace(f"{{{key}}}", os.environ[key]) return value missing = object() old_env = os.environ.copy() old_sys_path = sys.path.copy() old_sys_prefix = sys.prefix old_real_prefix = getattr(sys, "real_prefix", missing) try: for name, value in EXPORTS: os.environ[name] = interpolate_environ_value(value) venv_init(cfg) yield finally: echo(f"deactivate {cfg.python.venv}") os.environ.clear() os.environ.update(old_env) sys.path = old_sys_path sys.prefix = old_sys_prefix # activate_this.py sets sys.real_prefix on activation; restore it (or # remove it) so the attribute does not leak past this context. if old_real_prefix is missing: if hasattr(sys, "real_prefix"): delattr(sys, "real_prefix") else: setattr(sys, "real_prefix", old_real_prefix) class ActivateScriptPatcher(abc.ABC): activatescript: Union[str, Path] setpattern: str resetpattern: str old_env_pattern: str patchmarker: str replacements: list[tuple[str, str]] script: str @staticmethod @abc.abstractmethod def interpolate_environ_value(value: str) -> str: """ Translate value so the script can handle uninterpolated "{ENVVAR}" literals in value Example: # Assume the following subset of os.environ os.environ = { "PATH": "/bin:/usr/bin", "COMPILER_PATHS": "/compiler/A/bin:/compiler/B/bin", } # Now, setenv has been called with # setenv(PATH="{python.scriptdir}:{COMPILER_PATHS}:{PATH}") thus the # value of ``PATH`` in ``EXPORTS`` equals "/venv/bin:{COMPILER_PATHS}:{PATH}" as # ``COMPILER_PATHS`` and ``PATH`` haven't been interpolated yet. interpolate_environ_value(value) => /venv/bin:/compiler/A/bin:/compiler/B/bin:/bin:/usr/bin """ return value def patch_activate(schema: Type[ActivateScriptPatcher]) -> None: """Patch the activate script""" if exists(schema.activatescript): setters = [] resetters = set() old_value_setters = set() for name, value in EXPORTS: value = schema.interpolate_environ_value(value) setters.append(schema.setpattern.format(name=name, value=value)) resetters.add(schema.resetpattern.format(name=name)) old_value_setters.add(schema.old_env_pattern.format(name=name)) resetters_string = "\n".join(resetters) setters_string = "\n".join(setters) old_value_setters_string = "\n".join(old_value_setters) original = readtext(schema.activatescript) if schema.patchmarker not in original: shutil.copyfile( interpolate1(f"{schema.activatescript}"), interpolate1(f"{schema.activatescript}.bak"), ) info(f"Patching {schema.activatescript}") # Removing the byte order marker (BOM) ensures the absence of those in # the final scripts. BOMs in executables are not fully supported in # Powershell. original = ( readtext(f"{schema.activatescript}.bak").encode("utf-8").decode("utf-8-sig") ) for repl in schema.replacements: original = original.replace(repl[0], repl[1]) newscript = schema.script.format( patchmarker=schema.patchmarker, original=original, resetters=resetters_string, old_value_setters=old_value_setters_string, setters=setters_string, ) writetext(f"{schema.activatescript}", newscript) class BashActivate(ActivateScriptPatcher): patchmarker = "\n## Patched by csspin_python.python\n" activatescript = Path("{python.scriptdir}") / "activate" replacements = [ ("deactivate", "origdeactivate"), ] old_env_pattern = dedent(""" if [ -z ${{{name}+x}} ]; then export _OLD_SPIN_UNSET{name}="" else export _OLD_SPIN_VALUE{name}="${name}" fi """) setpattern = dedent(""" {name}="{value}" export {name} """) resetpattern = indent( dedent(""" if ! [ -z "${{_OLD_SPIN_VALUE{name}+_}}" ] ; then {name}="$_OLD_SPIN_VALUE{name}" export {name} unset _OLD_SPIN_VALUE{name} fi if ! [ -z "${{_OLD_SPIN_UNSET{name}+_}}" ] ; then unset {name} unset _OLD_SPIN_UNSET{name} fi """), prefix=" ", ) script = dedent(""" {patchmarker} {original} deactivate () {{ {resetters} if [ ! "${{1-}}" = "nondestructive" ] ; then # Self destruct! unset -f deactivate origdeactivate fi }} deactivate nondestructive {old_value_setters} {setters} # The hash command must be called to get it to forget past # commands. Without forgetting past commands the $PATH changes # we made may not be respected hash -r 2>/dev/null """) @staticmethod def interpolate_environ_value(value: str) -> str: if not value: return "" keys = re.findall(r"{(?P<key>\w+?)}", value) for key in keys: if key in os.environ: value = value.replace(f"{{{key}}}", f"${key}") return value class PowershellActivate(ActivateScriptPatcher): patchmarker = "\n## Patched by csspin_python.python\n" activatescript = Path("{python.scriptdir}") / "activate.ps1" replacements = [ ("deactivate", "origdeactivate"), ] old_env_pattern = ( "New-Variable -Scope global -Name _OLD_SPIN_{name} -Value $env:{name}" ) setpattern = dedent(""" $env:{name} = "{value}" """) resetpattern = indent( dedent(""" if (Test-Path variable:_OLD_SPIN_{name}) {{ $env:{name} = $variable:_OLD_SPIN_{name} Remove-Variable "_OLD_SPIN_{name}" -Scope global }} """), prefix=" ", ) script = dedent(""" {patchmarker} {original} function global:deactivate([switch] $NonDestructive) {{ {resetters} if (!$NonDestructive) {{ Remove-Item function:deactivate origdeactivate }} }} deactivate -nondestructive {old_value_setters} {setters} """) @staticmethod def interpolate_environ_value(value: str) -> str: if not value: return "" keys = re.findall(r"{(?P<key>\w+?)}", value) for key in keys: if key in os.environ: value = value.replace(f"{{{key}}}", f"$env:{key}") return value class BatchActivate(ActivateScriptPatcher): patchmarker = "\nREM Patched by csspin_python.python\n" activatescript = Path("{python.scriptdir}") / "activate.bat" replacements = [] old_env_pattern = dedent(""" if defined _OLD_SPIN_VALUE_{name} goto ENDIFSPIN{name}1 if defined _OLD_SPIN_UNSET_{name} goto ENDIFSPIN{name}2 if defined {name} goto ENDIFSPIN{name}3 goto ENDIFSPIN{name}4 :ENDIFSPIN{name}1 set "{name}=%_OLD_SPIN_VALUE_{name}%" set "_OLD_SPIN_VALUE_{name}=%{name}%" goto ENDIFSPIN{name}5 :ENDIFSPIN{name}2 set "{name}=" set "_OLD_SPIN_UNSET_{name}= " goto ENDIFSPIN{name}5 :ENDIFSPIN{name}3 set "_OLD_SPIN_VALUE_{name}=%{name}%" goto ENDIFSPIN{name}5 :ENDIFSPIN{name}4 set "_OLD_SPIN_UNSET_{name}= " goto ENDIFSPIN{name}5 :ENDIFSPIN{name}5 """) setpattern = 'set "{name}={value}"' resetpattern = "" script = dedent(""" @echo off {patchmarker} {original} {old_value_setters} {setters} """) @staticmethod def interpolate_environ_value(value: str) -> str: if not value: return "" keys = re.findall(r"{(?P<key>\w+?)}", value) for key in keys: if key in os.environ: value = value.replace(f"{{{key}}}", f"%{key}%") return value class BatchDeactivate(ActivateScriptPatcher): patchmarker = "\nREM Patched by csspin_python.python\n" activatescript = Path("{python.scriptdir}") / "deactivate.bat" replacements = [] old_env_pattern = "" setpattern = "" resetpattern = dedent(""" if defined _OLD_SPIN_VALUE_{name} goto ENDIFVSPIN{name}1 if defined _OLD_SPIN_UNSET_{name} goto ENDIFVSPIN{name}2 :ENDIFVSPIN{name}1 set "{name}=%_OLD_SPIN_VALUE_{name}%" set _OLD_SPIN_VALUE_{name}= goto ENDIFVSPIN{name}0 :ENDIFVSPIN{name}2 set {name}= set _OLD_SPIN_UNSET_{name}= goto ENDIFVSPIN{name}0 :ENDIFVSPIN{name}0 """) script = dedent(""" @echo off {patchmarker} {original} {resetters} """) class PythonActivate(ActivateScriptPatcher): patchmarker = "# Patched by csspin_python.python\n" activatescript = Path("{python.scriptdir}") / "activate_this.py" replacements = [] old_env_pattern = "" setpattern = 'os.environ["{name}"] = fr"{value}"' resetpattern = "" script = dedent(""" {patchmarker} {original} {setters} """) @staticmethod def interpolate_environ_value(value: str) -> str: if not value: return "" keys = re.findall(r"{(?P<key>\w+?)}", value) for key in keys: if key in os.environ: value = value.replace(f"{{{key}}}", f"{{os.environ['{key}']}}") return value @cache def get_project_metadata( # type: ignore[return] # pylint: disable=inconsistent-return-statements # noqa: E501 project_path: str, index_url: str, extra_index_urls: tuple[str, ...] = () ) -> dict: """ Retrieve project metadata of ``project_path`` via ``python -m build --metadata``. Cached since ``build --metadata`` is noisy and the output is identical for every caller within the same process. """ setenv(PIP_INDEX_URL=index_url) if extra_index_urls: setenv(PIP_EXTRA_INDEX_URL=" ".join(extra_index_urls)) kwargs = {} if CONFIG.verbosity < Verbosity.INFO: kwargs["stderr"] = subprocess.DEVNULL raw_metadata = backtick( "python", "-m", "build", "--metadata", project_path, **kwargs ) if extra_index_urls: setenv(PIP_EXTRA_INDEX_URL=None) setenv(PIP_INDEX_URL=None) if raw_metadata: return json.loads(raw_metadata) # type: ignore[no-any-return] die(f"Could not retrieve project metadata of '{project_path}'.") def get_site_packages(interpreter: Path) -> Path: """Return the path to the virtual environments site-packages.""" return Path( check_output( [ interpolate1(interpreter), "-c", 'import sysconfig; print(sysconfig.get_path("purelib"))', ], ) .decode() .strip(), ) def finalize_provision(cfg: ConfigTree) -> None: """Patching the activate scripts and preparing the site-packages""" cfg.python.provisioner.install(cfg) for schema in ( BashActivate, BatchActivate, BatchDeactivate, PowershellActivate, PythonActivate, ): patch_activate(schema) setenv_path = str(cfg.python.site_packages / "_set_env.pth") info(f"Create {setenv_path}") pthline = interpolate1( "import os; " "bindir=r'{python.bindir}'; " "os.environ['PATH'] = " "os.environ['PATH'] if bindir in os.environ['PATH'] " "else os.pathsep.join((bindir, os.environ['PATH']))\n" ) writetext(setenv_path, pthline) class ProvisionerProtocol: """An implementation of this protocol is used to provision requirements to a virtual environment. Separate plugins, can implement this interface and overwrite cfg.python.provisioner. .. note:: The provisioner will be memoized, so make sure it works with ``pickle.dumps``. """ _requirements: set[str] = set() def provision_python(self: Self, cfg: ConfigTree) -> None: """Provision the project's python interpreter""" if sys.platform == "win32": nuget_install(cfg) else: # Everything else (Linux and macOS) uses pyenv pyenv_install(cfg) # noinspection PyMethodMayBeStatic def provision_venv(self: Self, cfg: ConfigTree) -> None: """Provision the virtual environment of the project""" cmd = [ sys.executable, "-mvirtualenv", None if cfg.verbosity > Verbosity.NORMAL else "-q", ] virtualenv = Command(*cmd) # do not download seeds, since we update pip later anyway # add the plugin packages to the PYTHONPATH so that virtualenv will be # found; csspin versions without spin.plugin_site_packages install # them into the plugins directory itself plugin_site_packages = cfg.spin.get("plugin_site_packages") or ( cfg.spin.spin_dir / "plugins" ) virtualenv( "-p", cfg.python.interpreter, cfg.python.venv, env={"PYTHONPATH": plugin_site_packages}, ) def prerequisites(self: Self, cfg: ConfigTree) -> None: """Provide requirements for the provisioning strategy.""" def add( self: Self, cfg: ConfigTree, req: str # pylint: disable=unused-argument ) -> None: """ Add a single requirement `req`, that will be installed into the environment. """ self._requirements.add(req) def install(self: Self, cfg: ConfigTree) -> None: """Install the requirements""" def cleanup(self: Self, cfg: ConfigTree) -> None: """Cleanup the provisioned environment""" rmtree(cfg.python.venv) class SimpleProvisioner(ProvisionerProtocol): """ The simplest Python provisioner, using pip. This provisioner will never uninstall requirements that are no longer required. """ def __init__(self: Self, cfg: ConfigTree) -> None: self._m = Memoizer(interpolate1("{python.memo}")) self._install_command = Command( "pip", None if cfg.verbosity > Verbosity.NORMAL else "-q", "--disable-pip-version-check", "install", |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |