Datasets:
Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+59-59
- .idea/.gitignoreAdded+3
- .idea/inspectionProfiles/Project_Default.xmlAdded+30
- .idea/inspectionProfiles/profiles_settings.xmlAdded+6
- .idea/misc.xmlAdded+7
- .idea/modules.xmlAdded+8
- .idea/pac.imlAdded+10
- .idea/vcs.xmlAdded+6
- .idea/workspace.xmlAdded+84
- .venv/.gitignoreAdded+2
- .venv/Lib/site-packages/pip/__pip-runner__.pyAdded+50
- .venv/Lib/site-packages/pip/_internal/__init__.pyAdded+19
- .venv/Lib/site-packages/pip/_internal/build_env.pyAdded+311
- .venv/Lib/site-packages/pip/_internal/cache.pyAdded+292
- .venv/Lib/site-packages/pip/_internal/cli/__init__.pyAdded+4
- .venv/Lib/site-packages/pip/_internal/cli/autocompletion.pyAdded+171
- .venv/Lib/site-packages/pip/_internal/cli/base_command.pyAdded+236
- .venv/Lib/site-packages/pip/_internal/cli/cmdoptions.pyAdded+1074
- .venv/Lib/site-packages/pip/_internal/cli/command_context.pyAdded+27
- .venv/Lib/site-packages/pip/_internal/cli/main.pyAdded+79
- .venv/Lib/site-packages/pip/_internal/cli/main_parser.pyAdded+134
- .venv/Lib/site-packages/pip/_internal/cli/parser.pyAdded+294
- .venv/Lib/site-packages/pip/_internal/cli/progress_bars.pyAdded+68
- .venv/Lib/site-packages/pip/_internal/cli/req_command.pyAdded+508
- .venv/Lib/site-packages/pip/_internal/cli/spinners.pyAdded+159
- .venv/Lib/site-packages/pip/_internal/cli/status_codes.pyAdded+6
- .venv/Lib/site-packages/pip/_internal/commands/__init__.pyAdded+132
- .venv/Lib/site-packages/pip/_internal/commands/cache.pyAdded+222
- .venv/Lib/site-packages/pip/_internal/commands/check.pyAdded+54
- .venv/Lib/site-packages/pip/_internal/commands/completion.pyAdded+121
- .venv/Lib/site-packages/pip/_internal/commands/configuration.pyAdded+282
- .venv/Lib/site-packages/pip/_internal/commands/debug.pyAdded+199
- .venv/Lib/site-packages/pip/_internal/commands/download.pyAdded+147
- .venv/Lib/site-packages/pip/_internal/commands/freeze.pyAdded+108
- .venv/Lib/site-packages/pip/_internal/commands/hash.pyAdded+59
- .venv/Lib/site-packages/pip/_internal/commands/help.pyAdded+41
- .venv/Lib/site-packages/pip/_internal/commands/index.pyAdded+139
- .venv/Lib/site-packages/pip/_internal/commands/inspect.pyAdded+92
- .venv/Lib/site-packages/pip/_internal/commands/install.pyAdded+778
- .venv/Lib/site-packages/pip/_internal/commands/list.pyAdded+368
- .venv/Lib/site-packages/pip/_internal/commands/search.pyAdded+174
- .venv/Lib/site-packages/pip/_internal/commands/show.pyAdded+189
- .venv/Lib/site-packages/pip/_internal/commands/uninstall.pyAdded+113
- .venv/Lib/site-packages/pip/_internal/commands/wheel.pyAdded+183
- .venv/Lib/site-packages/pip/_internal/configuration.pyAdded+381
- .venv/Lib/site-packages/pip/_internal/distributions/__init__.pyAdded+21
- .venv/Lib/site-packages/pip/_internal/distributions/base.pyAdded+39
- .venv/Lib/site-packages/pip/_internal/distributions/installed.pyAdded+23
- .venv/Lib/site-packages/pip/_internal/distributions/sdist.pyAdded+150
- .venv/Lib/site-packages/pip/_internal/distributions/wheel.pyAdded+34
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.lz4 filter=lfs diff=lfs merge=lfs -text*.mds filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text# Audio files - uncompressed*.pcm filter=lfs diff=lfs merge=lfs -text*.sam filter=lfs diff=lfs merge=lfs -text*.raw filter=lfs diff=lfs merge=lfs -text# Audio files - compressed*.aac filter=lfs diff=lfs merge=lfs -text*.flac filter=lfs diff=lfs merge=lfs -text*.mp3 filter=lfs diff=lfs merge=lfs -text*.ogg filter=lfs diff=lfs merge=lfs -text*.wav filter=lfs diff=lfs merge=lfs -text# Image files - uncompressed*.bmp filter=lfs diff=lfs merge=lfs -text*.gif filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.tiff filter=lfs diff=lfs merge=lfs -text# Image files - compressed*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.webp filter=lfs diff=lfs merge=lfs -text# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -text1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.lz4 filter=lfs diff=lfs merge=lfs -text*.mds filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text# Audio files - uncompressed*.pcm filter=lfs diff=lfs merge=lfs -text*.sam filter=lfs diff=lfs merge=lfs -text*.raw filter=lfs diff=lfs merge=lfs -text# Audio files - compressed*.aac filter=lfs diff=lfs merge=lfs -text*.flac filter=lfs diff=lfs merge=lfs -text*.mp3 filter=lfs diff=lfs merge=lfs -text*.ogg filter=lfs diff=lfs merge=lfs -text*.wav filter=lfs diff=lfs merge=lfs -text# Image files - uncompressed*.bmp filter=lfs diff=lfs merge=lfs -text*.gif filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.tiff filter=lfs diff=lfs merge=lfs -text# Image files - compressed*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.webp filter=lfs diff=lfs merge=lfs -text# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -text
123# Default ignored files
/shelf/
/workspace.xml123456789101112131415161718192021222324252627282930<component name="InspectionProjectProfileManager"> <profile version="1.0"> <option name="myName" value="Project Default" /> <inspection_tool class="DuplicatedCode" enabled="true" level="WEAK WARNING" enabled_by_default="true"> <Languages> <language minSize="118" name="Python" /> </Languages> </inspection_tool> <inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" /> <inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true"> <option name="ignoredPackages"> <value> <list size="4"> <item index="0" class="java.lang.String" itemvalue="tensorflowjs" /> <item index="1" class="java.lang.String" itemvalue="tensorflow-io-gcs-filesystem" /> <item index="2" class="java.lang.String" itemvalue="typeguard" /> <item index="3" class="java.lang.String" itemvalue="tensorflow_addons" /> </list> </value> </option> </inspection_tool> <inspection_tool class="PyPep8Inspection" enabled="true" level="WEAK WARNING" enabled_by_default="true"> <option name="ignoredErrors"> <list> <option value="E731" /> </list> </option> </inspection_tool> </profile></component>123456<component name="InspectionProjectProfileManager"> <settings> <option name="USE_PROJECT_PROFILE" value="false" /> <version value="1.0" /> </settings></component>1234567<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Python 3.10 (pac)" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (pac)" project-jdk-type="Python SDK" />
</project>12345678<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/pac.iml" filepath="$PROJECT_DIR$/.idea/pac.iml" />
</modules>
</component>
</project>12345678910<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.10 (pac)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>123456<?xml version="1.0" encoding="UTF-8"?><project version="4"> <component name="VcsDirectoryMappings"> <mapping directory="" vcs="Git" /> </component></project>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384<?xml version="1.0" encoding="UTF-8"?><project version="4"> <component name="AutoImportSettings"> <option name="autoReloadType" value="SELECTIVE" /> </component> <component name="ChangeListManager"> <list default="true" id="444ec9ca-b004-44c2-93e4-451ebc131871" name="Changes" comment="Adds metadata"> <change beforePath="$PROJECT_DIR$/README.md" beforeDir="false" afterPath="$PROJECT_DIR$/README.md" afterDir="false" /> </list> <option name="SHOW_DIALOG" value="false" /> <option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" /> <option name="LAST_RESOLUTION" value="IGNORE" /> </component> <component name="Git.Settings"> <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" /> </component> <component name="GitHubPullRequestSearchHistory"><![CDATA[{ "lastFilter": { "state": "OPEN", "assignee": "fegemo" }}]]></component> <component name="GithubPullRequestsUISettings"><![CDATA[{ "selectedUrlAndAccountId": { "url": "git@github.com:plucksquire/pac.git", "accountId": "f7c969a6-2610-4425-915b-91e26a746a39" }}]]></component> <component name="ProjectColorInfo"><![CDATA[{ "associatedIndex": 7}]]></component> <component name="ProjectId" id="2qu9qC2IEXiviSGDMehtlXLkgWT" /> <component name="ProjectViewState"> <option name="hideEmptyMiddlePackages" value="true" /> <option name="showLibraryContents" value="true" /> </component> <component name="PropertiesComponent"><![CDATA[{ "keyToString": { "RunOnceActivity.ShowReadmeOnStart": "true", "RunOnceActivity.git.unshallow": "true", "git-widget-placeholder": "main", "ignore.virus.scanning.warn.message": "true", "node.js.detected.package.eslint": "true", "node.js.selected.package.eslint": "(autodetect)", "nodejs_package_manager_path": "npm" }}]]></component> <component name="SharedIndexes"> <attachedChunks> <set> <option value="bundled-python-sdk-0fc6c617c4bd-9a18a617cbe4-com.jetbrains.pycharm.pro.sharedIndexes.bundled-PY-243.22562.220" /> </set> </attachedChunks> </component> <component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" /> <component name="TaskManager"> <task active="true" id="Default" summary="Default task"> <changelist id="444ec9ca-b004-44c2-93e4-451ebc131871" name="Changes" comment="" /> <created>1735501782328</created> <option name="number" value="Default" /> <option name="presentableId" value="Default" /> <updated>1735501782328</updated> <workItem from="1735501783439" duration="2016000" /> </task> <task id="LOCAL-00001" summary="Adds metadata"> <option name="closed" value="true" /> <created>1735502948132</created> <option name="number" value="00001" /> <option name="presentableId" value="LOCAL-00001" /> <option name="project" value="LOCAL" /> <updated>1735502948132</updated> </task> <option name="localTasksCounter" value="2" /> <servers /> </component> <component name="TypeScriptGeneratedFilesManager"> <option name="version" value="3" /> </component> <component name="VcsManagerConfiguration"> <MESSAGE value="Adds metadata" /> <option name="LAST_COMMIT_MESSAGE" value="Adds metadata" /> </component></project>12# created by virtualenv automatically
*1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950"""Execute exactly this copy of pip, within a different environment.
This file is named as it is, to ensure that this module can't be imported viaan import statement."""
# /!\ This version compatibility check section must be Python 2 compatible. /!\
import sys
# Copied from setup.pyPYTHON_REQUIRES = (3, 7)
def version_str(version): # type: ignore return ".".join(str(v) for v in version)
if sys.version_info[:2] < PYTHON_REQUIRES: raise SystemExit( "This version of pip does not support python {} (requires >={}).".format( version_str(sys.version_info[:2]), version_str(PYTHON_REQUIRES) ) )
# From here on, we can use Python 3 features, but the syntax must remain# Python 2 compatible.
import runpy # noqa: E402from importlib.machinery import PathFinder # noqa: E402from os.path import dirname # noqa: E402
PIP_SOURCES_ROOT = dirname(dirname(__file__))
class PipImportRedirectingFinder: @classmethod def find_spec(self, fullname, path=None, target=None): # type: ignore if fullname != "pip": return None
spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target) assert spec, (PIP_SOURCES_ROOT, fullname) return spec
sys.meta_path.insert(0, PipImportRedirectingFinder())
assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module"runpy.run_module("pip", run_name="__main__", alter_sys=True)12345678910111213141516171819from typing import List, Optional
import pip._internal.utils.inject_securetransport # noqafrom pip._internal.utils import _log
# init_logging() must be called before any call to logging.getLogger()# which happens at import of most modules._log.init_logging()
def main(args: (Optional[List[str]]) = None) -> int: """This is preserved for old console scripts that may still be referencing it.
For additional details, see https://github.com/pypa/pip/issues/7498. """ from pip._internal.utils.entrypoints import _wrapper
return _wrapper(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311"""Build Environment used for isolation during sdist building"""
import loggingimport osimport pathlibimport siteimport sysimport textwrapfrom collections import OrderedDictfrom types import TracebackTypefrom typing import TYPE_CHECKING, Iterable, List, Optional, Set, Tuple, Type, Union
from pip._vendor.certifi import wherefrom pip._vendor.packaging.requirements import Requirementfrom pip._vendor.packaging.version import Version
from pip import __file__ as pip_locationfrom pip._internal.cli.spinners import open_spinnerfrom pip._internal.locations import get_platlib, get_purelib, get_schemefrom pip._internal.metadata import get_default_environment, get_environmentfrom pip._internal.utils.subprocess import call_subprocessfrom pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
if TYPE_CHECKING: from pip._internal.index.package_finder import PackageFinder
logger = logging.getLogger(__name__)
def _dedup(a: str, b: str) -> Union[Tuple[str], Tuple[str, str]]: return (a, b) if a != b else (a,)
class _Prefix: def __init__(self, path: str) -> None: self.path = path self.setup = False scheme = get_scheme("", prefix=path) self.bin_dir = scheme.scripts self.lib_dirs = _dedup(scheme.purelib, scheme.platlib)
def get_runnable_pip() -> str: """Get a file to pass to a Python executable, to run the currently-running pip.
This is used to run a pip subprocess, for installing requirements into the build environment. """ source = pathlib.Path(pip_location).resolve().parent
if not source.is_dir(): # This would happen if someone is using pip from inside a zip file. In that # case, we can use that directly. return str(source)
return os.fsdecode(source / "__pip-runner__.py")
def _get_system_sitepackages() -> Set[str]: """Get system site packages
Usually from site.getsitepackages, but fallback on `get_purelib()/get_platlib()` if unavailable (e.g. in a virtualenv created by virtualenv<20)
Returns normalized set of strings. """ if hasattr(site, "getsitepackages"): system_sites = site.getsitepackages() else: # virtualenv < 20 overwrites site.py without getsitepackages # fallback on get_purelib/get_platlib. # this is known to miss things, but shouldn't in the cases # where getsitepackages() has been removed (inside a virtualenv) system_sites = [get_purelib(), get_platlib()] return {os.path.normcase(path) for path in system_sites}
class BuildEnvironment: """Creates and manages an isolated environment to install build deps"""
def __init__(self) -> None: temp_dir = TempDirectory(kind=tempdir_kinds.BUILD_ENV, globally_managed=True)
self._prefixes = OrderedDict( (name, _Prefix(os.path.join(temp_dir.path, name))) for name in ("normal", "overlay") )
self._bin_dirs: List[str] = [] self._lib_dirs: List[str] = [] for prefix in reversed(list(self._prefixes.values())): self._bin_dirs.append(prefix.bin_dir) self._lib_dirs.extend(prefix.lib_dirs)
# Customize site to: # - ensure .pth files are honored # - prevent access to system site packages system_sites = _get_system_sitepackages()
self._site_dir = os.path.join(temp_dir.path, "site") if not os.path.exists(self._site_dir): os.mkdir(self._site_dir) with open( os.path.join(self._site_dir, "sitecustomize.py"), "w", encoding="utf-8" ) as fp: fp.write( textwrap.dedent( """ import os, site, sys
# First, drop system-sites related paths. original_sys_path = sys.path[:] known_paths = set() for path in {system_sites!r}: site.addsitedir(path, known_paths=known_paths) system_paths = set( os.path.normcase(path) for path in sys.path[len(original_sys_path):] ) original_sys_path = [ path for path in original_sys_path if os.path.normcase(path) not in system_paths ] sys.path = original_sys_path
# Second, add lib directories. # ensuring .pth file are processed. for path in {lib_dirs!r}: assert not path in sys.path site.addsitedir(path) """ ).format(system_sites=system_sites, lib_dirs=self._lib_dirs) )
def __enter__(self) -> None: self._save_env = { name: os.environ.get(name, None) for name in ("PATH", "PYTHONNOUSERSITE", "PYTHONPATH") }
path = self._bin_dirs[:] old_path = self._save_env["PATH"] if old_path: path.extend(old_path.split(os.pathsep))
pythonpath = [self._site_dir]
os.environ.update( { "PATH": os.pathsep.join(path), "PYTHONNOUSERSITE": "1", "PYTHONPATH": os.pathsep.join(pythonpath), } )
def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: for varname, old_value in self._save_env.items(): if old_value is None: os.environ.pop(varname, None) else: os.environ[varname] = old_value
def check_requirements( self, reqs: Iterable[str] ) -> Tuple[Set[Tuple[str, str]], Set[str]]: """Return 2 sets: - conflicting requirements: set of (installed, wanted) reqs tuples - missing requirements: set of reqs """ missing = set() conflicting = set() if reqs: env = ( get_environment(self._lib_dirs) if hasattr(self, "_lib_dirs") else get_default_environment() ) for req_str in reqs: req = Requirement(req_str) # We're explicitly evaluating with an empty extra value, since build # environments are not provided any mechanism to select specific extras. if req.marker is not None and not req.marker.evaluate({"extra": ""}): continue dist = env.get_distribution(req.name) if not dist: missing.add(req_str) continue if isinstance(dist.version, Version): installed_req_str = f"{req.name}=={dist.version}" else: installed_req_str = f"{req.name}==={dist.version}" if not req.specifier.contains(dist.version, prereleases=True): conflicting.add((installed_req_str, req_str)) # FIXME: Consider direct URL? return conflicting, missing
def install_requirements( self, finder: "PackageFinder", requirements: Iterable[str], prefix_as_string: str, *, kind: str, ) -> None: prefix = self._prefixes[prefix_as_string] assert not prefix.setup prefix.setup = True if not requirements: return self._install_requirements( get_runnable_pip(), finder, requirements, prefix, kind=kind, )
@staticmethod def _install_requirements( pip_runnable: str, finder: "PackageFinder", requirements: Iterable[str], prefix: _Prefix, *, kind: str, ) -> None: args: List[str] = [ sys.executable, pip_runnable, "install", "--ignore-installed", "--no-user", "--prefix", prefix.path, "--no-warn-script-location", ] if logger.getEffectiveLevel() <= logging.DEBUG: args.append("-v") for format_control in ("no_binary", "only_binary"): formats = getattr(finder.format_control, format_control) args.extend( ( "--" + format_control.replace("_", "-"), ",".join(sorted(formats or {":none:"})), ) )
index_urls = finder.index_urls if index_urls: args.extend(["-i", index_urls[0]]) for extra_index in index_urls[1:]: args.extend(["--extra-index-url", extra_index]) else: args.append("--no-index") for link in finder.find_links: args.extend(["--find-links", link])
for host in finder.trusted_hosts: args.extend(["--trusted-host", host]) if finder.allow_all_prereleases: args.append("--pre") if finder.prefer_binary: args.append("--prefer-binary") args.append("--") args.extend(requirements) extra_environ = {"_PIP_STANDALONE_CERT": where()} with open_spinner(f"Installing {kind}") as spinner: call_subprocess( args, command_desc=f"pip subprocess to install {kind}", spinner=spinner, extra_environ=extra_environ, )
class NoOpBuildEnvironment(BuildEnvironment): """A no-op drop-in replacement for BuildEnvironment"""
def __init__(self) -> None: pass
def __enter__(self) -> None: pass
def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: pass
def cleanup(self) -> None: pass
def install_requirements( self, finder: "PackageFinder", requirements: Iterable[str], prefix_as_string: str, *, kind: str, ) -> None: raise NotImplementedError()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292"""Cache Management"""
import hashlibimport jsonimport loggingimport osfrom pathlib import Pathfrom typing import Any, Dict, List, Optional
from pip._vendor.packaging.tags import Tag, interpreter_name, interpreter_versionfrom pip._vendor.packaging.utils import canonicalize_name
from pip._internal.exceptions import InvalidWheelFilenamefrom pip._internal.models.direct_url import DirectUrlfrom pip._internal.models.link import Linkfrom pip._internal.models.wheel import Wheelfrom pip._internal.utils.temp_dir import TempDirectory, tempdir_kindsfrom pip._internal.utils.urls import path_to_url
logger = logging.getLogger(__name__)
ORIGIN_JSON_NAME = "origin.json"
def _hash_dict(d: Dict[str, str]) -> str: """Return a stable sha224 of a dictionary.""" s = json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=True) return hashlib.sha224(s.encode("ascii")).hexdigest()
class Cache: """An abstract class - provides cache directories for data from links
:param cache_dir: The root of the cache. """
def __init__(self, cache_dir: str) -> None: super().__init__() assert not cache_dir or os.path.isabs(cache_dir) self.cache_dir = cache_dir or None
def _get_cache_path_parts(self, link: Link) -> List[str]: """Get parts of part that must be os.path.joined with cache_dir"""
# We want to generate an url to use as our cache key, we don't want to # just re-use the URL because it might have other items in the fragment # and we don't care about those. key_parts = {"url": link.url_without_fragment} if link.hash_name is not None and link.hash is not None: key_parts[link.hash_name] = link.hash if link.subdirectory_fragment: key_parts["subdirectory"] = link.subdirectory_fragment
# Include interpreter name, major and minor version in cache key # to cope with ill-behaved sdists that build a different wheel # depending on the python version their setup.py is being run on, # and don't encode the difference in compatibility tags. # https://github.com/pypa/pip/issues/7296 key_parts["interpreter_name"] = interpreter_name() key_parts["interpreter_version"] = interpreter_version()
# Encode our key url with sha224, we'll use this because it has similar # security properties to sha256, but with a shorter total output (and # thus less secure). However the differences don't make a lot of # difference for our use case here. hashed = _hash_dict(key_parts)
# We want to nest the directories some to prevent having a ton of top # level directories where we might run out of sub directories on some # FS. parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
return parts
def _get_candidates(self, link: Link, canonical_package_name: str) -> List[Any]: can_not_cache = not self.cache_dir or not canonical_package_name or not link if can_not_cache: return []
candidates = [] path = self.get_path_for_link(link) if os.path.isdir(path): for candidate in os.listdir(path): candidates.append((candidate, path)) return candidates
def get_path_for_link(self, link: Link) -> str: """Return a directory to store cached items in for link.""" raise NotImplementedError()
def get( self, link: Link, package_name: Optional[str], supported_tags: List[Tag], ) -> Link: """Returns a link to a cached item if it exists, otherwise returns the passed link. """ raise NotImplementedError()
class SimpleWheelCache(Cache): """A cache of wheels for future installs."""
def __init__(self, cache_dir: str) -> None: super().__init__(cache_dir)
def get_path_for_link(self, link: Link) -> str: """Return a directory to store cached wheels for link
Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits.
We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited.
:param link: The link of the sdist for which this will cache wheels. """ parts = self._get_cache_path_parts(link) assert self.cache_dir # Store wheels within the root cache_dir return os.path.join(self.cache_dir, "wheels", *parts)
def get( self, link: Link, package_name: Optional[str], supported_tags: List[Tag], ) -> Link: candidates = []
if not package_name: return link
canonical_package_name = canonicalize_name(package_name) for wheel_name, wheel_dir in self._get_candidates(link, canonical_package_name): try: wheel = Wheel(wheel_name) except InvalidWheelFilename: continue if canonicalize_name(wheel.name) != canonical_package_name: logger.debug( "Ignoring cached wheel %s for %s as it " "does not match the expected distribution name %s.", wheel_name, link, package_name, ) continue if not wheel.supported(supported_tags): # Built for a different python/arch/etc continue candidates.append( ( wheel.support_index_min(supported_tags), wheel_name, wheel_dir, ) )
if not candidates: return link
_, wheel_name, wheel_dir = min(candidates) return Link(path_to_url(os.path.join(wheel_dir, wheel_name)))
class EphemWheelCache(SimpleWheelCache): """A SimpleWheelCache that creates it's own temporary cache directory"""
def __init__(self) -> None: self._temp_dir = TempDirectory( kind=tempdir_kinds.EPHEM_WHEEL_CACHE, globally_managed=True, )
super().__init__(self._temp_dir.path)
class CacheEntry: def __init__( self, link: Link, persistent: bool, ): self.link = link self.persistent = persistent self.origin: Optional[DirectUrl] = None origin_direct_url_path = Path(self.link.file_path).parent / ORIGIN_JSON_NAME if origin_direct_url_path.exists(): try: self.origin = DirectUrl.from_json( origin_direct_url_path.read_text(encoding="utf-8") ) except Exception as e: logger.warning( "Ignoring invalid cache entry origin file %s for %s (%s)", origin_direct_url_path, link.filename, e, )
class WheelCache(Cache): """Wraps EphemWheelCache and SimpleWheelCache into a single Cache
This Cache allows for gracefully degradation, using the ephem wheel cache when a certain link is not found in the simple wheel cache first. """
def __init__(self, cache_dir: str) -> None: super().__init__(cache_dir) self._wheel_cache = SimpleWheelCache(cache_dir) self._ephem_cache = EphemWheelCache()
def get_path_for_link(self, link: Link) -> str: return self._wheel_cache.get_path_for_link(link)
def get_ephem_path_for_link(self, link: Link) -> str: return self._ephem_cache.get_path_for_link(link)
def get( self, link: Link, package_name: Optional[str], supported_tags: List[Tag], ) -> Link: cache_entry = self.get_cache_entry(link, package_name, supported_tags) if cache_entry is None: return link return cache_entry.link
def get_cache_entry( self, link: Link, package_name: Optional[str], supported_tags: List[Tag], ) -> Optional[CacheEntry]: """Returns a CacheEntry with a link to a cached item if it exists or None. The cache entry indicates if the item was found in the persistent or ephemeral cache. """ retval = self._wheel_cache.get( link=link, package_name=package_name, supported_tags=supported_tags, ) if retval is not link: return CacheEntry(retval, persistent=True)
retval = self._ephem_cache.get( link=link, package_name=package_name, supported_tags=supported_tags, ) if retval is not link: return CacheEntry(retval, persistent=False)
return None
@staticmethod def record_download_origin(cache_dir: str, download_info: DirectUrl) -> None: origin_path = Path(cache_dir) / ORIGIN_JSON_NAME if origin_path.exists(): try: origin = DirectUrl.from_json(origin_path.read_text(encoding="utf-8")) except Exception as e: logger.warning( "Could not read origin file %s in cache entry (%s). " "Will attempt to overwrite it.", origin_path, e, ) else: # TODO: use DirectUrl.equivalent when # https://github.com/pypa/pip/pull/10564 is merged. if origin.url != download_info.url: logger.warning( "Origin URL %s in cache entry %s does not match download URL " "%s. This is likely a pip bug or a cache corruption issue. " "Will overwrite it with the new value.", origin.url, cache_dir, download_info.url, ) origin_path.write_text(download_info.to_json(), encoding="utf-8")1234"""Subpackage containing all of pip's command line interface related code"""
# This file intentionally does not import submodules123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171"""Logic that powers autocompletion installed by ``pip completion``."""
import optparseimport osimport sysfrom itertools import chainfrom typing import Any, Iterable, List, Optional
from pip._internal.cli.main_parser import create_main_parserfrom pip._internal.commands import commands_dict, create_commandfrom pip._internal.metadata import get_default_environment
def autocomplete() -> None: """Entry Point for completion of main and subcommand options.""" # Don't complete if user hasn't sourced bash_completion file. if "PIP_AUTO_COMPLETE" not in os.environ: return cwords = os.environ["COMP_WORDS"].split()[1:] cword = int(os.environ["COMP_CWORD"]) try: current = cwords[cword - 1] except IndexError: current = ""
parser = create_main_parser() subcommands = list(commands_dict) options = []
# subcommand subcommand_name: Optional[str] = None for word in cwords: if word in subcommands: subcommand_name = word break # subcommand options if subcommand_name is not None: # special case: 'help' subcommand has no options if subcommand_name == "help": sys.exit(1) # special case: list locally installed dists for show and uninstall should_list_installed = not current.startswith("-") and subcommand_name in [ "show", "uninstall", ] if should_list_installed: env = get_default_environment() lc = current.lower() installed = [ dist.canonical_name for dist in env.iter_installed_distributions(local_only=True) if dist.canonical_name.startswith(lc) and dist.canonical_name not in cwords[1:] ] # if there are no dists installed, fall back to option completion if installed: for dist in installed: print(dist) sys.exit(1)
should_list_installables = ( not current.startswith("-") and subcommand_name == "install" ) if should_list_installables: for path in auto_complete_paths(current, "path"): print(path) sys.exit(1)
subcommand = create_command(subcommand_name)
for opt in subcommand.parser.option_list_all: if opt.help != optparse.SUPPRESS_HELP: for opt_str in opt._long_opts + opt._short_opts: options.append((opt_str, opt.nargs))
# filter out previously specified options from available options prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]] options = [(x, v) for (x, v) in options if x not in prev_opts] # filter options by current input options = [(k, v) for k, v in options if k.startswith(current)] # get completion type given cwords and available subcommand options completion_type = get_path_completion_type( cwords, cword, subcommand.parser.option_list_all, ) # get completion files and directories if ``completion_type`` is # ``<file>``, ``<dir>`` or ``<path>`` if completion_type: paths = auto_complete_paths(current, completion_type) options = [(path, 0) for path in paths] for option in options: opt_label = option[0] # append '=' to options which require args if option[1] and option[0][:2] == "--": opt_label += "=" print(opt_label) else: # show main parser options only when necessary
opts = [i.option_list for i in parser.option_groups] opts.append(parser.option_list) flattened_opts = chain.from_iterable(opts) if current.startswith("-"): for opt in flattened_opts: if opt.help != optparse.SUPPRESS_HELP: subcommands += opt._long_opts + opt._short_opts else: # get completion type given cwords and all available options completion_type = get_path_completion_type(cwords, cword, flattened_opts) if completion_type: subcommands = list(auto_complete_paths(current, completion_type))
print(" ".join([x for x in subcommands if x.startswith(current)])) sys.exit(1)
def get_path_completion_type( cwords: List[str], cword: int, opts: Iterable[Any]) -> Optional[str]: """Get the type of path completion (``file``, ``dir``, ``path`` or None)
:param cwords: same as the environmental variable ``COMP_WORDS`` :param cword: same as the environmental variable ``COMP_CWORD`` :param opts: The available options to check :return: path completion type (``file``, ``dir``, ``path`` or None) """ if cword < 2 or not cwords[cword - 2].startswith("-"): return None for opt in opts: if opt.help == optparse.SUPPRESS_HELP: continue for o in str(opt).split("/"): if cwords[cword - 2].split("=")[0] == o: if not opt.metavar or any( x in ("path", "file", "dir") for x in opt.metavar.split("/") ): return opt.metavar return None
def auto_complete_paths(current: str, completion_type: str) -> Iterable[str]: """If ``completion_type`` is ``file`` or ``path``, list all regular files and directories starting with ``current``; otherwise only list directories starting with ``current``.
:param current: The word to be completed :param completion_type: path completion type(``file``, ``path`` or ``dir``) :return: A generator of regular files and/or directories """ directory, filename = os.path.split(current) current_path = os.path.abspath(directory) # Don't complete paths if they can't be accessed if not os.access(current_path, os.R_OK): return filename = os.path.normcase(filename) # list all files that start with ``filename`` file_list = ( x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename) ) for f in file_list: opt = os.path.join(current_path, f) comp_file = os.path.normcase(os.path.join(directory, f)) # complete regular files when there is not ``<dir>`` after option # complete directories when there is ``<file>``, ``<path>`` or # ``<dir>``after option if completion_type != "dir" and os.path.isfile(opt): yield comp_file elif os.path.isdir(opt): yield os.path.join(comp_file, "")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236"""Base Command class, and related routines"""
import functoolsimport loggingimport logging.configimport optparseimport osimport sysimport tracebackfrom optparse import Valuesfrom typing import Any, Callable, List, Optional, Tuple
from pip._vendor.rich import traceback as rich_traceback
from pip._internal.cli import cmdoptionsfrom pip._internal.cli.command_context import CommandContextMixInfrom pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatterfrom pip._internal.cli.status_codes import ( ERROR, PREVIOUS_BUILD_DIR_ERROR, UNKNOWN_ERROR, VIRTUALENV_NOT_FOUND,)from pip._internal.exceptions import ( BadCommand, CommandError, DiagnosticPipError, InstallationError, NetworkConnectionError, PreviousBuildDirError, UninstallationError,)from pip._internal.utils.filesystem import check_path_ownerfrom pip._internal.utils.logging import BrokenStdoutLoggingError, setup_loggingfrom pip._internal.utils.misc import get_prog, normalize_pathfrom pip._internal.utils.temp_dir import TempDirectoryTypeRegistry as TempDirRegistryfrom pip._internal.utils.temp_dir import global_tempdir_manager, tempdir_registryfrom pip._internal.utils.virtualenv import running_under_virtualenv
__all__ = ["Command"]
logger = logging.getLogger(__name__)
class Command(CommandContextMixIn): usage: str = "" ignore_require_venv: bool = False
def __init__(self, name: str, summary: str, isolated: bool = False) -> None: super().__init__()
self.name = name self.summary = summary self.parser = ConfigOptionParser( usage=self.usage, prog=f"{get_prog()} {name}", formatter=UpdatingDefaultsHelpFormatter(), add_help_option=False, name=name, description=self.__doc__, isolated=isolated, )
self.tempdir_registry: Optional[TempDirRegistry] = None
# Commands should add options to this option group optgroup_name = f"{self.name.capitalize()} Options" self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)
# Add the general options gen_opts = cmdoptions.make_option_group( cmdoptions.general_group, self.parser, ) self.parser.add_option_group(gen_opts)
self.add_options()
def add_options(self) -> None: pass
def handle_pip_version_check(self, options: Values) -> None: """ This is a no-op so that commands by default do not do the pip version check. """ # Make sure we do the pip version check if the index_group options # are present. assert not hasattr(options, "no_index")
def run(self, options: Values, args: List[str]) -> int: raise NotImplementedError
def parse_args(self, args: List[str]) -> Tuple[Values, List[str]]: # factored out for testability return self.parser.parse_args(args)
def main(self, args: List[str]) -> int: try: with self.main_context(): return self._main(args) finally: logging.shutdown()
def _main(self, args: List[str]) -> int: # We must initialize this before the tempdir manager, otherwise the # configuration would not be accessible by the time we clean up the # tempdir manager. self.tempdir_registry = self.enter_context(tempdir_registry()) # Intentionally set as early as possible so globally-managed temporary # directories are available to the rest of the code. self.enter_context(global_tempdir_manager())
options, args = self.parse_args(args)
# Set verbosity so that it can be used elsewhere. self.verbosity = options.verbose - options.quiet
level_number = setup_logging( verbosity=self.verbosity, no_color=options.no_color, user_log_file=options.log, )
always_enabled_features = set(options.features_enabled) & set( cmdoptions.ALWAYS_ENABLED_FEATURES ) if always_enabled_features: logger.warning( "The following features are always enabled: %s. ", ", ".join(sorted(always_enabled_features)), )
# Make sure that the --python argument isn't specified after the # subcommand. We can tell, because if --python was specified, # we should only reach this point if we're running in the created # subprocess, which has the _PIP_RUNNING_IN_SUBPROCESS environment # variable set. if options.python and "_PIP_RUNNING_IN_SUBPROCESS" not in os.environ: logger.critical( "The --python option must be placed before the pip subcommand name" ) sys.exit(ERROR)
# TODO: Try to get these passing down from the command? # without resorting to os.environ to hold these. # This also affects isolated builds and it should.
if options.no_input: os.environ["PIP_NO_INPUT"] = "1"
if options.exists_action: os.environ["PIP_EXISTS_ACTION"] = " ".join(options.exists_action)
if options.require_venv and not self.ignore_require_venv: # If a venv is required check if it can really be found if not running_under_virtualenv(): logger.critical("Could not find an activated virtualenv (required).") sys.exit(VIRTUALENV_NOT_FOUND)
if options.cache_dir: options.cache_dir = normalize_path(options.cache_dir) if not check_path_owner(options.cache_dir): logger.warning( "The directory '%s' or its parent directory is not owned " "or is not writable by the current user. The cache " "has been disabled. Check the permissions and owner of " "that directory. If executing pip with sudo, you should " "use sudo's -H flag.", options.cache_dir, ) options.cache_dir = None
def intercepts_unhandled_exc( run_func: Callable[..., int] ) -> Callable[..., int]: @functools.wraps(run_func) def exc_logging_wrapper(*args: Any) -> int: try: status = run_func(*args) assert isinstance(status, int) return status except DiagnosticPipError as exc: logger.error("[present-rich] %s", exc) logger.debug("Exception information:", exc_info=True)
return ERROR except PreviousBuildDirError as exc: logger.critical(str(exc)) logger.debug("Exception information:", exc_info=True)
return PREVIOUS_BUILD_DIR_ERROR except ( InstallationError, UninstallationError, BadCommand, NetworkConnectionError, ) as exc: logger.critical(str(exc)) logger.debug("Exception information:", exc_info=True)
return ERROR except CommandError as exc: logger.critical("%s", exc) logger.debug("Exception information:", exc_info=True)
return ERROR except BrokenStdoutLoggingError: # Bypass our logger and write any remaining messages to # stderr because stdout no longer works. print("ERROR: Pipe to stdout was broken", file=sys.stderr) if level_number <= logging.DEBUG: traceback.print_exc(file=sys.stderr)
return ERROR except KeyboardInterrupt: logger.critical("Operation cancelled by user") logger.debug("Exception information:", exc_info=True)
return ERROR except BaseException: logger.critical("Exception:", exc_info=True)
return UNKNOWN_ERROR
return exc_logging_wrapper
try: if not options.debug_mode: run = intercepts_unhandled_exc(self.run) else: run = self.run rich_traceback.install(show_locals=True) return run(options, args) finally: self.handle_pip_version_check(options)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074"""shared options and groups
The principle here is to define options once, but *not* instantiate themglobally. One reason being that options with action='append' can carry statebetween parses. pip parses general options twice internally, and shouldn'tpass on state. To be consistent, all options will follow this design."""
# The following comment should be removed at some point in the future.# mypy: strict-optional=False
import importlib.utilimport loggingimport osimport textwrapfrom functools import partialfrom optparse import SUPPRESS_HELP, Option, OptionGroup, OptionParser, Valuesfrom textwrap import dedentfrom typing import Any, Callable, Dict, Optional, Tuple
from pip._vendor.packaging.utils import canonicalize_name
from pip._internal.cli.parser import ConfigOptionParserfrom pip._internal.exceptions import CommandErrorfrom pip._internal.locations import USER_CACHE_DIR, get_src_prefixfrom pip._internal.models.format_control import FormatControlfrom pip._internal.models.index import PyPIfrom pip._internal.models.target_python import TargetPythonfrom pip._internal.utils.hashes import STRONG_HASHESfrom pip._internal.utils.misc import strtobool
logger = logging.getLogger(__name__)
def raise_option_error(parser: OptionParser, option: Option, msg: str) -> None: """ Raise an option parsing error using parser.error().
Args: parser: an OptionParser instance. option: an Option instance. msg: the error text. """ msg = f"{option} error: {msg}" msg = textwrap.fill(" ".join(msg.split())) parser.error(msg)
def make_option_group(group: Dict[str, Any], parser: ConfigOptionParser) -> OptionGroup: """ Return an OptionGroup object group -- assumed to be dict with 'name' and 'options' keys parser -- an optparse Parser """ option_group = OptionGroup(parser, group["name"]) for option in group["options"]: option_group.add_option(option()) return option_group
def check_dist_restriction(options: Values, check_target: bool = False) -> None: """Function for determining if custom platform options are allowed.
:param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used. """ dist_restriction_set = any( [ options.python_version, options.platforms, options.abis, options.implementation, ] )
binary_only = FormatControl(set(), {":all:"}) sdist_dependencies_allowed = ( options.format_control != binary_only and not options.ignore_dependencies )
# Installations or downloads using dist restrictions must not combine # source distributions and dist-specific wheels, as they are not # guaranteed to be locally compatible. if dist_restriction_set and sdist_dependencies_allowed: raise CommandError( "When restricting platform and interpreter constraints using " "--python-version, --platform, --abi, or --implementation, " "either --no-deps must be set, or --only-binary=:all: must be " "set and --no-binary must not be set (or must be set to " ":none:)." )
if check_target: if dist_restriction_set and not options.target_dir: raise CommandError( "Can not use any platform or abi specific options unless " "installing via '--target'" )
def _path_option_check(option: Option, opt: str, value: str) -> str: return os.path.expanduser(value)
def _package_name_option_check(option: Option, opt: str, value: str) -> str: return canonicalize_name(value)
class PipOption(Option): TYPES = Option.TYPES + ("path", "package_name") TYPE_CHECKER = Option.TYPE_CHECKER.copy() TYPE_CHECKER["package_name"] = _package_name_option_check TYPE_CHECKER["path"] = _path_option_check
############ options ############
help_: Callable[..., Option] = partial( Option, "-h", "--help", dest="help", action="help", help="Show help.",)
debug_mode: Callable[..., Option] = partial( Option, "--debug", dest="debug_mode", action="store_true", default=False, help=( "Let unhandled exceptions propagate outside the main subroutine, " "instead of logging them to stderr." ),)
isolated_mode: Callable[..., Option] = partial( Option, "--isolated", dest="isolated_mode", action="store_true", default=False, help=( "Run pip in an isolated mode, ignoring environment variables and user " "configuration." ),)
require_virtualenv: Callable[..., Option] = partial( Option, "--require-virtualenv", "--require-venv", dest="require_venv", action="store_true", default=False, help=( "Allow pip to only run in a virtual environment; " "exit with an error otherwise." ),)
override_externally_managed: Callable[..., Option] = partial( Option, "--break-system-packages", dest="override_externally_managed", action="store_true", help="Allow pip to modify an EXTERNALLY-MANAGED Python installation",)
python: Callable[..., Option] = partial( Option, "--python", dest="python", help="Run pip with the specified Python interpreter.",)
verbose: Callable[..., Option] = partial( Option, "-v", "--verbose", dest="verbose", action="count", default=0, help="Give more output. Option is additive, and can be used up to 3 times.",)
no_color: Callable[..., Option] = partial( Option, "--no-color", dest="no_color", action="store_true", default=False, help="Suppress colored output.",)
version: Callable[..., Option] = partial( Option, "-V", "--version", dest="version", action="store_true", help="Show version and exit.",)
quiet: Callable[..., Option] = partial( Option, "-q", "--quiet", dest="quiet", action="count", default=0, help=( "Give less output. Option is additive, and can be used up to 3" " times (corresponding to WARNING, ERROR, and CRITICAL logging" " levels)." ),)
progress_bar: Callable[..., Option] = partial( Option, "--progress-bar", dest="progress_bar", type="choice", choices=["on", "off"], default="on", help="Specify whether the progress bar should be used [on, off] (default: on)",)
log: Callable[..., Option] = partial( PipOption, "--log", "--log-file", "--local-log", dest="log", metavar="path", type="path", help="Path to a verbose appending log.",)
no_input: Callable[..., Option] = partial( Option, # Don't ask for input "--no-input", dest="no_input", action="store_true", default=False, help="Disable prompting for input.",)
keyring_provider: Callable[..., Option] = partial( Option, "--keyring-provider", dest="keyring_provider", choices=["auto", "disabled", "import", "subprocess"], default="auto", help=( "Enable the credential lookup via the keyring library if user input is allowed." " Specify which mechanism to use [disabled, import, subprocess]." " (default: disabled)" ),)
proxy: Callable[..., Option] = partial( Option, "--proxy", dest="proxy", type="str", default="", help="Specify a proxy in the form scheme://[user:passwd@]proxy.server:port.",)
retries: Callable[..., Option] = partial( Option, "--retries", dest="retries", type="int", default=5, help="Maximum number of retries each connection should attempt " "(default %default times).",)
timeout: Callable[..., Option] = partial( Option, "--timeout", "--default-timeout", metavar="sec", dest="timeout", type="float", default=15, help="Set the socket timeout (default %default seconds).",)
def exists_action() -> Option: return Option( # Option when path already exist "--exists-action", dest="exists_action", type="choice", choices=["s", "i", "w", "b", "a"], default=[], action="append", metavar="action", help="Default action when a path already exists: " "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.", )
cert: Callable[..., Option] = partial( PipOption, "--cert", dest="cert", type="path", metavar="path", help=( "Path to PEM-encoded CA certificate bundle. " "If provided, overrides the default. " "See 'SSL Certificate Verification' in pip documentation " "for more information." ),)
client_cert: Callable[..., Option] = partial( PipOption, "--client-cert", dest="client_cert", type="path", default=None, metavar="path", help="Path to SSL client certificate, a single file containing the " "private key and the certificate in PEM format.",)
index_url: Callable[..., Option] = partial( Option, "-i", "--index-url", "--pypi-url", dest="index_url", metavar="URL", default=PyPI.simple_url, help="Base URL of the Python Package Index (default %default). " "This should point to a repository compliant with PEP 503 " "(the simple repository API) or a local directory laid out " "in the same format.",)
def extra_index_url() -> Option: return Option( "--extra-index-url", dest="extra_index_urls", metavar="URL", action="append", default=[], help="Extra URLs of package indexes to use in addition to " "--index-url. Should follow the same rules as " "--index-url.", )
no_index: Callable[..., Option] = partial( Option, "--no-index", dest="no_index", action="store_true", default=False, help="Ignore package index (only looking at --find-links URLs instead).",)
def find_links() -> Option: return Option( "-f", "--find-links", dest="find_links", action="append", default=[], metavar="url", help="If a URL or path to an html file, then parse for links to " "archives such as sdist (.tar.gz) or wheel (.whl) files. " "If a local path or file:// URL that's a directory, " "then look for archives in the directory listing. " "Links to VCS project URLs are not supported.", )
def trusted_host() -> Option: return Option( "--trusted-host", dest="trusted_hosts", action="append", metavar="HOSTNAME", default=[], help="Mark this host or host:port pair as trusted, even though it " "does not have valid or any HTTPS.", )
def constraints() -> Option: return Option( "-c", "--constraint", dest="constraints", action="append", default=[], metavar="file", help="Constrain versions using the given constraints file. " "This option can be used multiple times.", )
def requirements() -> Option: return Option( "-r", "--requirement", dest="requirements", action="append", default=[], metavar="file", help="Install from the given requirements file. " "This option can be used multiple times.", )
def editable() -> Option: return Option( "-e", "--editable", dest="editables", action="append", default=[], metavar="path/url", help=( "Install a project in editable mode (i.e. setuptools " '"develop mode") from a local project path or a VCS url.' ), )
def _handle_src(option: Option, opt_str: str, value: str, parser: OptionParser) -> None: value = os.path.abspath(value) setattr(parser.values, option.dest, value)
src: Callable[..., Option] = partial( PipOption, "--src", "--source", "--source-dir", "--source-directory", dest="src_dir", type="path", metavar="dir", default=get_src_prefix(), action="callback", callback=_handle_src, help="Directory to check out editable projects into. " 'The default in a virtualenv is "<venv path>/src". ' 'The default for global installs is "<current dir>/src".',)
def _get_format_control(values: Values, option: Option) -> Any: """Get a format_control object.""" return getattr(values, option.dest)
def _handle_no_binary( option: Option, opt_str: str, value: str, parser: OptionParser) -> None: existing = _get_format_control(parser.values, option) FormatControl.handle_mutual_excludes( value, existing.no_binary, existing.only_binary, )
def _handle_only_binary( option: Option, opt_str: str, value: str, parser: OptionParser) -> None: existing = _get_format_control(parser.values, option) FormatControl.handle_mutual_excludes( value, existing.only_binary, existing.no_binary, )
def no_binary() -> Option: format_control = FormatControl(set(), set()) return Option( "--no-binary", dest="format_control", action="callback", callback=_handle_no_binary, type="str", default=format_control, help="Do not use binary packages. Can be supplied multiple times, and " 'each time adds to the existing value. Accepts either ":all:" to ' 'disable all binary packages, ":none:" to empty the set (notice ' "the colons), or one or more package names with commas between " "them (no colons). Note that some packages are tricky to compile " "and may fail to install when this option is used on them.", )
def only_binary() -> Option: format_control = FormatControl(set(), set()) return Option( "--only-binary", dest="format_control", action="callback", callback=_handle_only_binary, type="str", default=format_control, help="Do not use source packages. Can be supplied multiple times, and " 'each time adds to the existing value. Accepts either ":all:" to ' 'disable all source packages, ":none:" to empty the set, or one ' "or more package names with commas between them. Packages " "without binary distributions will fail to install when this " "option is used on them.", )
platforms: Callable[..., Option] = partial( Option, "--platform", dest="platforms", metavar="platform", action="append", default=None, help=( "Only use wheels compatible with <platform>. Defaults to the " "platform of the running system. Use this option multiple times to " "specify multiple platforms supported by the target interpreter." ),)
# This was made a separate function for unit-testing purposes.def _convert_python_version(value: str) -> Tuple[Tuple[int, ...], Optional[str]]: """ Convert a version string like "3", "37", or "3.7.3" into a tuple of ints.
:return: A 2-tuple (version_info, error_msg), where `error_msg` is non-None if and only if there was a parsing error. """ if not value: # The empty string is the same as not providing a value. return (None, None)
parts = value.split(".") if len(parts) > 3: return ((), "at most three version parts are allowed")
if len(parts) == 1: # Then we are in the case of "3" or "37". value = parts[0] if len(value) > 1: parts = [value[0], value[1:]]
try: version_info = tuple(int(part) for part in parts) except ValueError: return ((), "each version part must be an integer")
return (version_info, None)
def _handle_python_version( option: Option, opt_str: str, value: str, parser: OptionParser) -> None: """ Handle a provided --python-version value. """ version_info, error_msg = _convert_python_version(value) if error_msg is not None: msg = "invalid --python-version value: {!r}: {}".format( value, error_msg, ) raise_option_error(parser, option=option, msg=msg)
parser.values.python_version = version_info
python_version: Callable[..., Option] = partial( Option, "--python-version", dest="python_version", metavar="python_version", action="callback", callback=_handle_python_version, type="str", default=None, help=dedent( """\ The Python interpreter version to use for wheel and "Requires-Python" compatibility checks. Defaults to a version derived from the running interpreter. The version can be specified using up to three dot-separated integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor version can also be given as a string without dots (e.g. "37" for 3.7.0). """ ),)
implementation: Callable[..., Option] = partial( Option, "--implementation", dest="implementation", metavar="implementation", default=None, help=( "Only use wheels compatible with Python " "implementation <implementation>, e.g. 'pp', 'jy', 'cp', " " or 'ip'. If not specified, then the current " "interpreter implementation is used. Use 'py' to force " "implementation-agnostic wheels." ),)
abis: Callable[..., Option] = partial( Option, "--abi", dest="abis", metavar="abi", action="append", default=None, help=( "Only use wheels compatible with Python abi <abi>, e.g. 'pypy_41'. " "If not specified, then the current interpreter abi tag is used. " "Use this option multiple times to specify multiple abis supported " "by the target interpreter. Generally you will need to specify " "--implementation, --platform, and --python-version when using this " "option." ),)
def add_target_python_options(cmd_opts: OptionGroup) -> None: cmd_opts.add_option(platforms()) cmd_opts.add_option(python_version()) cmd_opts.add_option(implementation()) cmd_opts.add_option(abis())
def make_target_python(options: Values) -> TargetPython: target_python = TargetPython( platforms=options.platforms, py_version_info=options.python_version, abis=options.abis, implementation=options.implementation, )
return target_python
def prefer_binary() -> Option: return Option( "--prefer-binary", dest="prefer_binary", action="store_true", default=False, help="Prefer older binary packages over newer source packages.", )
cache_dir: Callable[..., Option] = partial( PipOption, "--cache-dir", dest="cache_dir", default=USER_CACHE_DIR, metavar="dir", type="path", help="Store the cache data in <dir>.",)
def _handle_no_cache_dir( option: Option, opt: str, value: str, parser: OptionParser) -> None: """ Process a value provided for the --no-cache-dir option.
This is an optparse.Option callback for the --no-cache-dir option. """ # The value argument will be None if --no-cache-dir is passed via the # command-line, since the option doesn't accept arguments. However, # the value can be non-None if the option is triggered e.g. by an # environment variable, like PIP_NO_CACHE_DIR=true. if value is not None: # Then parse the string value to get argument error-checking. try: strtobool(value) except ValueError as exc: raise_option_error(parser, option=option, msg=str(exc))
# Originally, setting PIP_NO_CACHE_DIR to a value that strtobool() # converted to 0 (like "false" or "no") caused cache_dir to be disabled # rather than enabled (logic would say the latter). Thus, we disable # the cache directory not just on values that parse to True, but (for # backwards compatibility reasons) also on values that parse to False. # In other words, always set it to False if the option is provided in # some (valid) form. parser.values.cache_dir = False
no_cache: Callable[..., Option] = partial( Option, "--no-cache-dir", dest="cache_dir", action="callback", callback=_handle_no_cache_dir, help="Disable the cache.",)
no_deps: Callable[..., Option] = partial( Option, "--no-deps", "--no-dependencies", dest="ignore_dependencies", action="store_true", default=False, help="Don't install package dependencies.",)
ignore_requires_python: Callable[..., Option] = partial( Option, "--ignore-requires-python", dest="ignore_requires_python", action="store_true", help="Ignore the Requires-Python information.",)
no_build_isolation: Callable[..., Option] = partial( Option, "--no-build-isolation", dest="build_isolation", action="store_false", default=True, help="Disable isolation when building a modern source distribution. " "Build dependencies specified by PEP 518 must be already installed " "if this option is used.",)
check_build_deps: Callable[..., Option] = partial( Option, "--check-build-dependencies", dest="check_build_deps", action="store_true", default=False, help="Check the build dependencies when PEP517 is used.",)
def _handle_no_use_pep517( option: Option, opt: str, value: str, parser: OptionParser) -> None: """ Process a value provided for the --no-use-pep517 option.
This is an optparse.Option callback for the no_use_pep517 option. """ # Since --no-use-pep517 doesn't accept arguments, the value argument # will be None if --no-use-pep517 is passed via the command-line. # However, the value can be non-None if the option is triggered e.g. # by an environment variable, for example "PIP_NO_USE_PEP517=true". if value is not None: msg = """A value was passed for --no-use-pep517, probably using either the PIP_NO_USE_PEP517 environment variable or the "no-use-pep517" config file option. Use an appropriate value of the PIP_USE_PEP517 environment variable or the "use-pep517" config file option instead. """ raise_option_error(parser, option=option, msg=msg)
# If user doesn't wish to use pep517, we check if setuptools and wheel are installed # and raise error if it is not. packages = ("setuptools", "wheel") if not all(importlib.util.find_spec(package) for package in packages): msg = ( f"It is not possible to use --no-use-pep517 " f"without {' and '.join(packages)} installed." ) raise_option_error(parser, option=option, msg=msg)
# Otherwise, --no-use-pep517 was passed via the command-line. parser.values.use_pep517 = False
use_pep517: Any = partial( Option, "--use-pep517", dest="use_pep517", action="store_true", default=None, help="Use PEP 517 for building source distributions " "(use --no-use-pep517 to force legacy behaviour).",)
no_use_pep517: Any = partial( Option, "--no-use-pep517", dest="use_pep517", action="callback", callback=_handle_no_use_pep517, default=None, help=SUPPRESS_HELP,)
def _handle_config_settings( option: Option, opt_str: str, value: str, parser: OptionParser) -> None: key, sep, val = value.partition("=") if sep != "=": parser.error(f"Arguments to {opt_str} must be of the form KEY=VAL") # noqa dest = getattr(parser.values, option.dest) if dest is None: dest = {} setattr(parser.values, option.dest, dest) if key in dest: if isinstance(dest[key], list): dest[key].append(val) else: dest[key] = [dest[key], val] else: dest[key] = val
config_settings: Callable[..., Option] = partial( Option, "-C", "--config-settings", dest="config_settings", type=str, action="callback", callback=_handle_config_settings, metavar="settings", help="Configuration settings to be passed to the PEP 517 build backend. " "Settings take the form KEY=VALUE. Use multiple --config-settings options " "to pass multiple keys to the backend.",)
build_options: Callable[..., Option] = partial( Option, "--build-option", dest="build_options", metavar="options", action="append", help="Extra arguments to be supplied to 'setup.py bdist_wheel'.",)
global_options: Callable[..., Option] = partial( Option, "--global-option", dest="global_options", action="append", metavar="options", help="Extra global options to be supplied to the setup.py " "call before the install or bdist_wheel command.",)
no_clean: Callable[..., Option] = partial( Option, "--no-clean", action="store_true", default=False, help="Don't clean up build directories.",)
pre: Callable[..., Option] = partial( Option, "--pre", action="store_true", default=False, help="Include pre-release and development versions. By default, " "pip only finds stable versions.",)
disable_pip_version_check: Callable[..., Option] = partial( Option, "--disable-pip-version-check", dest="disable_pip_version_check", action="store_true", default=False, help="Don't periodically check PyPI to determine whether a new version " "of pip is available for download. Implied with --no-index.",)
root_user_action: Callable[..., Option] = partial( Option, "--root-user-action", dest="root_user_action", default="warn", choices=["warn", "ignore"], help="Action if pip is run as a root user. By default, a warning message is shown.",)
def _handle_merge_hash( option: Option, opt_str: str, value: str, parser: OptionParser) -> None: """Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.""" if not parser.values.hashes: parser.values.hashes = {} try: algo, digest = value.split(":", 1) except ValueError: parser.error( "Arguments to {} must be a hash name " # noqa "followed by a value, like --hash=sha256:" "abcde...".format(opt_str) ) if algo not in STRONG_HASHES: parser.error( "Allowed hash algorithms for {} are {}.".format( # noqa opt_str, ", ".join(STRONG_HASHES) ) ) parser.values.hashes.setdefault(algo, []).append(digest)
hash: Callable[..., Option] = partial( Option, "--hash", # Hash values eventually end up in InstallRequirement.hashes due to # __dict__ copying in process_line(). dest="hashes", action="callback", callback=_handle_merge_hash, type="string", help="Verify that the package's archive matches this " "hash before installing. Example: --hash=sha256:abcdef...",)
require_hashes: Callable[..., Option] = partial( Option, "--require-hashes", dest="require_hashes", action="store_true", default=False, help="Require a hash to check each requirement against, for " "repeatable installs. This option is implied when any package in a " "requirements file has a --hash option.",)
list_path: Callable[..., Option] = partial( PipOption, "--path", dest="path", type="path", action="append", help="Restrict to the specified installation path for listing " "packages (can be used multiple times).",)
def check_list_path_option(options: Values) -> None: if options.path and (options.user or options.local): raise CommandError("Cannot combine '--path' with '--user' or '--local'")
list_exclude: Callable[..., Option] = partial( PipOption, "--exclude", dest="excludes", action="append", metavar="package", type="package_name", help="Exclude specified package from the output",)
no_python_version_warning: Callable[..., Option] = partial( Option, "--no-python-version-warning", dest="no_python_version_warning", action="store_true", default=False, help="Silence deprecation warnings for upcoming unsupported Pythons.",)
# Features that are now always on. A warning is printed if they are used.ALWAYS_ENABLED_FEATURES = [ "no-binary-enable-wheel-cache", # always on since 23.1]
use_new_feature: Callable[..., Option] = partial( Option, "--use-feature", dest="features_enabled", metavar="feature", action="append", default=[], choices=[ "fast-deps", "truststore", ] + ALWAYS_ENABLED_FEATURES, help="Enable new functionality, that may be backward incompatible.",)
use_deprecated_feature: Callable[..., Option] = partial( Option, "--use-deprecated", dest="deprecated_features_enabled", metavar="feature", action="append", default=[], choices=[ "legacy-resolver", ], help=("Enable deprecated functionality, that will be removed in the future."),)
########### groups ###########
general_group: Dict[str, Any] = { "name": "General Options", "options": [ help_, debug_mode, isolated_mode, require_virtualenv, python, verbose, version, quiet, log, no_input, keyring_provider, proxy, retries, timeout, exists_action, trusted_host, cert, client_cert, cache_dir, no_cache, disable_pip_version_check, no_color, no_python_version_warning, use_new_feature, use_deprecated_feature, ],}
index_group: Dict[str, Any] = { "name": "Package Index Options", "options": [ index_url, extra_index_url, no_index, find_links, ],}123456789101112131415161718192021222324252627from contextlib import ExitStack, contextmanagerfrom typing import ContextManager, Generator, TypeVar
_T = TypeVar("_T", covariant=True)
class CommandContextMixIn: def __init__(self) -> None: super().__init__() self._in_main_context = False self._main_context = ExitStack()
@contextmanager def main_context(self) -> Generator[None, None, None]: assert not self._in_main_context
self._in_main_context = True try: with self._main_context: yield finally: self._in_main_context = False
def enter_context(self, context_provider: ContextManager[_T]) -> _T: assert self._in_main_context
return self._main_context.enter_context(context_provider)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""Primary application entrypoint."""import localeimport loggingimport osimport sysimport warningsfrom typing import List, Optional
from pip._internal.cli.autocompletion import autocompletefrom pip._internal.cli.main_parser import parse_commandfrom pip._internal.commands import create_commandfrom pip._internal.exceptions import PipErrorfrom pip._internal.utils import deprecation
logger = logging.getLogger(__name__)
# Do not import and use main() directly! Using it directly is actively# discouraged by pip's maintainers. The name, location and behavior of# this function is subject to change, so calling it directly is not# portable across different pip versions.
# In addition, running pip in-process is unsupported and unsafe. This is# elaborated in detail at# https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program.# That document also provides suggestions that should work for nearly# all users that are considering importing and using main() directly.
# However, we know that certain users will still want to invoke pip# in-process. If you understand and accept the implications of using pip# in an unsupported manner, the best approach is to use runpy to avoid# depending on the exact location of this entry point.
# The following example shows how to use runpy to invoke pip in that# case:## sys.argv = ["pip", your, args, here]# runpy.run_module("pip", run_name="__main__")## Note that this will exit the process after running, unlike a direct# call to main. As it is not safe to do any processing after calling# main, this should not be an issue in practice.
def main(args: Optional[List[str]] = None) -> int: if args is None: args = sys.argv[1:]
# Suppress the pkg_resources deprecation warning # Note - we use a module of .*pkg_resources to cover # the normal case (pip._vendor.pkg_resources) and the # devendored case (a bare pkg_resources) warnings.filterwarnings( action="ignore", category=DeprecationWarning, module=".*pkg_resources" )
# Configure our deprecation warnings to be sent through loggers deprecation.install_warning_logger()
autocomplete()
try: cmd_name, cmd_args = parse_command(args) except PipError as exc: sys.stderr.write(f"ERROR: {exc}") sys.stderr.write(os.linesep) sys.exit(1)
# Needed for locale.getpreferredencoding(False) to work # in pip._internal.utils.encoding.auto_decode try: locale.setlocale(locale.LC_ALL, "") except locale.Error as e: # setlocale can apparently crash if locale are uninitialized logger.debug("Ignoring error %s when setting locale", e) command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
return command.main(cmd_args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134"""A single place for constructing and exposing the main parser"""
import osimport subprocessimport sysfrom typing import List, Optional, Tuple
from pip._internal.build_env import get_runnable_pipfrom pip._internal.cli import cmdoptionsfrom pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatterfrom pip._internal.commands import commands_dict, get_similar_commandsfrom pip._internal.exceptions import CommandErrorfrom pip._internal.utils.misc import get_pip_version, get_prog
__all__ = ["create_main_parser", "parse_command"]
def create_main_parser() -> ConfigOptionParser: """Creates and returns the main parser for pip's CLI"""
parser = ConfigOptionParser( usage="\n%prog <command> [options]", add_help_option=False, formatter=UpdatingDefaultsHelpFormatter(), name="global", prog=get_prog(), ) parser.disable_interspersed_args()
parser.version = get_pip_version()
# add the general options gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser) parser.add_option_group(gen_opts)
# so the help formatter knows parser.main = True # type: ignore
# create command listing for description description = [""] + [ f"{name:27} {command_info.summary}" for name, command_info in commands_dict.items() ] parser.description = "\n".join(description)
return parser
def identify_python_interpreter(python: str) -> Optional[str]: # If the named file exists, use it. # If it's a directory, assume it's a virtual environment and # look for the environment's Python executable. if os.path.exists(python): if os.path.isdir(python): # bin/python for Unix, Scripts/python.exe for Windows # Try both in case of odd cases like cygwin. for exe in ("bin/python", "Scripts/python.exe"): py = os.path.join(python, exe) if os.path.exists(py): return py else: return python
# Could not find the interpreter specified return None
def parse_command(args: List[str]) -> Tuple[str, List[str]]: parser = create_main_parser()
# Note: parser calls disable_interspersed_args(), so the result of this # call is to split the initial args into the general options before the # subcommand and everything else. # For example: # args: ['--timeout=5', 'install', '--user', 'INITools'] # general_options: ['--timeout==5'] # args_else: ['install', '--user', 'INITools'] general_options, args_else = parser.parse_args(args)
# --python if general_options.python and "_PIP_RUNNING_IN_SUBPROCESS" not in os.environ: # Re-invoke pip using the specified Python interpreter interpreter = identify_python_interpreter(general_options.python) if interpreter is None: raise CommandError( f"Could not locate Python interpreter {general_options.python}" )
pip_cmd = [ interpreter, get_runnable_pip(), ] pip_cmd.extend(args)
# Set a flag so the child doesn't re-invoke itself, causing # an infinite loop. os.environ["_PIP_RUNNING_IN_SUBPROCESS"] = "1" returncode = 0 try: proc = subprocess.run(pip_cmd) returncode = proc.returncode except (subprocess.SubprocessError, OSError) as exc: raise CommandError(f"Failed to run pip under {interpreter}: {exc}") sys.exit(returncode)
# --version if general_options.version: sys.stdout.write(parser.version) sys.stdout.write(os.linesep) sys.exit()
# pip || pip help -> print_help() if not args_else or (args_else[0] == "help" and len(args_else) == 1): parser.print_help() sys.exit()
# the subcommand name cmd_name = args_else[0]
if cmd_name not in commands_dict: guess = get_similar_commands(cmd_name)
msg = [f'unknown command "{cmd_name}"'] if guess: msg.append(f'maybe you meant "{guess}"')
raise CommandError(" - ".join(msg))
# all the args without the subcommand cmd_args = args[:] cmd_args.remove(cmd_name)
return cmd_name, cmd_args123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294"""Base option parser setup"""
import loggingimport optparseimport shutilimport sysimport textwrapfrom contextlib import suppressfrom typing import Any, Dict, Generator, List, Tuple
from pip._internal.cli.status_codes import UNKNOWN_ERRORfrom pip._internal.configuration import Configuration, ConfigurationErrorfrom pip._internal.utils.misc import redact_auth_from_url, strtobool
logger = logging.getLogger(__name__)
class PrettyHelpFormatter(optparse.IndentedHelpFormatter): """A prettier/less verbose help formatter for optparse."""
def __init__(self, *args: Any, **kwargs: Any) -> None: # help position must be aligned with __init__.parseopts.description kwargs["max_help_position"] = 30 kwargs["indent_increment"] = 1 kwargs["width"] = shutil.get_terminal_size()[0] - 2 super().__init__(*args, **kwargs)
def format_option_strings(self, option: optparse.Option) -> str: return self._format_option_strings(option)
def _format_option_strings( self, option: optparse.Option, mvarfmt: str = " <{}>", optsep: str = ", " ) -> str: """ Return a comma-separated list of option strings and metavars.
:param option: tuple of (short opt, long opt), e.g: ('-f', '--format') :param mvarfmt: metavar format string :param optsep: separator """ opts = []
if option._short_opts: opts.append(option._short_opts[0]) if option._long_opts: opts.append(option._long_opts[0]) if len(opts) > 1: opts.insert(1, optsep)
if option.takes_value(): assert option.dest is not None metavar = option.metavar or option.dest.lower() opts.append(mvarfmt.format(metavar.lower()))
return "".join(opts)
def format_heading(self, heading: str) -> str: if heading == "Options": return "" return heading + ":\n"
def format_usage(self, usage: str) -> str: """ Ensure there is only one newline between usage and the first heading if there is no description. """ msg = "\nUsage: {}\n".format(self.indent_lines(textwrap.dedent(usage), " ")) return msg
def format_description(self, description: str) -> str: # leave full control over description to us if description: if hasattr(self.parser, "main"): label = "Commands" else: label = "Description" # some doc strings have initial newlines, some don't description = description.lstrip("\n") # some doc strings have final newlines and spaces, some don't description = description.rstrip() # dedent, then reindent description = self.indent_lines(textwrap.dedent(description), " ") description = f"{label}:\n{description}\n" return description else: return ""
def format_epilog(self, epilog: str) -> str: # leave full control over epilog to us if epilog: return epilog else: return ""
def indent_lines(self, text: str, indent: str) -> str: new_lines = [indent + line for line in text.split("\n")] return "\n".join(new_lines)
class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter): """Custom help formatter for use in ConfigOptionParser.
This is updates the defaults before expanding them, allowing them to show up correctly in the help listing.
Also redact auth from url type options """
def expand_default(self, option: optparse.Option) -> str: default_values = None if self.parser is not None: assert isinstance(self.parser, ConfigOptionParser) self.parser._update_defaults(self.parser.defaults) assert option.dest is not None default_values = self.parser.defaults.get(option.dest) help_text = super().expand_default(option)
if default_values and option.metavar == "URL": if isinstance(default_values, str): default_values = [default_values]
# If its not a list, we should abort and just return the help text if not isinstance(default_values, list): default_values = []
for val in default_values: help_text = help_text.replace(val, redact_auth_from_url(val))
return help_text
class CustomOptionParser(optparse.OptionParser): def insert_option_group( self, idx: int, *args: Any, **kwargs: Any ) -> optparse.OptionGroup: """Insert an OptionGroup at a given position.""" group = self.add_option_group(*args, **kwargs)
self.option_groups.pop() self.option_groups.insert(idx, group)
return group
@property def option_list_all(self) -> List[optparse.Option]: """Get a list of all options, including those in option groups.""" res = self.option_list[:] for i in self.option_groups: res.extend(i.option_list)
return res
class ConfigOptionParser(CustomOptionParser): """Custom option parser which updates its defaults by checking the configuration files and environmental variables"""
def __init__( self, *args: Any, name: str, isolated: bool = False, **kwargs: Any, ) -> None: self.name = name self.config = Configuration(isolated)
assert self.name super().__init__(*args, **kwargs)
def check_default(self, option: optparse.Option, key: str, val: Any) -> Any: try: return option.check_value(key, val) except optparse.OptionValueError as exc: print(f"An error occurred during configuration: {exc}") sys.exit(3)
def _get_ordered_configuration_items( self, ) -> Generator[Tuple[str, Any], None, None]: # Configuration gives keys in an unordered manner. Order them. override_order = ["global", self.name, ":env:"]
# Pool the options into different groups section_items: Dict[str, List[Tuple[str, Any]]] = { name: [] for name in override_order } for section_key, val in self.config.items(): # ignore empty values if not val: logger.debug( "Ignoring configuration key '%s' as it's value is empty.", section_key, ) continue
section, key = section_key.split(".", 1) if section in override_order: section_items[section].append((key, val))
# Yield each group in their override order for section in override_order: for key, val in section_items[section]: yield key, val
def _update_defaults(self, defaults: Dict[str, Any]) -> Dict[str, Any]: """Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists)."""
# Accumulate complex default state. self.values = optparse.Values(self.defaults) late_eval = set() # Then set the options with those values for key, val in self._get_ordered_configuration_items(): # '--' because configuration supports only long names option = self.get_option("--" + key)
# Ignore options not present in this parser. E.g. non-globals put # in [global] by users that want them to apply to all applicable # commands. if option is None: continue
assert option.dest is not None
if option.action in ("store_true", "store_false"): try: val = strtobool(val) except ValueError: self.error( "{} is not a valid value for {} option, " # noqa "please specify a boolean value like yes/no, " "true/false or 1/0 instead.".format(val, key) ) elif option.action == "count": with suppress(ValueError): val = strtobool(val) with suppress(ValueError): val = int(val) if not isinstance(val, int) or val < 0: self.error( "{} is not a valid value for {} option, " # noqa "please instead specify either a non-negative integer " "or a boolean value like yes/no or false/true " "which is equivalent to 1/0.".format(val, key) ) elif option.action == "append": val = val.split() val = [self.check_default(option, key, v) for v in val] elif option.action == "callback": assert option.callback is not None late_eval.add(option.dest) opt_str = option.get_opt_string() val = option.convert_value(opt_str, val) # From take_action args = option.callback_args or () kwargs = option.callback_kwargs or {} option.callback(option, opt_str, val, self, *args, **kwargs) else: val = self.check_default(option, key, val)
defaults[option.dest] = val
for key in late_eval: defaults[key] = getattr(self.values, key) self.values = None return defaults
def get_default_values(self) -> optparse.Values: """Overriding to make updating the defaults after instantiation of the option parser possible, _update_defaults() does the dirty work.""" if not self.process_default_values: # Old, pre-Optik 1.5 behaviour. return optparse.Values(self.defaults)
# Load the configuration, or error out in case of an error try: self.config.load() except ConfigurationError as err: self.exit(UNKNOWN_ERROR, str(err))
defaults = self._update_defaults(self.defaults.copy()) # ours for option in self._get_all_options(): assert option.dest is not None default = defaults.get(option.dest) if isinstance(default, str): opt_str = option.get_opt_string() defaults[option.dest] = option.check_value(opt_str, default) return optparse.Values(defaults)
def error(self, msg: str) -> None: self.print_usage(sys.stderr) self.exit(UNKNOWN_ERROR, f"{msg}\n")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import functoolsfrom typing import Callable, Generator, Iterable, Iterator, Optional, Tuple
from pip._vendor.rich.progress import ( BarColumn, DownloadColumn, FileSizeColumn, Progress, ProgressColumn, SpinnerColumn, TextColumn, TimeElapsedColumn, TimeRemainingColumn, TransferSpeedColumn,)
from pip._internal.utils.logging import get_indentation
DownloadProgressRenderer = Callable[[Iterable[bytes]], Iterator[bytes]]
def _rich_progress_bar( iterable: Iterable[bytes], *, bar_type: str, size: int,) -> Generator[bytes, None, None]: assert bar_type == "on", "This should only be used in the default mode."
if not size: total = float("inf") columns: Tuple[ProgressColumn, ...] = ( TextColumn("[progress.description]{task.description}"), SpinnerColumn("line", speed=1.5), FileSizeColumn(), TransferSpeedColumn(), TimeElapsedColumn(), ) else: total = size columns = ( TextColumn("[progress.description]{task.description}"), BarColumn(), DownloadColumn(), TransferSpeedColumn(), TextColumn("eta"), TimeRemainingColumn(), )
progress = Progress(*columns, refresh_per_second=30) task_id = progress.add_task(" " * (get_indentation() + 2), total=total) with progress: for chunk in iterable: yield chunk progress.update(task_id, advance=len(chunk))
def get_download_progress_renderer( *, bar_type: str, size: Optional[int] = None) -> DownloadProgressRenderer: """Get an object that can be used to render the download progress.
Returns a callable, that takes an iterable to "wrap". """ if bar_type == "on": return functools.partial(_rich_progress_bar, bar_type=bar_type, size=size) else: return iter # no-op, when passed an iterator123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508"""Contains the Command base classes that depend on PipSession.
The classes in this module are in a separate module so the commands notneeding download / PackageFinder capability don't unnecessarily import thePackageFinder machinery and all its vendored dependencies, etc."""
import loggingimport osimport sysfrom functools import partialfrom optparse import Valuesfrom typing import TYPE_CHECKING, Any, List, Optional, Tuple
from pip._internal.cache import WheelCachefrom pip._internal.cli import cmdoptionsfrom pip._internal.cli.base_command import Commandfrom pip._internal.cli.command_context import CommandContextMixInfrom pip._internal.exceptions import CommandError, PreviousBuildDirErrorfrom pip._internal.index.collector import LinkCollectorfrom pip._internal.index.package_finder import PackageFinderfrom pip._internal.models.selection_prefs import SelectionPreferencesfrom pip._internal.models.target_python import TargetPythonfrom pip._internal.network.session import PipSessionfrom pip._internal.operations.build.build_tracker import BuildTrackerfrom pip._internal.operations.prepare import RequirementPreparerfrom pip._internal.req.constructors import ( install_req_from_editable, install_req_from_line, install_req_from_parsed_requirement, install_req_from_req_string,)from pip._internal.req.req_file import parse_requirementsfrom pip._internal.req.req_install import InstallRequirementfrom pip._internal.resolution.base import BaseResolverfrom pip._internal.self_outdated_check import pip_self_version_checkfrom pip._internal.utils.temp_dir import ( TempDirectory, TempDirectoryTypeRegistry, tempdir_kinds,)from pip._internal.utils.virtualenv import running_under_virtualenv
if TYPE_CHECKING: from ssl import SSLContext
logger = logging.getLogger(__name__)
def _create_truststore_ssl_context() -> Optional["SSLContext"]: if sys.version_info < (3, 10): raise CommandError("The truststore feature is only available for Python 3.10+")
try: import ssl except ImportError: logger.warning("Disabling truststore since ssl support is missing") return None
try: import truststore except ImportError: raise CommandError( "To use the truststore feature, 'truststore' must be installed into " "pip's current environment." )
return truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
class SessionCommandMixin(CommandContextMixIn):
""" A class mixin for command classes needing _build_session(). """
def __init__(self) -> None: super().__init__() self._session: Optional[PipSession] = None
@classmethod def _get_index_urls(cls, options: Values) -> Optional[List[str]]: """Return a list of index urls from user-provided options.""" index_urls = [] if not getattr(options, "no_index", False): url = getattr(options, "index_url", None) if url: index_urls.append(url) urls = getattr(options, "extra_index_urls", None) if urls: index_urls.extend(urls) # Return None rather than an empty list return index_urls or None
def get_default_session(self, options: Values) -> PipSession: """Get a default-managed session.""" if self._session is None: self._session = self.enter_context(self._build_session(options)) # there's no type annotation on requests.Session, so it's # automatically ContextManager[Any] and self._session becomes Any, # then https://github.com/python/mypy/issues/7696 kicks in assert self._session is not None return self._session
def _build_session( self, options: Values, retries: Optional[int] = None, timeout: Optional[int] = None, fallback_to_certifi: bool = False, ) -> PipSession: cache_dir = options.cache_dir assert not cache_dir or os.path.isabs(cache_dir)
if "truststore" in options.features_enabled: try: ssl_context = _create_truststore_ssl_context() except Exception: if not fallback_to_certifi: raise ssl_context = None else: ssl_context = None
session = PipSession( cache=os.path.join(cache_dir, "http") if cache_dir else None, retries=retries if retries is not None else options.retries, trusted_hosts=options.trusted_hosts, index_urls=self._get_index_urls(options), ssl_context=ssl_context, )
# Handle custom ca-bundles from the user if options.cert: session.verify = options.cert
# Handle SSL client certificate if options.client_cert: session.cert = options.client_cert
# Handle timeouts if options.timeout or timeout: session.timeout = timeout if timeout is not None else options.timeout
# Handle configured proxies if options.proxy: session.proxies = { "http": options.proxy, "https": options.proxy, }
# Determine if we can prompt the user for authentication or not session.auth.prompting = not options.no_input session.auth.keyring_provider = options.keyring_provider
return session
class IndexGroupCommand(Command, SessionCommandMixin):
""" Abstract base class for commands with the index_group options.
This also corresponds to the commands that permit the pip version check. """
def handle_pip_version_check(self, options: Values) -> None: """ Do the pip version check if not disabled.
This overrides the default behavior of not doing the check. """ # Make sure the index_group options are present. assert hasattr(options, "no_index")
if options.disable_pip_version_check or options.no_index: return
# Otherwise, check if we're using the latest version of pip available. session = self._build_session( options, retries=0, timeout=min(5, options.timeout), # This is set to ensure the function does not fail when truststore is # specified in use-feature but cannot be loaded. This usually raises a # CommandError and shows a nice user-facing error, but this function is not # called in that try-except block. fallback_to_certifi=True, ) with session: pip_self_version_check(session, options)
KEEPABLE_TEMPDIR_TYPES = [ tempdir_kinds.BUILD_ENV, tempdir_kinds.EPHEM_WHEEL_CACHE, tempdir_kinds.REQ_BUILD,]
def warn_if_run_as_root() -> None: """Output a warning for sudo users on Unix.
In a virtual environment, sudo pip still writes to virtualenv. On Windows, users may run pip as Administrator without issues. This warning only applies to Unix root users outside of virtualenv. """ if running_under_virtualenv(): return if not hasattr(os, "getuid"): return # On Windows, there are no "system managed" Python packages. Installing as # Administrator via pip is the correct way of updating system environments. # # We choose sys.platform over utils.compat.WINDOWS here to enable Mypy platform # checks: https://mypy.readthedocs.io/en/stable/common_issues.html if sys.platform == "win32" or sys.platform == "cygwin": return
if os.getuid() != 0: return
logger.warning( "Running pip as the 'root' user can result in broken permissions and " "conflicting behaviour with the system package manager. " "It is recommended to use a virtual environment instead: " "https://pip.pypa.io/warnings/venv" )
def with_cleanup(func: Any) -> Any: """Decorator for common logic related to managing temporary directories. """
def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None: for t in KEEPABLE_TEMPDIR_TYPES: registry.set_delete(t, False)
def wrapper( self: RequirementCommand, options: Values, args: List[Any] ) -> Optional[int]: assert self.tempdir_registry is not None if options.no_clean: configure_tempdir_registry(self.tempdir_registry)
try: return func(self, options, args) except PreviousBuildDirError: # This kind of conflict can occur when the user passes an explicit # build directory with a pre-existing folder. In that case we do # not want to accidentally remove it. configure_tempdir_registry(self.tempdir_registry) raise
return wrapper
class RequirementCommand(IndexGroupCommand): def __init__(self, *args: Any, **kw: Any) -> None: super().__init__(*args, **kw)
self.cmd_opts.add_option(cmdoptions.no_clean())
@staticmethod def determine_resolver_variant(options: Values) -> str: """Determines which resolver should be used, based on the given options.""" if "legacy-resolver" in options.deprecated_features_enabled: return "legacy"
return "2020-resolver"
@classmethod def make_requirement_preparer( cls, temp_build_dir: TempDirectory, options: Values, build_tracker: BuildTracker, session: PipSession, finder: PackageFinder, use_user_site: bool, download_dir: Optional[str] = None, verbosity: int = 0, ) -> RequirementPreparer: """ Create a RequirementPreparer instance for the given parameters. """ temp_build_dir_path = temp_build_dir.path assert temp_build_dir_path is not None legacy_resolver = False
resolver_variant = cls.determine_resolver_variant(options) if resolver_variant == "2020-resolver": lazy_wheel = "fast-deps" in options.features_enabled if lazy_wheel: logger.warning( "pip is using lazily downloaded wheels using HTTP " "range requests to obtain dependency information. " "This experimental feature is enabled through " "--use-feature=fast-deps and it is not ready for " "production." ) else: legacy_resolver = True lazy_wheel = False if "fast-deps" in options.features_enabled: logger.warning( "fast-deps has no effect when used with the legacy resolver." )
return RequirementPreparer( build_dir=temp_build_dir_path, src_dir=options.src_dir, download_dir=download_dir, build_isolation=options.build_isolation, check_build_deps=options.check_build_deps, build_tracker=build_tracker, session=session, progress_bar=options.progress_bar, finder=finder, require_hashes=options.require_hashes, use_user_site=use_user_site, lazy_wheel=lazy_wheel, verbosity=verbosity, legacy_resolver=legacy_resolver, )
@classmethod def make_resolver( cls, preparer: RequirementPreparer, finder: PackageFinder, options: Values, wheel_cache: Optional[WheelCache] = None, use_user_site: bool = False, ignore_installed: bool = True, ignore_requires_python: bool = False, force_reinstall: bool = False, upgrade_strategy: str = "to-satisfy-only", use_pep517: Optional[bool] = None, py_version_info: Optional[Tuple[int, ...]] = None, ) -> BaseResolver: """ Create a Resolver instance for the given parameters. """ make_install_req = partial( install_req_from_req_string, isolated=options.isolated_mode, use_pep517=use_pep517, ) resolver_variant = cls.determine_resolver_variant(options) # The long import name and duplicated invocation is needed to convince # Mypy into correctly typechecking. Otherwise it would complain the # "Resolver" class being redefined. if resolver_variant == "2020-resolver": import pip._internal.resolution.resolvelib.resolver
return pip._internal.resolution.resolvelib.resolver.Resolver( preparer=preparer, finder=finder, wheel_cache=wheel_cache, make_install_req=make_install_req, use_user_site=use_user_site, ignore_dependencies=options.ignore_dependencies, ignore_installed=ignore_installed, ignore_requires_python=ignore_requires_python, force_reinstall=force_reinstall, upgrade_strategy=upgrade_strategy, py_version_info=py_version_info, ) import pip._internal.resolution.legacy.resolver
return pip._internal.resolution.legacy.resolver.Resolver( preparer=preparer, finder=finder, wheel_cache=wheel_cache, make_install_req=make_install_req, use_user_site=use_user_site, ignore_dependencies=options.ignore_dependencies, ignore_installed=ignore_installed, ignore_requires_python=ignore_requires_python, force_reinstall=force_reinstall, upgrade_strategy=upgrade_strategy, py_version_info=py_version_info, )
def get_requirements( self, args: List[str], options: Values, finder: PackageFinder, session: PipSession, ) -> List[InstallRequirement]: """ Parse command-line arguments into the corresponding requirements. """ requirements: List[InstallRequirement] = [] for filename in options.constraints: for parsed_req in parse_requirements( filename, constraint=True, finder=finder, options=options, session=session, ): req_to_add = install_req_from_parsed_requirement( parsed_req, isolated=options.isolated_mode, user_supplied=False, ) requirements.append(req_to_add)
for req in args: req_to_add = install_req_from_line( req, comes_from=None, isolated=options.isolated_mode, use_pep517=options.use_pep517, user_supplied=True, config_settings=getattr(options, "config_settings", None), ) requirements.append(req_to_add)
for req in options.editables: req_to_add = install_req_from_editable( req, user_supplied=True, isolated=options.isolated_mode, use_pep517=options.use_pep517, config_settings=getattr(options, "config_settings", None), ) requirements.append(req_to_add)
# NOTE: options.require_hashes may be set if --require-hashes is True for filename in options.requirements: for parsed_req in parse_requirements( filename, finder=finder, options=options, session=session ): req_to_add = install_req_from_parsed_requirement( parsed_req, isolated=options.isolated_mode, use_pep517=options.use_pep517, user_supplied=True, config_settings=parsed_req.options.get("config_settings") if parsed_req.options else None, ) requirements.append(req_to_add)
# If any requirement has hash options, enable hash checking. if any(req.has_hash_options for req in requirements): options.require_hashes = True
if not (args or options.editables or options.requirements): opts = {"name": self.name} if options.find_links: raise CommandError( "You must give at least one requirement to {name} " '(maybe you meant "pip {name} {links}"?)'.format( **dict(opts, links=" ".join(options.find_links)) ) ) else: raise CommandError( "You must give at least one requirement to {name} " '(see "pip help {name}")'.format(**opts) )
return requirements
@staticmethod def trace_basic_info(finder: PackageFinder) -> None: """ Trace basic information about the provided objects. """ # Display where finder is looking for packages search_scope = finder.search_scope locations = search_scope.get_formatted_locations() if locations: logger.info(locations)
def _build_package_finder( self, options: Values, session: PipSession, target_python: Optional[TargetPython] = None, ignore_requires_python: Optional[bool] = None, ) -> PackageFinder: """ Create a package finder appropriate to this requirement command.
:param ignore_requires_python: Whether to ignore incompatible "Requires-Python" values in links. Defaults to False. """ link_collector = LinkCollector.create(session, options=options) selection_prefs = SelectionPreferences( allow_yanked=True, format_control=options.format_control, allow_all_prereleases=options.pre, prefer_binary=options.prefer_binary, ignore_requires_python=ignore_requires_python, )
return PackageFinder.create( link_collector=link_collector, selection_prefs=selection_prefs, target_python=target_python, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159import contextlibimport itertoolsimport loggingimport sysimport timefrom typing import IO, Generator, Optional
from pip._internal.utils.compat import WINDOWSfrom pip._internal.utils.logging import get_indentation
logger = logging.getLogger(__name__)
class SpinnerInterface: def spin(self) -> None: raise NotImplementedError()
def finish(self, final_status: str) -> None: raise NotImplementedError()
class InteractiveSpinner(SpinnerInterface): def __init__( self, message: str, file: Optional[IO[str]] = None, spin_chars: str = "-\\|/", # Empirically, 8 updates/second looks nice min_update_interval_seconds: float = 0.125, ): self._message = message if file is None: file = sys.stdout self._file = file self._rate_limiter = RateLimiter(min_update_interval_seconds) self._finished = False
self._spin_cycle = itertools.cycle(spin_chars)
self._file.write(" " * get_indentation() + self._message + " ... ") self._width = 0
def _write(self, status: str) -> None: assert not self._finished # Erase what we wrote before by backspacing to the beginning, writing # spaces to overwrite the old text, and then backspacing again backup = "\b" * self._width self._file.write(backup + " " * self._width + backup) # Now we have a blank slate to add our status self._file.write(status) self._width = len(status) self._file.flush() self._rate_limiter.reset()
def spin(self) -> None: if self._finished: return if not self._rate_limiter.ready(): return self._write(next(self._spin_cycle))
def finish(self, final_status: str) -> None: if self._finished: return self._write(final_status) self._file.write("\n") self._file.flush() self._finished = True
# Used for dumb terminals, non-interactive installs (no tty), etc.# We still print updates occasionally (once every 60 seconds by default) to# act as a keep-alive for systems like Travis-CI that take lack-of-output as# an indication that a task has frozen.class NonInteractiveSpinner(SpinnerInterface): def __init__(self, message: str, min_update_interval_seconds: float = 60.0) -> None: self._message = message self._finished = False self._rate_limiter = RateLimiter(min_update_interval_seconds) self._update("started")
def _update(self, status: str) -> None: assert not self._finished self._rate_limiter.reset() logger.info("%s: %s", self._message, status)
def spin(self) -> None: if self._finished: return if not self._rate_limiter.ready(): return self._update("still running...")
def finish(self, final_status: str) -> None: if self._finished: return self._update(f"finished with status '{final_status}'") self._finished = True
class RateLimiter: def __init__(self, min_update_interval_seconds: float) -> None: self._min_update_interval_seconds = min_update_interval_seconds self._last_update: float = 0
def ready(self) -> bool: now = time.time() delta = now - self._last_update return delta >= self._min_update_interval_seconds
def reset(self) -> None: self._last_update = time.time()
@contextlib.contextmanagerdef open_spinner(message: str) -> Generator[SpinnerInterface, None, None]: # Interactive spinner goes directly to sys.stdout rather than being routed # through the logging system, but it acts like it has level INFO, # i.e. it's only displayed if we're at level INFO or better. # Non-interactive spinner goes through the logging system, so it is always # in sync with logging configuration. if sys.stdout.isatty() and logger.getEffectiveLevel() <= logging.INFO: spinner: SpinnerInterface = InteractiveSpinner(message) else: spinner = NonInteractiveSpinner(message) try: with hidden_cursor(sys.stdout): yield spinner except KeyboardInterrupt: spinner.finish("canceled") raise except Exception: spinner.finish("error") raise else: spinner.finish("done")
HIDE_CURSOR = "\x1b[?25l"SHOW_CURSOR = "\x1b[?25h"
@contextlib.contextmanagerdef hidden_cursor(file: IO[str]) -> Generator[None, None, None]: # The Windows terminal does not support the hide/show cursor ANSI codes, # even via colorama. So don't even try. if WINDOWS: yield # We don't want to clutter the output with control characters if we're # writing to a file, or if the user is running with --quiet. # See https://github.com/pypa/pip/issues/3418 elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO: yield else: file.write(HIDE_CURSOR) try: yield finally: file.write(SHOW_CURSOR)123456SUCCESS = 0ERROR = 1UNKNOWN_ERROR = 2VIRTUALENV_NOT_FOUND = 3PREVIOUS_BUILD_DIR_ERROR = 4NO_MATCHES_FOUND = 23123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132"""Package containing all pip commands"""
import importlibfrom collections import namedtuplefrom typing import Any, Dict, Optional
from pip._internal.cli.base_command import Command
CommandInfo = namedtuple("CommandInfo", "module_path, class_name, summary")
# This dictionary does a bunch of heavy lifting for help output:# - Enables avoiding additional (costly) imports for presenting `--help`.# - The ordering matters for help display.## Even though the module path starts with the same "pip._internal.commands"# prefix, the full path makes testing easier (specifically when modifying# `commands_dict` in test setup / teardown).commands_dict: Dict[str, CommandInfo] = { "install": CommandInfo( "pip._internal.commands.install", "InstallCommand", "Install packages.", ), "download": CommandInfo( "pip._internal.commands.download", "DownloadCommand", "Download packages.", ), "uninstall": CommandInfo( "pip._internal.commands.uninstall", "UninstallCommand", "Uninstall packages.", ), "freeze": CommandInfo( "pip._internal.commands.freeze", "FreezeCommand", "Output installed packages in requirements format.", ), "inspect": CommandInfo( "pip._internal.commands.inspect", "InspectCommand", "Inspect the python environment.", ), "list": CommandInfo( "pip._internal.commands.list", "ListCommand", "List installed packages.", ), "show": CommandInfo( "pip._internal.commands.show", "ShowCommand", "Show information about installed packages.", ), "check": CommandInfo( "pip._internal.commands.check", "CheckCommand", "Verify installed packages have compatible dependencies.", ), "config": CommandInfo( "pip._internal.commands.configuration", "ConfigurationCommand", "Manage local and global configuration.", ), "search": CommandInfo( "pip._internal.commands.search", "SearchCommand", "Search PyPI for packages.", ), "cache": CommandInfo( "pip._internal.commands.cache", "CacheCommand", "Inspect and manage pip's wheel cache.", ), "index": CommandInfo( "pip._internal.commands.index", "IndexCommand", "Inspect information available from package indexes.", ), "wheel": CommandInfo( "pip._internal.commands.wheel", "WheelCommand", "Build wheels from your requirements.", ), "hash": CommandInfo( "pip._internal.commands.hash", "HashCommand", "Compute hashes of package archives.", ), "completion": CommandInfo( "pip._internal.commands.completion", "CompletionCommand", "A helper command used for command completion.", ), "debug": CommandInfo( "pip._internal.commands.debug", "DebugCommand", "Show information useful for debugging.", ), "help": CommandInfo( "pip._internal.commands.help", "HelpCommand", "Show help for commands.", ),}
def create_command(name: str, **kwargs: Any) -> Command: """ Create an instance of the Command class with the given name. """ module_path, class_name, summary = commands_dict[name] module = importlib.import_module(module_path) command_class = getattr(module, class_name) command = command_class(name=name, summary=summary, **kwargs)
return command
def get_similar_commands(name: str) -> Optional[str]: """Command name auto-correct.""" from difflib import get_close_matches
name = name.lower()
close_commands = get_close_matches(name, commands_dict.keys())
if close_commands: return close_commands[0] else: return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222import osimport textwrapfrom optparse import Valuesfrom typing import Any, List
import pip._internal.utils.filesystem as filesystemfrom pip._internal.cli.base_command import Commandfrom pip._internal.cli.status_codes import ERROR, SUCCESSfrom pip._internal.exceptions import CommandError, PipErrorfrom pip._internal.utils.logging import getLogger
logger = getLogger(__name__)
class CacheCommand(Command): """ Inspect and manage pip's wheel cache.
Subcommands:
- dir: Show the cache directory. - info: Show information about the cache. - list: List filenames of packages stored in the cache. - remove: Remove one or more package from the cache. - purge: Remove all items from the cache.
``<pattern>`` can be a glob expression or a package name. """
ignore_require_venv = True usage = """ %prog dir %prog info %prog list [<pattern>] [--format=[human, abspath]] %prog remove <pattern> %prog purge """
def add_options(self) -> None: self.cmd_opts.add_option( "--format", action="store", dest="list_format", default="human", choices=("human", "abspath"), help="Select the output format among: human (default) or abspath", )
self.parser.insert_option_group(0, self.cmd_opts)
def run(self, options: Values, args: List[str]) -> int: handlers = { "dir": self.get_cache_dir, "info": self.get_cache_info, "list": self.list_cache_items, "remove": self.remove_cache_items, "purge": self.purge_cache, }
if not options.cache_dir: logger.error("pip cache commands can not function since cache is disabled.") return ERROR
# Determine action if not args or args[0] not in handlers: logger.error( "Need an action (%s) to perform.", ", ".join(sorted(handlers)), ) return ERROR
action = args[0]
# Error handling happens here, not in the action-handlers. try: handlers[action](options, args[1:]) except PipError as e: logger.error(e.args[0]) return ERROR
return SUCCESS
def get_cache_dir(self, options: Values, args: List[Any]) -> None: if args: raise CommandError("Too many arguments")
logger.info(options.cache_dir)
def get_cache_info(self, options: Values, args: List[Any]) -> None: if args: raise CommandError("Too many arguments")
num_http_files = len(self._find_http_files(options)) num_packages = len(self._find_wheels(options, "*"))
http_cache_location = self._cache_dir(options, "http") wheels_cache_location = self._cache_dir(options, "wheels") http_cache_size = filesystem.format_directory_size(http_cache_location) wheels_cache_size = filesystem.format_directory_size(wheels_cache_location)
message = ( textwrap.dedent( """ Package index page cache location: {http_cache_location} Package index page cache size: {http_cache_size} Number of HTTP files: {num_http_files} Locally built wheels location: {wheels_cache_location} Locally built wheels size: {wheels_cache_size} Number of locally built wheels: {package_count} """ ) .format( http_cache_location=http_cache_location, http_cache_size=http_cache_size, num_http_files=num_http_files, wheels_cache_location=wheels_cache_location, package_count=num_packages, wheels_cache_size=wheels_cache_size, ) .strip() )
logger.info(message)
def list_cache_items(self, options: Values, args: List[Any]) -> None: if len(args) > 1: raise CommandError("Too many arguments")
if args: pattern = args[0] else: pattern = "*"
files = self._find_wheels(options, pattern) if options.list_format == "human": self.format_for_human(files) else: self.format_for_abspath(files)
def format_for_human(self, files: List[str]) -> None: if not files: logger.info("No locally built wheels cached.") return
results = [] for filename in files: wheel = os.path.basename(filename) size = filesystem.format_file_size(filename) results.append(f" - {wheel} ({size})") logger.info("Cache contents:\n") logger.info("\n".join(sorted(results)))
def format_for_abspath(self, files: List[str]) -> None: if not files: return
results = [] for filename in files: results.append(filename)
logger.info("\n".join(sorted(results)))
def remove_cache_items(self, options: Values, args: List[Any]) -> None: if len(args) > 1: raise CommandError("Too many arguments")
if not args: raise CommandError("Please provide a pattern")
files = self._find_wheels(options, args[0])
no_matching_msg = "No matching packages" if args[0] == "*": # Only fetch http files if no specific pattern given files += self._find_http_files(options) else: # Add the pattern to the log message no_matching_msg += ' for pattern "{}"'.format(args[0])
if not files: logger.warning(no_matching_msg)
for filename in files: os.unlink(filename) logger.verbose("Removed %s", filename) logger.info("Files removed: %s", len(files))
def purge_cache(self, options: Values, args: List[Any]) -> None: if args: raise CommandError("Too many arguments")
return self.remove_cache_items(options, ["*"])
def _cache_dir(self, options: Values, subdir: str) -> str: return os.path.join(options.cache_dir, subdir)
def _find_http_files(self, options: Values) -> List[str]: http_dir = self._cache_dir(options, "http") return filesystem.find_files(http_dir, "*")
def _find_wheels(self, options: Values, pattern: str) -> List[str]: wheel_dir = self._cache_dir(options, "wheels")
# The wheel filename format, as specified in PEP 427, is: # {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl # # Additionally, non-alphanumeric values in the distribution are # normalized to underscores (_), meaning hyphens can never occur # before `-{version}`. # # Given that information: # - If the pattern we're given contains a hyphen (-), the user is # providing at least the version. Thus, we can just append `*.whl` # to match the rest of it. # - If the pattern we're given doesn't contain a hyphen (-), the # user is only providing the name. Thus, we append `-*.whl` to # match the hyphen before the version, followed by anything else. # # PEP 427: https://www.python.org/dev/peps/pep-0427/ pattern = pattern + ("*.whl" if "-" in pattern else "-*.whl")
return filesystem.find_files(wheel_dir, pattern)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354import loggingfrom optparse import Valuesfrom typing import List
from pip._internal.cli.base_command import Commandfrom pip._internal.cli.status_codes import ERROR, SUCCESSfrom pip._internal.operations.check import ( check_package_set, create_package_set_from_installed, warn_legacy_versions_and_specifiers,)from pip._internal.utils.misc import write_output
logger = logging.getLogger(__name__)
class CheckCommand(Command): """Verify installed packages have compatible dependencies."""
usage = """ %prog [options]"""
def run(self, options: Values, args: List[str]) -> int: package_set, parsing_probs = create_package_set_from_installed() warn_legacy_versions_and_specifiers(package_set) missing, conflicting = check_package_set(package_set)
for project_name in missing: version = package_set[project_name].version for dependency in missing[project_name]: write_output( "%s %s requires %s, which is not installed.", project_name, version, dependency[0], )
for project_name in conflicting: version = package_set[project_name].version for dep_name, dep_version, req in conflicting[project_name]: write_output( "%s %s has requirement %s, but you have %s %s.", project_name, version, req, dep_name, dep_version, )
if missing or conflicting or parsing_probs: return ERROR else: write_output("No broken requirements found.") return SUCCESS123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121import sysimport textwrapfrom optparse import Valuesfrom typing import List
from pip._internal.cli.base_command import Commandfrom pip._internal.cli.status_codes import SUCCESSfrom pip._internal.utils.misc import get_prog
BASE_COMPLETION = """# pip {shell} completion start{script}# pip {shell} completion end"""
COMPLETION_SCRIPTS = { "bash": """ _pip_completion() {{ COMPREPLY=( $( COMP_WORDS="${{COMP_WORDS[*]}}" \\ COMP_CWORD=$COMP_CWORD \\ PIP_AUTO_COMPLETE=1 $1 2>/dev/null ) ) }} complete -o default -F _pip_completion {prog} """, "zsh": """ #compdef -P pip[0-9.]# compadd $( COMP_WORDS="$words[*]" \\ COMP_CWORD=$((CURRENT-1)) \\ PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null ) """, "fish": """ function __fish_complete_pip set -lx COMP_WORDS (commandline -o) "" set -lx COMP_CWORD ( \\ math (contains -i -- (commandline -t) $COMP_WORDS)-1 \\ ) set -lx PIP_AUTO_COMPLETE 1 string split \\ -- (eval $COMP_WORDS[1]) end complete -fa "(__fish_complete_pip)" -c {prog} """, "powershell": """ if ((Test-Path Function:\\TabExpansion) -and -not ` (Test-Path Function:\\_pip_completeBackup)) {{ Rename-Item Function:\\TabExpansion _pip_completeBackup }} function TabExpansion($line, $lastWord) {{ $lastBlock = [regex]::Split($line, '[|;]')[-1].TrimStart() if ($lastBlock.StartsWith("{prog} ")) {{ $Env:COMP_WORDS=$lastBlock $Env:COMP_CWORD=$lastBlock.Split().Length - 1 $Env:PIP_AUTO_COMPLETE=1 (& {prog}).Split() Remove-Item Env:COMP_WORDS Remove-Item Env:COMP_CWORD Remove-Item Env:PIP_AUTO_COMPLETE }} elseif (Test-Path Function:\\_pip_completeBackup) {{ # Fall back on existing tab expansion _pip_completeBackup $line $lastWord }} }} """,}
class CompletionCommand(Command): """A helper command to be used for command completion."""
ignore_require_venv = True
def add_options(self) -> None: self.cmd_opts.add_option( "--bash", "-b", action="store_const", const="bash", dest="shell", help="Emit completion code for bash", ) self.cmd_opts.add_option( "--zsh", "-z", action="store_const", const="zsh", dest="shell", help="Emit completion code for zsh", ) self.cmd_opts.add_option( "--fish", "-f", action="store_const", const="fish", dest="shell", help="Emit completion code for fish", ) self.cmd_opts.add_option( "--powershell", "-p", action="store_const", const="powershell", dest="shell", help="Emit completion code for powershell", )
self.parser.insert_option_group(0, self.cmd_opts)
def run(self, options: Values, args: List[str]) -> int: """Prints the completion code of the given shell""" shells = COMPLETION_SCRIPTS.keys() shell_options = ["--" + shell for shell in sorted(shells)] if options.shell in shells: script = textwrap.dedent( COMPLETION_SCRIPTS.get(options.shell, "").format(prog=get_prog()) ) print(BASE_COMPLETION.format(script=script, shell=options.shell)) return SUCCESS else: sys.stderr.write( "ERROR: You must pass {}\n".format(" or ".join(shell_options)) ) return SUCCESS123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282import loggingimport osimport subprocessfrom optparse import Valuesfrom typing import Any, List, Optional
from pip._internal.cli.base_command import Commandfrom pip._internal.cli.status_codes import ERROR, SUCCESSfrom pip._internal.configuration import ( Configuration, Kind, get_configuration_files, kinds,)from pip._internal.exceptions import PipErrorfrom pip._internal.utils.logging import indent_logfrom pip._internal.utils.misc import get_prog, write_output
logger = logging.getLogger(__name__)
class ConfigurationCommand(Command): """ Manage local and global configuration.
Subcommands:
- list: List the active configuration (or from the file specified) - edit: Edit the configuration file in an editor - get: Get the value associated with command.option - set: Set the command.option=value - unset: Unset the value associated with command.option - debug: List the configuration files and values defined under them
Configuration keys should be dot separated command and option name, with the special prefix "global" affecting any command. For example, "pip config set global.index-url https://example.org/" would configure the index url for all commands, but "pip config set download.timeout 10" would configure a 10 second timeout only for "pip download" commands.
If none of --user, --global and --site are passed, a virtual environment configuration file is used if one is active and the file exists. Otherwise, all modifications happen to the user file by default. """
ignore_require_venv = True usage = """ %prog [<file-option>] list %prog [<file-option>] [--editor <editor-path>] edit
%prog [<file-option>] get command.option %prog [<file-option>] set command.option value %prog [<file-option>] unset command.option %prog [<file-option>] debug """
def add_options(self) -> None: self.cmd_opts.add_option( "--editor", dest="editor", action="store", default=None, help=( "Editor to use to edit the file. Uses VISUAL or EDITOR " "environment variables if not provided." ), )
self.cmd_opts.add_option( "--global", dest="global_file", action="store_true", default=False, help="Use the system-wide configuration file only", )
self.cmd_opts.add_option( "--user", dest="user_file", action="store_true", default=False, help="Use the user configuration file only", )
self.cmd_opts.add_option( "--site", dest="site_file", action="store_true", default=False, help="Use the current environment configuration file only", )
self.parser.insert_option_group(0, self.cmd_opts)
def run(self, options: Values, args: List[str]) -> int: handlers = { "list": self.list_values, "edit": self.open_in_editor, "get": self.get_name, "set": self.set_name_value, "unset": self.unset_name, "debug": self.list_config_values, }
# Determine action if not args or args[0] not in handlers: logger.error( "Need an action (%s) to perform.", ", ".join(sorted(handlers)), ) return ERROR
action = args[0]
# Determine which configuration files are to be loaded # Depends on whether the command is modifying. try: load_only = self._determine_file( options, need_value=(action in ["get", "set", "unset", "edit"]) ) except PipError as e: logger.error(e.args[0]) return ERROR
# Load a new configuration self.configuration = Configuration( isolated=options.isolated_mode, load_only=load_only ) self.configuration.load()
# Error handling happens here, not in the action-handlers. try: handlers[action](options, args[1:]) except PipError as e: logger.error(e.args[0]) return ERROR
return SUCCESS
def _determine_file(self, options: Values, need_value: bool) -> Optional[Kind]: file_options = [ key for key, value in ( (kinds.USER, options.user_file), (kinds.GLOBAL, options.global_file), (kinds.SITE, options.site_file), ) if value ]
if not file_options: if not need_value: return None # Default to user, unless there's a site file. elif any( os.path.exists(site_config_file) for site_config_file in get_configuration_files()[kinds.SITE] ): return kinds.SITE else: return kinds.USER elif len(file_options) == 1: return file_options[0]
raise PipError( "Need exactly one file to operate upon " "(--user, --site, --global) to perform." )
def list_values(self, options: Values, args: List[str]) -> None: self._get_n_args(args, "list", n=0)
for key, value in sorted(self.configuration.items()): write_output("%s=%r", key, value)
def get_name(self, options: Values, args: List[str]) -> None: key = self._get_n_args(args, "get [name]", n=1) value = self.configuration.get_value(key)
write_output("%s", value)
def set_name_value(self, options: Values, args: List[str]) -> None: key, value = self._get_n_args(args, "set [name] [value]", n=2) self.configuration.set_value(key, value)
self._save_configuration()
def unset_name(self, options: Values, args: List[str]) -> None: key = self._get_n_args(args, "unset [name]", n=1) self.configuration.unset_value(key)
self._save_configuration()
def list_config_values(self, options: Values, args: List[str]) -> None: """List config key-value pairs across different config files""" self._get_n_args(args, "debug", n=0)
self.print_env_var_values() # Iterate over config files and print if they exist, and the # key-value pairs present in them if they do for variant, files in sorted(self.configuration.iter_config_files()): write_output("%s:", variant) for fname in files: with indent_log(): file_exists = os.path.exists(fname) write_output("%s, exists: %r", fname, file_exists) if file_exists: self.print_config_file_values(variant)
def print_config_file_values(self, variant: Kind) -> None: """Get key-value pairs from the file of a variant""" for name, value in self.configuration.get_values_in_config(variant).items(): with indent_log(): write_output("%s: %s", name, value)
def print_env_var_values(self) -> None: """Get key-values pairs present as environment variables""" write_output("%s:", "env_var") with indent_log(): for key, value in sorted(self.configuration.get_environ_vars()): env_var = f"PIP_{key.upper()}" write_output("%s=%r", env_var, value)
def open_in_editor(self, options: Values, args: List[str]) -> None: editor = self._determine_editor(options)
fname = self.configuration.get_file_to_edit() if fname is None: raise PipError("Could not determine appropriate file.") elif '"' in fname: # This shouldn't happen, unless we see a username like that. # If that happens, we'd appreciate a pull request fixing this. raise PipError( f'Can not open an editor for a file name containing "\n{fname}' )
try: subprocess.check_call(f'{editor} "{fname}"', shell=True) except FileNotFoundError as e: if not e.filename: e.filename = editor raise except subprocess.CalledProcessError as e: raise PipError( "Editor Subprocess exited with exit code {}".format(e.returncode) )
def _get_n_args(self, args: List[str], example: str, n: int) -> Any: """Helper to make sure the command got the right number of arguments""" if len(args) != n: msg = ( "Got unexpected number of arguments, expected {}. " '(example: "{} config {}")' ).format(n, get_prog(), example) raise PipError(msg)
if n == 1: return args[0] else: return args
def _save_configuration(self) -> None: # We successfully ran a modifying command. Need to save the # configuration. try: self.configuration.save() except Exception: logger.exception( "Unable to save configuration. Please report this as a bug." ) raise PipError("Internal Error.")
def _determine_editor(self, options: Values) -> str: if options.editor is not None: return options.editor elif "VISUAL" in os.environ: return os.environ["VISUAL"] elif "EDITOR" in os.environ: return os.environ["EDITOR"] else: raise PipError("Could not determine editor to use.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199import importlib.resourcesimport localeimport loggingimport osimport sysfrom optparse import Valuesfrom types import ModuleTypefrom typing import Any, Dict, List, Optional
import pip._vendorfrom pip._vendor.certifi import wherefrom pip._vendor.packaging.version import parse as parse_version
from pip._internal.cli import cmdoptionsfrom pip._internal.cli.base_command import Commandfrom pip._internal.cli.cmdoptions import make_target_pythonfrom pip._internal.cli.status_codes import SUCCESSfrom pip._internal.configuration import Configurationfrom pip._internal.metadata import get_environmentfrom pip._internal.utils.logging import indent_logfrom pip._internal.utils.misc import get_pip_version
logger = logging.getLogger(__name__)
def show_value(name: str, value: Any) -> None: logger.info("%s: %s", name, value)
def show_sys_implementation() -> None: logger.info("sys.implementation:") implementation_name = sys.implementation.name with indent_log(): show_value("name", implementation_name)
def create_vendor_txt_map() -> Dict[str, str]: with importlib.resources.open_text("pip._vendor", "vendor.txt") as f: # Purge non version specifying lines. # Also, remove any space prefix or suffixes (including comments). lines = [ line.strip().split(" ", 1)[0] for line in f.readlines() if "==" in line ]
# Transform into "module" -> version dict. return dict(line.split("==", 1) for line in lines)
def get_module_from_module_name(module_name: str) -> ModuleType: # Module name can be uppercase in vendor.txt for some reason... module_name = module_name.lower().replace("-", "_") # PATCH: setuptools is actually only pkg_resources. if module_name == "setuptools": module_name = "pkg_resources"
__import__(f"pip._vendor.{module_name}", globals(), locals(), level=0) return getattr(pip._vendor, module_name)
def get_vendor_version_from_module(module_name: str) -> Optional[str]: module = get_module_from_module_name(module_name) version = getattr(module, "__version__", None)
if not version: # Try to find version in debundled module info. assert module.__file__ is not None env = get_environment([os.path.dirname(module.__file__)]) dist = env.get_distribution(module_name) if dist: version = str(dist.version)
return version
def show_actual_vendor_versions(vendor_txt_versions: Dict[str, str]) -> None: """Log the actual version and print extra info if there is a conflict or if the actual version could not be imported. """ for module_name, expected_version in vendor_txt_versions.items(): extra_message = "" actual_version = get_vendor_version_from_module(module_name) if not actual_version: extra_message = ( " (Unable to locate actual module version, using" " vendor.txt specified version)" ) actual_version = expected_version elif parse_version(actual_version) != parse_version(expected_version): extra_message = ( " (CONFLICT: vendor.txt suggests version should" " be {})".format(expected_version) ) logger.info("%s==%s%s", module_name, actual_version, extra_message)
def show_vendor_versions() -> None: logger.info("vendored library versions:")
vendor_txt_versions = create_vendor_txt_map() with indent_log(): show_actual_vendor_versions(vendor_txt_versions)
def show_tags(options: Values) -> None: tag_limit = 10
target_python = make_target_python(options) tags = target_python.get_tags()
# Display the target options that were explicitly provided. formatted_target = target_python.format_given() suffix = "" if formatted_target: suffix = f" (target: {formatted_target})"
msg = "Compatible tags: {}{}".format(len(tags), suffix) logger.info(msg)
if options.verbose < 1 and len(tags) > tag_limit: tags_limited = True tags = tags[:tag_limit] else: tags_limited = False
with indent_log(): for tag in tags: logger.info(str(tag))
if tags_limited: msg = ( "...\n[First {tag_limit} tags shown. Pass --verbose to show all.]" ).format(tag_limit=tag_limit) logger.info(msg)
def ca_bundle_info(config: Configuration) -> str: levels = set() for key, _ in config.items(): levels.add(key.split(".")[0])
if not levels: return "Not specified"
levels_that_override_global = ["install", "wheel", "download"] global_overriding_level = [ level for level in levels if level in levels_that_override_global ] if not global_overriding_level: return "global"
if "global" in levels: levels.remove("global") return ", ".join(levels)
class DebugCommand(Command): """ Display debug information. """
usage = """ %prog <options>""" ignore_require_venv = True
def add_options(self) -> None: cmdoptions.add_target_python_options(self.cmd_opts) self.parser.insert_option_group(0, self.cmd_opts) self.parser.config.load()
def run(self, options: Values, args: List[str]) -> int: logger.warning( "This command is only meant for debugging. " "Do not use this with automation for parsing and getting these " "details, since the output and options of this command may " "change without notice." ) show_value("pip version", get_pip_version()) show_value("sys.version", sys.version) show_value("sys.executable", sys.executable) show_value("sys.getdefaultencoding", sys.getdefaultencoding()) show_value("sys.getfilesystemencoding", sys.getfilesystemencoding()) show_value( "locale.getpreferredencoding", locale.getpreferredencoding(), ) show_value("sys.platform", sys.platform) show_sys_implementation()
show_value("'cert' config value", ca_bundle_info(self.parser.config)) show_value("REQUESTS_CA_BUNDLE", os.environ.get("REQUESTS_CA_BUNDLE")) show_value("CURL_CA_BUNDLE", os.environ.get("CURL_CA_BUNDLE")) show_value("pip._vendor.certifi.where()", where()) show_value("pip._vendor.DEBUNDLED", pip._vendor.DEBUNDLED)
show_vendor_versions()
show_tags(options)
return SUCCESS123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147import loggingimport osfrom optparse import Valuesfrom typing import List
from pip._internal.cli import cmdoptionsfrom pip._internal.cli.cmdoptions import make_target_pythonfrom pip._internal.cli.req_command import RequirementCommand, with_cleanupfrom pip._internal.cli.status_codes import SUCCESSfrom pip._internal.operations.build.build_tracker import get_build_trackerfrom pip._internal.req.req_install import check_legacy_setup_py_optionsfrom pip._internal.utils.misc import ensure_dir, normalize_path, write_outputfrom pip._internal.utils.temp_dir import TempDirectory
logger = logging.getLogger(__name__)
class DownloadCommand(RequirementCommand): """ Download packages from:
- PyPI (and other indexes) using requirement specifiers. - VCS project urls. - Local project directories. - Local or remote source archives.
pip also supports downloading from "requirements files", which provide an easy way to specify a whole environment to be downloaded. """
usage = """ %prog [options] <requirement specifier> [package-index-options] ... %prog [options] -r <requirements file> [package-index-options] ... %prog [options] <vcs project url> ... %prog [options] <local project path> ... %prog [options] <archive url/path> ..."""
def add_options(self) -> None: self.cmd_opts.add_option(cmdoptions.constraints()) self.cmd_opts.add_option(cmdoptions.requirements()) self.cmd_opts.add_option(cmdoptions.no_deps()) self.cmd_opts.add_option(cmdoptions.global_options()) self.cmd_opts.add_option(cmdoptions.no_binary()) self.cmd_opts.add_option(cmdoptions.only_binary()) self.cmd_opts.add_option(cmdoptions.prefer_binary()) self.cmd_opts.add_option(cmdoptions.src()) self.cmd_opts.add_option(cmdoptions.pre()) self.cmd_opts.add_option(cmdoptions.require_hashes()) self.cmd_opts.add_option(cmdoptions.progress_bar()) self.cmd_opts.add_option(cmdoptions.no_build_isolation()) self.cmd_opts.add_option(cmdoptions.use_pep517()) self.cmd_opts.add_option(cmdoptions.no_use_pep517()) self.cmd_opts.add_option(cmdoptions.check_build_deps()) self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
self.cmd_opts.add_option( "-d", "--dest", "--destination-dir", "--destination-directory", dest="download_dir", metavar="dir", default=os.curdir, help="Download packages into <dir>.", )
cmdoptions.add_target_python_options(self.cmd_opts)
index_opts = cmdoptions.make_option_group( cmdoptions.index_group, self.parser, )
self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, self.cmd_opts)
@with_cleanup def run(self, options: Values, args: List[str]) -> int: options.ignore_installed = True # editable doesn't really make sense for `pip download`, but the bowels # of the RequirementSet code require that property. options.editables = []
cmdoptions.check_dist_restriction(options)
options.download_dir = normalize_path(options.download_dir) ensure_dir(options.download_dir)
session = self.get_default_session(options)
target_python = make_target_python(options) finder = self._build_package_finder( options=options, session=session, target_python=target_python, ignore_requires_python=options.ignore_requires_python, )
build_tracker = self.enter_context(get_build_tracker())
directory = TempDirectory( delete=not options.no_clean, kind="download", globally_managed=True, )
reqs = self.get_requirements(args, options, finder, session) check_legacy_setup_py_options(options, reqs)
preparer = self.make_requirement_preparer( temp_build_dir=directory, options=options, build_tracker=build_tracker, session=session, finder=finder, download_dir=options.download_dir, use_user_site=False, verbosity=self.verbosity, )
resolver = self.make_resolver( preparer=preparer, finder=finder, options=options, ignore_requires_python=options.ignore_requires_python, use_pep517=options.use_pep517, py_version_info=options.python_version, )
self.trace_basic_info(finder)
requirement_set = resolver.resolve(reqs, check_supported_wheels=True)
downloaded: List[str] = [] for req in requirement_set.requirements.values(): if req.satisfied_by is None: assert req.name is not None preparer.save_linked_requirement(req) downloaded.append(req.name)
preparer.prepare_linked_requirements_more(requirement_set.requirements.values()) requirement_set.warn_legacy_versions_and_specifiers()
if downloaded: write_output("Successfully downloaded %s", " ".join(downloaded))
return SUCCESS123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108import sysfrom optparse import Valuesfrom typing import AbstractSet, List
from pip._internal.cli import cmdoptionsfrom pip._internal.cli.base_command import Commandfrom pip._internal.cli.status_codes import SUCCESSfrom pip._internal.operations.freeze import freezefrom pip._internal.utils.compat import stdlib_pkgs
def _should_suppress_build_backends() -> bool: return sys.version_info < (3, 12)
def _dev_pkgs() -> AbstractSet[str]: pkgs = {"pip"}
if _should_suppress_build_backends(): pkgs |= {"setuptools", "distribute", "wheel"}
return pkgs
class FreezeCommand(Command): """ Output installed packages in requirements format.
packages are listed in a case-insensitive sorted order. """
usage = """ %prog [options]""" log_streams = ("ext://sys.stderr", "ext://sys.stderr")
def add_options(self) -> None: self.cmd_opts.add_option( "-r", "--requirement", dest="requirements", action="append", default=[], metavar="file", help=( "Use the order in the given requirements file and its " "comments when generating output. This option can be " "used multiple times." ), ) self.cmd_opts.add_option( "-l", "--local", dest="local", action="store_true", default=False, help=( "If in a virtualenv that has global access, do not output " "globally-installed packages." ), ) self.cmd_opts.add_option( "--user", dest="user", action="store_true", default=False, help="Only output packages installed in user-site.", ) self.cmd_opts.add_option(cmdoptions.list_path()) self.cmd_opts.add_option( "--all", dest="freeze_all", action="store_true", help=( "Do not skip these packages in the output:" " {}".format(", ".join(_dev_pkgs())) ), ) self.cmd_opts.add_option( "--exclude-editable", dest="exclude_editable", action="store_true", help="Exclude editable package from output.", ) self.cmd_opts.add_option(cmdoptions.list_exclude())
self.parser.insert_option_group(0, self.cmd_opts)
def run(self, options: Values, args: List[str]) -> int: skip = set(stdlib_pkgs) if not options.freeze_all: skip.update(_dev_pkgs())
if options.excludes: skip.update(options.excludes)
cmdoptions.check_list_path_option(options)
for line in freeze( requirement=options.requirements, local_only=options.local, user_only=options.user, paths=options.path, isolated=options.isolated_mode, skip=skip, exclude_editable=options.exclude_editable, ): sys.stdout.write(line + "\n") return SUCCESS1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import hashlibimport loggingimport sysfrom optparse import Valuesfrom typing import List
from pip._internal.cli.base_command import Commandfrom pip._internal.cli.status_codes import ERROR, SUCCESSfrom pip._internal.utils.hashes import FAVORITE_HASH, STRONG_HASHESfrom pip._internal.utils.misc import read_chunks, write_output
logger = logging.getLogger(__name__)
class HashCommand(Command): """ Compute a hash of a local package archive.
These can be used with --hash in a requirements file to do repeatable installs. """
usage = "%prog [options] <file> ..." ignore_require_venv = True
def add_options(self) -> None: self.cmd_opts.add_option( "-a", "--algorithm", dest="algorithm", choices=STRONG_HASHES, action="store", default=FAVORITE_HASH, help="The hash algorithm to use: one of {}".format( ", ".join(STRONG_HASHES) ), ) self.parser.insert_option_group(0, self.cmd_opts)
def run(self, options: Values, args: List[str]) -> int: if not args: self.parser.print_usage(sys.stderr) return ERROR
algorithm = options.algorithm for path in args: write_output( "%s:\n--hash=%s:%s", path, algorithm, _hash_of_file(path, algorithm) ) return SUCCESS
def _hash_of_file(path: str, algorithm: str) -> str: """Return the hash digest of a file.""" with open(path, "rb") as archive: hash = hashlib.new(algorithm) for chunk in read_chunks(archive): hash.update(chunk) return hash.hexdigest()1234567891011121314151617181920212223242526272829303132333435363738394041from optparse import Valuesfrom typing import List
from pip._internal.cli.base_command import Commandfrom pip._internal.cli.status_codes import SUCCESSfrom pip._internal.exceptions import CommandError
class HelpCommand(Command): """Show help for commands"""
usage = """ %prog <command>""" ignore_require_venv = True
def run(self, options: Values, args: List[str]) -> int: from pip._internal.commands import ( commands_dict, create_command, get_similar_commands, )
try: # 'pip help' with no args is handled by pip.__init__.parseopt() cmd_name = args[0] # the command we need help for except IndexError: return SUCCESS
if cmd_name not in commands_dict: guess = get_similar_commands(cmd_name)
msg = [f'unknown command "{cmd_name}"'] if guess: msg.append(f'maybe you meant "{guess}"')
raise CommandError(" - ".join(msg))
command = create_command(cmd_name) command.parser.print_help()
return SUCCESS123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139import loggingfrom optparse import Valuesfrom typing import Any, Iterable, List, Optional, Union
from pip._vendor.packaging.version import LegacyVersion, Version
from pip._internal.cli import cmdoptionsfrom pip._internal.cli.req_command import IndexGroupCommandfrom pip._internal.cli.status_codes import ERROR, SUCCESSfrom pip._internal.commands.search import print_dist_installation_infofrom pip._internal.exceptions import CommandError, DistributionNotFound, PipErrorfrom pip._internal.index.collector import LinkCollectorfrom pip._internal.index.package_finder import PackageFinderfrom pip._internal.models.selection_prefs import SelectionPreferencesfrom pip._internal.models.target_python import TargetPythonfrom pip._internal.network.session import PipSessionfrom pip._internal.utils.misc import write_output
logger = logging.getLogger(__name__)
class IndexCommand(IndexGroupCommand): """ Inspect information available from package indexes. """
ignore_require_venv = True usage = """ %prog versions <package> """
def add_options(self) -> None: cmdoptions.add_target_python_options(self.cmd_opts)
self.cmd_opts.add_option(cmdoptions.ignore_requires_python()) self.cmd_opts.add_option(cmdoptions.pre()) self.cmd_opts.add_option(cmdoptions.no_binary()) self.cmd_opts.add_option(cmdoptions.only_binary())
index_opts = cmdoptions.make_option_group( cmdoptions.index_group, self.parser, )
self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, self.cmd_opts)
def run(self, options: Values, args: List[str]) -> int: handlers = { "versions": self.get_available_package_versions, }
logger.warning( "pip index is currently an experimental command. " "It may be removed/changed in a future release " "without prior warning." )
# Determine action if not args or args[0] not in handlers: logger.error( "Need an action (%s) to perform.", ", ".join(sorted(handlers)), ) return ERROR
action = args[0]
# Error handling happens here, not in the action-handlers. try: handlers[action](options, args[1:]) except PipError as e: logger.error(e.args[0]) return ERROR
return SUCCESS
def _build_package_finder( self, options: Values, session: PipSession, target_python: Optional[TargetPython] = None, ignore_requires_python: Optional[bool] = None, ) -> PackageFinder: """ Create a package finder appropriate to the index command. """ link_collector = LinkCollector.create(session, options=options)
# Pass allow_yanked=False to ignore yanked versions. selection_prefs = SelectionPreferences( allow_yanked=False, allow_all_prereleases=options.pre, ignore_requires_python=ignore_requires_python, )
return PackageFinder.create( link_collector=link_collector, selection_prefs=selection_prefs, target_python=target_python, )
def get_available_package_versions(self, options: Values, args: List[Any]) -> None: if len(args) != 1: raise CommandError("You need to specify exactly one argument")
target_python = cmdoptions.make_target_python(options) query = args[0]
with self._build_session(options) as session: finder = self._build_package_finder( options=options, session=session, target_python=target_python, ignore_requires_python=options.ignore_requires_python, )
versions: Iterable[Union[LegacyVersion, Version]] = ( candidate.version for candidate in finder.find_all_candidates(query) )
if not options.pre: # Remove prereleases versions = ( version for version in versions if not version.is_prerelease ) versions = set(versions)
if not versions: raise DistributionNotFound( "No matching distribution found for {}".format(query) )
formatted_versions = [str(ver) for ver in sorted(versions, reverse=True)] latest = formatted_versions[0]
write_output("{} ({})".format(query, latest)) write_output("Available versions: {}".format(", ".join(formatted_versions))) print_dist_installation_info(query, latest)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192import loggingfrom optparse import Valuesfrom typing import Any, Dict, List
from pip._vendor.packaging.markers import default_environmentfrom pip._vendor.rich import print_json
from pip import __version__from pip._internal.cli import cmdoptionsfrom pip._internal.cli.req_command import Commandfrom pip._internal.cli.status_codes import SUCCESSfrom pip._internal.metadata import BaseDistribution, get_environmentfrom pip._internal.utils.compat import stdlib_pkgsfrom pip._internal.utils.urls import path_to_url
logger = logging.getLogger(__name__)
class InspectCommand(Command): """ Inspect the content of a Python environment and produce a report in JSON format. """
ignore_require_venv = True usage = """ %prog [options]"""
def add_options(self) -> None: self.cmd_opts.add_option( "--local", action="store_true", default=False, help=( "If in a virtualenv that has global access, do not list " "globally-installed packages." ), ) self.cmd_opts.add_option( "--user", dest="user", action="store_true", default=False, help="Only output packages installed in user-site.", ) self.cmd_opts.add_option(cmdoptions.list_path()) self.parser.insert_option_group(0, self.cmd_opts)
def run(self, options: Values, args: List[str]) -> int: cmdoptions.check_list_path_option(options) dists = get_environment(options.path).iter_installed_distributions( local_only=options.local, user_only=options.user, skip=set(stdlib_pkgs), ) output = { "version": "1", "pip_version": __version__, "installed": [self._dist_to_dict(dist) for dist in dists], "environment": default_environment(), # TODO tags? scheme? } print_json(data=output) return SUCCESS
def _dist_to_dict(self, dist: BaseDistribution) -> Dict[str, Any]: res: Dict[str, Any] = { "metadata": dist.metadata_dict, "metadata_location": dist.info_location, } # direct_url. Note that we don't have download_info (as in the installation # report) since it is not recorded in installed metadata. direct_url = dist.direct_url if direct_url is not None: res["direct_url"] = direct_url.to_dict() else: # Emulate direct_url for legacy editable installs. editable_project_location = dist.editable_project_location if editable_project_location is not None: res["direct_url"] = { "url": path_to_url(editable_project_location), "dir_info": { "editable": True, }, } # installer installer = dist.installer if dist.installer: res["installer"] = installer # requested if dist.installed_with_dist_info: res["requested"] = dist.requested return res123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778import errnoimport jsonimport operatorimport osimport shutilimport sitefrom optparse import SUPPRESS_HELP, Valuesfrom typing import List, Optional
from pip._vendor.rich import print_json
from pip._internal.cache import WheelCachefrom pip._internal.cli import cmdoptionsfrom pip._internal.cli.cmdoptions import make_target_pythonfrom pip._internal.cli.req_command import ( RequirementCommand, warn_if_run_as_root, with_cleanup,)from pip._internal.cli.status_codes import ERROR, SUCCESSfrom pip._internal.exceptions import CommandError, InstallationErrorfrom pip._internal.locations import get_schemefrom pip._internal.metadata import get_environmentfrom pip._internal.models.installation_report import InstallationReportfrom pip._internal.operations.build.build_tracker import get_build_trackerfrom pip._internal.operations.check import ConflictDetails, check_install_conflictsfrom pip._internal.req import install_given_reqsfrom pip._internal.req.req_install import ( InstallRequirement, check_legacy_setup_py_options,)from pip._internal.utils.compat import WINDOWSfrom pip._internal.utils.filesystem import test_writable_dirfrom pip._internal.utils.logging import getLoggerfrom pip._internal.utils.misc import ( check_externally_managed, ensure_dir, get_pip_version, protect_pip_from_modification_on_windows, write_output,)from pip._internal.utils.temp_dir import TempDirectoryfrom pip._internal.utils.virtualenv import ( running_under_virtualenv, virtualenv_no_global,)from pip._internal.wheel_builder import build, should_build_for_install_command
logger = getLogger(__name__)
class InstallCommand(RequirementCommand): """ Install packages from:
- PyPI (and other indexes) using requirement specifiers. - VCS project urls. - Local project directories. - Local or remote source archives.
pip also supports installing from "requirements files", which provide an easy way to specify a whole environment to be installed. """
usage = """ %prog [options] <requirement specifier> [package-index-options] ... %prog [options] -r <requirements file> [package-index-options] ... %prog [options] [-e] <vcs project url> ... %prog [options] [-e] <local project path> ... %prog [options] <archive url/path> ..."""
def add_options(self) -> None: self.cmd_opts.add_option(cmdoptions.requirements()) self.cmd_opts.add_option(cmdoptions.constraints()) self.cmd_opts.add_option(cmdoptions.no_deps()) self.cmd_opts.add_option(cmdoptions.pre())
self.cmd_opts.add_option(cmdoptions.editable()) self.cmd_opts.add_option( "--dry-run", action="store_true", dest="dry_run", default=False, help=( "Don't actually install anything, just print what would be. " "Can be used in combination with --ignore-installed " "to 'resolve' the requirements." ), ) self.cmd_opts.add_option( "-t", "--target", dest="target_dir", metavar="dir", default=None, help=( "Install packages into <dir>. " "By default this will not replace existing files/folders in " "<dir>. Use --upgrade to replace existing packages in <dir> " "with new versions." ), ) cmdoptions.add_target_python_options(self.cmd_opts)
self.cmd_opts.add_option( "--user", dest="use_user_site", action="store_true", help=( "Install to the Python user install directory for your " "platform. Typically ~/.local/, or %APPDATA%\\Python on " "Windows. (See the Python documentation for site.USER_BASE " "for full details.)" ), ) self.cmd_opts.add_option( "--no-user", dest="use_user_site", action="store_false", help=SUPPRESS_HELP, ) self.cmd_opts.add_option( "--root", dest="root_path", metavar="dir", default=None, help="Install everything relative to this alternate root directory.", ) self.cmd_opts.add_option( "--prefix", dest="prefix_path", metavar="dir", default=None, help=( "Installation prefix where lib, bin and other top-level " "folders are placed. Note that the resulting installation may " "contain scripts and other resources which reference the " "Python interpreter of pip, and not that of ``--prefix``. " "See also the ``--python`` option if the intention is to " "install packages into another (possibly pip-free) " "environment." ), )
self.cmd_opts.add_option(cmdoptions.src())
self.cmd_opts.add_option( "-U", "--upgrade", dest="upgrade", action="store_true", help=( "Upgrade all specified packages to the newest available " "version. The handling of dependencies depends on the " "upgrade-strategy used." ), )
self.cmd_opts.add_option( "--upgrade-strategy", dest="upgrade_strategy", default="only-if-needed", choices=["only-if-needed", "eager"], help=( "Determines how dependency upgrading should be handled " "[default: %default]. " '"eager" - dependencies are upgraded regardless of ' "whether the currently installed version satisfies the " "requirements of the upgraded package(s). " '"only-if-needed" - are upgraded only when they do not ' "satisfy the requirements of the upgraded package(s)." ), )
self.cmd_opts.add_option( "--force-reinstall", dest="force_reinstall", action="store_true", help="Reinstall all packages even if they are already up-to-date.", )
self.cmd_opts.add_option( "-I", "--ignore-installed", dest="ignore_installed", action="store_true", help=( "Ignore the installed packages, overwriting them. " "This can break your system if the existing package " "is of a different version or was installed " "with a different package manager!" ), )
self.cmd_opts.add_option(cmdoptions.ignore_requires_python()) self.cmd_opts.add_option(cmdoptions.no_build_isolation()) self.cmd_opts.add_option(cmdoptions.use_pep517()) self.cmd_opts.add_option(cmdoptions.no_use_pep517()) self.cmd_opts.add_option(cmdoptions.check_build_deps()) self.cmd_opts.add_option(cmdoptions.override_externally_managed())
self.cmd_opts.add_option(cmdoptions.config_settings()) self.cmd_opts.add_option(cmdoptions.global_options())
self.cmd_opts.add_option( "--compile", action="store_true", dest="compile", default=True, help="Compile Python source files to bytecode", )
self.cmd_opts.add_option( "--no-compile", action="store_false", dest="compile", help="Do not compile Python source files to bytecode", )
self.cmd_opts.add_option( "--no-warn-script-location", action="store_false", dest="warn_script_location", default=True, help="Do not warn when installing scripts outside PATH", ) self.cmd_opts.add_option( "--no-warn-conflicts", action="store_false", dest="warn_about_conflicts", default=True, help="Do not warn about broken dependencies", ) self.cmd_opts.add_option(cmdoptions.no_binary()) self.cmd_opts.add_option(cmdoptions.only_binary()) self.cmd_opts.add_option(cmdoptions.prefer_binary()) self.cmd_opts.add_option(cmdoptions.require_hashes()) self.cmd_opts.add_option(cmdoptions.progress_bar()) self.cmd_opts.add_option(cmdoptions.root_user_action())
index_opts = cmdoptions.make_option_group( cmdoptions.index_group, self.parser, )
self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, self.cmd_opts)
self.cmd_opts.add_option( "--report", dest="json_report_file", metavar="file", default=None, help=( "Generate a JSON file describing what pip did to install " "the provided requirements. " "Can be used in combination with --dry-run and --ignore-installed " "to 'resolve' the requirements. " "When - is used as file name it writes to stdout. " "When writing to stdout, please combine with the --quiet option " "to avoid mixing pip logging output with JSON output." ), )
@with_cleanup def run(self, options: Values, args: List[str]) -> int: if options.use_user_site and options.target_dir is not None: raise CommandError("Can not combine '--user' and '--target'")
# Check whether the environment we're installing into is externally # managed, as specified in PEP 668. Specifying --root, --target, or # --prefix disables the check, since there's no reliable way to locate # the EXTERNALLY-MANAGED file for those cases. An exception is also # made specifically for "--dry-run --report" for convenience. installing_into_current_environment = ( not (options.dry_run and options.json_report_file) and options.root_path is None and options.target_dir is None and options.prefix_path is None ) if ( installing_into_current_environment and not options.override_externally_managed ): check_externally_managed()
upgrade_strategy = "to-satisfy-only" if options.upgrade: upgrade_strategy = options.upgrade_strategy
cmdoptions.check_dist_restriction(options, check_target=True)
logger.verbose("Using %s", get_pip_version()) options.use_user_site = decide_user_install( options.use_user_site, prefix_path=options.prefix_path, target_dir=options.target_dir, root_path=options.root_path, isolated_mode=options.isolated_mode, )
target_temp_dir: Optional[TempDirectory] = None target_temp_dir_path: Optional[str] = None if options.target_dir: options.ignore_installed = True options.target_dir = os.path.abspath(options.target_dir) if ( # fmt: off os.path.exists(options.target_dir) and not os.path.isdir(options.target_dir) # fmt: on ): raise CommandError( "Target path exists but is not a directory, will not continue." )
# Create a target directory for using with the target option target_temp_dir = TempDirectory(kind="target") target_temp_dir_path = target_temp_dir.path self.enter_context(target_temp_dir)
global_options = options.global_options or []
session = self.get_default_session(options)
target_python = make_target_python(options) finder = self._build_package_finder( options=options, session=session, target_python=target_python, ignore_requires_python=options.ignore_requires_python, ) build_tracker = self.enter_context(get_build_tracker())
directory = TempDirectory( delete=not options.no_clean, kind="install", globally_managed=True, )
try: reqs = self.get_requirements(args, options, finder, session) check_legacy_setup_py_options(options, reqs)
wheel_cache = WheelCache(options.cache_dir)
# Only when installing is it permitted to use PEP 660. # In other circumstances (pip wheel, pip download) we generate # regular (i.e. non editable) metadata and wheels. for req in reqs: req.permit_editable_wheels = True
preparer = self.make_requirement_preparer( temp_build_dir=directory, options=options, build_tracker=build_tracker, session=session, finder=finder, use_user_site=options.use_user_site, verbosity=self.verbosity, ) resolver = self.make_resolver( preparer=preparer, finder=finder, options=options, wheel_cache=wheel_cache, use_user_site=options.use_user_site, ignore_installed=options.ignore_installed, ignore_requires_python=options.ignore_requires_python, force_reinstall=options.force_reinstall, upgrade_strategy=upgrade_strategy, use_pep517=options.use_pep517, )
self.trace_basic_info(finder)
requirement_set = resolver.resolve( reqs, check_supported_wheels=not options.target_dir )
if options.json_report_file: report = InstallationReport(requirement_set.requirements_to_install) if options.json_report_file == "-": print_json(data=report.to_dict()) else: with open(options.json_report_file, "w", encoding="utf-8") as f: json.dump(report.to_dict(), f, indent=2, ensure_ascii=False)
if options.dry_run: # In non dry-run mode, the legacy versions and specifiers check # will be done as part of conflict detection. requirement_set.warn_legacy_versions_and_specifiers() would_install_items = sorted( (r.metadata["name"], r.metadata["version"]) for r in requirement_set.requirements_to_install ) if would_install_items: write_output( "Would install %s", " ".join("-".join(item) for item in would_install_items), ) return SUCCESS
try: pip_req = requirement_set.get_requirement("pip") except KeyError: modifying_pip = False else: # If we're not replacing an already installed pip, # we're not modifying it. modifying_pip = pip_req.satisfied_by is None protect_pip_from_modification_on_windows(modifying_pip=modifying_pip)
reqs_to_build = [ r for r in requirement_set.requirements.values() if should_build_for_install_command(r) ]
_, build_failures = build( reqs_to_build, wheel_cache=wheel_cache, verify=True, build_options=[], global_options=global_options, )
if build_failures: raise InstallationError( "Could not build wheels for {}, which is required to " "install pyproject.toml-based projects".format( ", ".join(r.name for r in build_failures) # type: ignore ) )
to_install = resolver.get_installation_order(requirement_set)
# Check for conflicts in the package set we're installing. conflicts: Optional[ConflictDetails] = None should_warn_about_conflicts = ( not options.ignore_dependencies and options.warn_about_conflicts ) if should_warn_about_conflicts: conflicts = self._determine_conflicts(to_install)
# Don't warn about script install locations if # --target or --prefix has been specified warn_script_location = options.warn_script_location if options.target_dir or options.prefix_path: warn_script_location = False
installed = install_given_reqs( to_install, global_options, root=options.root_path, home=target_temp_dir_path, prefix=options.prefix_path, warn_script_location=warn_script_location, use_user_site=options.use_user_site, pycompile=options.compile, )
lib_locations = get_lib_location_guesses( user=options.use_user_site, home=target_temp_dir_path, root=options.root_path, prefix=options.prefix_path, isolated=options.isolated_mode, ) env = get_environment(lib_locations)
installed.sort(key=operator.attrgetter("name")) items = [] for result in installed: item = result.name try: installed_dist = env.get_distribution(item) if installed_dist is not None: item = f"{item}-{installed_dist.version}" except Exception: pass items.append(item)
if conflicts is not None: self._warn_about_conflicts( conflicts, resolver_variant=self.determine_resolver_variant(options), )
installed_desc = " ".join(items) if installed_desc: write_output( "Successfully installed %s", installed_desc, ) except OSError as error: show_traceback = self.verbosity >= 1
message = create_os_error_message( error, show_traceback, options.use_user_site, ) logger.error(message, exc_info=show_traceback) # noqa
return ERROR
if options.target_dir: assert target_temp_dir self._handle_target_dir( options.target_dir, target_temp_dir, options.upgrade ) if options.root_user_action == "warn": warn_if_run_as_root() return SUCCESS
def _handle_target_dir( self, target_dir: str, target_temp_dir: TempDirectory, upgrade: bool ) -> None: ensure_dir(target_dir)
# Checking both purelib and platlib directories for installed # packages to be moved to target directory lib_dir_list = []
# Checking both purelib and platlib directories for installed # packages to be moved to target directory scheme = get_scheme("", home=target_temp_dir.path) purelib_dir = scheme.purelib platlib_dir = scheme.platlib data_dir = scheme.data
if os.path.exists(purelib_dir): lib_dir_list.append(purelib_dir) if os.path.exists(platlib_dir) and platlib_dir != purelib_dir: lib_dir_list.append(platlib_dir) if os.path.exists(data_dir): lib_dir_list.append(data_dir)
for lib_dir in lib_dir_list: for item in os.listdir(lib_dir): if lib_dir == data_dir: ddir = os.path.join(data_dir, item) if any(s.startswith(ddir) for s in lib_dir_list[:-1]): continue target_item_dir = os.path.join(target_dir, item) if os.path.exists(target_item_dir): if not upgrade: logger.warning( "Target directory %s already exists. Specify " "--upgrade to force replacement.", target_item_dir, ) continue if os.path.islink(target_item_dir): logger.warning( "Target directory %s already exists and is " "a link. pip will not automatically replace " "links, please remove if replacement is " "desired.", target_item_dir, ) continue if os.path.isdir(target_item_dir): shutil.rmtree(target_item_dir) else: os.remove(target_item_dir)
shutil.move(os.path.join(lib_dir, item), target_item_dir)
def _determine_conflicts( self, to_install: List[InstallRequirement] ) -> Optional[ConflictDetails]: try: return check_install_conflicts(to_install) except Exception: logger.exception( "Error while checking for conflicts. Please file an issue on " "pip's issue tracker: https://github.com/pypa/pip/issues/new" ) return None
def _warn_about_conflicts( self, conflict_details: ConflictDetails, resolver_variant: str ) -> None: package_set, (missing, conflicting) = conflict_details if not missing and not conflicting: return
parts: List[str] = [] if resolver_variant == "legacy": parts.append( "pip's legacy dependency resolver does not consider dependency " "conflicts when selecting packages. This behaviour is the " "source of the following dependency conflicts." ) else: assert resolver_variant == "2020-resolver" parts.append( "pip's dependency resolver does not currently take into account " "all the packages that are installed. This behaviour is the " "source of the following dependency conflicts." )
# NOTE: There is some duplication here, with commands/check.py for project_name in missing: version = package_set[project_name][0] for dependency in missing[project_name]: message = ( "{name} {version} requires {requirement}, " "which is not installed." ).format( name=project_name, version=version, requirement=dependency[1], ) parts.append(message)
for project_name in conflicting: version = package_set[project_name][0] for dep_name, dep_version, req in conflicting[project_name]: message = ( "{name} {version} requires {requirement}, but {you} have " "{dep_name} {dep_version} which is incompatible." ).format( name=project_name, version=version, requirement=req, dep_name=dep_name, dep_version=dep_version, you=("you" if resolver_variant == "2020-resolver" else "you'll"), ) parts.append(message)
logger.critical("\n".join(parts))
def get_lib_location_guesses( user: bool = False, home: Optional[str] = None, root: Optional[str] = None, isolated: bool = False, prefix: Optional[str] = None,) -> List[str]: scheme = get_scheme( "", user=user, home=home, root=root, isolated=isolated, prefix=prefix, ) return [scheme.purelib, scheme.platlib]
def site_packages_writable(root: Optional[str], isolated: bool) -> bool: return all( test_writable_dir(d) for d in set(get_lib_location_guesses(root=root, isolated=isolated)) )
def decide_user_install( use_user_site: Optional[bool], prefix_path: Optional[str] = None, target_dir: Optional[str] = None, root_path: Optional[str] = None, isolated_mode: bool = False,) -> bool: """Determine whether to do a user install based on the input options.
If use_user_site is False, no additional checks are done. If use_user_site is True, it is checked for compatibility with other options. If use_user_site is None, the default behaviour depends on the environment, which is provided by the other arguments. """ # In some cases (config from tox), use_user_site can be set to an integer # rather than a bool, which 'use_user_site is False' wouldn't catch. if (use_user_site is not None) and (not use_user_site): logger.debug("Non-user install by explicit request") return False
if use_user_site: if prefix_path: raise CommandError( "Can not combine '--user' and '--prefix' as they imply " "different installation locations" ) if virtualenv_no_global(): raise InstallationError( "Can not perform a '--user' install. User site-packages " "are not visible in this virtualenv." ) logger.debug("User install by explicit request") return True
# If we are here, user installs have not been explicitly requested/avoided assert use_user_site is None
# user install incompatible with --prefix/--target if prefix_path or target_dir: logger.debug("Non-user install due to --prefix or --target option") return False
# If user installs are not enabled, choose a non-user install if not site.ENABLE_USER_SITE: logger.debug("Non-user install because user site-packages disabled") return False
# If we have permission for a non-user install, do that, # otherwise do a user install. if site_packages_writable(root=root_path, isolated=isolated_mode): logger.debug("Non-user install because site-packages writeable") return False
logger.info( "Defaulting to user installation because normal site-packages " "is not writeable" ) return True
def create_os_error_message( error: OSError, show_traceback: bool, using_user_site: bool) -> str: """Format an error message for an OSError
It may occur anytime during the execution of the install command. """ parts = []
# Mention the error if we are not going to show a traceback parts.append("Could not install packages due to an OSError") if not show_traceback: parts.append(": ") parts.append(str(error)) else: parts.append(".")
# Spilt the error indication from a helper message (if any) parts[-1] += "\n"
# Suggest useful actions to the user: # (1) using user site-packages or (2) verifying the permissions if error.errno == errno.EACCES: user_option_part = "Consider using the `--user` option" permissions_part = "Check the permissions"
if not running_under_virtualenv() and not using_user_site: parts.extend( [ user_option_part, " or ", permissions_part.lower(), ] ) else: parts.append(permissions_part) parts.append(".\n")
# Suggest the user to enable Long Paths if path length is # more than 260 if ( WINDOWS and error.errno == errno.ENOENT and error.filename and len(error.filename) > 260 ): parts.append( "HINT: This error might have occurred since " "this system does not have Windows Long Path " "support enabled. You can find information on " "how to enable this at " "https://pip.pypa.io/warnings/enable-long-paths\n" )
return "".join(parts).strip() + "\n"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368import jsonimport loggingfrom optparse import Valuesfrom typing import TYPE_CHECKING, Generator, List, Optional, Sequence, Tuple, cast
from pip._vendor.packaging.utils import canonicalize_name
from pip._internal.cli import cmdoptionsfrom pip._internal.cli.req_command import IndexGroupCommandfrom pip._internal.cli.status_codes import SUCCESSfrom pip._internal.exceptions import CommandErrorfrom pip._internal.index.collector import LinkCollectorfrom pip._internal.index.package_finder import PackageFinderfrom pip._internal.metadata import BaseDistribution, get_environmentfrom pip._internal.models.selection_prefs import SelectionPreferencesfrom pip._internal.network.session import PipSessionfrom pip._internal.utils.compat import stdlib_pkgsfrom pip._internal.utils.misc import tabulate, write_output
if TYPE_CHECKING: from pip._internal.metadata.base import DistributionVersion
class _DistWithLatestInfo(BaseDistribution): """Give the distribution object a couple of extra fields.
These will be populated during ``get_outdated()``. This is dirty but makes the rest of the code much cleaner. """
latest_version: DistributionVersion latest_filetype: str
_ProcessedDists = Sequence[_DistWithLatestInfo]
logger = logging.getLogger(__name__)
class ListCommand(IndexGroupCommand): """ List installed packages, including editables.
Packages are listed in a case-insensitive sorted order. """
ignore_require_venv = True usage = """ %prog [options]"""
def add_options(self) -> None: self.cmd_opts.add_option( "-o", "--outdated", action="store_true", default=False, help="List outdated packages", ) self.cmd_opts.add_option( "-u", "--uptodate", action="store_true", default=False, help="List uptodate packages", ) self.cmd_opts.add_option( "-e", "--editable", action="store_true", default=False, help="List editable projects.", ) self.cmd_opts.add_option( "-l", "--local", action="store_true", default=False, help=( "If in a virtualenv that has global access, do not list " "globally-installed packages." ), ) self.cmd_opts.add_option( "--user", dest="user", action="store_true", default=False, help="Only output packages installed in user-site.", ) self.cmd_opts.add_option(cmdoptions.list_path()) self.cmd_opts.add_option( "--pre", action="store_true", default=False, help=( "Include pre-release and development versions. By default, " "pip only finds stable versions." ), )
self.cmd_opts.add_option( "--format", action="store", dest="list_format", default="columns", choices=("columns", "freeze", "json"), help=( "Select the output format among: columns (default), freeze, or json. " "The 'freeze' format cannot be used with the --outdated option." ), )
self.cmd_opts.add_option( "--not-required", action="store_true", dest="not_required", help="List packages that are not dependencies of installed packages.", )
self.cmd_opts.add_option( "--exclude-editable", action="store_false", dest="include_editable", help="Exclude editable package from output.", ) self.cmd_opts.add_option( "--include-editable", action="store_true", dest="include_editable", help="Include editable package from output.", default=True, ) self.cmd_opts.add_option(cmdoptions.list_exclude()) index_opts = cmdoptions.make_option_group(cmdoptions.index_group, self.parser)
self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, self.cmd_opts)
def _build_package_finder( self, options: Values, session: PipSession ) -> PackageFinder: """ Create a package finder appropriate to this list command. """ link_collector = LinkCollector.create(session, options=options)
# Pass allow_yanked=False to ignore yanked versions. selection_prefs = SelectionPreferences( allow_yanked=False, allow_all_prereleases=options.pre, )
return PackageFinder.create( link_collector=link_collector, selection_prefs=selection_prefs, )
def run(self, options: Values, args: List[str]) -> int: if options.outdated and options.uptodate: raise CommandError("Options --outdated and --uptodate cannot be combined.")
if options.outdated and options.list_format == "freeze": raise CommandError( "List format 'freeze' cannot be used with the --outdated option." )
cmdoptions.check_list_path_option(options)
skip = set(stdlib_pkgs) if options.excludes: skip.update(canonicalize_name(n) for n in options.excludes)
packages: "_ProcessedDists" = [ cast("_DistWithLatestInfo", d) for d in get_environment(options.path).iter_installed_distributions( local_only=options.local, user_only=options.user, editables_only=options.editable, include_editables=options.include_editable, skip=skip, ) ]
# get_not_required must be called firstly in order to find and # filter out all dependencies correctly. Otherwise a package # can't be identified as requirement because some parent packages # could be filtered out before. if options.not_required: packages = self.get_not_required(packages, options)
if options.outdated: packages = self.get_outdated(packages, options) elif options.uptodate: packages = self.get_uptodate(packages, options)
self.output_package_listing(packages, options) return SUCCESS
def get_outdated( self, packages: "_ProcessedDists", options: Values ) -> "_ProcessedDists": return [ dist for dist in self.iter_packages_latest_infos(packages, options) if dist.latest_version > dist.version ]
def get_uptodate( self, packages: "_ProcessedDists", options: Values ) -> "_ProcessedDists": return [ dist for dist in self.iter_packages_latest_infos(packages, options) if dist.latest_version == dist.version ]
def get_not_required( self, packages: "_ProcessedDists", options: Values ) -> "_ProcessedDists": dep_keys = { canonicalize_name(dep.name) for dist in packages for dep in (dist.iter_dependencies() or ()) }
# Create a set to remove duplicate packages, and cast it to a list # to keep the return type consistent with get_outdated and # get_uptodate return list({pkg for pkg in packages if pkg.canonical_name not in dep_keys})
def iter_packages_latest_infos( self, packages: "_ProcessedDists", options: Values ) -> Generator["_DistWithLatestInfo", None, None]: with self._build_session(options) as session: finder = self._build_package_finder(options, session)
def latest_info( dist: "_DistWithLatestInfo", ) -> Optional["_DistWithLatestInfo"]: all_candidates = finder.find_all_candidates(dist.canonical_name) if not options.pre: # Remove prereleases all_candidates = [ candidate for candidate in all_candidates if not candidate.version.is_prerelease ]
evaluator = finder.make_candidate_evaluator( project_name=dist.canonical_name, ) best_candidate = evaluator.sort_best_candidate(all_candidates) if best_candidate is None: return None
remote_version = best_candidate.version if best_candidate.link.is_wheel: typ = "wheel" else: typ = "sdist" dist.latest_version = remote_version dist.latest_filetype = typ return dist
for dist in map(latest_info, packages): if dist is not None: yield dist
def output_package_listing( self, packages: "_ProcessedDists", options: Values ) -> None: packages = sorted( packages, key=lambda dist: dist.canonical_name, ) if options.list_format == "columns" and packages: data, header = format_for_columns(packages, options) self.output_package_listing_columns(data, header) elif options.list_format == "freeze": for dist in packages: if options.verbose >= 1: write_output( "%s==%s (%s)", dist.raw_name, dist.version, dist.location ) else: write_output("%s==%s", dist.raw_name, dist.version) elif options.list_format == "json": write_output(format_for_json(packages, options))
def output_package_listing_columns( self, data: List[List[str]], header: List[str] ) -> None: # insert the header first: we need to know the size of column names if len(data) > 0: data.insert(0, header)
pkg_strings, sizes = tabulate(data)
# Create and add a separator. if len(data) > 0: pkg_strings.insert(1, " ".join(map(lambda x: "-" * x, sizes)))
for val in pkg_strings: write_output(val)
def format_for_columns( pkgs: "_ProcessedDists", options: Values) -> Tuple[List[List[str]], List[str]]: """ Convert the package data into something usable by output_package_listing_columns. """ header = ["Package", "Version"]
running_outdated = options.outdated if running_outdated: header.extend(["Latest", "Type"])
has_editables = any(x.editable for x in pkgs) if has_editables: header.append("Editable project location")
if options.verbose >= 1: header.append("Location") if options.verbose >= 1: header.append("Installer")
data = [] for proj in pkgs: # if we're working on the 'outdated' list, separate out the # latest_version and type row = [proj.raw_name, str(proj.version)]
if running_outdated: row.append(str(proj.latest_version)) row.append(proj.latest_filetype)
if has_editables: row.append(proj.editable_project_location or "")
if options.verbose >= 1: row.append(proj.location or "") if options.verbose >= 1: row.append(proj.installer)
data.append(row)
return data, header
def format_for_json(packages: "_ProcessedDists", options: Values) -> str: data = [] for dist in packages: info = { "name": dist.raw_name, "version": str(dist.version), } if options.verbose >= 1: info["location"] = dist.location or "" info["installer"] = dist.installer if options.outdated: info["latest_version"] = str(dist.latest_version) info["latest_filetype"] = dist.latest_filetype editable_project_location = dist.editable_project_location if editable_project_location: info["editable_project_location"] = editable_project_location data.append(info) return json.dumps(data)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174import loggingimport shutilimport sysimport textwrapimport xmlrpc.clientfrom collections import OrderedDictfrom optparse import Valuesfrom typing import TYPE_CHECKING, Dict, List, Optional
from pip._vendor.packaging.version import parse as parse_version
from pip._internal.cli.base_command import Commandfrom pip._internal.cli.req_command import SessionCommandMixinfrom pip._internal.cli.status_codes import NO_MATCHES_FOUND, SUCCESSfrom pip._internal.exceptions import CommandErrorfrom pip._internal.metadata import get_default_environmentfrom pip._internal.models.index import PyPIfrom pip._internal.network.xmlrpc import PipXmlrpcTransportfrom pip._internal.utils.logging import indent_logfrom pip._internal.utils.misc import write_output
if TYPE_CHECKING: from typing import TypedDict
class TransformedHit(TypedDict): name: str summary: str versions: List[str]
logger = logging.getLogger(__name__)
class SearchCommand(Command, SessionCommandMixin): """Search for PyPI packages whose name or summary contains <query>."""
usage = """ %prog [options] <query>""" ignore_require_venv = True
def add_options(self) -> None: self.cmd_opts.add_option( "-i", "--index", dest="index", metavar="URL", default=PyPI.pypi_url, help="Base URL of Python Package Index (default %default)", )
self.parser.insert_option_group(0, self.cmd_opts)
def run(self, options: Values, args: List[str]) -> int: if not args: raise CommandError("Missing required argument (search query).") query = args pypi_hits = self.search(query, options) hits = transform_hits(pypi_hits)
terminal_width = None if sys.stdout.isatty(): terminal_width = shutil.get_terminal_size()[0]
print_results(hits, terminal_width=terminal_width) if pypi_hits: return SUCCESS return NO_MATCHES_FOUND
def search(self, query: List[str], options: Values) -> List[Dict[str, str]]: index_url = options.index
session = self.get_default_session(options)
transport = PipXmlrpcTransport(index_url, session) pypi = xmlrpc.client.ServerProxy(index_url, transport) try: hits = pypi.search({"name": query, "summary": query}, "or") except xmlrpc.client.Fault as fault: message = "XMLRPC request failed [code: {code}]\n{string}".format( code=fault.faultCode, string=fault.faultString, ) raise CommandError(message) assert isinstance(hits, list) return hits
def transform_hits(hits: List[Dict[str, str]]) -> List["TransformedHit"]: """ The list from pypi is really a list of versions. We want a list of packages with the list of versions stored inline. This converts the list from pypi into one we can use. """ packages: Dict[str, "TransformedHit"] = OrderedDict() for hit in hits: name = hit["name"] summary = hit["summary"] version = hit["version"]
if name not in packages.keys(): packages[name] = { "name": name, "summary": summary, "versions": [version], } else: packages[name]["versions"].append(version)
# if this is the highest version, replace summary and score if version == highest_version(packages[name]["versions"]): packages[name]["summary"] = summary
return list(packages.values())
def print_dist_installation_info(name: str, latest: str) -> None: env = get_default_environment() dist = env.get_distribution(name) if dist is not None: with indent_log(): if dist.version == latest: write_output("INSTALLED: %s (latest)", dist.version) else: write_output("INSTALLED: %s", dist.version) if parse_version(latest).pre: write_output( "LATEST: %s (pre-release; install" " with `pip install --pre`)", latest, ) else: write_output("LATEST: %s", latest)
def print_results( hits: List["TransformedHit"], name_column_width: Optional[int] = None, terminal_width: Optional[int] = None,) -> None: if not hits: return if name_column_width is None: name_column_width = ( max( [ len(hit["name"]) + len(highest_version(hit.get("versions", ["-"]))) for hit in hits ] ) + 4 )
for hit in hits: name = hit["name"] summary = hit["summary"] or "" latest = highest_version(hit.get("versions", ["-"])) if terminal_width is not None: target_width = terminal_width - name_column_width - 5 if target_width > 10: # wrap and indent summary to fit terminal summary_lines = textwrap.wrap(summary, target_width) summary = ("\n" + " " * (name_column_width + 3)).join(summary_lines)
name_latest = f"{name} ({latest})" line = f"{name_latest:{name_column_width}} - {summary}" try: write_output(line) print_dist_installation_info(name, latest) except UnicodeEncodeError: pass
def highest_version(versions: List[str]) -> str: return max(versions, key=parse_version)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189import loggingfrom optparse import Valuesfrom typing import Generator, Iterable, Iterator, List, NamedTuple, Optional
from pip._vendor.packaging.utils import canonicalize_name
from pip._internal.cli.base_command import Commandfrom pip._internal.cli.status_codes import ERROR, SUCCESSfrom pip._internal.metadata import BaseDistribution, get_default_environmentfrom pip._internal.utils.misc import write_output
logger = logging.getLogger(__name__)
class ShowCommand(Command): """ Show information about one or more installed packages.
The output is in RFC-compliant mail header format. """
usage = """ %prog [options] <package> ...""" ignore_require_venv = True
def add_options(self) -> None: self.cmd_opts.add_option( "-f", "--files", dest="files", action="store_true", default=False, help="Show the full list of installed files for each package.", )
self.parser.insert_option_group(0, self.cmd_opts)
def run(self, options: Values, args: List[str]) -> int: if not args: logger.warning("ERROR: Please provide a package name or names.") return ERROR query = args
results = search_packages_info(query) if not print_results( results, list_files=options.files, verbose=options.verbose ): return ERROR return SUCCESS
class _PackageInfo(NamedTuple): name: str version: str location: str editable_project_location: Optional[str] requires: List[str] required_by: List[str] installer: str metadata_version: str classifiers: List[str] summary: str homepage: str project_urls: List[str] author: str author_email: str license: str entry_points: List[str] files: Optional[List[str]]
def search_packages_info(query: List[str]) -> Generator[_PackageInfo, None, None]: """ Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory. """ env = get_default_environment()
installed = {dist.canonical_name: dist for dist in env.iter_all_distributions()} query_names = [canonicalize_name(name) for name in query] missing = sorted( [name for name, pkg in zip(query, query_names) if pkg not in installed] ) if missing: logger.warning("Package(s) not found: %s", ", ".join(missing))
def _get_requiring_packages(current_dist: BaseDistribution) -> Iterator[str]: return ( dist.metadata["Name"] or "UNKNOWN" for dist in installed.values() if current_dist.canonical_name in {canonicalize_name(d.name) for d in dist.iter_dependencies()} )
for query_name in query_names: try: dist = installed[query_name] except KeyError: continue
requires = sorted((req.name for req in dist.iter_dependencies()), key=str.lower) required_by = sorted(_get_requiring_packages(dist), key=str.lower)
try: entry_points_text = dist.read_text("entry_points.txt") entry_points = entry_points_text.splitlines(keepends=False) except FileNotFoundError: entry_points = []
files_iter = dist.iter_declared_entries() if files_iter is None: files: Optional[List[str]] = None else: files = sorted(files_iter)
metadata = dist.metadata
yield _PackageInfo( name=dist.raw_name, version=str(dist.version), location=dist.location or "", editable_project_location=dist.editable_project_location, requires=requires, required_by=required_by, installer=dist.installer, metadata_version=dist.metadata_version or "", classifiers=metadata.get_all("Classifier", []), summary=metadata.get("Summary", ""), homepage=metadata.get("Home-page", ""), project_urls=metadata.get_all("Project-URL", []), author=metadata.get("Author", ""), author_email=metadata.get("Author-email", ""), license=metadata.get("License", ""), entry_points=entry_points, files=files, )
def print_results( distributions: Iterable[_PackageInfo], list_files: bool, verbose: bool,) -> bool: """ Print the information from installed distributions found. """ results_printed = False for i, dist in enumerate(distributions): results_printed = True if i > 0: write_output("---")
write_output("Name: %s", dist.name) write_output("Version: %s", dist.version) write_output("Summary: %s", dist.summary) write_output("Home-page: %s", dist.homepage) write_output("Author: %s", dist.author) write_output("Author-email: %s", dist.author_email) write_output("License: %s", dist.license) write_output("Location: %s", dist.location) if dist.editable_project_location is not None: write_output( "Editable project location: %s", dist.editable_project_location ) write_output("Requires: %s", ", ".join(dist.requires)) write_output("Required-by: %s", ", ".join(dist.required_by))
if verbose: write_output("Metadata-Version: %s", dist.metadata_version) write_output("Installer: %s", dist.installer) write_output("Classifiers:") for classifier in dist.classifiers: write_output(" %s", classifier) write_output("Entry-points:") for entry in dist.entry_points: write_output(" %s", entry.strip()) write_output("Project-URLs:") for project_url in dist.project_urls: write_output(" %s", project_url) if list_files: write_output("Files:") if dist.files is None: write_output("Cannot locate RECORD or installed-files.txt") else: for line in dist.files: write_output(" %s", line.strip()) return results_printed123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113import loggingfrom optparse import Valuesfrom typing import List
from pip._vendor.packaging.utils import canonicalize_name
from pip._internal.cli import cmdoptionsfrom pip._internal.cli.base_command import Commandfrom pip._internal.cli.req_command import SessionCommandMixin, warn_if_run_as_rootfrom pip._internal.cli.status_codes import SUCCESSfrom pip._internal.exceptions import InstallationErrorfrom pip._internal.req import parse_requirementsfrom pip._internal.req.constructors import ( install_req_from_line, install_req_from_parsed_requirement,)from pip._internal.utils.misc import ( check_externally_managed, protect_pip_from_modification_on_windows,)
logger = logging.getLogger(__name__)
class UninstallCommand(Command, SessionCommandMixin): """ Uninstall packages.
pip is able to uninstall most installed packages. Known exceptions are:
- Pure distutils packages installed with ``python setup.py install``, which leave behind no metadata to determine what files were installed. - Script wrappers installed by ``python setup.py develop``. """
usage = """ %prog [options] <package> ... %prog [options] -r <requirements file> ..."""
def add_options(self) -> None: self.cmd_opts.add_option( "-r", "--requirement", dest="requirements", action="append", default=[], metavar="file", help=( "Uninstall all the packages listed in the given requirements " "file. This option can be used multiple times." ), ) self.cmd_opts.add_option( "-y", "--yes", dest="yes", action="store_true", help="Don't ask for confirmation of uninstall deletions.", ) self.cmd_opts.add_option(cmdoptions.root_user_action()) self.cmd_opts.add_option(cmdoptions.override_externally_managed()) self.parser.insert_option_group(0, self.cmd_opts)
def run(self, options: Values, args: List[str]) -> int: session = self.get_default_session(options)
reqs_to_uninstall = {} for name in args: req = install_req_from_line( name, isolated=options.isolated_mode, ) if req.name: reqs_to_uninstall[canonicalize_name(req.name)] = req else: logger.warning( "Invalid requirement: %r ignored -" " the uninstall command expects named" " requirements.", name, ) for filename in options.requirements: for parsed_req in parse_requirements( filename, options=options, session=session ): req = install_req_from_parsed_requirement( parsed_req, isolated=options.isolated_mode ) if req.name: reqs_to_uninstall[canonicalize_name(req.name)] = req if not reqs_to_uninstall: raise InstallationError( f"You must give at least one requirement to {self.name} (see " f'"pip help {self.name}")' )
if not options.override_externally_managed: check_externally_managed()
protect_pip_from_modification_on_windows( modifying_pip="pip" in reqs_to_uninstall )
for req in reqs_to_uninstall.values(): uninstall_pathset = req.uninstall( auto_confirm=options.yes, verbose=self.verbosity > 0, ) if uninstall_pathset: uninstall_pathset.commit() if options.root_user_action == "warn": warn_if_run_as_root() return SUCCESS123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183import loggingimport osimport shutilfrom optparse import Valuesfrom typing import List
from pip._internal.cache import WheelCachefrom pip._internal.cli import cmdoptionsfrom pip._internal.cli.req_command import RequirementCommand, with_cleanupfrom pip._internal.cli.status_codes import SUCCESSfrom pip._internal.exceptions import CommandErrorfrom pip._internal.operations.build.build_tracker import get_build_trackerfrom pip._internal.req.req_install import ( InstallRequirement, check_legacy_setup_py_options,)from pip._internal.utils.misc import ensure_dir, normalize_pathfrom pip._internal.utils.temp_dir import TempDirectoryfrom pip._internal.wheel_builder import build, should_build_for_wheel_command
logger = logging.getLogger(__name__)
class WheelCommand(RequirementCommand): """ Build Wheel archives for your requirements and dependencies.
Wheel is a built-package format, and offers the advantage of not recompiling your software during every install. For more details, see the wheel docs: https://wheel.readthedocs.io/en/latest/
'pip wheel' uses the build system interface as described here: https://pip.pypa.io/en/stable/reference/build-system/
"""
usage = """ %prog [options] <requirement specifier> ... %prog [options] -r <requirements file> ... %prog [options] [-e] <vcs project url> ... %prog [options] [-e] <local project path> ... %prog [options] <archive url/path> ..."""
def add_options(self) -> None: self.cmd_opts.add_option( "-w", "--wheel-dir", dest="wheel_dir", metavar="dir", default=os.curdir, help=( "Build wheels into <dir>, where the default is the " "current working directory." ), ) self.cmd_opts.add_option(cmdoptions.no_binary()) self.cmd_opts.add_option(cmdoptions.only_binary()) self.cmd_opts.add_option(cmdoptions.prefer_binary()) self.cmd_opts.add_option(cmdoptions.no_build_isolation()) self.cmd_opts.add_option(cmdoptions.use_pep517()) self.cmd_opts.add_option(cmdoptions.no_use_pep517()) self.cmd_opts.add_option(cmdoptions.check_build_deps()) self.cmd_opts.add_option(cmdoptions.constraints()) self.cmd_opts.add_option(cmdoptions.editable()) self.cmd_opts.add_option(cmdoptions.requirements()) self.cmd_opts.add_option(cmdoptions.src()) self.cmd_opts.add_option(cmdoptions.ignore_requires_python()) self.cmd_opts.add_option(cmdoptions.no_deps()) self.cmd_opts.add_option(cmdoptions.progress_bar())
self.cmd_opts.add_option( "--no-verify", dest="no_verify", action="store_true", default=False, help="Don't verify if built wheel is valid.", )
self.cmd_opts.add_option(cmdoptions.config_settings()) self.cmd_opts.add_option(cmdoptions.build_options()) self.cmd_opts.add_option(cmdoptions.global_options())
self.cmd_opts.add_option( "--pre", action="store_true", default=False, help=( "Include pre-release and development versions. By default, " "pip only finds stable versions." ), )
self.cmd_opts.add_option(cmdoptions.require_hashes())
index_opts = cmdoptions.make_option_group( cmdoptions.index_group, self.parser, )
self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, self.cmd_opts)
@with_cleanup def run(self, options: Values, args: List[str]) -> int: session = self.get_default_session(options)
finder = self._build_package_finder(options, session)
options.wheel_dir = normalize_path(options.wheel_dir) ensure_dir(options.wheel_dir)
build_tracker = self.enter_context(get_build_tracker())
directory = TempDirectory( delete=not options.no_clean, kind="wheel", globally_managed=True, )
reqs = self.get_requirements(args, options, finder, session) check_legacy_setup_py_options(options, reqs)
wheel_cache = WheelCache(options.cache_dir)
preparer = self.make_requirement_preparer( temp_build_dir=directory, options=options, build_tracker=build_tracker, session=session, finder=finder, download_dir=options.wheel_dir, use_user_site=False, verbosity=self.verbosity, )
resolver = self.make_resolver( preparer=preparer, finder=finder, options=options, wheel_cache=wheel_cache, ignore_requires_python=options.ignore_requires_python, use_pep517=options.use_pep517, )
self.trace_basic_info(finder)
requirement_set = resolver.resolve(reqs, check_supported_wheels=True)
reqs_to_build: List[InstallRequirement] = [] for req in requirement_set.requirements.values(): if req.is_wheel: preparer.save_linked_requirement(req) elif should_build_for_wheel_command(req): reqs_to_build.append(req)
preparer.prepare_linked_requirements_more(requirement_set.requirements.values()) requirement_set.warn_legacy_versions_and_specifiers()
# build wheels build_successes, build_failures = build( reqs_to_build, wheel_cache=wheel_cache, verify=(not options.no_verify), build_options=options.build_options or [], global_options=options.global_options or [], ) for req in build_successes: assert req.link and req.link.is_wheel assert req.local_file_path # copy from cache to target directory try: shutil.copy(req.local_file_path, options.wheel_dir) except OSError as e: logger.warning( "Building wheel for %s failed: %s", req.name, e, ) build_failures.append(req) if len(build_failures) != 0: raise CommandError("Failed to build one or more wheels")
return SUCCESS123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381"""Configuration management setup
Some terminology:- name As written in config files.- value Value associated with a name- key Name combined with it's section (section.name)- variant A single word describing where the configuration key-value pair came from"""
import configparserimport localeimport osimport sysfrom typing import Any, Dict, Iterable, List, NewType, Optional, Tuple
from pip._internal.exceptions import ( ConfigurationError, ConfigurationFileCouldNotBeLoaded,)from pip._internal.utils import appdirsfrom pip._internal.utils.compat import WINDOWSfrom pip._internal.utils.logging import getLoggerfrom pip._internal.utils.misc import ensure_dir, enum
RawConfigParser = configparser.RawConfigParser # ShorthandKind = NewType("Kind", str)
CONFIG_BASENAME = "pip.ini" if WINDOWS else "pip.conf"ENV_NAMES_IGNORED = "version", "help"
# The kinds of configurations there are.kinds = enum( USER="user", # User Specific GLOBAL="global", # System Wide SITE="site", # [Virtual] Environment Specific ENV="env", # from PIP_CONFIG_FILE ENV_VAR="env-var", # from Environment Variables)OVERRIDE_ORDER = kinds.GLOBAL, kinds.USER, kinds.SITE, kinds.ENV, kinds.ENV_VARVALID_LOAD_ONLY = kinds.USER, kinds.GLOBAL, kinds.SITE
logger = getLogger(__name__)
# NOTE: Maybe use the optionx attribute to normalize keynames.def _normalize_name(name: str) -> str: """Make a name consistent regardless of source (environment or file)""" name = name.lower().replace("_", "-") if name.startswith("--"): name = name[2:] # only prefer long opts return name
def _disassemble_key(name: str) -> List[str]: if "." not in name: error_message = ( "Key does not contain dot separated section and key. " "Perhaps you wanted to use 'global.{}' instead?" ).format(name) raise ConfigurationError(error_message) return name.split(".", 1)
def get_configuration_files() -> Dict[Kind, List[str]]: global_config_files = [ os.path.join(path, CONFIG_BASENAME) for path in appdirs.site_config_dirs("pip") ]
site_config_file = os.path.join(sys.prefix, CONFIG_BASENAME) legacy_config_file = os.path.join( os.path.expanduser("~"), "pip" if WINDOWS else ".pip", CONFIG_BASENAME, ) new_config_file = os.path.join(appdirs.user_config_dir("pip"), CONFIG_BASENAME) return { kinds.GLOBAL: global_config_files, kinds.SITE: [site_config_file], kinds.USER: [legacy_config_file, new_config_file], }
class Configuration: """Handles management of configuration.
Provides an interface to accessing and managing configuration files.
This class converts provides an API that takes "section.key-name" style keys and stores the value associated with it as "key-name" under the section "section".
This allows for a clean interface wherein the both the section and the key-name are preserved in an easy to manage form in the configuration files and the data stored is also nice. """
def __init__(self, isolated: bool, load_only: Optional[Kind] = None) -> None: super().__init__()
if load_only is not None and load_only not in VALID_LOAD_ONLY: raise ConfigurationError( "Got invalid value for load_only - should be one of {}".format( ", ".join(map(repr, VALID_LOAD_ONLY)) ) ) self.isolated = isolated self.load_only = load_only
# Because we keep track of where we got the data from self._parsers: Dict[Kind, List[Tuple[str, RawConfigParser]]] = { variant: [] for variant in OVERRIDE_ORDER } self._config: Dict[Kind, Dict[str, Any]] = { variant: {} for variant in OVERRIDE_ORDER } self._modified_parsers: List[Tuple[str, RawConfigParser]] = []
def load(self) -> None: """Loads configuration from configuration files and environment""" self._load_config_files() if not self.isolated: self._load_environment_vars()
def get_file_to_edit(self) -> Optional[str]: """Returns the file with highest priority in configuration""" assert self.load_only is not None, "Need to be specified a file to be editing"
try: return self._get_parser_to_modify()[0] except IndexError: return None
def items(self) -> Iterable[Tuple[str, Any]]: """Returns key-value pairs like dict.items() representing the loaded configuration """ return self._dictionary.items()
def get_value(self, key: str) -> Any: """Get a value from the configuration.""" orig_key = key key = _normalize_name(key) try: return self._dictionary[key] except KeyError: # disassembling triggers a more useful error message than simply # "No such key" in the case that the key isn't in the form command.option _disassemble_key(key) raise ConfigurationError(f"No such key - {orig_key}")
def set_value(self, key: str, value: Any) -> None: """Modify a value in the configuration.""" key = _normalize_name(key) self._ensure_have_load_only()
assert self.load_only fname, parser = self._get_parser_to_modify()
if parser is not None: section, name = _disassemble_key(key)
# Modify the parser and the configuration if not parser.has_section(section): parser.add_section(section) parser.set(section, name, value)
self._config[self.load_only][key] = value self._mark_as_modified(fname, parser)
def unset_value(self, key: str) -> None: """Unset a value in the configuration.""" orig_key = key key = _normalize_name(key) self._ensure_have_load_only()
assert self.load_only if key not in self._config[self.load_only]: raise ConfigurationError(f"No such key - {orig_key}")
fname, parser = self._get_parser_to_modify()
if parser is not None: section, name = _disassemble_key(key) if not ( parser.has_section(section) and parser.remove_option(section, name) ): # The option was not removed. raise ConfigurationError( "Fatal Internal error [id=1]. Please report as a bug." )
# The section may be empty after the option was removed. if not parser.items(section): parser.remove_section(section) self._mark_as_modified(fname, parser)
del self._config[self.load_only][key]
def save(self) -> None: """Save the current in-memory state.""" self._ensure_have_load_only()
for fname, parser in self._modified_parsers: logger.info("Writing to %s", fname)
# Ensure directory exists. ensure_dir(os.path.dirname(fname))
# Ensure directory's permission(need to be writeable) try: with open(fname, "w") as f: parser.write(f) except OSError as error: raise ConfigurationError( f"An error occurred while writing to the configuration file " f"{fname}: {error}" )
# # Private routines #
def _ensure_have_load_only(self) -> None: if self.load_only is None: raise ConfigurationError("Needed a specific file to be modifying.") logger.debug("Will be working with %s variant only", self.load_only)
@property def _dictionary(self) -> Dict[str, Any]: """A dictionary representing the loaded configuration.""" # NOTE: Dictionaries are not populated if not loaded. So, conditionals # are not needed here. retval = {}
for variant in OVERRIDE_ORDER: retval.update(self._config[variant])
return retval
def _load_config_files(self) -> None: """Loads configuration from configuration files""" config_files = dict(self.iter_config_files()) if config_files[kinds.ENV][0:1] == [os.devnull]: logger.debug( "Skipping loading configuration files due to " "environment's PIP_CONFIG_FILE being os.devnull" ) return
for variant, files in config_files.items(): for fname in files: # If there's specific variant set in `load_only`, load only # that variant, not the others. if self.load_only is not None and variant != self.load_only: logger.debug("Skipping file '%s' (variant: %s)", fname, variant) continue
parser = self._load_file(variant, fname)
# Keeping track of the parsers used self._parsers[variant].append((fname, parser))
def _load_file(self, variant: Kind, fname: str) -> RawConfigParser: logger.verbose("For variant '%s', will try loading '%s'", variant, fname) parser = self._construct_parser(fname)
for section in parser.sections(): items = parser.items(section) self._config[variant].update(self._normalized_keys(section, items))
return parser
def _construct_parser(self, fname: str) -> RawConfigParser: parser = configparser.RawConfigParser() # If there is no such file, don't bother reading it but create the # parser anyway, to hold the data. # Doing this is useful when modifying and saving files, where we don't # need to construct a parser. if os.path.exists(fname): locale_encoding = locale.getpreferredencoding(False) try: parser.read(fname, encoding=locale_encoding) except UnicodeDecodeError: # See https://github.com/pypa/pip/issues/4963 raise ConfigurationFileCouldNotBeLoaded( reason=f"contains invalid {locale_encoding} characters", fname=fname, ) except configparser.Error as error: # See https://github.com/pypa/pip/issues/4893 raise ConfigurationFileCouldNotBeLoaded(error=error) return parser
def _load_environment_vars(self) -> None: """Loads configuration from environment variables""" self._config[kinds.ENV_VAR].update( self._normalized_keys(":env:", self.get_environ_vars()) )
def _normalized_keys( self, section: str, items: Iterable[Tuple[str, Any]] ) -> Dict[str, Any]: """Normalizes items to construct a dictionary with normalized keys.
This routine is where the names become keys and are made the same regardless of source - configuration files or environment. """ normalized = {} for name, val in items: key = section + "." + _normalize_name(name) normalized[key] = val return normalized
def get_environ_vars(self) -> Iterable[Tuple[str, str]]: """Returns a generator with all environmental vars with prefix PIP_""" for key, val in os.environ.items(): if key.startswith("PIP_"): name = key[4:].lower() if name not in ENV_NAMES_IGNORED: yield name, val
# XXX: This is patched in the tests. def iter_config_files(self) -> Iterable[Tuple[Kind, List[str]]]: """Yields variant and configuration files associated with it.
This should be treated like items of a dictionary. """ # SMELL: Move the conditions out of this function
# environment variables have the lowest priority config_file = os.environ.get("PIP_CONFIG_FILE", None) if config_file is not None: yield kinds.ENV, [config_file] else: yield kinds.ENV, []
config_files = get_configuration_files()
# at the base we have any global configuration yield kinds.GLOBAL, config_files[kinds.GLOBAL]
# per-user configuration next should_load_user_config = not self.isolated and not ( config_file and os.path.exists(config_file) ) if should_load_user_config: # The legacy config file is overridden by the new config file yield kinds.USER, config_files[kinds.USER]
# finally virtualenv configuration first trumping others yield kinds.SITE, config_files[kinds.SITE]
def get_values_in_config(self, variant: Kind) -> Dict[str, Any]: """Get values present in a config file""" return self._config[variant]
def _get_parser_to_modify(self) -> Tuple[str, RawConfigParser]: # Determine which parser to modify assert self.load_only parsers = self._parsers[self.load_only] if not parsers: # This should not happen if everything works correctly. raise ConfigurationError( "Fatal Internal error [id=2]. Please report as a bug." )
# Use the highest priority parser. return parsers[-1]
# XXX: This is patched in the tests. def _mark_as_modified(self, fname: str, parser: RawConfigParser) -> None: file_parser_tuple = (fname, parser) if file_parser_tuple not in self._modified_parsers: self._modified_parsers.append(file_parser_tuple)
def __repr__(self) -> str: return f"{self.__class__.__name__}({self._dictionary!r})"123456789101112131415161718192021from pip._internal.distributions.base import AbstractDistributionfrom pip._internal.distributions.sdist import SourceDistributionfrom pip._internal.distributions.wheel import WheelDistributionfrom pip._internal.req.req_install import InstallRequirement
def make_distribution_for_install_requirement( install_req: InstallRequirement,) -> AbstractDistribution: """Returns a Distribution for the given InstallRequirement""" # Editable requirements will always be source distributions. They use the # legacy logic until we create a modern standard for them. if install_req.editable: return SourceDistribution(install_req)
# If it's a wheel, it's a WheelDistribution if install_req.is_wheel: return WheelDistribution(install_req)
# Otherwise, a SourceDistribution return SourceDistribution(install_req)123456789101112131415161718192021222324252627282930313233343536373839import abc
from pip._internal.index.package_finder import PackageFinderfrom pip._internal.metadata.base import BaseDistributionfrom pip._internal.req import InstallRequirement
class AbstractDistribution(metaclass=abc.ABCMeta): """A base class for handling installable artifacts.
The requirements for anything installable are as follows:
- we must be able to determine the requirement name (or we can't correctly handle the non-upgrade case).
- for packages with setup requirements, we must also be able to determine their requirements without installing additional packages (for the same reason as run-time dependencies)
- we must be able to create a Distribution object exposing the above metadata. """
def __init__(self, req: InstallRequirement) -> None: super().__init__() self.req = req
@abc.abstractmethod def get_metadata_distribution(self) -> BaseDistribution: raise NotImplementedError()
@abc.abstractmethod def prepare_distribution_metadata( self, finder: PackageFinder, build_isolation: bool, check_build_deps: bool, ) -> None: raise NotImplementedError()1234567891011121314151617181920212223from pip._internal.distributions.base import AbstractDistributionfrom pip._internal.index.package_finder import PackageFinderfrom pip._internal.metadata import BaseDistribution
class InstalledDistribution(AbstractDistribution): """Represents an installed package.
This does not need any preparation as the required information has already been computed. """
def get_metadata_distribution(self) -> BaseDistribution: assert self.req.satisfied_by is not None, "not actually installed" return self.req.satisfied_by
def prepare_distribution_metadata( self, finder: PackageFinder, build_isolation: bool, check_build_deps: bool, ) -> None: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150import loggingfrom typing import Iterable, Set, Tuple
from pip._internal.build_env import BuildEnvironmentfrom pip._internal.distributions.base import AbstractDistributionfrom pip._internal.exceptions import InstallationErrorfrom pip._internal.index.package_finder import PackageFinderfrom pip._internal.metadata import BaseDistributionfrom pip._internal.utils.subprocess import runner_with_spinner_message
logger = logging.getLogger(__name__)
class SourceDistribution(AbstractDistribution): """Represents a source distribution.
The preparation step for these needs metadata for the packages to be generated, either using PEP 517 or using the legacy `setup.py egg_info`. """
def get_metadata_distribution(self) -> BaseDistribution: return self.req.get_dist()
def prepare_distribution_metadata( self, finder: PackageFinder, build_isolation: bool, check_build_deps: bool, ) -> None: # Load pyproject.toml, to determine whether PEP 517 is to be used self.req.load_pyproject_toml()
# Set up the build isolation, if this requirement should be isolated should_isolate = self.req.use_pep517 and build_isolation if should_isolate: # Setup an isolated environment and install the build backend static # requirements in it. self._prepare_build_backend(finder) # Check that if the requirement is editable, it either supports PEP 660 or # has a setup.py or a setup.cfg. This cannot be done earlier because we need # to setup the build backend to verify it supports build_editable, nor can # it be done later, because we want to avoid installing build requirements # needlessly. Doing it here also works around setuptools generating # UNKNOWN.egg-info when running get_requires_for_build_wheel on a directory # without setup.py nor setup.cfg. self.req.isolated_editable_sanity_check() # Install the dynamic build requirements. self._install_build_reqs(finder) # Check if the current environment provides build dependencies should_check_deps = self.req.use_pep517 and check_build_deps if should_check_deps: pyproject_requires = self.req.pyproject_requires assert pyproject_requires is not None conflicting, missing = self.req.build_env.check_requirements( pyproject_requires ) if conflicting: self._raise_conflicts("the backend dependencies", conflicting) if missing: self._raise_missing_reqs(missing) self.req.prepare_metadata()
def _prepare_build_backend(self, finder: PackageFinder) -> None: # Isolate in a BuildEnvironment and install the build-time # requirements. pyproject_requires = self.req.pyproject_requires assert pyproject_requires is not None
self.req.build_env = BuildEnvironment() self.req.build_env.install_requirements( finder, pyproject_requires, "overlay", kind="build dependencies" ) conflicting, missing = self.req.build_env.check_requirements( self.req.requirements_to_check ) if conflicting: self._raise_conflicts("PEP 517/518 supported requirements", conflicting) if missing: logger.warning( "Missing build requirements in pyproject.toml for %s.", self.req, ) logger.warning( "The project does not specify a build backend, and " "pip cannot fall back to setuptools without %s.", " and ".join(map(repr, sorted(missing))), )
def _get_build_requires_wheel(self) -> Iterable[str]: with self.req.build_env: runner = runner_with_spinner_message("Getting requirements to build wheel") backend = self.req.pep517_backend assert backend is not None with backend.subprocess_runner(runner): return backend.get_requires_for_build_wheel()
def _get_build_requires_editable(self) -> Iterable[str]: with self.req.build_env: runner = runner_with_spinner_message( "Getting requirements to build editable" ) backend = self.req.pep517_backend assert backend is not None with backend.subprocess_runner(runner): return backend.get_requires_for_build_editable()
def _install_build_reqs(self, finder: PackageFinder) -> None: # Install any extra build dependencies that the backend requests. # This must be done in a second pass, as the pyproject.toml # dependencies must be installed before we can call the backend. if ( self.req.editable and self.req.permit_editable_wheels and self.req.supports_pyproject_editable() ): build_reqs = self._get_build_requires_editable() else: build_reqs = self._get_build_requires_wheel() conflicting, missing = self.req.build_env.check_requirements(build_reqs) if conflicting: self._raise_conflicts("the backend dependencies", conflicting) self.req.build_env.install_requirements( finder, missing, "normal", kind="backend dependencies" )
def _raise_conflicts( self, conflicting_with: str, conflicting_reqs: Set[Tuple[str, str]] ) -> None: format_string = ( "Some build dependencies for {requirement} " "conflict with {conflicting_with}: {description}." ) error_message = format_string.format( requirement=self.req, conflicting_with=conflicting_with, description=", ".join( f"{installed} is incompatible with {wanted}" for installed, wanted in sorted(conflicting_reqs) ), ) raise InstallationError(error_message)
def _raise_missing_reqs(self, missing: Set[str]) -> None: format_string = ( "Some build dependencies for {requirement} are missing: {missing}." ) error_message = format_string.format( requirement=self.req, missing=", ".join(map(repr, sorted(missing))) ) raise InstallationError(error_message)12345678910111213141516171819202122232425262728293031323334from pip._vendor.packaging.utils import canonicalize_name
from pip._internal.distributions.base import AbstractDistributionfrom pip._internal.index.package_finder import PackageFinderfrom pip._internal.metadata import ( BaseDistribution, FilesystemWheel, get_wheel_distribution,)
class WheelDistribution(AbstractDistribution): """Represents a wheel distribution.
This does not need any preparation as wheels can be directly unpacked. """
def get_metadata_distribution(self) -> BaseDistribution: """Loads the metadata from the wheel file into memory and returns a Distribution that uses it, not relying on the wheel file or requirement. """ assert self.req.local_file_path, "Set as part of preparation during download" assert self.req.name, "Wheels are never unnamed" wheel = FilesystemWheel(self.req.local_file_path) return get_wheel_distribution(wheel, canonicalize_name(self.req.name))
def prepare_distribution_metadata( self, finder: PackageFinder, build_isolation: bool, check_build_deps: bool, ) -> None: pass.gitattributes+59-59
.idea/.gitignoreAdded+3
.idea/inspectionProfiles/Project_Default.xmlAdded+30
.idea/inspectionProfiles/profiles_settings.xmlAdded+6
.idea/misc.xmlAdded+7
.idea/modules.xmlAdded+8
.idea/pac.imlAdded+10
.idea/vcs.xmlAdded+6
.idea/workspace.xmlAdded+84
.venv/.gitignoreAdded+2
.venv/Lib/site-packages/pip/__pip-runner__.pyAdded+50
.venv/Lib/site-packages/pip/_internal/__init__.pyAdded+19
.venv/Lib/site-packages/pip/_internal/build_env.pyAdded+311
.venv/Lib/site-packages/pip/_internal/cache.pyAdded+292
.venv/Lib/site-packages/pip/_internal/cli/__init__.pyAdded+4
.venv/Lib/site-packages/pip/_internal/cli/autocompletion.pyAdded+171
.venv/Lib/site-packages/pip/_internal/cli/base_command.pyAdded+236
.venv/Lib/site-packages/pip/_internal/cli/cmdoptions.pyAdded+1074
.venv/Lib/site-packages/pip/_internal/cli/command_context.pyAdded+27
.venv/Lib/site-packages/pip/_internal/cli/main.pyAdded+79
.venv/Lib/site-packages/pip/_internal/cli/main_parser.pyAdded+134
.venv/Lib/site-packages/pip/_internal/cli/parser.pyAdded+294
.venv/Lib/site-packages/pip/_internal/cli/progress_bars.pyAdded+68
.venv/Lib/site-packages/pip/_internal/cli/req_command.pyAdded+508
.venv/Lib/site-packages/pip/_internal/cli/spinners.pyAdded+159
.venv/Lib/site-packages/pip/_internal/cli/status_codes.pyAdded+6
.venv/Lib/site-packages/pip/_internal/commands/__init__.pyAdded+132
.venv/Lib/site-packages/pip/_internal/commands/cache.pyAdded+222
.venv/Lib/site-packages/pip/_internal/commands/check.pyAdded+54
.venv/Lib/site-packages/pip/_internal/commands/completion.pyAdded+121
.venv/Lib/site-packages/pip/_internal/commands/configuration.pyAdded+282
.venv/Lib/site-packages/pip/_internal/commands/debug.pyAdded+199
.venv/Lib/site-packages/pip/_internal/commands/download.pyAdded+147
.venv/Lib/site-packages/pip/_internal/commands/freeze.pyAdded+108
.venv/Lib/site-packages/pip/_internal/commands/hash.pyAdded+59
.venv/Lib/site-packages/pip/_internal/commands/help.pyAdded+41
.venv/Lib/site-packages/pip/_internal/commands/index.pyAdded+139
.venv/Lib/site-packages/pip/_internal/commands/inspect.pyAdded+92
.venv/Lib/site-packages/pip/_internal/commands/install.pyAdded+778
.venv/Lib/site-packages/pip/_internal/commands/list.pyAdded+368
.venv/Lib/site-packages/pip/_internal/commands/search.pyAdded+174
.venv/Lib/site-packages/pip/_internal/commands/show.pyAdded+189
.venv/Lib/site-packages/pip/_internal/commands/uninstall.pyAdded+113
.venv/Lib/site-packages/pip/_internal/commands/wheel.pyAdded+183
.venv/Lib/site-packages/pip/_internal/configuration.pyAdded+381
.venv/Lib/site-packages/pip/_internal/distributions/__init__.pyAdded+21
.venv/Lib/site-packages/pip/_internal/distributions/base.pyAdded+39
.venv/Lib/site-packages/pip/_internal/distributions/installed.pyAdded+23
.venv/Lib/site-packages/pip/_internal/distributions/sdist.pyAdded+150
.venv/Lib/site-packages/pip/_internal/distributions/wheel.pyAdded+34