applied-ai-018 commited on
Commit
5c5fe2b
·
verified ·
1 Parent(s): 46fcc36

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/__init__.cpython-310.pyc +0 -0
  3. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/autocompletion.cpython-310.pyc +0 -0
  4. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-310.pyc +0 -0
  5. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-310.pyc +0 -0
  6. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/command_context.cpython-310.pyc +0 -0
  7. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/main.cpython-310.pyc +0 -0
  8. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/main_parser.cpython-310.pyc +0 -0
  9. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/parser.cpython-310.pyc +0 -0
  10. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-310.pyc +0 -0
  11. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/req_command.cpython-310.pyc +0 -0
  12. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/spinners.cpython-310.pyc +0 -0
  13. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/status_codes.cpython-310.pyc +0 -0
  14. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/autocompletion.py +171 -0
  15. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/base_command.py +220 -0
  16. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/cmdoptions.py +1018 -0
  17. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/command_context.py +27 -0
  18. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/main_parser.py +87 -0
  19. scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/parser.py +292 -0
  20. scripts/myenv/lib/python3.10/site-packages/pip/_internal/metadata/__init__.py +62 -0
  21. scripts/myenv/lib/python3.10/site-packages/pip/_internal/metadata/__pycache__/__init__.cpython-310.pyc +0 -0
  22. scripts/myenv/lib/python3.10/site-packages/pip/_internal/metadata/__pycache__/base.cpython-310.pyc +0 -0
  23. scripts/myenv/lib/python3.10/site-packages/pip/_internal/metadata/__pycache__/pkg_resources.cpython-310.pyc +0 -0
  24. scripts/myenv/lib/python3.10/site-packages/pip/_internal/metadata/base.py +546 -0
  25. scripts/myenv/lib/python3.10/site-packages/pip/_internal/metadata/pkg_resources.py +256 -0
  26. scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__init__.py +2 -0
  27. scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/__init__.cpython-310.pyc +0 -0
  28. scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/auth.cpython-310.pyc +0 -0
  29. scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/cache.cpython-310.pyc +0 -0
  30. scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/download.cpython-310.pyc +0 -0
  31. scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/lazy_wheel.cpython-310.pyc +0 -0
  32. scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/session.cpython-310.pyc +0 -0
  33. scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/utils.cpython-310.pyc +0 -0
  34. scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/xmlrpc.cpython-310.pyc +0 -0
  35. scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/auth.py +323 -0
  36. scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/cache.py +69 -0
  37. scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/download.py +185 -0
  38. scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/lazy_wheel.py +210 -0
  39. scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/session.py +454 -0
  40. scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/utils.py +96 -0
  41. scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/xmlrpc.py +60 -0
  42. scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/__init__.py +0 -0
  43. scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/__pycache__/freeze.cpython-310.pyc +0 -0
  44. scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/build/__init__.py +0 -0
  45. scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/__init__.cpython-310.pyc +0 -0
  46. scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/metadata.cpython-310.pyc +0 -0
  47. scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/metadata_editable.cpython-310.pyc +0 -0
  48. scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/wheel.cpython-310.pyc +0 -0
  49. scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/wheel_legacy.cpython-310.pyc +0 -0
  50. scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/build/metadata.py +39 -0
.gitattributes CHANGED
@@ -59,3 +59,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
  scripts/temp.txt filter=lfs diff=lfs merge=lfs -text
61
  scripts/blacklisted_urls.txt filter=lfs diff=lfs merge=lfs -text
 
 
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
  scripts/temp.txt filter=lfs diff=lfs merge=lfs -text
61
  scripts/blacklisted_urls.txt filter=lfs diff=lfs merge=lfs -text
62
+ scripts/unique_source_documents.json filter=lfs diff=lfs merge=lfs -text
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (275 Bytes). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/autocompletion.cpython-310.pyc ADDED
Binary file (5.31 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-310.pyc ADDED
Binary file (6.25 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-310.pyc ADDED
Binary file (22.6 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/command_context.cpython-310.pyc ADDED
Binary file (1.31 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/main.cpython-310.pyc ADDED
Binary file (1.37 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/main_parser.cpython-310.pyc ADDED
Binary file (2.16 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/parser.cpython-310.pyc ADDED
Binary file (9.95 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-310.pyc ADDED
Binary file (9.24 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/req_command.cpython-310.pyc ADDED
Binary file (13.5 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/spinners.cpython-310.pyc ADDED
Binary file (4.95 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/status_codes.cpython-310.pyc ADDED
Binary file (354 Bytes). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/autocompletion.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Logic that powers autocompletion installed by ``pip completion``.
2
+ """
3
+
4
+ import optparse
5
+ import os
6
+ import sys
7
+ from itertools import chain
8
+ from typing import Any, Iterable, List, Optional
9
+
10
+ from pip._internal.cli.main_parser import create_main_parser
11
+ from pip._internal.commands import commands_dict, create_command
12
+ from pip._internal.metadata import get_default_environment
13
+
14
+
15
+ def autocomplete() -> None:
16
+ """Entry Point for completion of main and subcommand options."""
17
+ # Don't complete if user hasn't sourced bash_completion file.
18
+ if "PIP_AUTO_COMPLETE" not in os.environ:
19
+ return
20
+ cwords = os.environ["COMP_WORDS"].split()[1:]
21
+ cword = int(os.environ["COMP_CWORD"])
22
+ try:
23
+ current = cwords[cword - 1]
24
+ except IndexError:
25
+ current = ""
26
+
27
+ parser = create_main_parser()
28
+ subcommands = list(commands_dict)
29
+ options = []
30
+
31
+ # subcommand
32
+ subcommand_name: Optional[str] = None
33
+ for word in cwords:
34
+ if word in subcommands:
35
+ subcommand_name = word
36
+ break
37
+ # subcommand options
38
+ if subcommand_name is not None:
39
+ # special case: 'help' subcommand has no options
40
+ if subcommand_name == "help":
41
+ sys.exit(1)
42
+ # special case: list locally installed dists for show and uninstall
43
+ should_list_installed = not current.startswith("-") and subcommand_name in [
44
+ "show",
45
+ "uninstall",
46
+ ]
47
+ if should_list_installed:
48
+ env = get_default_environment()
49
+ lc = current.lower()
50
+ installed = [
51
+ dist.canonical_name
52
+ for dist in env.iter_installed_distributions(local_only=True)
53
+ if dist.canonical_name.startswith(lc)
54
+ and dist.canonical_name not in cwords[1:]
55
+ ]
56
+ # if there are no dists installed, fall back to option completion
57
+ if installed:
58
+ for dist in installed:
59
+ print(dist)
60
+ sys.exit(1)
61
+
62
+ should_list_installables = (
63
+ not current.startswith("-") and subcommand_name == "install"
64
+ )
65
+ if should_list_installables:
66
+ for path in auto_complete_paths(current, "path"):
67
+ print(path)
68
+ sys.exit(1)
69
+
70
+ subcommand = create_command(subcommand_name)
71
+
72
+ for opt in subcommand.parser.option_list_all:
73
+ if opt.help != optparse.SUPPRESS_HELP:
74
+ for opt_str in opt._long_opts + opt._short_opts:
75
+ options.append((opt_str, opt.nargs))
76
+
77
+ # filter out previously specified options from available options
78
+ prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]]
79
+ options = [(x, v) for (x, v) in options if x not in prev_opts]
80
+ # filter options by current input
81
+ options = [(k, v) for k, v in options if k.startswith(current)]
82
+ # get completion type given cwords and available subcommand options
83
+ completion_type = get_path_completion_type(
84
+ cwords,
85
+ cword,
86
+ subcommand.parser.option_list_all,
87
+ )
88
+ # get completion files and directories if ``completion_type`` is
89
+ # ``<file>``, ``<dir>`` or ``<path>``
90
+ if completion_type:
91
+ paths = auto_complete_paths(current, completion_type)
92
+ options = [(path, 0) for path in paths]
93
+ for option in options:
94
+ opt_label = option[0]
95
+ # append '=' to options which require args
96
+ if option[1] and option[0][:2] == "--":
97
+ opt_label += "="
98
+ print(opt_label)
99
+ else:
100
+ # show main parser options only when necessary
101
+
102
+ opts = [i.option_list for i in parser.option_groups]
103
+ opts.append(parser.option_list)
104
+ flattened_opts = chain.from_iterable(opts)
105
+ if current.startswith("-"):
106
+ for opt in flattened_opts:
107
+ if opt.help != optparse.SUPPRESS_HELP:
108
+ subcommands += opt._long_opts + opt._short_opts
109
+ else:
110
+ # get completion type given cwords and all available options
111
+ completion_type = get_path_completion_type(cwords, cword, flattened_opts)
112
+ if completion_type:
113
+ subcommands = list(auto_complete_paths(current, completion_type))
114
+
115
+ print(" ".join([x for x in subcommands if x.startswith(current)]))
116
+ sys.exit(1)
117
+
118
+
119
+ def get_path_completion_type(
120
+ cwords: List[str], cword: int, opts: Iterable[Any]
121
+ ) -> Optional[str]:
122
+ """Get the type of path completion (``file``, ``dir``, ``path`` or None)
123
+
124
+ :param cwords: same as the environmental variable ``COMP_WORDS``
125
+ :param cword: same as the environmental variable ``COMP_CWORD``
126
+ :param opts: The available options to check
127
+ :return: path completion type (``file``, ``dir``, ``path`` or None)
128
+ """
129
+ if cword < 2 or not cwords[cword - 2].startswith("-"):
130
+ return None
131
+ for opt in opts:
132
+ if opt.help == optparse.SUPPRESS_HELP:
133
+ continue
134
+ for o in str(opt).split("/"):
135
+ if cwords[cword - 2].split("=")[0] == o:
136
+ if not opt.metavar or any(
137
+ x in ("path", "file", "dir") for x in opt.metavar.split("/")
138
+ ):
139
+ return opt.metavar
140
+ return None
141
+
142
+
143
+ def auto_complete_paths(current: str, completion_type: str) -> Iterable[str]:
144
+ """If ``completion_type`` is ``file`` or ``path``, list all regular files
145
+ and directories starting with ``current``; otherwise only list directories
146
+ starting with ``current``.
147
+
148
+ :param current: The word to be completed
149
+ :param completion_type: path completion type(``file``, ``path`` or ``dir``)
150
+ :return: A generator of regular files and/or directories
151
+ """
152
+ directory, filename = os.path.split(current)
153
+ current_path = os.path.abspath(directory)
154
+ # Don't complete paths if they can't be accessed
155
+ if not os.access(current_path, os.R_OK):
156
+ return
157
+ filename = os.path.normcase(filename)
158
+ # list all files that start with ``filename``
159
+ file_list = (
160
+ x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)
161
+ )
162
+ for f in file_list:
163
+ opt = os.path.join(current_path, f)
164
+ comp_file = os.path.normcase(os.path.join(directory, f))
165
+ # complete regular files when there is not ``<dir>`` after option
166
+ # complete directories when there is ``<file>``, ``<path>`` or
167
+ # ``<dir>``after option
168
+ if completion_type != "dir" and os.path.isfile(opt):
169
+ yield comp_file
170
+ elif os.path.isdir(opt):
171
+ yield os.path.join(comp_file, "")
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/base_command.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base Command class, and related routines"""
2
+
3
+ import functools
4
+ import logging
5
+ import logging.config
6
+ import optparse
7
+ import os
8
+ import sys
9
+ import traceback
10
+ from optparse import Values
11
+ from typing import Any, Callable, List, Optional, Tuple
12
+
13
+ from pip._internal.cli import cmdoptions
14
+ from pip._internal.cli.command_context import CommandContextMixIn
15
+ from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
16
+ from pip._internal.cli.status_codes import (
17
+ ERROR,
18
+ PREVIOUS_BUILD_DIR_ERROR,
19
+ UNKNOWN_ERROR,
20
+ VIRTUALENV_NOT_FOUND,
21
+ )
22
+ from pip._internal.exceptions import (
23
+ BadCommand,
24
+ CommandError,
25
+ DiagnosticPipError,
26
+ InstallationError,
27
+ NetworkConnectionError,
28
+ PreviousBuildDirError,
29
+ UninstallationError,
30
+ )
31
+ from pip._internal.utils.filesystem import check_path_owner
32
+ from pip._internal.utils.logging import BrokenStdoutLoggingError, setup_logging
33
+ from pip._internal.utils.misc import get_prog, normalize_path
34
+ from pip._internal.utils.temp_dir import TempDirectoryTypeRegistry as TempDirRegistry
35
+ from pip._internal.utils.temp_dir import global_tempdir_manager, tempdir_registry
36
+ from pip._internal.utils.virtualenv import running_under_virtualenv
37
+
38
+ __all__ = ["Command"]
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+
43
+ class Command(CommandContextMixIn):
44
+ usage: str = ""
45
+ ignore_require_venv: bool = False
46
+
47
+ def __init__(self, name: str, summary: str, isolated: bool = False) -> None:
48
+ super().__init__()
49
+
50
+ self.name = name
51
+ self.summary = summary
52
+ self.parser = ConfigOptionParser(
53
+ usage=self.usage,
54
+ prog=f"{get_prog()} {name}",
55
+ formatter=UpdatingDefaultsHelpFormatter(),
56
+ add_help_option=False,
57
+ name=name,
58
+ description=self.__doc__,
59
+ isolated=isolated,
60
+ )
61
+
62
+ self.tempdir_registry: Optional[TempDirRegistry] = None
63
+
64
+ # Commands should add options to this option group
65
+ optgroup_name = f"{self.name.capitalize()} Options"
66
+ self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)
67
+
68
+ # Add the general options
69
+ gen_opts = cmdoptions.make_option_group(
70
+ cmdoptions.general_group,
71
+ self.parser,
72
+ )
73
+ self.parser.add_option_group(gen_opts)
74
+
75
+ self.add_options()
76
+
77
+ def add_options(self) -> None:
78
+ pass
79
+
80
+ def handle_pip_version_check(self, options: Values) -> None:
81
+ """
82
+ This is a no-op so that commands by default do not do the pip version
83
+ check.
84
+ """
85
+ # Make sure we do the pip version check if the index_group options
86
+ # are present.
87
+ assert not hasattr(options, "no_index")
88
+
89
+ def run(self, options: Values, args: List[str]) -> int:
90
+ raise NotImplementedError
91
+
92
+ def parse_args(self, args: List[str]) -> Tuple[Values, List[str]]:
93
+ # factored out for testability
94
+ return self.parser.parse_args(args)
95
+
96
+ def main(self, args: List[str]) -> int:
97
+ try:
98
+ with self.main_context():
99
+ return self._main(args)
100
+ finally:
101
+ logging.shutdown()
102
+
103
+ def _main(self, args: List[str]) -> int:
104
+ # We must initialize this before the tempdir manager, otherwise the
105
+ # configuration would not be accessible by the time we clean up the
106
+ # tempdir manager.
107
+ self.tempdir_registry = self.enter_context(tempdir_registry())
108
+ # Intentionally set as early as possible so globally-managed temporary
109
+ # directories are available to the rest of the code.
110
+ self.enter_context(global_tempdir_manager())
111
+
112
+ options, args = self.parse_args(args)
113
+
114
+ # Set verbosity so that it can be used elsewhere.
115
+ self.verbosity = options.verbose - options.quiet
116
+
117
+ level_number = setup_logging(
118
+ verbosity=self.verbosity,
119
+ no_color=options.no_color,
120
+ user_log_file=options.log,
121
+ )
122
+
123
+ # TODO: Try to get these passing down from the command?
124
+ # without resorting to os.environ to hold these.
125
+ # This also affects isolated builds and it should.
126
+
127
+ if options.no_input:
128
+ os.environ["PIP_NO_INPUT"] = "1"
129
+
130
+ if options.exists_action:
131
+ os.environ["PIP_EXISTS_ACTION"] = " ".join(options.exists_action)
132
+
133
+ if options.require_venv and not self.ignore_require_venv:
134
+ # If a venv is required check if it can really be found
135
+ if not running_under_virtualenv():
136
+ logger.critical("Could not find an activated virtualenv (required).")
137
+ sys.exit(VIRTUALENV_NOT_FOUND)
138
+
139
+ if options.cache_dir:
140
+ options.cache_dir = normalize_path(options.cache_dir)
141
+ if not check_path_owner(options.cache_dir):
142
+ logger.warning(
143
+ "The directory '%s' or its parent directory is not owned "
144
+ "or is not writable by the current user. The cache "
145
+ "has been disabled. Check the permissions and owner of "
146
+ "that directory. If executing pip with sudo, you should "
147
+ "use sudo's -H flag.",
148
+ options.cache_dir,
149
+ )
150
+ options.cache_dir = None
151
+
152
+ if "2020-resolver" in options.features_enabled:
153
+ logger.warning(
154
+ "--use-feature=2020-resolver no longer has any effect, "
155
+ "since it is now the default dependency resolver in pip. "
156
+ "This will become an error in pip 21.0."
157
+ )
158
+
159
+ def intercepts_unhandled_exc(
160
+ run_func: Callable[..., int]
161
+ ) -> Callable[..., int]:
162
+ @functools.wraps(run_func)
163
+ def exc_logging_wrapper(*args: Any) -> int:
164
+ try:
165
+ status = run_func(*args)
166
+ assert isinstance(status, int)
167
+ return status
168
+ except DiagnosticPipError as exc:
169
+ logger.error("[present-diagnostic] %s", exc)
170
+ logger.debug("Exception information:", exc_info=True)
171
+
172
+ return ERROR
173
+ except PreviousBuildDirError as exc:
174
+ logger.critical(str(exc))
175
+ logger.debug("Exception information:", exc_info=True)
176
+
177
+ return PREVIOUS_BUILD_DIR_ERROR
178
+ except (
179
+ InstallationError,
180
+ UninstallationError,
181
+ BadCommand,
182
+ NetworkConnectionError,
183
+ ) as exc:
184
+ logger.critical(str(exc))
185
+ logger.debug("Exception information:", exc_info=True)
186
+
187
+ return ERROR
188
+ except CommandError as exc:
189
+ logger.critical("%s", exc)
190
+ logger.debug("Exception information:", exc_info=True)
191
+
192
+ return ERROR
193
+ except BrokenStdoutLoggingError:
194
+ # Bypass our logger and write any remaining messages to
195
+ # stderr because stdout no longer works.
196
+ print("ERROR: Pipe to stdout was broken", file=sys.stderr)
197
+ if level_number <= logging.DEBUG:
198
+ traceback.print_exc(file=sys.stderr)
199
+
200
+ return ERROR
201
+ except KeyboardInterrupt:
202
+ logger.critical("Operation cancelled by user")
203
+ logger.debug("Exception information:", exc_info=True)
204
+
205
+ return ERROR
206
+ except BaseException:
207
+ logger.critical("Exception:", exc_info=True)
208
+
209
+ return UNKNOWN_ERROR
210
+
211
+ return exc_logging_wrapper
212
+
213
+ try:
214
+ if not options.debug_mode:
215
+ run = intercepts_unhandled_exc(self.run)
216
+ else:
217
+ run = self.run
218
+ return run(options, args)
219
+ finally:
220
+ self.handle_pip_version_check(options)
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/cmdoptions.py ADDED
@@ -0,0 +1,1018 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ shared options and groups
3
+
4
+ The principle here is to define options once, but *not* instantiate them
5
+ globally. One reason being that options with action='append' can carry state
6
+ between parses. pip parses general options twice internally, and shouldn't
7
+ pass on state. To be consistent, all options will follow this design.
8
+ """
9
+
10
+ # The following comment should be removed at some point in the future.
11
+ # mypy: strict-optional=False
12
+
13
+ import logging
14
+ import os
15
+ import textwrap
16
+ from functools import partial
17
+ from optparse import SUPPRESS_HELP, Option, OptionGroup, OptionParser, Values
18
+ from textwrap import dedent
19
+ from typing import Any, Callable, Dict, Optional, Tuple
20
+
21
+ from pip._vendor.packaging.utils import canonicalize_name
22
+
23
+ from pip._internal.cli.parser import ConfigOptionParser
24
+ from pip._internal.cli.progress_bars import BAR_TYPES
25
+ from pip._internal.exceptions import CommandError
26
+ from pip._internal.locations import USER_CACHE_DIR, get_src_prefix
27
+ from pip._internal.models.format_control import FormatControl
28
+ from pip._internal.models.index import PyPI
29
+ from pip._internal.models.target_python import TargetPython
30
+ from pip._internal.utils.hashes import STRONG_HASHES
31
+ from pip._internal.utils.misc import strtobool
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+
36
+ def raise_option_error(parser: OptionParser, option: Option, msg: str) -> None:
37
+ """
38
+ Raise an option parsing error using parser.error().
39
+
40
+ Args:
41
+ parser: an OptionParser instance.
42
+ option: an Option instance.
43
+ msg: the error text.
44
+ """
45
+ msg = f"{option} error: {msg}"
46
+ msg = textwrap.fill(" ".join(msg.split()))
47
+ parser.error(msg)
48
+
49
+
50
+ def make_option_group(group: Dict[str, Any], parser: ConfigOptionParser) -> OptionGroup:
51
+ """
52
+ Return an OptionGroup object
53
+ group -- assumed to be dict with 'name' and 'options' keys
54
+ parser -- an optparse Parser
55
+ """
56
+ option_group = OptionGroup(parser, group["name"])
57
+ for option in group["options"]:
58
+ option_group.add_option(option())
59
+ return option_group
60
+
61
+
62
+ def check_install_build_global(
63
+ options: Values, check_options: Optional[Values] = None
64
+ ) -> None:
65
+ """Disable wheels if per-setup.py call options are set.
66
+
67
+ :param options: The OptionParser options to update.
68
+ :param check_options: The options to check, if not supplied defaults to
69
+ options.
70
+ """
71
+ if check_options is None:
72
+ check_options = options
73
+
74
+ def getname(n: str) -> Optional[Any]:
75
+ return getattr(check_options, n, None)
76
+
77
+ names = ["build_options", "global_options", "install_options"]
78
+ if any(map(getname, names)):
79
+ control = options.format_control
80
+ control.disallow_binaries()
81
+ logger.warning(
82
+ "Disabling all use of wheels due to the use of --build-option "
83
+ "/ --global-option / --install-option.",
84
+ )
85
+
86
+
87
+ def check_dist_restriction(options: Values, check_target: bool = False) -> None:
88
+ """Function for determining if custom platform options are allowed.
89
+
90
+ :param options: The OptionParser options.
91
+ :param check_target: Whether or not to check if --target is being used.
92
+ """
93
+ dist_restriction_set = any(
94
+ [
95
+ options.python_version,
96
+ options.platforms,
97
+ options.abis,
98
+ options.implementation,
99
+ ]
100
+ )
101
+
102
+ binary_only = FormatControl(set(), {":all:"})
103
+ sdist_dependencies_allowed = (
104
+ options.format_control != binary_only and not options.ignore_dependencies
105
+ )
106
+
107
+ # Installations or downloads using dist restrictions must not combine
108
+ # source distributions and dist-specific wheels, as they are not
109
+ # guaranteed to be locally compatible.
110
+ if dist_restriction_set and sdist_dependencies_allowed:
111
+ raise CommandError(
112
+ "When restricting platform and interpreter constraints using "
113
+ "--python-version, --platform, --abi, or --implementation, "
114
+ "either --no-deps must be set, or --only-binary=:all: must be "
115
+ "set and --no-binary must not be set (or must be set to "
116
+ ":none:)."
117
+ )
118
+
119
+ if check_target:
120
+ if dist_restriction_set and not options.target_dir:
121
+ raise CommandError(
122
+ "Can not use any platform or abi specific options unless "
123
+ "installing via '--target'"
124
+ )
125
+
126
+
127
+ def _path_option_check(option: Option, opt: str, value: str) -> str:
128
+ return os.path.expanduser(value)
129
+
130
+
131
+ def _package_name_option_check(option: Option, opt: str, value: str) -> str:
132
+ return canonicalize_name(value)
133
+
134
+
135
+ class PipOption(Option):
136
+ TYPES = Option.TYPES + ("path", "package_name")
137
+ TYPE_CHECKER = Option.TYPE_CHECKER.copy()
138
+ TYPE_CHECKER["package_name"] = _package_name_option_check
139
+ TYPE_CHECKER["path"] = _path_option_check
140
+
141
+
142
+ ###########
143
+ # options #
144
+ ###########
145
+
146
+ help_: Callable[..., Option] = partial(
147
+ Option,
148
+ "-h",
149
+ "--help",
150
+ dest="help",
151
+ action="help",
152
+ help="Show help.",
153
+ )
154
+
155
+ debug_mode: Callable[..., Option] = partial(
156
+ Option,
157
+ "--debug",
158
+ dest="debug_mode",
159
+ action="store_true",
160
+ default=False,
161
+ help=(
162
+ "Let unhandled exceptions propagate outside the main subroutine, "
163
+ "instead of logging them to stderr."
164
+ ),
165
+ )
166
+
167
+ isolated_mode: Callable[..., Option] = partial(
168
+ Option,
169
+ "--isolated",
170
+ dest="isolated_mode",
171
+ action="store_true",
172
+ default=False,
173
+ help=(
174
+ "Run pip in an isolated mode, ignoring environment variables and user "
175
+ "configuration."
176
+ ),
177
+ )
178
+
179
+ require_virtualenv: Callable[..., Option] = partial(
180
+ Option,
181
+ "--require-virtualenv",
182
+ "--require-venv",
183
+ dest="require_venv",
184
+ action="store_true",
185
+ default=False,
186
+ help=(
187
+ "Allow pip to only run in a virtual environment; "
188
+ "exit with an error otherwise."
189
+ ),
190
+ )
191
+
192
+ verbose: Callable[..., Option] = partial(
193
+ Option,
194
+ "-v",
195
+ "--verbose",
196
+ dest="verbose",
197
+ action="count",
198
+ default=0,
199
+ help="Give more output. Option is additive, and can be used up to 3 times.",
200
+ )
201
+
202
+ no_color: Callable[..., Option] = partial(
203
+ Option,
204
+ "--no-color",
205
+ dest="no_color",
206
+ action="store_true",
207
+ default=False,
208
+ help="Suppress colored output.",
209
+ )
210
+
211
+ version: Callable[..., Option] = partial(
212
+ Option,
213
+ "-V",
214
+ "--version",
215
+ dest="version",
216
+ action="store_true",
217
+ help="Show version and exit.",
218
+ )
219
+
220
+ quiet: Callable[..., Option] = partial(
221
+ Option,
222
+ "-q",
223
+ "--quiet",
224
+ dest="quiet",
225
+ action="count",
226
+ default=0,
227
+ help=(
228
+ "Give less output. Option is additive, and can be used up to 3"
229
+ " times (corresponding to WARNING, ERROR, and CRITICAL logging"
230
+ " levels)."
231
+ ),
232
+ )
233
+
234
+ progress_bar: Callable[..., Option] = partial(
235
+ Option,
236
+ "--progress-bar",
237
+ dest="progress_bar",
238
+ type="choice",
239
+ choices=list(BAR_TYPES.keys()),
240
+ default="on",
241
+ help=(
242
+ "Specify type of progress to be displayed ["
243
+ + "|".join(BAR_TYPES.keys())
244
+ + "] (default: %default)"
245
+ ),
246
+ )
247
+
248
+ log: Callable[..., Option] = partial(
249
+ PipOption,
250
+ "--log",
251
+ "--log-file",
252
+ "--local-log",
253
+ dest="log",
254
+ metavar="path",
255
+ type="path",
256
+ help="Path to a verbose appending log.",
257
+ )
258
+
259
+ no_input: Callable[..., Option] = partial(
260
+ Option,
261
+ # Don't ask for input
262
+ "--no-input",
263
+ dest="no_input",
264
+ action="store_true",
265
+ default=False,
266
+ help="Disable prompting for input.",
267
+ )
268
+
269
+ proxy: Callable[..., Option] = partial(
270
+ Option,
271
+ "--proxy",
272
+ dest="proxy",
273
+ type="str",
274
+ default="",
275
+ help="Specify a proxy in the form [user:passwd@]proxy.server:port.",
276
+ )
277
+
278
+ retries: Callable[..., Option] = partial(
279
+ Option,
280
+ "--retries",
281
+ dest="retries",
282
+ type="int",
283
+ default=5,
284
+ help="Maximum number of retries each connection should attempt "
285
+ "(default %default times).",
286
+ )
287
+
288
+ timeout: Callable[..., Option] = partial(
289
+ Option,
290
+ "--timeout",
291
+ "--default-timeout",
292
+ metavar="sec",
293
+ dest="timeout",
294
+ type="float",
295
+ default=15,
296
+ help="Set the socket timeout (default %default seconds).",
297
+ )
298
+
299
+
300
+ def exists_action() -> Option:
301
+ return Option(
302
+ # Option when path already exist
303
+ "--exists-action",
304
+ dest="exists_action",
305
+ type="choice",
306
+ choices=["s", "i", "w", "b", "a"],
307
+ default=[],
308
+ action="append",
309
+ metavar="action",
310
+ help="Default action when a path already exists: "
311
+ "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.",
312
+ )
313
+
314
+
315
+ cert: Callable[..., Option] = partial(
316
+ PipOption,
317
+ "--cert",
318
+ dest="cert",
319
+ type="path",
320
+ metavar="path",
321
+ help=(
322
+ "Path to PEM-encoded CA certificate bundle. "
323
+ "If provided, overrides the default. "
324
+ "See 'SSL Certificate Verification' in pip documentation "
325
+ "for more information."
326
+ ),
327
+ )
328
+
329
+ client_cert: Callable[..., Option] = partial(
330
+ PipOption,
331
+ "--client-cert",
332
+ dest="client_cert",
333
+ type="path",
334
+ default=None,
335
+ metavar="path",
336
+ help="Path to SSL client certificate, a single file containing the "
337
+ "private key and the certificate in PEM format.",
338
+ )
339
+
340
+ index_url: Callable[..., Option] = partial(
341
+ Option,
342
+ "-i",
343
+ "--index-url",
344
+ "--pypi-url",
345
+ dest="index_url",
346
+ metavar="URL",
347
+ default=PyPI.simple_url,
348
+ help="Base URL of the Python Package Index (default %default). "
349
+ "This should point to a repository compliant with PEP 503 "
350
+ "(the simple repository API) or a local directory laid out "
351
+ "in the same format.",
352
+ )
353
+
354
+
355
+ def extra_index_url() -> Option:
356
+ return Option(
357
+ "--extra-index-url",
358
+ dest="extra_index_urls",
359
+ metavar="URL",
360
+ action="append",
361
+ default=[],
362
+ help="Extra URLs of package indexes to use in addition to "
363
+ "--index-url. Should follow the same rules as "
364
+ "--index-url.",
365
+ )
366
+
367
+
368
+ no_index: Callable[..., Option] = partial(
369
+ Option,
370
+ "--no-index",
371
+ dest="no_index",
372
+ action="store_true",
373
+ default=False,
374
+ help="Ignore package index (only looking at --find-links URLs instead).",
375
+ )
376
+
377
+
378
+ def find_links() -> Option:
379
+ return Option(
380
+ "-f",
381
+ "--find-links",
382
+ dest="find_links",
383
+ action="append",
384
+ default=[],
385
+ metavar="url",
386
+ help="If a URL or path to an html file, then parse for links to "
387
+ "archives such as sdist (.tar.gz) or wheel (.whl) files. "
388
+ "If a local path or file:// URL that's a directory, "
389
+ "then look for archives in the directory listing. "
390
+ "Links to VCS project URLs are not supported.",
391
+ )
392
+
393
+
394
+ def trusted_host() -> Option:
395
+ return Option(
396
+ "--trusted-host",
397
+ dest="trusted_hosts",
398
+ action="append",
399
+ metavar="HOSTNAME",
400
+ default=[],
401
+ help="Mark this host or host:port pair as trusted, even though it "
402
+ "does not have valid or any HTTPS.",
403
+ )
404
+
405
+
406
+ def constraints() -> Option:
407
+ return Option(
408
+ "-c",
409
+ "--constraint",
410
+ dest="constraints",
411
+ action="append",
412
+ default=[],
413
+ metavar="file",
414
+ help="Constrain versions using the given constraints file. "
415
+ "This option can be used multiple times.",
416
+ )
417
+
418
+
419
+ def requirements() -> Option:
420
+ return Option(
421
+ "-r",
422
+ "--requirement",
423
+ dest="requirements",
424
+ action="append",
425
+ default=[],
426
+ metavar="file",
427
+ help="Install from the given requirements file. "
428
+ "This option can be used multiple times.",
429
+ )
430
+
431
+
432
+ def editable() -> Option:
433
+ return Option(
434
+ "-e",
435
+ "--editable",
436
+ dest="editables",
437
+ action="append",
438
+ default=[],
439
+ metavar="path/url",
440
+ help=(
441
+ "Install a project in editable mode (i.e. setuptools "
442
+ '"develop mode") from a local project path or a VCS url.'
443
+ ),
444
+ )
445
+
446
+
447
+ def _handle_src(option: Option, opt_str: str, value: str, parser: OptionParser) -> None:
448
+ value = os.path.abspath(value)
449
+ setattr(parser.values, option.dest, value)
450
+
451
+
452
+ src: Callable[..., Option] = partial(
453
+ PipOption,
454
+ "--src",
455
+ "--source",
456
+ "--source-dir",
457
+ "--source-directory",
458
+ dest="src_dir",
459
+ type="path",
460
+ metavar="dir",
461
+ default=get_src_prefix(),
462
+ action="callback",
463
+ callback=_handle_src,
464
+ help="Directory to check out editable projects into. "
465
+ 'The default in a virtualenv is "<venv path>/src". '
466
+ 'The default for global installs is "<current dir>/src".',
467
+ )
468
+
469
+
470
+ def _get_format_control(values: Values, option: Option) -> Any:
471
+ """Get a format_control object."""
472
+ return getattr(values, option.dest)
473
+
474
+
475
+ def _handle_no_binary(
476
+ option: Option, opt_str: str, value: str, parser: OptionParser
477
+ ) -> None:
478
+ existing = _get_format_control(parser.values, option)
479
+ FormatControl.handle_mutual_excludes(
480
+ value,
481
+ existing.no_binary,
482
+ existing.only_binary,
483
+ )
484
+
485
+
486
+ def _handle_only_binary(
487
+ option: Option, opt_str: str, value: str, parser: OptionParser
488
+ ) -> None:
489
+ existing = _get_format_control(parser.values, option)
490
+ FormatControl.handle_mutual_excludes(
491
+ value,
492
+ existing.only_binary,
493
+ existing.no_binary,
494
+ )
495
+
496
+
497
+ def no_binary() -> Option:
498
+ format_control = FormatControl(set(), set())
499
+ return Option(
500
+ "--no-binary",
501
+ dest="format_control",
502
+ action="callback",
503
+ callback=_handle_no_binary,
504
+ type="str",
505
+ default=format_control,
506
+ help="Do not use binary packages. Can be supplied multiple times, and "
507
+ 'each time adds to the existing value. Accepts either ":all:" to '
508
+ 'disable all binary packages, ":none:" to empty the set (notice '
509
+ "the colons), or one or more package names with commas between "
510
+ "them (no colons). Note that some packages are tricky to compile "
511
+ "and may fail to install when this option is used on them.",
512
+ )
513
+
514
+
515
+ def only_binary() -> Option:
516
+ format_control = FormatControl(set(), set())
517
+ return Option(
518
+ "--only-binary",
519
+ dest="format_control",
520
+ action="callback",
521
+ callback=_handle_only_binary,
522
+ type="str",
523
+ default=format_control,
524
+ help="Do not use source packages. Can be supplied multiple times, and "
525
+ 'each time adds to the existing value. Accepts either ":all:" to '
526
+ 'disable all source packages, ":none:" to empty the set, or one '
527
+ "or more package names with commas between them. Packages "
528
+ "without binary distributions will fail to install when this "
529
+ "option is used on them.",
530
+ )
531
+
532
+
533
+ platforms: Callable[..., Option] = partial(
534
+ Option,
535
+ "--platform",
536
+ dest="platforms",
537
+ metavar="platform",
538
+ action="append",
539
+ default=None,
540
+ help=(
541
+ "Only use wheels compatible with <platform>. Defaults to the "
542
+ "platform of the running system. Use this option multiple times to "
543
+ "specify multiple platforms supported by the target interpreter."
544
+ ),
545
+ )
546
+
547
+
548
+ # This was made a separate function for unit-testing purposes.
549
+ def _convert_python_version(value: str) -> Tuple[Tuple[int, ...], Optional[str]]:
550
+ """
551
+ Convert a version string like "3", "37", or "3.7.3" into a tuple of ints.
552
+
553
+ :return: A 2-tuple (version_info, error_msg), where `error_msg` is
554
+ non-None if and only if there was a parsing error.
555
+ """
556
+ if not value:
557
+ # The empty string is the same as not providing a value.
558
+ return (None, None)
559
+
560
+ parts = value.split(".")
561
+ if len(parts) > 3:
562
+ return ((), "at most three version parts are allowed")
563
+
564
+ if len(parts) == 1:
565
+ # Then we are in the case of "3" or "37".
566
+ value = parts[0]
567
+ if len(value) > 1:
568
+ parts = [value[0], value[1:]]
569
+
570
+ try:
571
+ version_info = tuple(int(part) for part in parts)
572
+ except ValueError:
573
+ return ((), "each version part must be an integer")
574
+
575
+ return (version_info, None)
576
+
577
+
578
+ def _handle_python_version(
579
+ option: Option, opt_str: str, value: str, parser: OptionParser
580
+ ) -> None:
581
+ """
582
+ Handle a provided --python-version value.
583
+ """
584
+ version_info, error_msg = _convert_python_version(value)
585
+ if error_msg is not None:
586
+ msg = "invalid --python-version value: {!r}: {}".format(
587
+ value,
588
+ error_msg,
589
+ )
590
+ raise_option_error(parser, option=option, msg=msg)
591
+
592
+ parser.values.python_version = version_info
593
+
594
+
595
+ python_version: Callable[..., Option] = partial(
596
+ Option,
597
+ "--python-version",
598
+ dest="python_version",
599
+ metavar="python_version",
600
+ action="callback",
601
+ callback=_handle_python_version,
602
+ type="str",
603
+ default=None,
604
+ help=dedent(
605
+ """\
606
+ The Python interpreter version to use for wheel and "Requires-Python"
607
+ compatibility checks. Defaults to a version derived from the running
608
+ interpreter. The version can be specified using up to three dot-separated
609
+ integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor
610
+ version can also be given as a string without dots (e.g. "37" for 3.7.0).
611
+ """
612
+ ),
613
+ )
614
+
615
+
616
+ implementation: Callable[..., Option] = partial(
617
+ Option,
618
+ "--implementation",
619
+ dest="implementation",
620
+ metavar="implementation",
621
+ default=None,
622
+ help=(
623
+ "Only use wheels compatible with Python "
624
+ "implementation <implementation>, e.g. 'pp', 'jy', 'cp', "
625
+ " or 'ip'. If not specified, then the current "
626
+ "interpreter implementation is used. Use 'py' to force "
627
+ "implementation-agnostic wheels."
628
+ ),
629
+ )
630
+
631
+
632
+ abis: Callable[..., Option] = partial(
633
+ Option,
634
+ "--abi",
635
+ dest="abis",
636
+ metavar="abi",
637
+ action="append",
638
+ default=None,
639
+ help=(
640
+ "Only use wheels compatible with Python abi <abi>, e.g. 'pypy_41'. "
641
+ "If not specified, then the current interpreter abi tag is used. "
642
+ "Use this option multiple times to specify multiple abis supported "
643
+ "by the target interpreter. Generally you will need to specify "
644
+ "--implementation, --platform, and --python-version when using this "
645
+ "option."
646
+ ),
647
+ )
648
+
649
+
650
+ def add_target_python_options(cmd_opts: OptionGroup) -> None:
651
+ cmd_opts.add_option(platforms())
652
+ cmd_opts.add_option(python_version())
653
+ cmd_opts.add_option(implementation())
654
+ cmd_opts.add_option(abis())
655
+
656
+
657
+ def make_target_python(options: Values) -> TargetPython:
658
+ target_python = TargetPython(
659
+ platforms=options.platforms,
660
+ py_version_info=options.python_version,
661
+ abis=options.abis,
662
+ implementation=options.implementation,
663
+ )
664
+
665
+ return target_python
666
+
667
+
668
+ def prefer_binary() -> Option:
669
+ return Option(
670
+ "--prefer-binary",
671
+ dest="prefer_binary",
672
+ action="store_true",
673
+ default=False,
674
+ help="Prefer older binary packages over newer source packages.",
675
+ )
676
+
677
+
678
+ cache_dir: Callable[..., Option] = partial(
679
+ PipOption,
680
+ "--cache-dir",
681
+ dest="cache_dir",
682
+ default=USER_CACHE_DIR,
683
+ metavar="dir",
684
+ type="path",
685
+ help="Store the cache data in <dir>.",
686
+ )
687
+
688
+
689
+ def _handle_no_cache_dir(
690
+ option: Option, opt: str, value: str, parser: OptionParser
691
+ ) -> None:
692
+ """
693
+ Process a value provided for the --no-cache-dir option.
694
+
695
+ This is an optparse.Option callback for the --no-cache-dir option.
696
+ """
697
+ # The value argument will be None if --no-cache-dir is passed via the
698
+ # command-line, since the option doesn't accept arguments. However,
699
+ # the value can be non-None if the option is triggered e.g. by an
700
+ # environment variable, like PIP_NO_CACHE_DIR=true.
701
+ if value is not None:
702
+ # Then parse the string value to get argument error-checking.
703
+ try:
704
+ strtobool(value)
705
+ except ValueError as exc:
706
+ raise_option_error(parser, option=option, msg=str(exc))
707
+
708
+ # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool()
709
+ # converted to 0 (like "false" or "no") caused cache_dir to be disabled
710
+ # rather than enabled (logic would say the latter). Thus, we disable
711
+ # the cache directory not just on values that parse to True, but (for
712
+ # backwards compatibility reasons) also on values that parse to False.
713
+ # In other words, always set it to False if the option is provided in
714
+ # some (valid) form.
715
+ parser.values.cache_dir = False
716
+
717
+
718
+ no_cache: Callable[..., Option] = partial(
719
+ Option,
720
+ "--no-cache-dir",
721
+ dest="cache_dir",
722
+ action="callback",
723
+ callback=_handle_no_cache_dir,
724
+ help="Disable the cache.",
725
+ )
726
+
727
+ no_deps: Callable[..., Option] = partial(
728
+ Option,
729
+ "--no-deps",
730
+ "--no-dependencies",
731
+ dest="ignore_dependencies",
732
+ action="store_true",
733
+ default=False,
734
+ help="Don't install package dependencies.",
735
+ )
736
+
737
+ ignore_requires_python: Callable[..., Option] = partial(
738
+ Option,
739
+ "--ignore-requires-python",
740
+ dest="ignore_requires_python",
741
+ action="store_true",
742
+ help="Ignore the Requires-Python information.",
743
+ )
744
+
745
+ no_build_isolation: Callable[..., Option] = partial(
746
+ Option,
747
+ "--no-build-isolation",
748
+ dest="build_isolation",
749
+ action="store_false",
750
+ default=True,
751
+ help="Disable isolation when building a modern source distribution. "
752
+ "Build dependencies specified by PEP 518 must be already installed "
753
+ "if this option is used.",
754
+ )
755
+
756
+
757
+ def _handle_no_use_pep517(
758
+ option: Option, opt: str, value: str, parser: OptionParser
759
+ ) -> None:
760
+ """
761
+ Process a value provided for the --no-use-pep517 option.
762
+
763
+ This is an optparse.Option callback for the no_use_pep517 option.
764
+ """
765
+ # Since --no-use-pep517 doesn't accept arguments, the value argument
766
+ # will be None if --no-use-pep517 is passed via the command-line.
767
+ # However, the value can be non-None if the option is triggered e.g.
768
+ # by an environment variable, for example "PIP_NO_USE_PEP517=true".
769
+ if value is not None:
770
+ msg = """A value was passed for --no-use-pep517,
771
+ probably using either the PIP_NO_USE_PEP517 environment variable
772
+ or the "no-use-pep517" config file option. Use an appropriate value
773
+ of the PIP_USE_PEP517 environment variable or the "use-pep517"
774
+ config file option instead.
775
+ """
776
+ raise_option_error(parser, option=option, msg=msg)
777
+
778
+ # Otherwise, --no-use-pep517 was passed via the command-line.
779
+ parser.values.use_pep517 = False
780
+
781
+
782
+ use_pep517: Any = partial(
783
+ Option,
784
+ "--use-pep517",
785
+ dest="use_pep517",
786
+ action="store_true",
787
+ default=None,
788
+ help="Use PEP 517 for building source distributions "
789
+ "(use --no-use-pep517 to force legacy behaviour).",
790
+ )
791
+
792
+ no_use_pep517: Any = partial(
793
+ Option,
794
+ "--no-use-pep517",
795
+ dest="use_pep517",
796
+ action="callback",
797
+ callback=_handle_no_use_pep517,
798
+ default=None,
799
+ help=SUPPRESS_HELP,
800
+ )
801
+
802
+ install_options: Callable[..., Option] = partial(
803
+ Option,
804
+ "--install-option",
805
+ dest="install_options",
806
+ action="append",
807
+ metavar="options",
808
+ help="Extra arguments to be supplied to the setup.py install "
809
+ 'command (use like --install-option="--install-scripts=/usr/local/'
810
+ 'bin"). Use multiple --install-option options to pass multiple '
811
+ "options to setup.py install. If you are using an option with a "
812
+ "directory path, be sure to use absolute path.",
813
+ )
814
+
815
+ build_options: Callable[..., Option] = partial(
816
+ Option,
817
+ "--build-option",
818
+ dest="build_options",
819
+ metavar="options",
820
+ action="append",
821
+ help="Extra arguments to be supplied to 'setup.py bdist_wheel'.",
822
+ )
823
+
824
+ global_options: Callable[..., Option] = partial(
825
+ Option,
826
+ "--global-option",
827
+ dest="global_options",
828
+ action="append",
829
+ metavar="options",
830
+ help="Extra global options to be supplied to the setup.py "
831
+ "call before the install or bdist_wheel command.",
832
+ )
833
+
834
+ no_clean: Callable[..., Option] = partial(
835
+ Option,
836
+ "--no-clean",
837
+ action="store_true",
838
+ default=False,
839
+ help="Don't clean up build directories.",
840
+ )
841
+
842
+ pre: Callable[..., Option] = partial(
843
+ Option,
844
+ "--pre",
845
+ action="store_true",
846
+ default=False,
847
+ help="Include pre-release and development versions. By default, "
848
+ "pip only finds stable versions.",
849
+ )
850
+
851
+ disable_pip_version_check: Callable[..., Option] = partial(
852
+ Option,
853
+ "--disable-pip-version-check",
854
+ dest="disable_pip_version_check",
855
+ action="store_true",
856
+ default=True,
857
+ help="Don't periodically check PyPI to determine whether a new version "
858
+ "of pip is available for download. Implied with --no-index.",
859
+ )
860
+
861
+
862
+ def _handle_merge_hash(
863
+ option: Option, opt_str: str, value: str, parser: OptionParser
864
+ ) -> None:
865
+ """Given a value spelled "algo:digest", append the digest to a list
866
+ pointed to in a dict by the algo name."""
867
+ if not parser.values.hashes:
868
+ parser.values.hashes = {}
869
+ try:
870
+ algo, digest = value.split(":", 1)
871
+ except ValueError:
872
+ parser.error(
873
+ "Arguments to {} must be a hash name " # noqa
874
+ "followed by a value, like --hash=sha256:"
875
+ "abcde...".format(opt_str)
876
+ )
877
+ if algo not in STRONG_HASHES:
878
+ parser.error(
879
+ "Allowed hash algorithms for {} are {}.".format( # noqa
880
+ opt_str, ", ".join(STRONG_HASHES)
881
+ )
882
+ )
883
+ parser.values.hashes.setdefault(algo, []).append(digest)
884
+
885
+
886
+ hash: Callable[..., Option] = partial(
887
+ Option,
888
+ "--hash",
889
+ # Hash values eventually end up in InstallRequirement.hashes due to
890
+ # __dict__ copying in process_line().
891
+ dest="hashes",
892
+ action="callback",
893
+ callback=_handle_merge_hash,
894
+ type="string",
895
+ help="Verify that the package's archive matches this "
896
+ "hash before installing. Example: --hash=sha256:abcdef...",
897
+ )
898
+
899
+
900
+ require_hashes: Callable[..., Option] = partial(
901
+ Option,
902
+ "--require-hashes",
903
+ dest="require_hashes",
904
+ action="store_true",
905
+ default=False,
906
+ help="Require a hash to check each requirement against, for "
907
+ "repeatable installs. This option is implied when any package in a "
908
+ "requirements file has a --hash option.",
909
+ )
910
+
911
+
912
+ list_path: Callable[..., Option] = partial(
913
+ PipOption,
914
+ "--path",
915
+ dest="path",
916
+ type="path",
917
+ action="append",
918
+ help="Restrict to the specified installation path for listing "
919
+ "packages (can be used multiple times).",
920
+ )
921
+
922
+
923
+ def check_list_path_option(options: Values) -> None:
924
+ if options.path and (options.user or options.local):
925
+ raise CommandError("Cannot combine '--path' with '--user' or '--local'")
926
+
927
+
928
+ list_exclude: Callable[..., Option] = partial(
929
+ PipOption,
930
+ "--exclude",
931
+ dest="excludes",
932
+ action="append",
933
+ metavar="package",
934
+ type="package_name",
935
+ help="Exclude specified package from the output",
936
+ )
937
+
938
+
939
+ no_python_version_warning: Callable[..., Option] = partial(
940
+ Option,
941
+ "--no-python-version-warning",
942
+ dest="no_python_version_warning",
943
+ action="store_true",
944
+ default=False,
945
+ help="Silence deprecation warnings for upcoming unsupported Pythons.",
946
+ )
947
+
948
+
949
+ use_new_feature: Callable[..., Option] = partial(
950
+ Option,
951
+ "--use-feature",
952
+ dest="features_enabled",
953
+ metavar="feature",
954
+ action="append",
955
+ default=[],
956
+ choices=["2020-resolver", "fast-deps", "in-tree-build"],
957
+ help="Enable new functionality, that may be backward incompatible.",
958
+ )
959
+
960
+ use_deprecated_feature: Callable[..., Option] = partial(
961
+ Option,
962
+ "--use-deprecated",
963
+ dest="deprecated_features_enabled",
964
+ metavar="feature",
965
+ action="append",
966
+ default=[],
967
+ choices=[
968
+ "legacy-resolver",
969
+ "out-of-tree-build",
970
+ "backtrack-on-build-failures",
971
+ "html5lib",
972
+ ],
973
+ help=("Enable deprecated functionality, that will be removed in the future."),
974
+ )
975
+
976
+
977
+ ##########
978
+ # groups #
979
+ ##########
980
+
981
+ general_group: Dict[str, Any] = {
982
+ "name": "General Options",
983
+ "options": [
984
+ help_,
985
+ debug_mode,
986
+ isolated_mode,
987
+ require_virtualenv,
988
+ verbose,
989
+ version,
990
+ quiet,
991
+ log,
992
+ no_input,
993
+ proxy,
994
+ retries,
995
+ timeout,
996
+ exists_action,
997
+ trusted_host,
998
+ cert,
999
+ client_cert,
1000
+ cache_dir,
1001
+ no_cache,
1002
+ disable_pip_version_check,
1003
+ no_color,
1004
+ no_python_version_warning,
1005
+ use_new_feature,
1006
+ use_deprecated_feature,
1007
+ ],
1008
+ }
1009
+
1010
+ index_group: Dict[str, Any] = {
1011
+ "name": "Package Index Options",
1012
+ "options": [
1013
+ index_url,
1014
+ extra_index_url,
1015
+ no_index,
1016
+ find_links,
1017
+ ],
1018
+ }
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/command_context.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import ExitStack, contextmanager
2
+ from typing import ContextManager, Iterator, TypeVar
3
+
4
+ _T = TypeVar("_T", covariant=True)
5
+
6
+
7
+ class CommandContextMixIn:
8
+ def __init__(self) -> None:
9
+ super().__init__()
10
+ self._in_main_context = False
11
+ self._main_context = ExitStack()
12
+
13
+ @contextmanager
14
+ def main_context(self) -> Iterator[None]:
15
+ assert not self._in_main_context
16
+
17
+ self._in_main_context = True
18
+ try:
19
+ with self._main_context:
20
+ yield
21
+ finally:
22
+ self._in_main_context = False
23
+
24
+ def enter_context(self, context_provider: ContextManager[_T]) -> _T:
25
+ assert self._in_main_context
26
+
27
+ return self._main_context.enter_context(context_provider)
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/main_parser.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A single place for constructing and exposing the main parser
2
+ """
3
+
4
+ import os
5
+ import sys
6
+ from typing import List, Tuple
7
+
8
+ from pip._internal.cli import cmdoptions
9
+ from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
10
+ from pip._internal.commands import commands_dict, get_similar_commands
11
+ from pip._internal.exceptions import CommandError
12
+ from pip._internal.utils.misc import get_pip_version, get_prog
13
+
14
+ __all__ = ["create_main_parser", "parse_command"]
15
+
16
+
17
+ def create_main_parser() -> ConfigOptionParser:
18
+ """Creates and returns the main parser for pip's CLI"""
19
+
20
+ parser = ConfigOptionParser(
21
+ usage="\n%prog <command> [options]",
22
+ add_help_option=False,
23
+ formatter=UpdatingDefaultsHelpFormatter(),
24
+ name="global",
25
+ prog=get_prog(),
26
+ )
27
+ parser.disable_interspersed_args()
28
+
29
+ parser.version = get_pip_version()
30
+
31
+ # add the general options
32
+ gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)
33
+ parser.add_option_group(gen_opts)
34
+
35
+ # so the help formatter knows
36
+ parser.main = True # type: ignore
37
+
38
+ # create command listing for description
39
+ description = [""] + [
40
+ f"{name:27} {command_info.summary}"
41
+ for name, command_info in commands_dict.items()
42
+ ]
43
+ parser.description = "\n".join(description)
44
+
45
+ return parser
46
+
47
+
48
+ def parse_command(args: List[str]) -> Tuple[str, List[str]]:
49
+ parser = create_main_parser()
50
+
51
+ # Note: parser calls disable_interspersed_args(), so the result of this
52
+ # call is to split the initial args into the general options before the
53
+ # subcommand and everything else.
54
+ # For example:
55
+ # args: ['--timeout=5', 'install', '--user', 'INITools']
56
+ # general_options: ['--timeout==5']
57
+ # args_else: ['install', '--user', 'INITools']
58
+ general_options, args_else = parser.parse_args(args)
59
+
60
+ # --version
61
+ if general_options.version:
62
+ sys.stdout.write(parser.version)
63
+ sys.stdout.write(os.linesep)
64
+ sys.exit()
65
+
66
+ # pip || pip help -> print_help()
67
+ if not args_else or (args_else[0] == "help" and len(args_else) == 1):
68
+ parser.print_help()
69
+ sys.exit()
70
+
71
+ # the subcommand name
72
+ cmd_name = args_else[0]
73
+
74
+ if cmd_name not in commands_dict:
75
+ guess = get_similar_commands(cmd_name)
76
+
77
+ msg = [f'unknown command "{cmd_name}"']
78
+ if guess:
79
+ msg.append(f'maybe you meant "{guess}"')
80
+
81
+ raise CommandError(" - ".join(msg))
82
+
83
+ # all the args without the subcommand
84
+ cmd_args = args[:]
85
+ cmd_args.remove(cmd_name)
86
+
87
+ return cmd_name, cmd_args
scripts/myenv/lib/python3.10/site-packages/pip/_internal/cli/parser.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base option parser setup"""
2
+
3
+ import logging
4
+ import optparse
5
+ import shutil
6
+ import sys
7
+ import textwrap
8
+ from contextlib import suppress
9
+ from typing import Any, Dict, Iterator, List, Tuple
10
+
11
+ from pip._internal.cli.status_codes import UNKNOWN_ERROR
12
+ from pip._internal.configuration import Configuration, ConfigurationError
13
+ from pip._internal.utils.misc import redact_auth_from_url, strtobool
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
19
+ """A prettier/less verbose help formatter for optparse."""
20
+
21
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
22
+ # help position must be aligned with __init__.parseopts.description
23
+ kwargs["max_help_position"] = 30
24
+ kwargs["indent_increment"] = 1
25
+ kwargs["width"] = shutil.get_terminal_size()[0] - 2
26
+ super().__init__(*args, **kwargs)
27
+
28
+ def format_option_strings(self, option: optparse.Option) -> str:
29
+ return self._format_option_strings(option)
30
+
31
+ def _format_option_strings(
32
+ self, option: optparse.Option, mvarfmt: str = " <{}>", optsep: str = ", "
33
+ ) -> str:
34
+ """
35
+ Return a comma-separated list of option strings and metavars.
36
+
37
+ :param option: tuple of (short opt, long opt), e.g: ('-f', '--format')
38
+ :param mvarfmt: metavar format string
39
+ :param optsep: separator
40
+ """
41
+ opts = []
42
+
43
+ if option._short_opts:
44
+ opts.append(option._short_opts[0])
45
+ if option._long_opts:
46
+ opts.append(option._long_opts[0])
47
+ if len(opts) > 1:
48
+ opts.insert(1, optsep)
49
+
50
+ if option.takes_value():
51
+ assert option.dest is not None
52
+ metavar = option.metavar or option.dest.lower()
53
+ opts.append(mvarfmt.format(metavar.lower()))
54
+
55
+ return "".join(opts)
56
+
57
+ def format_heading(self, heading: str) -> str:
58
+ if heading == "Options":
59
+ return ""
60
+ return heading + ":\n"
61
+
62
+ def format_usage(self, usage: str) -> str:
63
+ """
64
+ Ensure there is only one newline between usage and the first heading
65
+ if there is no description.
66
+ """
67
+ msg = "\nUsage: {}\n".format(self.indent_lines(textwrap.dedent(usage), " "))
68
+ return msg
69
+
70
+ def format_description(self, description: str) -> str:
71
+ # leave full control over description to us
72
+ if description:
73
+ if hasattr(self.parser, "main"):
74
+ label = "Commands"
75
+ else:
76
+ label = "Description"
77
+ # some doc strings have initial newlines, some don't
78
+ description = description.lstrip("\n")
79
+ # some doc strings have final newlines and spaces, some don't
80
+ description = description.rstrip()
81
+ # dedent, then reindent
82
+ description = self.indent_lines(textwrap.dedent(description), " ")
83
+ description = f"{label}:\n{description}\n"
84
+ return description
85
+ else:
86
+ return ""
87
+
88
+ def format_epilog(self, epilog: str) -> str:
89
+ # leave full control over epilog to us
90
+ if epilog:
91
+ return epilog
92
+ else:
93
+ return ""
94
+
95
+ def indent_lines(self, text: str, indent: str) -> str:
96
+ new_lines = [indent + line for line in text.split("\n")]
97
+ return "\n".join(new_lines)
98
+
99
+
100
+ class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):
101
+ """Custom help formatter for use in ConfigOptionParser.
102
+
103
+ This is updates the defaults before expanding them, allowing
104
+ them to show up correctly in the help listing.
105
+
106
+ Also redact auth from url type options
107
+ """
108
+
109
+ def expand_default(self, option: optparse.Option) -> str:
110
+ default_values = None
111
+ if self.parser is not None:
112
+ assert isinstance(self.parser, ConfigOptionParser)
113
+ self.parser._update_defaults(self.parser.defaults)
114
+ assert option.dest is not None
115
+ default_values = self.parser.defaults.get(option.dest)
116
+ help_text = super().expand_default(option)
117
+
118
+ if default_values and option.metavar == "URL":
119
+ if isinstance(default_values, str):
120
+ default_values = [default_values]
121
+
122
+ # If its not a list, we should abort and just return the help text
123
+ if not isinstance(default_values, list):
124
+ default_values = []
125
+
126
+ for val in default_values:
127
+ help_text = help_text.replace(val, redact_auth_from_url(val))
128
+
129
+ return help_text
130
+
131
+
132
+ class CustomOptionParser(optparse.OptionParser):
133
+ def insert_option_group(
134
+ self, idx: int, *args: Any, **kwargs: Any
135
+ ) -> optparse.OptionGroup:
136
+ """Insert an OptionGroup at a given position."""
137
+ group = self.add_option_group(*args, **kwargs)
138
+
139
+ self.option_groups.pop()
140
+ self.option_groups.insert(idx, group)
141
+
142
+ return group
143
+
144
+ @property
145
+ def option_list_all(self) -> List[optparse.Option]:
146
+ """Get a list of all options, including those in option groups."""
147
+ res = self.option_list[:]
148
+ for i in self.option_groups:
149
+ res.extend(i.option_list)
150
+
151
+ return res
152
+
153
+
154
+ class ConfigOptionParser(CustomOptionParser):
155
+ """Custom option parser which updates its defaults by checking the
156
+ configuration files and environmental variables"""
157
+
158
+ def __init__(
159
+ self,
160
+ *args: Any,
161
+ name: str,
162
+ isolated: bool = False,
163
+ **kwargs: Any,
164
+ ) -> None:
165
+ self.name = name
166
+ self.config = Configuration(isolated)
167
+
168
+ assert self.name
169
+ super().__init__(*args, **kwargs)
170
+
171
+ def check_default(self, option: optparse.Option, key: str, val: Any) -> Any:
172
+ try:
173
+ return option.check_value(key, val)
174
+ except optparse.OptionValueError as exc:
175
+ print(f"An error occurred during configuration: {exc}")
176
+ sys.exit(3)
177
+
178
+ def _get_ordered_configuration_items(self) -> Iterator[Tuple[str, Any]]:
179
+ # Configuration gives keys in an unordered manner. Order them.
180
+ override_order = ["global", self.name, ":env:"]
181
+
182
+ # Pool the options into different groups
183
+ section_items: Dict[str, List[Tuple[str, Any]]] = {
184
+ name: [] for name in override_order
185
+ }
186
+ for section_key, val in self.config.items():
187
+ # ignore empty values
188
+ if not val:
189
+ logger.debug(
190
+ "Ignoring configuration key '%s' as it's value is empty.",
191
+ section_key,
192
+ )
193
+ continue
194
+
195
+ section, key = section_key.split(".", 1)
196
+ if section in override_order:
197
+ section_items[section].append((key, val))
198
+
199
+ # Yield each group in their override order
200
+ for section in override_order:
201
+ for key, val in section_items[section]:
202
+ yield key, val
203
+
204
+ def _update_defaults(self, defaults: Dict[str, Any]) -> Dict[str, Any]:
205
+ """Updates the given defaults with values from the config files and
206
+ the environ. Does a little special handling for certain types of
207
+ options (lists)."""
208
+
209
+ # Accumulate complex default state.
210
+ self.values = optparse.Values(self.defaults)
211
+ late_eval = set()
212
+ # Then set the options with those values
213
+ for key, val in self._get_ordered_configuration_items():
214
+ # '--' because configuration supports only long names
215
+ option = self.get_option("--" + key)
216
+
217
+ # Ignore options not present in this parser. E.g. non-globals put
218
+ # in [global] by users that want them to apply to all applicable
219
+ # commands.
220
+ if option is None:
221
+ continue
222
+
223
+ assert option.dest is not None
224
+
225
+ if option.action in ("store_true", "store_false"):
226
+ try:
227
+ val = strtobool(val)
228
+ except ValueError:
229
+ self.error(
230
+ "{} is not a valid value for {} option, " # noqa
231
+ "please specify a boolean value like yes/no, "
232
+ "true/false or 1/0 instead.".format(val, key)
233
+ )
234
+ elif option.action == "count":
235
+ with suppress(ValueError):
236
+ val = strtobool(val)
237
+ with suppress(ValueError):
238
+ val = int(val)
239
+ if not isinstance(val, int) or val < 0:
240
+ self.error(
241
+ "{} is not a valid value for {} option, " # noqa
242
+ "please instead specify either a non-negative integer "
243
+ "or a boolean value like yes/no or false/true "
244
+ "which is equivalent to 1/0.".format(val, key)
245
+ )
246
+ elif option.action == "append":
247
+ val = val.split()
248
+ val = [self.check_default(option, key, v) for v in val]
249
+ elif option.action == "callback":
250
+ assert option.callback is not None
251
+ late_eval.add(option.dest)
252
+ opt_str = option.get_opt_string()
253
+ val = option.convert_value(opt_str, val)
254
+ # From take_action
255
+ args = option.callback_args or ()
256
+ kwargs = option.callback_kwargs or {}
257
+ option.callback(option, opt_str, val, self, *args, **kwargs)
258
+ else:
259
+ val = self.check_default(option, key, val)
260
+
261
+ defaults[option.dest] = val
262
+
263
+ for key in late_eval:
264
+ defaults[key] = getattr(self.values, key)
265
+ self.values = None
266
+ return defaults
267
+
268
+ def get_default_values(self) -> optparse.Values:
269
+ """Overriding to make updating the defaults after instantiation of
270
+ the option parser possible, _update_defaults() does the dirty work."""
271
+ if not self.process_default_values:
272
+ # Old, pre-Optik 1.5 behaviour.
273
+ return optparse.Values(self.defaults)
274
+
275
+ # Load the configuration, or error out in case of an error
276
+ try:
277
+ self.config.load()
278
+ except ConfigurationError as err:
279
+ self.exit(UNKNOWN_ERROR, str(err))
280
+
281
+ defaults = self._update_defaults(self.defaults.copy()) # ours
282
+ for option in self._get_all_options():
283
+ assert option.dest is not None
284
+ default = defaults.get(option.dest)
285
+ if isinstance(default, str):
286
+ opt_str = option.get_opt_string()
287
+ defaults[option.dest] = option.check_value(opt_str, default)
288
+ return optparse.Values(defaults)
289
+
290
+ def error(self, msg: str) -> None:
291
+ self.print_usage(sys.stderr)
292
+ self.exit(UNKNOWN_ERROR, f"{msg}\n")
scripts/myenv/lib/python3.10/site-packages/pip/_internal/metadata/__init__.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+
3
+ from .base import BaseDistribution, BaseEnvironment, FilesystemWheel, MemoryWheel, Wheel
4
+
5
+ __all__ = [
6
+ "BaseDistribution",
7
+ "BaseEnvironment",
8
+ "FilesystemWheel",
9
+ "MemoryWheel",
10
+ "Wheel",
11
+ "get_default_environment",
12
+ "get_environment",
13
+ "get_wheel_distribution",
14
+ ]
15
+
16
+
17
+ def get_default_environment() -> BaseEnvironment:
18
+ """Get the default representation for the current environment.
19
+
20
+ This returns an Environment instance from the chosen backend. The default
21
+ Environment instance should be built from ``sys.path`` and may use caching
22
+ to share instance state accorss calls.
23
+ """
24
+ from .pkg_resources import Environment
25
+
26
+ return Environment.default()
27
+
28
+
29
+ def get_environment(paths: Optional[List[str]]) -> BaseEnvironment:
30
+ """Get a representation of the environment specified by ``paths``.
31
+
32
+ This returns an Environment instance from the chosen backend based on the
33
+ given import paths. The backend must build a fresh instance representing
34
+ the state of installed distributions when this function is called.
35
+ """
36
+ from .pkg_resources import Environment
37
+
38
+ return Environment.from_paths(paths)
39
+
40
+
41
+ def get_directory_distribution(directory: str) -> BaseDistribution:
42
+ """Get the distribution metadata representation in the specified directory.
43
+
44
+ This returns a Distribution instance from the chosen backend based on
45
+ the given on-disk ``.dist-info`` directory.
46
+ """
47
+ from .pkg_resources import Distribution
48
+
49
+ return Distribution.from_directory(directory)
50
+
51
+
52
+ def get_wheel_distribution(wheel: Wheel, canonical_name: str) -> BaseDistribution:
53
+ """Get the representation of the specified wheel's distribution metadata.
54
+
55
+ This returns a Distribution instance from the chosen backend based on
56
+ the given wheel's ``.dist-info`` directory.
57
+
58
+ :param canonical_name: Normalized project name of the given wheel.
59
+ """
60
+ from .pkg_resources import Distribution
61
+
62
+ return Distribution.from_wheel(wheel, canonical_name)
scripts/myenv/lib/python3.10/site-packages/pip/_internal/metadata/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.3 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/metadata/__pycache__/base.cpython-310.pyc ADDED
Binary file (20.8 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/metadata/__pycache__/pkg_resources.cpython-310.pyc ADDED
Binary file (9.87 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/metadata/base.py ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ import email.message
3
+ import json
4
+ import logging
5
+ import pathlib
6
+ import re
7
+ import zipfile
8
+ from typing import (
9
+ IO,
10
+ TYPE_CHECKING,
11
+ Collection,
12
+ Container,
13
+ Iterable,
14
+ Iterator,
15
+ List,
16
+ Optional,
17
+ Tuple,
18
+ Union,
19
+ )
20
+
21
+ from pip._vendor.packaging.requirements import Requirement
22
+ from pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet
23
+ from pip._vendor.packaging.utils import NormalizedName
24
+ from pip._vendor.packaging.version import LegacyVersion, Version
25
+
26
+ from pip._internal.exceptions import NoneMetadataError
27
+ from pip._internal.locations import site_packages, user_site
28
+ from pip._internal.models.direct_url import (
29
+ DIRECT_URL_METADATA_NAME,
30
+ DirectUrl,
31
+ DirectUrlValidationError,
32
+ )
33
+ from pip._internal.utils.compat import stdlib_pkgs # TODO: Move definition here.
34
+ from pip._internal.utils.egg_link import (
35
+ egg_link_path_from_location,
36
+ egg_link_path_from_sys_path,
37
+ )
38
+ from pip._internal.utils.misc import is_local, normalize_path
39
+ from pip._internal.utils.urls import url_to_path
40
+
41
+ if TYPE_CHECKING:
42
+ from typing import Protocol
43
+ else:
44
+ Protocol = object
45
+
46
+ DistributionVersion = Union[LegacyVersion, Version]
47
+
48
+ InfoPath = Union[str, pathlib.PurePosixPath]
49
+
50
+ logger = logging.getLogger(__name__)
51
+
52
+
53
+ class BaseEntryPoint(Protocol):
54
+ @property
55
+ def name(self) -> str:
56
+ raise NotImplementedError()
57
+
58
+ @property
59
+ def value(self) -> str:
60
+ raise NotImplementedError()
61
+
62
+ @property
63
+ def group(self) -> str:
64
+ raise NotImplementedError()
65
+
66
+
67
+ def _convert_installed_files_path(
68
+ entry: Tuple[str, ...],
69
+ info: Tuple[str, ...],
70
+ ) -> str:
71
+ """Convert a legacy installed-files.txt path into modern RECORD path.
72
+
73
+ The legacy format stores paths relative to the info directory, while the
74
+ modern format stores paths relative to the package root, e.g. the
75
+ site-packages directory.
76
+
77
+ :param entry: Path parts of the installed-files.txt entry.
78
+ :param info: Path parts of the egg-info directory relative to package root.
79
+ :returns: The converted entry.
80
+
81
+ For best compatibility with symlinks, this does not use ``abspath()`` or
82
+ ``Path.resolve()``, but tries to work with path parts:
83
+
84
+ 1. While ``entry`` starts with ``..``, remove the equal amounts of parts
85
+ from ``info``; if ``info`` is empty, start appending ``..`` instead.
86
+ 2. Join the two directly.
87
+ """
88
+ while entry and entry[0] == "..":
89
+ if not info or info[-1] == "..":
90
+ info += ("..",)
91
+ else:
92
+ info = info[:-1]
93
+ entry = entry[1:]
94
+ return str(pathlib.Path(*info, *entry))
95
+
96
+
97
+ class BaseDistribution(Protocol):
98
+ def __repr__(self) -> str:
99
+ return f"{self.raw_name} {self.version} ({self.location})"
100
+
101
+ def __str__(self) -> str:
102
+ return f"{self.raw_name} {self.version}"
103
+
104
+ @property
105
+ def location(self) -> Optional[str]:
106
+ """Where the distribution is loaded from.
107
+
108
+ A string value is not necessarily a filesystem path, since distributions
109
+ can be loaded from other sources, e.g. arbitrary zip archives. ``None``
110
+ means the distribution is created in-memory.
111
+
112
+ Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
113
+ this is a symbolic link, we want to preserve the relative path between
114
+ it and files in the distribution.
115
+ """
116
+ raise NotImplementedError()
117
+
118
+ @property
119
+ def editable_project_location(self) -> Optional[str]:
120
+ """The project location for editable distributions.
121
+
122
+ This is the directory where pyproject.toml or setup.py is located.
123
+ None if the distribution is not installed in editable mode.
124
+ """
125
+ # TODO: this property is relatively costly to compute, memoize it ?
126
+ direct_url = self.direct_url
127
+ if direct_url:
128
+ if direct_url.is_local_editable():
129
+ return url_to_path(direct_url.url)
130
+ else:
131
+ # Search for an .egg-link file by walking sys.path, as it was
132
+ # done before by dist_is_editable().
133
+ egg_link_path = egg_link_path_from_sys_path(self.raw_name)
134
+ if egg_link_path:
135
+ # TODO: get project location from second line of egg_link file
136
+ # (https://github.com/pypa/pip/issues/10243)
137
+ return self.location
138
+ return None
139
+
140
+ @property
141
+ def installed_location(self) -> Optional[str]:
142
+ """The distribution's "installed" location.
143
+
144
+ This should generally be a ``site-packages`` directory. This is
145
+ usually ``dist.location``, except for legacy develop-installed packages,
146
+ where ``dist.location`` is the source code location, and this is where
147
+ the ``.egg-link`` file is.
148
+
149
+ The returned location is normalized (in particular, with symlinks removed).
150
+ """
151
+ egg_link = egg_link_path_from_location(self.raw_name)
152
+ if egg_link:
153
+ location = egg_link
154
+ elif self.location:
155
+ location = self.location
156
+ else:
157
+ return None
158
+ return normalize_path(location)
159
+
160
+ @property
161
+ def info_location(self) -> Optional[str]:
162
+ """Location of the .[egg|dist]-info directory or file.
163
+
164
+ Similarly to ``location``, a string value is not necessarily a
165
+ filesystem path. ``None`` means the distribution is created in-memory.
166
+
167
+ For a modern .dist-info installation on disk, this should be something
168
+ like ``{location}/{raw_name}-{version}.dist-info``.
169
+
170
+ Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
171
+ this is a symbolic link, we want to preserve the relative path between
172
+ it and other files in the distribution.
173
+ """
174
+ raise NotImplementedError()
175
+
176
+ @property
177
+ def installed_by_distutils(self) -> bool:
178
+ """Whether this distribution is installed with legacy distutils format.
179
+
180
+ A distribution installed with "raw" distutils not patched by setuptools
181
+ uses one single file at ``info_location`` to store metadata. We need to
182
+ treat this specially on uninstallation.
183
+ """
184
+ info_location = self.info_location
185
+ if not info_location:
186
+ return False
187
+ return pathlib.Path(info_location).is_file()
188
+
189
+ @property
190
+ def installed_as_egg(self) -> bool:
191
+ """Whether this distribution is installed as an egg.
192
+
193
+ This usually indicates the distribution was installed by (older versions
194
+ of) easy_install.
195
+ """
196
+ location = self.location
197
+ if not location:
198
+ return False
199
+ return location.endswith(".egg")
200
+
201
+ @property
202
+ def installed_with_setuptools_egg_info(self) -> bool:
203
+ """Whether this distribution is installed with the ``.egg-info`` format.
204
+
205
+ This usually indicates the distribution was installed with setuptools
206
+ with an old pip version or with ``single-version-externally-managed``.
207
+
208
+ Note that this ensure the metadata store is a directory. distutils can
209
+ also installs an ``.egg-info``, but as a file, not a directory. This
210
+ property is *False* for that case. Also see ``installed_by_distutils``.
211
+ """
212
+ info_location = self.info_location
213
+ if not info_location:
214
+ return False
215
+ if not info_location.endswith(".egg-info"):
216
+ return False
217
+ return pathlib.Path(info_location).is_dir()
218
+
219
+ @property
220
+ def installed_with_dist_info(self) -> bool:
221
+ """Whether this distribution is installed with the "modern format".
222
+
223
+ This indicates a "modern" installation, e.g. storing metadata in the
224
+ ``.dist-info`` directory. This applies to installations made by
225
+ setuptools (but through pip, not directly), or anything using the
226
+ standardized build backend interface (PEP 517).
227
+ """
228
+ info_location = self.info_location
229
+ if not info_location:
230
+ return False
231
+ if not info_location.endswith(".dist-info"):
232
+ return False
233
+ return pathlib.Path(info_location).is_dir()
234
+
235
+ @property
236
+ def canonical_name(self) -> NormalizedName:
237
+ raise NotImplementedError()
238
+
239
+ @property
240
+ def version(self) -> DistributionVersion:
241
+ raise NotImplementedError()
242
+
243
+ @property
244
+ def setuptools_filename(self) -> str:
245
+ """Convert a project name to its setuptools-compatible filename.
246
+
247
+ This is a copy of ``pkg_resources.to_filename()`` for compatibility.
248
+ """
249
+ return self.raw_name.replace("-", "_")
250
+
251
+ @property
252
+ def direct_url(self) -> Optional[DirectUrl]:
253
+ """Obtain a DirectUrl from this distribution.
254
+
255
+ Returns None if the distribution has no `direct_url.json` metadata,
256
+ or if `direct_url.json` is invalid.
257
+ """
258
+ try:
259
+ content = self.read_text(DIRECT_URL_METADATA_NAME)
260
+ except FileNotFoundError:
261
+ return None
262
+ try:
263
+ return DirectUrl.from_json(content)
264
+ except (
265
+ UnicodeDecodeError,
266
+ json.JSONDecodeError,
267
+ DirectUrlValidationError,
268
+ ) as e:
269
+ logger.warning(
270
+ "Error parsing %s for %s: %s",
271
+ DIRECT_URL_METADATA_NAME,
272
+ self.canonical_name,
273
+ e,
274
+ )
275
+ return None
276
+
277
+ @property
278
+ def installer(self) -> str:
279
+ try:
280
+ installer_text = self.read_text("INSTALLER")
281
+ except (OSError, ValueError, NoneMetadataError):
282
+ return "" # Fail silently if the installer file cannot be read.
283
+ for line in installer_text.splitlines():
284
+ cleaned_line = line.strip()
285
+ if cleaned_line:
286
+ return cleaned_line
287
+ return ""
288
+
289
+ @property
290
+ def editable(self) -> bool:
291
+ return bool(self.editable_project_location)
292
+
293
+ @property
294
+ def local(self) -> bool:
295
+ """If distribution is installed in the current virtual environment.
296
+
297
+ Always True if we're not in a virtualenv.
298
+ """
299
+ if self.installed_location is None:
300
+ return False
301
+ return is_local(self.installed_location)
302
+
303
+ @property
304
+ def in_usersite(self) -> bool:
305
+ if self.installed_location is None or user_site is None:
306
+ return False
307
+ return self.installed_location.startswith(normalize_path(user_site))
308
+
309
+ @property
310
+ def in_site_packages(self) -> bool:
311
+ if self.installed_location is None or site_packages is None:
312
+ return False
313
+ return self.installed_location.startswith(normalize_path(site_packages))
314
+
315
+ def is_file(self, path: InfoPath) -> bool:
316
+ """Check whether an entry in the info directory is a file."""
317
+ raise NotImplementedError()
318
+
319
+ def iterdir(self, path: InfoPath) -> Iterator[pathlib.PurePosixPath]:
320
+ """Iterate through a directory in the info directory.
321
+
322
+ Each item yielded would be a path relative to the info directory.
323
+
324
+ :raise FileNotFoundError: If ``name`` does not exist in the directory.
325
+ :raise NotADirectoryError: If ``name`` does not point to a directory.
326
+ """
327
+ raise NotImplementedError()
328
+
329
+ def read_text(self, path: InfoPath) -> str:
330
+ """Read a file in the info directory.
331
+
332
+ :raise FileNotFoundError: If ``name`` does not exist in the directory.
333
+ :raise NoneMetadataError: If ``name`` exists in the info directory, but
334
+ cannot be read.
335
+ """
336
+ raise NotImplementedError()
337
+
338
+ def iter_entry_points(self) -> Iterable[BaseEntryPoint]:
339
+ raise NotImplementedError()
340
+
341
+ @property
342
+ def metadata(self) -> email.message.Message:
343
+ """Metadata of distribution parsed from e.g. METADATA or PKG-INFO.
344
+
345
+ This should return an empty message if the metadata file is unavailable.
346
+
347
+ :raises NoneMetadataError: If the metadata file is available, but does
348
+ not contain valid metadata.
349
+ """
350
+ raise NotImplementedError()
351
+
352
+ @property
353
+ def metadata_version(self) -> Optional[str]:
354
+ """Value of "Metadata-Version:" in distribution metadata, if available."""
355
+ return self.metadata.get("Metadata-Version")
356
+
357
+ @property
358
+ def raw_name(self) -> str:
359
+ """Value of "Name:" in distribution metadata."""
360
+ # The metadata should NEVER be missing the Name: key, but if it somehow
361
+ # does, fall back to the known canonical name.
362
+ return self.metadata.get("Name", self.canonical_name)
363
+
364
+ @property
365
+ def requires_python(self) -> SpecifierSet:
366
+ """Value of "Requires-Python:" in distribution metadata.
367
+
368
+ If the key does not exist or contains an invalid value, an empty
369
+ SpecifierSet should be returned.
370
+ """
371
+ value = self.metadata.get("Requires-Python")
372
+ if value is None:
373
+ return SpecifierSet()
374
+ try:
375
+ # Convert to str to satisfy the type checker; this can be a Header object.
376
+ spec = SpecifierSet(str(value))
377
+ except InvalidSpecifier as e:
378
+ message = "Package %r has an invalid Requires-Python: %s"
379
+ logger.warning(message, self.raw_name, e)
380
+ return SpecifierSet()
381
+ return spec
382
+
383
+ def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:
384
+ """Dependencies of this distribution.
385
+
386
+ For modern .dist-info distributions, this is the collection of
387
+ "Requires-Dist:" entries in distribution metadata.
388
+ """
389
+ raise NotImplementedError()
390
+
391
+ def iter_provided_extras(self) -> Iterable[str]:
392
+ """Extras provided by this distribution.
393
+
394
+ For modern .dist-info distributions, this is the collection of
395
+ "Provides-Extra:" entries in distribution metadata.
396
+ """
397
+ raise NotImplementedError()
398
+
399
+ def _iter_declared_entries_from_record(self) -> Optional[Iterator[str]]:
400
+ try:
401
+ text = self.read_text("RECORD")
402
+ except FileNotFoundError:
403
+ return None
404
+ # This extra Path-str cast normalizes entries.
405
+ return (str(pathlib.Path(row[0])) for row in csv.reader(text.splitlines()))
406
+
407
+ def _iter_declared_entries_from_legacy(self) -> Optional[Iterator[str]]:
408
+ try:
409
+ text = self.read_text("installed-files.txt")
410
+ except FileNotFoundError:
411
+ return None
412
+ paths = (p for p in text.splitlines(keepends=False) if p)
413
+ root = self.location
414
+ info = self.info_location
415
+ if root is None or info is None:
416
+ return paths
417
+ try:
418
+ info_rel = pathlib.Path(info).relative_to(root)
419
+ except ValueError: # info is not relative to root.
420
+ return paths
421
+ if not info_rel.parts: # info *is* root.
422
+ return paths
423
+ return (
424
+ _convert_installed_files_path(pathlib.Path(p).parts, info_rel.parts)
425
+ for p in paths
426
+ )
427
+
428
+ def iter_declared_entries(self) -> Optional[Iterator[str]]:
429
+ """Iterate through file entires declared in this distribution.
430
+
431
+ For modern .dist-info distributions, this is the files listed in the
432
+ ``RECORD`` metadata file. For legacy setuptools distributions, this
433
+ comes from ``installed-files.txt``, with entries normalized to be
434
+ compatible with the format used by ``RECORD``.
435
+
436
+ :return: An iterator for listed entries, or None if the distribution
437
+ contains neither ``RECORD`` nor ``installed-files.txt``.
438
+ """
439
+ return (
440
+ self._iter_declared_entries_from_record()
441
+ or self._iter_declared_entries_from_legacy()
442
+ )
443
+
444
+
445
+ class BaseEnvironment:
446
+ """An environment containing distributions to introspect."""
447
+
448
+ @classmethod
449
+ def default(cls) -> "BaseEnvironment":
450
+ raise NotImplementedError()
451
+
452
+ @classmethod
453
+ def from_paths(cls, paths: Optional[List[str]]) -> "BaseEnvironment":
454
+ raise NotImplementedError()
455
+
456
+ def get_distribution(self, name: str) -> Optional["BaseDistribution"]:
457
+ """Given a requirement name, return the installed distributions.
458
+
459
+ The name may not be normalized. The implementation must canonicalize
460
+ it for lookup.
461
+ """
462
+ raise NotImplementedError()
463
+
464
+ def _iter_distributions(self) -> Iterator["BaseDistribution"]:
465
+ """Iterate through installed distributions.
466
+
467
+ This function should be implemented by subclass, but never called
468
+ directly. Use the public ``iter_distribution()`` instead, which
469
+ implements additional logic to make sure the distributions are valid.
470
+ """
471
+ raise NotImplementedError()
472
+
473
+ def iter_distributions(self) -> Iterator["BaseDistribution"]:
474
+ """Iterate through installed distributions."""
475
+ for dist in self._iter_distributions():
476
+ # Make sure the distribution actually comes from a valid Python
477
+ # packaging distribution. Pip's AdjacentTempDirectory leaves folders
478
+ # e.g. ``~atplotlib.dist-info`` if cleanup was interrupted. The
479
+ # valid project name pattern is taken from PEP 508.
480
+ project_name_valid = re.match(
481
+ r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$",
482
+ dist.canonical_name,
483
+ flags=re.IGNORECASE,
484
+ )
485
+ if not project_name_valid:
486
+ logger.warning(
487
+ "Ignoring invalid distribution %s (%s)",
488
+ dist.canonical_name,
489
+ dist.location,
490
+ )
491
+ continue
492
+ yield dist
493
+
494
+ def iter_installed_distributions(
495
+ self,
496
+ local_only: bool = True,
497
+ skip: Container[str] = stdlib_pkgs,
498
+ include_editables: bool = True,
499
+ editables_only: bool = False,
500
+ user_only: bool = False,
501
+ ) -> Iterator[BaseDistribution]:
502
+ """Return a list of installed distributions.
503
+
504
+ :param local_only: If True (default), only return installations
505
+ local to the current virtualenv, if in a virtualenv.
506
+ :param skip: An iterable of canonicalized project names to ignore;
507
+ defaults to ``stdlib_pkgs``.
508
+ :param include_editables: If False, don't report editables.
509
+ :param editables_only: If True, only report editables.
510
+ :param user_only: If True, only report installations in the user
511
+ site directory.
512
+ """
513
+ it = self.iter_distributions()
514
+ if local_only:
515
+ it = (d for d in it if d.local)
516
+ if not include_editables:
517
+ it = (d for d in it if not d.editable)
518
+ if editables_only:
519
+ it = (d for d in it if d.editable)
520
+ if user_only:
521
+ it = (d for d in it if d.in_usersite)
522
+ return (d for d in it if d.canonical_name not in skip)
523
+
524
+
525
+ class Wheel(Protocol):
526
+ location: str
527
+
528
+ def as_zipfile(self) -> zipfile.ZipFile:
529
+ raise NotImplementedError()
530
+
531
+
532
+ class FilesystemWheel(Wheel):
533
+ def __init__(self, location: str) -> None:
534
+ self.location = location
535
+
536
+ def as_zipfile(self) -> zipfile.ZipFile:
537
+ return zipfile.ZipFile(self.location, allowZip64=True)
538
+
539
+
540
+ class MemoryWheel(Wheel):
541
+ def __init__(self, location: str, stream: IO[bytes]) -> None:
542
+ self.location = location
543
+ self.stream = stream
544
+
545
+ def as_zipfile(self) -> zipfile.ZipFile:
546
+ return zipfile.ZipFile(self.stream, allowZip64=True)
scripts/myenv/lib/python3.10/site-packages/pip/_internal/metadata/pkg_resources.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import email.message
2
+ import email.parser
3
+ import logging
4
+ import os
5
+ import pathlib
6
+ import zipfile
7
+ from typing import Collection, Iterable, Iterator, List, Mapping, NamedTuple, Optional
8
+
9
+ from pip._vendor import pkg_resources
10
+ from pip._vendor.packaging.requirements import Requirement
11
+ from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
12
+ from pip._vendor.packaging.version import parse as parse_version
13
+
14
+ from pip._internal.exceptions import InvalidWheel, NoneMetadataError, UnsupportedWheel
15
+ from pip._internal.utils.misc import display_path
16
+ from pip._internal.utils.wheel import parse_wheel, read_wheel_metadata_file
17
+
18
+ from .base import (
19
+ BaseDistribution,
20
+ BaseEntryPoint,
21
+ BaseEnvironment,
22
+ DistributionVersion,
23
+ InfoPath,
24
+ Wheel,
25
+ )
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ class EntryPoint(NamedTuple):
31
+ name: str
32
+ value: str
33
+ group: str
34
+
35
+
36
+ class WheelMetadata:
37
+ """IMetadataProvider that reads metadata files from a dictionary.
38
+
39
+ This also maps metadata decoding exceptions to our internal exception type.
40
+ """
41
+
42
+ def __init__(self, metadata: Mapping[str, bytes], wheel_name: str) -> None:
43
+ self._metadata = metadata
44
+ self._wheel_name = wheel_name
45
+
46
+ def has_metadata(self, name: str) -> bool:
47
+ return name in self._metadata
48
+
49
+ def get_metadata(self, name: str) -> str:
50
+ try:
51
+ return self._metadata[name].decode()
52
+ except UnicodeDecodeError as e:
53
+ # Augment the default error with the origin of the file.
54
+ raise UnsupportedWheel(
55
+ f"Error decoding metadata for {self._wheel_name}: {e} in {name} file"
56
+ )
57
+
58
+ def get_metadata_lines(self, name: str) -> Iterable[str]:
59
+ return pkg_resources.yield_lines(self.get_metadata(name))
60
+
61
+ def metadata_isdir(self, name: str) -> bool:
62
+ return False
63
+
64
+ def metadata_listdir(self, name: str) -> List[str]:
65
+ return []
66
+
67
+ def run_script(self, script_name: str, namespace: str) -> None:
68
+ pass
69
+
70
+
71
+ class Distribution(BaseDistribution):
72
+ def __init__(self, dist: pkg_resources.Distribution) -> None:
73
+ self._dist = dist
74
+
75
+ @classmethod
76
+ def from_directory(cls, directory: str) -> "Distribution":
77
+ dist_dir = directory.rstrip(os.sep)
78
+
79
+ # Build a PathMetadata object, from path to metadata. :wink:
80
+ base_dir, dist_dir_name = os.path.split(dist_dir)
81
+ metadata = pkg_resources.PathMetadata(base_dir, dist_dir)
82
+
83
+ # Determine the correct Distribution object type.
84
+ if dist_dir.endswith(".egg-info"):
85
+ dist_cls = pkg_resources.Distribution
86
+ dist_name = os.path.splitext(dist_dir_name)[0]
87
+ else:
88
+ assert dist_dir.endswith(".dist-info")
89
+ dist_cls = pkg_resources.DistInfoDistribution
90
+ dist_name = os.path.splitext(dist_dir_name)[0].split("-")[0]
91
+
92
+ dist = dist_cls(base_dir, project_name=dist_name, metadata=metadata)
93
+ return cls(dist)
94
+
95
+ @classmethod
96
+ def from_wheel(cls, wheel: Wheel, name: str) -> "Distribution":
97
+ """Load the distribution from a given wheel.
98
+
99
+ :raises InvalidWheel: Whenever loading of the wheel causes a
100
+ :py:exc:`zipfile.BadZipFile` exception to be thrown.
101
+ :raises UnsupportedWheel: If the wheel is a valid zip, but malformed
102
+ internally.
103
+ """
104
+ try:
105
+ with wheel.as_zipfile() as zf:
106
+ info_dir, _ = parse_wheel(zf, name)
107
+ metadata_text = {
108
+ path.split("/", 1)[-1]: read_wheel_metadata_file(zf, path)
109
+ for path in zf.namelist()
110
+ if path.startswith(f"{info_dir}/")
111
+ }
112
+ except zipfile.BadZipFile as e:
113
+ raise InvalidWheel(wheel.location, name) from e
114
+ except UnsupportedWheel as e:
115
+ raise UnsupportedWheel(f"{name} has an invalid wheel, {e}")
116
+ dist = pkg_resources.DistInfoDistribution(
117
+ location=wheel.location,
118
+ metadata=WheelMetadata(metadata_text, wheel.location),
119
+ project_name=name,
120
+ )
121
+ return cls(dist)
122
+
123
+ @property
124
+ def location(self) -> Optional[str]:
125
+ return self._dist.location
126
+
127
+ @property
128
+ def info_location(self) -> Optional[str]:
129
+ return self._dist.egg_info
130
+
131
+ @property
132
+ def installed_by_distutils(self) -> bool:
133
+ # A distutils-installed distribution is provided by FileMetadata. This
134
+ # provider has a "path" attribute not present anywhere else. Not the
135
+ # best introspection logic, but pip has been doing this for a long time.
136
+ try:
137
+ return bool(self._dist._provider.path)
138
+ except AttributeError:
139
+ return False
140
+
141
+ @property
142
+ def canonical_name(self) -> NormalizedName:
143
+ return canonicalize_name(self._dist.project_name)
144
+
145
+ @property
146
+ def version(self) -> DistributionVersion:
147
+ return parse_version(self._dist.version)
148
+
149
+ def is_file(self, path: InfoPath) -> bool:
150
+ return self._dist.has_metadata(str(path))
151
+
152
+ def iterdir(self, path: InfoPath) -> Iterator[pathlib.PurePosixPath]:
153
+ name = str(path)
154
+ if not self._dist.has_metadata(name):
155
+ raise FileNotFoundError(name)
156
+ if not self._dist.isdir(name):
157
+ raise NotADirectoryError(name)
158
+ for child in self._dist.metadata_listdir(name):
159
+ yield pathlib.PurePosixPath(path, child)
160
+
161
+ def read_text(self, path: InfoPath) -> str:
162
+ name = str(path)
163
+ if not self._dist.has_metadata(name):
164
+ raise FileNotFoundError(name)
165
+ content = self._dist.get_metadata(name)
166
+ if content is None:
167
+ raise NoneMetadataError(self, name)
168
+ return content
169
+
170
+ def iter_entry_points(self) -> Iterable[BaseEntryPoint]:
171
+ for group, entries in self._dist.get_entry_map().items():
172
+ for name, entry_point in entries.items():
173
+ name, _, value = str(entry_point).partition("=")
174
+ yield EntryPoint(name=name.strip(), value=value.strip(), group=group)
175
+
176
+ @property
177
+ def metadata(self) -> email.message.Message:
178
+ """
179
+ :raises NoneMetadataError: if the distribution reports `has_metadata()`
180
+ True but `get_metadata()` returns None.
181
+ """
182
+ if isinstance(self._dist, pkg_resources.DistInfoDistribution):
183
+ metadata_name = "METADATA"
184
+ else:
185
+ metadata_name = "PKG-INFO"
186
+ try:
187
+ metadata = self.read_text(metadata_name)
188
+ except FileNotFoundError:
189
+ if self.location:
190
+ displaying_path = display_path(self.location)
191
+ else:
192
+ displaying_path = repr(self.location)
193
+ logger.warning("No metadata found in %s", displaying_path)
194
+ metadata = ""
195
+ feed_parser = email.parser.FeedParser()
196
+ feed_parser.feed(metadata)
197
+ return feed_parser.close()
198
+
199
+ def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:
200
+ if extras: # pkg_resources raises on invalid extras, so we sanitize.
201
+ extras = frozenset(extras).intersection(self._dist.extras)
202
+ return self._dist.requires(extras)
203
+
204
+ def iter_provided_extras(self) -> Iterable[str]:
205
+ return self._dist.extras
206
+
207
+
208
+ class Environment(BaseEnvironment):
209
+ def __init__(self, ws: pkg_resources.WorkingSet) -> None:
210
+ self._ws = ws
211
+
212
+ @classmethod
213
+ def default(cls) -> BaseEnvironment:
214
+ return cls(pkg_resources.working_set)
215
+
216
+ @classmethod
217
+ def from_paths(cls, paths: Optional[List[str]]) -> BaseEnvironment:
218
+ return cls(pkg_resources.WorkingSet(paths))
219
+
220
+ def _search_distribution(self, name: str) -> Optional[BaseDistribution]:
221
+ """Find a distribution matching the ``name`` in the environment.
222
+
223
+ This searches from *all* distributions available in the environment, to
224
+ match the behavior of ``pkg_resources.get_distribution()``.
225
+ """
226
+ canonical_name = canonicalize_name(name)
227
+ for dist in self.iter_distributions():
228
+ if dist.canonical_name == canonical_name:
229
+ return dist
230
+ return None
231
+
232
+ def get_distribution(self, name: str) -> Optional[BaseDistribution]:
233
+ # Search the distribution by looking through the working set.
234
+ dist = self._search_distribution(name)
235
+ if dist:
236
+ return dist
237
+
238
+ # If distribution could not be found, call working_set.require to
239
+ # update the working set, and try to find the distribution again.
240
+ # This might happen for e.g. when you install a package twice, once
241
+ # using setup.py develop and again using setup.py install. Now when
242
+ # running pip uninstall twice, the package gets removed from the
243
+ # working set in the first uninstall, so we have to populate the
244
+ # working set again so that pip knows about it and the packages gets
245
+ # picked up and is successfully uninstalled the second time too.
246
+ try:
247
+ # We didn't pass in any version specifiers, so this can never
248
+ # raise pkg_resources.VersionConflict.
249
+ self._ws.require(name)
250
+ except pkg_resources.DistributionNotFound:
251
+ return None
252
+ return self._search_distribution(name)
253
+
254
+ def _iter_distributions(self) -> Iterator[BaseDistribution]:
255
+ for dist in self._ws:
256
+ yield Distribution(dist)
scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """Contains purely network-related utilities.
2
+ """
scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (251 Bytes). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/auth.cpython-310.pyc ADDED
Binary file (7.52 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/cache.cpython-310.pyc ADDED
Binary file (2.93 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/download.cpython-310.pyc ADDED
Binary file (5.5 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/lazy_wheel.cpython-310.pyc ADDED
Binary file (8.41 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/session.cpython-310.pyc ADDED
Binary file (10.7 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/utils.cpython-310.pyc ADDED
Binary file (1.45 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/xmlrpc.cpython-310.pyc ADDED
Binary file (2.06 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/auth.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Network Authentication Helpers
2
+
3
+ Contains interface (MultiDomainBasicAuth) and associated glue code for
4
+ providing credentials in the context of network requests.
5
+ """
6
+
7
+ import urllib.parse
8
+ from typing import Any, Dict, List, Optional, Tuple
9
+
10
+ from pip._vendor.requests.auth import AuthBase, HTTPBasicAuth
11
+ from pip._vendor.requests.models import Request, Response
12
+ from pip._vendor.requests.utils import get_netrc_auth
13
+
14
+ from pip._internal.utils.logging import getLogger
15
+ from pip._internal.utils.misc import (
16
+ ask,
17
+ ask_input,
18
+ ask_password,
19
+ remove_auth_from_url,
20
+ split_auth_netloc_from_url,
21
+ )
22
+ from pip._internal.vcs.versioncontrol import AuthInfo
23
+
24
+ logger = getLogger(__name__)
25
+
26
+ Credentials = Tuple[str, str, str]
27
+
28
+ try:
29
+ import keyring
30
+ except ImportError:
31
+ keyring = None # type: ignore[assignment]
32
+ except Exception as exc:
33
+ logger.warning(
34
+ "Keyring is skipped due to an exception: %s",
35
+ str(exc),
36
+ )
37
+ keyring = None # type: ignore[assignment]
38
+
39
+
40
+ def get_keyring_auth(url: Optional[str], username: Optional[str]) -> Optional[AuthInfo]:
41
+ """Return the tuple auth for a given url from keyring."""
42
+ global keyring
43
+ if not url or not keyring:
44
+ return None
45
+
46
+ try:
47
+ try:
48
+ get_credential = keyring.get_credential
49
+ except AttributeError:
50
+ pass
51
+ else:
52
+ logger.debug("Getting credentials from keyring for %s", url)
53
+ cred = get_credential(url, username)
54
+ if cred is not None:
55
+ return cred.username, cred.password
56
+ return None
57
+
58
+ if username:
59
+ logger.debug("Getting password from keyring for %s", url)
60
+ password = keyring.get_password(url, username)
61
+ if password:
62
+ return username, password
63
+
64
+ except Exception as exc:
65
+ logger.warning(
66
+ "Keyring is skipped due to an exception: %s",
67
+ str(exc),
68
+ )
69
+ keyring = None # type: ignore[assignment]
70
+ return None
71
+
72
+
73
+ class MultiDomainBasicAuth(AuthBase):
74
+ def __init__(
75
+ self, prompting: bool = True, index_urls: Optional[List[str]] = None
76
+ ) -> None:
77
+ self.prompting = prompting
78
+ self.index_urls = index_urls
79
+ self.passwords: Dict[str, AuthInfo] = {}
80
+ # When the user is prompted to enter credentials and keyring is
81
+ # available, we will offer to save them. If the user accepts,
82
+ # this value is set to the credentials they entered. After the
83
+ # request authenticates, the caller should call
84
+ # ``save_credentials`` to save these.
85
+ self._credentials_to_save: Optional[Credentials] = None
86
+
87
+ def _get_index_url(self, url: str) -> Optional[str]:
88
+ """Return the original index URL matching the requested URL.
89
+
90
+ Cached or dynamically generated credentials may work against
91
+ the original index URL rather than just the netloc.
92
+
93
+ The provided url should have had its username and password
94
+ removed already. If the original index url had credentials then
95
+ they will be included in the return value.
96
+
97
+ Returns None if no matching index was found, or if --no-index
98
+ was specified by the user.
99
+ """
100
+ if not url or not self.index_urls:
101
+ return None
102
+
103
+ for u in self.index_urls:
104
+ prefix = remove_auth_from_url(u).rstrip("/") + "/"
105
+ if url.startswith(prefix):
106
+ return u
107
+ return None
108
+
109
+ def _get_new_credentials(
110
+ self,
111
+ original_url: str,
112
+ allow_netrc: bool = True,
113
+ allow_keyring: bool = False,
114
+ ) -> AuthInfo:
115
+ """Find and return credentials for the specified URL."""
116
+ # Split the credentials and netloc from the url.
117
+ url, netloc, url_user_password = split_auth_netloc_from_url(
118
+ original_url,
119
+ )
120
+
121
+ # Start with the credentials embedded in the url
122
+ username, password = url_user_password
123
+ if username is not None and password is not None:
124
+ logger.debug("Found credentials in url for %s", netloc)
125
+ return url_user_password
126
+
127
+ # Find a matching index url for this request
128
+ index_url = self._get_index_url(url)
129
+ if index_url:
130
+ # Split the credentials from the url.
131
+ index_info = split_auth_netloc_from_url(index_url)
132
+ if index_info:
133
+ index_url, _, index_url_user_password = index_info
134
+ logger.debug("Found index url %s", index_url)
135
+
136
+ # If an index URL was found, try its embedded credentials
137
+ if index_url and index_url_user_password[0] is not None:
138
+ username, password = index_url_user_password
139
+ if username is not None and password is not None:
140
+ logger.debug("Found credentials in index url for %s", netloc)
141
+ return index_url_user_password
142
+
143
+ # Get creds from netrc if we still don't have them
144
+ if allow_netrc:
145
+ netrc_auth = get_netrc_auth(original_url)
146
+ if netrc_auth:
147
+ logger.debug("Found credentials in netrc for %s", netloc)
148
+ return netrc_auth
149
+
150
+ # If we don't have a password and keyring is available, use it.
151
+ if allow_keyring:
152
+ # The index url is more specific than the netloc, so try it first
153
+ # fmt: off
154
+ kr_auth = (
155
+ get_keyring_auth(index_url, username) or
156
+ get_keyring_auth(netloc, username)
157
+ )
158
+ # fmt: on
159
+ if kr_auth:
160
+ logger.debug("Found credentials in keyring for %s", netloc)
161
+ return kr_auth
162
+
163
+ return username, password
164
+
165
+ def _get_url_and_credentials(
166
+ self, original_url: str
167
+ ) -> Tuple[str, Optional[str], Optional[str]]:
168
+ """Return the credentials to use for the provided URL.
169
+
170
+ If allowed, netrc and keyring may be used to obtain the
171
+ correct credentials.
172
+
173
+ Returns (url_without_credentials, username, password). Note
174
+ that even if the original URL contains credentials, this
175
+ function may return a different username and password.
176
+ """
177
+ url, netloc, _ = split_auth_netloc_from_url(original_url)
178
+
179
+ # Try to get credentials from original url
180
+ username, password = self._get_new_credentials(original_url)
181
+
182
+ # If credentials not found, use any stored credentials for this netloc.
183
+ # Do this if either the username or the password is missing.
184
+ # This accounts for the situation in which the user has specified
185
+ # the username in the index url, but the password comes from keyring.
186
+ if (username is None or password is None) and netloc in self.passwords:
187
+ un, pw = self.passwords[netloc]
188
+ # It is possible that the cached credentials are for a different username,
189
+ # in which case the cache should be ignored.
190
+ if username is None or username == un:
191
+ username, password = un, pw
192
+
193
+ if username is not None or password is not None:
194
+ # Convert the username and password if they're None, so that
195
+ # this netloc will show up as "cached" in the conditional above.
196
+ # Further, HTTPBasicAuth doesn't accept None, so it makes sense to
197
+ # cache the value that is going to be used.
198
+ username = username or ""
199
+ password = password or ""
200
+
201
+ # Store any acquired credentials.
202
+ self.passwords[netloc] = (username, password)
203
+
204
+ assert (
205
+ # Credentials were found
206
+ (username is not None and password is not None)
207
+ # Credentials were not found
208
+ or (username is None and password is None)
209
+ ), f"Could not load credentials from url: {original_url}"
210
+
211
+ return url, username, password
212
+
213
+ def __call__(self, req: Request) -> Request:
214
+ # Get credentials for this request
215
+ url, username, password = self._get_url_and_credentials(req.url)
216
+
217
+ # Set the url of the request to the url without any credentials
218
+ req.url = url
219
+
220
+ if username is not None and password is not None:
221
+ # Send the basic auth with this request
222
+ req = HTTPBasicAuth(username, password)(req)
223
+
224
+ # Attach a hook to handle 401 responses
225
+ req.register_hook("response", self.handle_401)
226
+
227
+ return req
228
+
229
+ # Factored out to allow for easy patching in tests
230
+ def _prompt_for_password(
231
+ self, netloc: str
232
+ ) -> Tuple[Optional[str], Optional[str], bool]:
233
+ username = ask_input(f"User for {netloc}: ")
234
+ if not username:
235
+ return None, None, False
236
+ auth = get_keyring_auth(netloc, username)
237
+ if auth and auth[0] is not None and auth[1] is not None:
238
+ return auth[0], auth[1], False
239
+ password = ask_password("Password: ")
240
+ return username, password, True
241
+
242
+ # Factored out to allow for easy patching in tests
243
+ def _should_save_password_to_keyring(self) -> bool:
244
+ if not keyring:
245
+ return False
246
+ return ask("Save credentials to keyring [y/N]: ", ["y", "n"]) == "y"
247
+
248
+ def handle_401(self, resp: Response, **kwargs: Any) -> Response:
249
+ # We only care about 401 responses, anything else we want to just
250
+ # pass through the actual response
251
+ if resp.status_code != 401:
252
+ return resp
253
+
254
+ # We are not able to prompt the user so simply return the response
255
+ if not self.prompting:
256
+ return resp
257
+
258
+ parsed = urllib.parse.urlparse(resp.url)
259
+
260
+ # Query the keyring for credentials:
261
+ username, password = self._get_new_credentials(
262
+ resp.url,
263
+ allow_netrc=False,
264
+ allow_keyring=True,
265
+ )
266
+
267
+ # Prompt the user for a new username and password
268
+ save = False
269
+ if not username and not password:
270
+ username, password, save = self._prompt_for_password(parsed.netloc)
271
+
272
+ # Store the new username and password to use for future requests
273
+ self._credentials_to_save = None
274
+ if username is not None and password is not None:
275
+ self.passwords[parsed.netloc] = (username, password)
276
+
277
+ # Prompt to save the password to keyring
278
+ if save and self._should_save_password_to_keyring():
279
+ self._credentials_to_save = (parsed.netloc, username, password)
280
+
281
+ # Consume content and release the original connection to allow our new
282
+ # request to reuse the same one.
283
+ resp.content
284
+ resp.raw.release_conn()
285
+
286
+ # Add our new username and password to the request
287
+ req = HTTPBasicAuth(username or "", password or "")(resp.request)
288
+ req.register_hook("response", self.warn_on_401)
289
+
290
+ # On successful request, save the credentials that were used to
291
+ # keyring. (Note that if the user responded "no" above, this member
292
+ # is not set and nothing will be saved.)
293
+ if self._credentials_to_save:
294
+ req.register_hook("response", self.save_credentials)
295
+
296
+ # Send our new request
297
+ new_resp = resp.connection.send(req, **kwargs)
298
+ new_resp.history.append(resp)
299
+
300
+ return new_resp
301
+
302
+ def warn_on_401(self, resp: Response, **kwargs: Any) -> None:
303
+ """Response callback to warn about incorrect credentials."""
304
+ if resp.status_code == 401:
305
+ logger.warning(
306
+ "401 Error, Credentials not correct for %s",
307
+ resp.request.url,
308
+ )
309
+
310
+ def save_credentials(self, resp: Response, **kwargs: Any) -> None:
311
+ """Response callback to save credentials on success."""
312
+ assert keyring is not None, "should never reach here without keyring"
313
+ if not keyring:
314
+ return
315
+
316
+ creds = self._credentials_to_save
317
+ self._credentials_to_save = None
318
+ if creds and resp.status_code < 400:
319
+ try:
320
+ logger.info("Saving credentials to keyring")
321
+ keyring.set_password(*creds)
322
+ except Exception:
323
+ logger.exception("Failed to save credentials")
scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/cache.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP cache implementation.
2
+ """
3
+
4
+ import os
5
+ from contextlib import contextmanager
6
+ from typing import Iterator, Optional
7
+
8
+ from pip._vendor.cachecontrol.cache import BaseCache
9
+ from pip._vendor.cachecontrol.caches import FileCache
10
+ from pip._vendor.requests.models import Response
11
+
12
+ from pip._internal.utils.filesystem import adjacent_tmp_file, replace
13
+ from pip._internal.utils.misc import ensure_dir
14
+
15
+
16
+ def is_from_cache(response: Response) -> bool:
17
+ return getattr(response, "from_cache", False)
18
+
19
+
20
+ @contextmanager
21
+ def suppressed_cache_errors() -> Iterator[None]:
22
+ """If we can't access the cache then we can just skip caching and process
23
+ requests as if caching wasn't enabled.
24
+ """
25
+ try:
26
+ yield
27
+ except OSError:
28
+ pass
29
+
30
+
31
+ class SafeFileCache(BaseCache):
32
+ """
33
+ A file based cache which is safe to use even when the target directory may
34
+ not be accessible or writable.
35
+ """
36
+
37
+ def __init__(self, directory: str) -> None:
38
+ assert directory is not None, "Cache directory must not be None."
39
+ super().__init__()
40
+ self.directory = directory
41
+
42
+ def _get_cache_path(self, name: str) -> str:
43
+ # From cachecontrol.caches.file_cache.FileCache._fn, brought into our
44
+ # class for backwards-compatibility and to avoid using a non-public
45
+ # method.
46
+ hashed = FileCache.encode(name)
47
+ parts = list(hashed[:5]) + [hashed]
48
+ return os.path.join(self.directory, *parts)
49
+
50
+ def get(self, key: str) -> Optional[bytes]:
51
+ path = self._get_cache_path(key)
52
+ with suppressed_cache_errors():
53
+ with open(path, "rb") as f:
54
+ return f.read()
55
+
56
+ def set(self, key: str, value: bytes, expires: Optional[int] = None) -> None:
57
+ path = self._get_cache_path(key)
58
+ with suppressed_cache_errors():
59
+ ensure_dir(os.path.dirname(path))
60
+
61
+ with adjacent_tmp_file(path) as f:
62
+ f.write(value)
63
+
64
+ replace(f.name, path)
65
+
66
+ def delete(self, key: str) -> None:
67
+ path = self._get_cache_path(key)
68
+ with suppressed_cache_errors():
69
+ os.remove(path)
scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/download.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Download files with progress indicators.
2
+ """
3
+ import cgi
4
+ import logging
5
+ import mimetypes
6
+ import os
7
+ from typing import Iterable, Optional, Tuple
8
+
9
+ from pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response
10
+
11
+ from pip._internal.cli.progress_bars import get_download_progress_renderer
12
+ from pip._internal.exceptions import NetworkConnectionError
13
+ from pip._internal.models.index import PyPI
14
+ from pip._internal.models.link import Link
15
+ from pip._internal.network.cache import is_from_cache
16
+ from pip._internal.network.session import PipSession
17
+ from pip._internal.network.utils import HEADERS, raise_for_status, response_chunks
18
+ from pip._internal.utils.misc import format_size, redact_auth_from_url, splitext
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ def _get_http_response_size(resp: Response) -> Optional[int]:
24
+ try:
25
+ return int(resp.headers["content-length"])
26
+ except (ValueError, KeyError, TypeError):
27
+ return None
28
+
29
+
30
+ def _prepare_download(
31
+ resp: Response,
32
+ link: Link,
33
+ progress_bar: str,
34
+ ) -> Iterable[bytes]:
35
+ total_length = _get_http_response_size(resp)
36
+
37
+ if link.netloc == PyPI.file_storage_domain:
38
+ url = link.show_url
39
+ else:
40
+ url = link.url_without_fragment
41
+
42
+ logged_url = redact_auth_from_url(url)
43
+
44
+ if total_length:
45
+ logged_url = "{} ({})".format(logged_url, format_size(total_length))
46
+
47
+ if is_from_cache(resp):
48
+ logger.info("Using cached %s", logged_url)
49
+ else:
50
+ logger.info("Downloading %s", logged_url)
51
+
52
+ if logger.getEffectiveLevel() > logging.INFO:
53
+ show_progress = False
54
+ elif is_from_cache(resp):
55
+ show_progress = False
56
+ elif not total_length:
57
+ show_progress = True
58
+ elif total_length > (40 * 1000):
59
+ show_progress = True
60
+ else:
61
+ show_progress = False
62
+
63
+ chunks = response_chunks(resp, CONTENT_CHUNK_SIZE)
64
+
65
+ if not show_progress:
66
+ return chunks
67
+
68
+ renderer = get_download_progress_renderer(bar_type=progress_bar, size=total_length)
69
+ return renderer(chunks)
70
+
71
+
72
+ def sanitize_content_filename(filename: str) -> str:
73
+ """
74
+ Sanitize the "filename" value from a Content-Disposition header.
75
+ """
76
+ return os.path.basename(filename)
77
+
78
+
79
+ def parse_content_disposition(content_disposition: str, default_filename: str) -> str:
80
+ """
81
+ Parse the "filename" value from a Content-Disposition header, and
82
+ return the default filename if the result is empty.
83
+ """
84
+ _type, params = cgi.parse_header(content_disposition)
85
+ filename = params.get("filename")
86
+ if filename:
87
+ # We need to sanitize the filename to prevent directory traversal
88
+ # in case the filename contains ".." path parts.
89
+ filename = sanitize_content_filename(filename)
90
+ return filename or default_filename
91
+
92
+
93
+ def _get_http_response_filename(resp: Response, link: Link) -> str:
94
+ """Get an ideal filename from the given HTTP response, falling back to
95
+ the link filename if not provided.
96
+ """
97
+ filename = link.filename # fallback
98
+ # Have a look at the Content-Disposition header for a better guess
99
+ content_disposition = resp.headers.get("content-disposition")
100
+ if content_disposition:
101
+ filename = parse_content_disposition(content_disposition, filename)
102
+ ext: Optional[str] = splitext(filename)[1]
103
+ if not ext:
104
+ ext = mimetypes.guess_extension(resp.headers.get("content-type", ""))
105
+ if ext:
106
+ filename += ext
107
+ if not ext and link.url != resp.url:
108
+ ext = os.path.splitext(resp.url)[1]
109
+ if ext:
110
+ filename += ext
111
+ return filename
112
+
113
+
114
+ def _http_get_download(session: PipSession, link: Link) -> Response:
115
+ target_url = link.url.split("#", 1)[0]
116
+ resp = session.get(target_url, headers=HEADERS, stream=True)
117
+ raise_for_status(resp)
118
+ return resp
119
+
120
+
121
+ class Downloader:
122
+ def __init__(
123
+ self,
124
+ session: PipSession,
125
+ progress_bar: str,
126
+ ) -> None:
127
+ self._session = session
128
+ self._progress_bar = progress_bar
129
+
130
+ def __call__(self, link: Link, location: str) -> Tuple[str, str]:
131
+ """Download the file given by link into location."""
132
+ try:
133
+ resp = _http_get_download(self._session, link)
134
+ except NetworkConnectionError as e:
135
+ assert e.response is not None
136
+ logger.critical(
137
+ "HTTP error %s while getting %s", e.response.status_code, link
138
+ )
139
+ raise
140
+
141
+ filename = _get_http_response_filename(resp, link)
142
+ filepath = os.path.join(location, filename)
143
+
144
+ chunks = _prepare_download(resp, link, self._progress_bar)
145
+ with open(filepath, "wb") as content_file:
146
+ for chunk in chunks:
147
+ content_file.write(chunk)
148
+ content_type = resp.headers.get("Content-Type", "")
149
+ return filepath, content_type
150
+
151
+
152
+ class BatchDownloader:
153
+ def __init__(
154
+ self,
155
+ session: PipSession,
156
+ progress_bar: str,
157
+ ) -> None:
158
+ self._session = session
159
+ self._progress_bar = progress_bar
160
+
161
+ def __call__(
162
+ self, links: Iterable[Link], location: str
163
+ ) -> Iterable[Tuple[Link, Tuple[str, str]]]:
164
+ """Download the files given by links into location."""
165
+ for link in links:
166
+ try:
167
+ resp = _http_get_download(self._session, link)
168
+ except NetworkConnectionError as e:
169
+ assert e.response is not None
170
+ logger.critical(
171
+ "HTTP error %s while getting %s",
172
+ e.response.status_code,
173
+ link,
174
+ )
175
+ raise
176
+
177
+ filename = _get_http_response_filename(resp, link)
178
+ filepath = os.path.join(location, filename)
179
+
180
+ chunks = _prepare_download(resp, link, self._progress_bar)
181
+ with open(filepath, "wb") as content_file:
182
+ for chunk in chunks:
183
+ content_file.write(chunk)
184
+ content_type = resp.headers.get("Content-Type", "")
185
+ yield link, (filepath, content_type)
scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/lazy_wheel.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lazy ZIP over HTTP"""
2
+
3
+ __all__ = ["HTTPRangeRequestUnsupported", "dist_from_wheel_url"]
4
+
5
+ from bisect import bisect_left, bisect_right
6
+ from contextlib import contextmanager
7
+ from tempfile import NamedTemporaryFile
8
+ from typing import Any, Dict, Iterator, List, Optional, Tuple
9
+ from zipfile import BadZipfile, ZipFile
10
+
11
+ from pip._vendor.packaging.utils import canonicalize_name
12
+ from pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response
13
+
14
+ from pip._internal.metadata import BaseDistribution, MemoryWheel, get_wheel_distribution
15
+ from pip._internal.network.session import PipSession
16
+ from pip._internal.network.utils import HEADERS, raise_for_status, response_chunks
17
+
18
+
19
+ class HTTPRangeRequestUnsupported(Exception):
20
+ pass
21
+
22
+
23
+ def dist_from_wheel_url(name: str, url: str, session: PipSession) -> BaseDistribution:
24
+ """Return a distribution object from the given wheel URL.
25
+
26
+ This uses HTTP range requests to only fetch the potion of the wheel
27
+ containing metadata, just enough for the object to be constructed.
28
+ If such requests are not supported, HTTPRangeRequestUnsupported
29
+ is raised.
30
+ """
31
+ with LazyZipOverHTTP(url, session) as zf:
32
+ # For read-only ZIP files, ZipFile only needs methods read,
33
+ # seek, seekable and tell, not the whole IO protocol.
34
+ wheel = MemoryWheel(zf.name, zf) # type: ignore
35
+ # After context manager exit, wheel.name
36
+ # is an invalid file by intention.
37
+ return get_wheel_distribution(wheel, canonicalize_name(name))
38
+
39
+
40
+ class LazyZipOverHTTP:
41
+ """File-like object mapped to a ZIP file over HTTP.
42
+
43
+ This uses HTTP range requests to lazily fetch the file's content,
44
+ which is supposed to be fed to ZipFile. If such requests are not
45
+ supported by the server, raise HTTPRangeRequestUnsupported
46
+ during initialization.
47
+ """
48
+
49
+ def __init__(
50
+ self, url: str, session: PipSession, chunk_size: int = CONTENT_CHUNK_SIZE
51
+ ) -> None:
52
+ head = session.head(url, headers=HEADERS)
53
+ raise_for_status(head)
54
+ assert head.status_code == 200
55
+ self._session, self._url, self._chunk_size = session, url, chunk_size
56
+ self._length = int(head.headers["Content-Length"])
57
+ self._file = NamedTemporaryFile()
58
+ self.truncate(self._length)
59
+ self._left: List[int] = []
60
+ self._right: List[int] = []
61
+ if "bytes" not in head.headers.get("Accept-Ranges", "none"):
62
+ raise HTTPRangeRequestUnsupported("range request is not supported")
63
+ self._check_zip()
64
+
65
+ @property
66
+ def mode(self) -> str:
67
+ """Opening mode, which is always rb."""
68
+ return "rb"
69
+
70
+ @property
71
+ def name(self) -> str:
72
+ """Path to the underlying file."""
73
+ return self._file.name
74
+
75
+ def seekable(self) -> bool:
76
+ """Return whether random access is supported, which is True."""
77
+ return True
78
+
79
+ def close(self) -> None:
80
+ """Close the file."""
81
+ self._file.close()
82
+
83
+ @property
84
+ def closed(self) -> bool:
85
+ """Whether the file is closed."""
86
+ return self._file.closed
87
+
88
+ def read(self, size: int = -1) -> bytes:
89
+ """Read up to size bytes from the object and return them.
90
+
91
+ As a convenience, if size is unspecified or -1,
92
+ all bytes until EOF are returned. Fewer than
93
+ size bytes may be returned if EOF is reached.
94
+ """
95
+ download_size = max(size, self._chunk_size)
96
+ start, length = self.tell(), self._length
97
+ stop = length if size < 0 else min(start + download_size, length)
98
+ start = max(0, stop - download_size)
99
+ self._download(start, stop - 1)
100
+ return self._file.read(size)
101
+
102
+ def readable(self) -> bool:
103
+ """Return whether the file is readable, which is True."""
104
+ return True
105
+
106
+ def seek(self, offset: int, whence: int = 0) -> int:
107
+ """Change stream position and return the new absolute position.
108
+
109
+ Seek to offset relative position indicated by whence:
110
+ * 0: Start of stream (the default). pos should be >= 0;
111
+ * 1: Current position - pos may be negative;
112
+ * 2: End of stream - pos usually negative.
113
+ """
114
+ return self._file.seek(offset, whence)
115
+
116
+ def tell(self) -> int:
117
+ """Return the current position."""
118
+ return self._file.tell()
119
+
120
+ def truncate(self, size: Optional[int] = None) -> int:
121
+ """Resize the stream to the given size in bytes.
122
+
123
+ If size is unspecified resize to the current position.
124
+ The current stream position isn't changed.
125
+
126
+ Return the new file size.
127
+ """
128
+ return self._file.truncate(size)
129
+
130
+ def writable(self) -> bool:
131
+ """Return False."""
132
+ return False
133
+
134
+ def __enter__(self) -> "LazyZipOverHTTP":
135
+ self._file.__enter__()
136
+ return self
137
+
138
+ def __exit__(self, *exc: Any) -> Optional[bool]:
139
+ return self._file.__exit__(*exc)
140
+
141
+ @contextmanager
142
+ def _stay(self) -> Iterator[None]:
143
+ """Return a context manager keeping the position.
144
+
145
+ At the end of the block, seek back to original position.
146
+ """
147
+ pos = self.tell()
148
+ try:
149
+ yield
150
+ finally:
151
+ self.seek(pos)
152
+
153
+ def _check_zip(self) -> None:
154
+ """Check and download until the file is a valid ZIP."""
155
+ end = self._length - 1
156
+ for start in reversed(range(0, end, self._chunk_size)):
157
+ self._download(start, end)
158
+ with self._stay():
159
+ try:
160
+ # For read-only ZIP files, ZipFile only needs
161
+ # methods read, seek, seekable and tell.
162
+ ZipFile(self) # type: ignore
163
+ except BadZipfile:
164
+ pass
165
+ else:
166
+ break
167
+
168
+ def _stream_response(
169
+ self, start: int, end: int, base_headers: Dict[str, str] = HEADERS
170
+ ) -> Response:
171
+ """Return HTTP response to a range request from start to end."""
172
+ headers = base_headers.copy()
173
+ headers["Range"] = f"bytes={start}-{end}"
174
+ # TODO: Get range requests to be correctly cached
175
+ headers["Cache-Control"] = "no-cache"
176
+ return self._session.get(self._url, headers=headers, stream=True)
177
+
178
+ def _merge(
179
+ self, start: int, end: int, left: int, right: int
180
+ ) -> Iterator[Tuple[int, int]]:
181
+ """Return an iterator of intervals to be fetched.
182
+
183
+ Args:
184
+ start (int): Start of needed interval
185
+ end (int): End of needed interval
186
+ left (int): Index of first overlapping downloaded data
187
+ right (int): Index after last overlapping downloaded data
188
+ """
189
+ lslice, rslice = self._left[left:right], self._right[left:right]
190
+ i = start = min([start] + lslice[:1])
191
+ end = max([end] + rslice[-1:])
192
+ for j, k in zip(lslice, rslice):
193
+ if j > i:
194
+ yield i, j - 1
195
+ i = k + 1
196
+ if i <= end:
197
+ yield i, end
198
+ self._left[left:right], self._right[left:right] = [start], [end]
199
+
200
+ def _download(self, start: int, end: int) -> None:
201
+ """Download bytes from start to end inclusively."""
202
+ with self._stay():
203
+ left = bisect_left(self._right, start)
204
+ right = bisect_right(self._left, end)
205
+ for start, end in self._merge(start, end, left, right):
206
+ response = self._stream_response(start, end)
207
+ response.raise_for_status()
208
+ self.seek(start)
209
+ for chunk in response_chunks(response, self._chunk_size):
210
+ self._file.write(chunk)
scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/session.py ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PipSession and supporting code, containing all pip-specific
2
+ network request configuration and behavior.
3
+ """
4
+
5
+ import email.utils
6
+ import io
7
+ import ipaddress
8
+ import json
9
+ import logging
10
+ import mimetypes
11
+ import os
12
+ import platform
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ import urllib.parse
17
+ import warnings
18
+ from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple, Union
19
+
20
+ from pip._vendor import requests, urllib3
21
+ from pip._vendor.cachecontrol import CacheControlAdapter
22
+ from pip._vendor.requests.adapters import BaseAdapter, HTTPAdapter
23
+ from pip._vendor.requests.models import PreparedRequest, Response
24
+ from pip._vendor.requests.structures import CaseInsensitiveDict
25
+ from pip._vendor.urllib3.connectionpool import ConnectionPool
26
+ from pip._vendor.urllib3.exceptions import InsecureRequestWarning
27
+
28
+ from pip import __version__
29
+ from pip._internal.metadata import get_default_environment
30
+ from pip._internal.models.link import Link
31
+ from pip._internal.network.auth import MultiDomainBasicAuth
32
+ from pip._internal.network.cache import SafeFileCache
33
+
34
+ # Import ssl from compat so the initial import occurs in only one place.
35
+ from pip._internal.utils.compat import has_tls
36
+ from pip._internal.utils.glibc import libc_ver
37
+ from pip._internal.utils.misc import build_url_from_netloc, parse_netloc
38
+ from pip._internal.utils.urls import url_to_path
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+ SecureOrigin = Tuple[str, str, Optional[Union[int, str]]]
43
+
44
+
45
+ # Ignore warning raised when using --trusted-host.
46
+ warnings.filterwarnings("ignore", category=InsecureRequestWarning)
47
+
48
+
49
+ SECURE_ORIGINS: List[SecureOrigin] = [
50
+ # protocol, hostname, port
51
+ # Taken from Chrome's list of secure origins (See: http://bit.ly/1qrySKC)
52
+ ("https", "*", "*"),
53
+ ("*", "localhost", "*"),
54
+ ("*", "127.0.0.0/8", "*"),
55
+ ("*", "::1/128", "*"),
56
+ ("file", "*", None),
57
+ # ssh is always secure.
58
+ ("ssh", "*", "*"),
59
+ ]
60
+
61
+
62
+ # These are environment variables present when running under various
63
+ # CI systems. For each variable, some CI systems that use the variable
64
+ # are indicated. The collection was chosen so that for each of a number
65
+ # of popular systems, at least one of the environment variables is used.
66
+ # This list is used to provide some indication of and lower bound for
67
+ # CI traffic to PyPI. Thus, it is okay if the list is not comprehensive.
68
+ # For more background, see: https://github.com/pypa/pip/issues/5499
69
+ CI_ENVIRONMENT_VARIABLES = (
70
+ # Azure Pipelines
71
+ "BUILD_BUILDID",
72
+ # Jenkins
73
+ "BUILD_ID",
74
+ # AppVeyor, CircleCI, Codeship, Gitlab CI, Shippable, Travis CI
75
+ "CI",
76
+ # Explicit environment variable.
77
+ "PIP_IS_CI",
78
+ )
79
+
80
+
81
+ def looks_like_ci() -> bool:
82
+ """
83
+ Return whether it looks like pip is running under CI.
84
+ """
85
+ # We don't use the method of checking for a tty (e.g. using isatty())
86
+ # because some CI systems mimic a tty (e.g. Travis CI). Thus that
87
+ # method doesn't provide definitive information in either direction.
88
+ return any(name in os.environ for name in CI_ENVIRONMENT_VARIABLES)
89
+
90
+
91
+ def user_agent() -> str:
92
+ """
93
+ Return a string representing the user agent.
94
+ """
95
+ data: Dict[str, Any] = {
96
+ "installer": {"name": "pip", "version": __version__},
97
+ "python": platform.python_version(),
98
+ "implementation": {
99
+ "name": platform.python_implementation(),
100
+ },
101
+ }
102
+
103
+ if data["implementation"]["name"] == "CPython":
104
+ data["implementation"]["version"] = platform.python_version()
105
+ elif data["implementation"]["name"] == "PyPy":
106
+ pypy_version_info = sys.pypy_version_info # type: ignore
107
+ if pypy_version_info.releaselevel == "final":
108
+ pypy_version_info = pypy_version_info[:3]
109
+ data["implementation"]["version"] = ".".join(
110
+ [str(x) for x in pypy_version_info]
111
+ )
112
+ elif data["implementation"]["name"] == "Jython":
113
+ # Complete Guess
114
+ data["implementation"]["version"] = platform.python_version()
115
+ elif data["implementation"]["name"] == "IronPython":
116
+ # Complete Guess
117
+ data["implementation"]["version"] = platform.python_version()
118
+
119
+ if sys.platform.startswith("linux"):
120
+ from pip._vendor import distro
121
+
122
+ linux_distribution = distro.name(), distro.version(), distro.codename()
123
+ distro_infos: Dict[str, Any] = dict(
124
+ filter(
125
+ lambda x: x[1],
126
+ zip(["name", "version", "id"], linux_distribution),
127
+ )
128
+ )
129
+ libc = dict(
130
+ filter(
131
+ lambda x: x[1],
132
+ zip(["lib", "version"], libc_ver()),
133
+ )
134
+ )
135
+ if libc:
136
+ distro_infos["libc"] = libc
137
+ if distro_infos:
138
+ data["distro"] = distro_infos
139
+
140
+ if sys.platform.startswith("darwin") and platform.mac_ver()[0]:
141
+ data["distro"] = {"name": "macOS", "version": platform.mac_ver()[0]}
142
+
143
+ if platform.system():
144
+ data.setdefault("system", {})["name"] = platform.system()
145
+
146
+ if platform.release():
147
+ data.setdefault("system", {})["release"] = platform.release()
148
+
149
+ if platform.machine():
150
+ data["cpu"] = platform.machine()
151
+
152
+ if has_tls():
153
+ import _ssl as ssl
154
+
155
+ data["openssl_version"] = ssl.OPENSSL_VERSION
156
+
157
+ setuptools_dist = get_default_environment().get_distribution("setuptools")
158
+ if setuptools_dist is not None:
159
+ data["setuptools_version"] = str(setuptools_dist.version)
160
+
161
+ if shutil.which("rustc") is not None:
162
+ # If for any reason `rustc --version` fails, silently ignore it
163
+ try:
164
+ rustc_output = subprocess.check_output(
165
+ ["rustc", "--version"], stderr=subprocess.STDOUT, timeout=0.5
166
+ )
167
+ except Exception:
168
+ pass
169
+ else:
170
+ if rustc_output.startswith(b"rustc "):
171
+ # The format of `rustc --version` is:
172
+ # `b'rustc 1.52.1 (9bc8c42bb 2021-05-09)\n'`
173
+ # We extract just the middle (1.52.1) part
174
+ data["rustc_version"] = rustc_output.split(b" ")[1].decode()
175
+
176
+ # Use None rather than False so as not to give the impression that
177
+ # pip knows it is not being run under CI. Rather, it is a null or
178
+ # inconclusive result. Also, we include some value rather than no
179
+ # value to make it easier to know that the check has been run.
180
+ data["ci"] = True if looks_like_ci() else None
181
+
182
+ user_data = os.environ.get("PIP_USER_AGENT_USER_DATA")
183
+ if user_data is not None:
184
+ data["user_data"] = user_data
185
+
186
+ return "{data[installer][name]}/{data[installer][version]} {json}".format(
187
+ data=data,
188
+ json=json.dumps(data, separators=(",", ":"), sort_keys=True),
189
+ )
190
+
191
+
192
+ class LocalFSAdapter(BaseAdapter):
193
+ def send(
194
+ self,
195
+ request: PreparedRequest,
196
+ stream: bool = False,
197
+ timeout: Optional[Union[float, Tuple[float, float]]] = None,
198
+ verify: Union[bool, str] = True,
199
+ cert: Optional[Union[str, Tuple[str, str]]] = None,
200
+ proxies: Optional[Mapping[str, str]] = None,
201
+ ) -> Response:
202
+ pathname = url_to_path(request.url)
203
+
204
+ resp = Response()
205
+ resp.status_code = 200
206
+ resp.url = request.url
207
+
208
+ try:
209
+ stats = os.stat(pathname)
210
+ except OSError as exc:
211
+ # format the exception raised as a io.BytesIO object,
212
+ # to return a better error message:
213
+ resp.status_code = 404
214
+ resp.reason = type(exc).__name__
215
+ resp.raw = io.BytesIO(f"{resp.reason}: {exc}".encode("utf8"))
216
+ else:
217
+ modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
218
+ content_type = mimetypes.guess_type(pathname)[0] or "text/plain"
219
+ resp.headers = CaseInsensitiveDict(
220
+ {
221
+ "Content-Type": content_type,
222
+ "Content-Length": stats.st_size,
223
+ "Last-Modified": modified,
224
+ }
225
+ )
226
+
227
+ resp.raw = open(pathname, "rb")
228
+ resp.close = resp.raw.close
229
+
230
+ return resp
231
+
232
+ def close(self) -> None:
233
+ pass
234
+
235
+
236
+ class InsecureHTTPAdapter(HTTPAdapter):
237
+ def cert_verify(
238
+ self,
239
+ conn: ConnectionPool,
240
+ url: str,
241
+ verify: Union[bool, str],
242
+ cert: Optional[Union[str, Tuple[str, str]]],
243
+ ) -> None:
244
+ super().cert_verify(conn=conn, url=url, verify=False, cert=cert)
245
+
246
+
247
+ class InsecureCacheControlAdapter(CacheControlAdapter):
248
+ def cert_verify(
249
+ self,
250
+ conn: ConnectionPool,
251
+ url: str,
252
+ verify: Union[bool, str],
253
+ cert: Optional[Union[str, Tuple[str, str]]],
254
+ ) -> None:
255
+ super().cert_verify(conn=conn, url=url, verify=False, cert=cert)
256
+
257
+
258
+ class PipSession(requests.Session):
259
+
260
+ timeout: Optional[int] = None
261
+
262
+ def __init__(
263
+ self,
264
+ *args: Any,
265
+ retries: int = 0,
266
+ cache: Optional[str] = None,
267
+ trusted_hosts: Sequence[str] = (),
268
+ index_urls: Optional[List[str]] = None,
269
+ **kwargs: Any,
270
+ ) -> None:
271
+ """
272
+ :param trusted_hosts: Domains not to emit warnings for when not using
273
+ HTTPS.
274
+ """
275
+ super().__init__(*args, **kwargs)
276
+
277
+ # Namespace the attribute with "pip_" just in case to prevent
278
+ # possible conflicts with the base class.
279
+ self.pip_trusted_origins: List[Tuple[str, Optional[int]]] = []
280
+
281
+ # Attach our User Agent to the request
282
+ self.headers["User-Agent"] = user_agent()
283
+
284
+ # Attach our Authentication handler to the session
285
+ self.auth = MultiDomainBasicAuth(index_urls=index_urls)
286
+
287
+ # Create our urllib3.Retry instance which will allow us to customize
288
+ # how we handle retries.
289
+ retries = urllib3.Retry(
290
+ # Set the total number of retries that a particular request can
291
+ # have.
292
+ total=retries,
293
+ # A 503 error from PyPI typically means that the Fastly -> Origin
294
+ # connection got interrupted in some way. A 503 error in general
295
+ # is typically considered a transient error so we'll go ahead and
296
+ # retry it.
297
+ # A 500 may indicate transient error in Amazon S3
298
+ # A 520 or 527 - may indicate transient error in CloudFlare
299
+ status_forcelist=[500, 503, 520, 527],
300
+ # Add a small amount of back off between failed requests in
301
+ # order to prevent hammering the service.
302
+ backoff_factor=0.25,
303
+ ) # type: ignore
304
+
305
+ # Our Insecure HTTPAdapter disables HTTPS validation. It does not
306
+ # support caching so we'll use it for all http:// URLs.
307
+ # If caching is disabled, we will also use it for
308
+ # https:// hosts that we've marked as ignoring
309
+ # TLS errors for (trusted-hosts).
310
+ insecure_adapter = InsecureHTTPAdapter(max_retries=retries)
311
+
312
+ # We want to _only_ cache responses on securely fetched origins or when
313
+ # the host is specified as trusted. We do this because
314
+ # we can't validate the response of an insecurely/untrusted fetched
315
+ # origin, and we don't want someone to be able to poison the cache and
316
+ # require manual eviction from the cache to fix it.
317
+ if cache:
318
+ secure_adapter = CacheControlAdapter(
319
+ cache=SafeFileCache(cache),
320
+ max_retries=retries,
321
+ )
322
+ self._trusted_host_adapter = InsecureCacheControlAdapter(
323
+ cache=SafeFileCache(cache),
324
+ max_retries=retries,
325
+ )
326
+ else:
327
+ secure_adapter = HTTPAdapter(max_retries=retries)
328
+ self._trusted_host_adapter = insecure_adapter
329
+
330
+ self.mount("https://", secure_adapter)
331
+ self.mount("http://", insecure_adapter)
332
+
333
+ # Enable file:// urls
334
+ self.mount("file://", LocalFSAdapter())
335
+
336
+ for host in trusted_hosts:
337
+ self.add_trusted_host(host, suppress_logging=True)
338
+
339
+ def update_index_urls(self, new_index_urls: List[str]) -> None:
340
+ """
341
+ :param new_index_urls: New index urls to update the authentication
342
+ handler with.
343
+ """
344
+ self.auth.index_urls = new_index_urls
345
+
346
+ def add_trusted_host(
347
+ self, host: str, source: Optional[str] = None, suppress_logging: bool = False
348
+ ) -> None:
349
+ """
350
+ :param host: It is okay to provide a host that has previously been
351
+ added.
352
+ :param source: An optional source string, for logging where the host
353
+ string came from.
354
+ """
355
+ if not suppress_logging:
356
+ msg = f"adding trusted host: {host!r}"
357
+ if source is not None:
358
+ msg += f" (from {source})"
359
+ logger.info(msg)
360
+
361
+ host_port = parse_netloc(host)
362
+ if host_port not in self.pip_trusted_origins:
363
+ self.pip_trusted_origins.append(host_port)
364
+
365
+ self.mount(
366
+ build_url_from_netloc(host, scheme="http") + "/", self._trusted_host_adapter
367
+ )
368
+ self.mount(build_url_from_netloc(host) + "/", self._trusted_host_adapter)
369
+ if not host_port[1]:
370
+ self.mount(
371
+ build_url_from_netloc(host, scheme="http") + ":",
372
+ self._trusted_host_adapter,
373
+ )
374
+ # Mount wildcard ports for the same host.
375
+ self.mount(build_url_from_netloc(host) + ":", self._trusted_host_adapter)
376
+
377
+ def iter_secure_origins(self) -> Iterator[SecureOrigin]:
378
+ yield from SECURE_ORIGINS
379
+ for host, port in self.pip_trusted_origins:
380
+ yield ("*", host, "*" if port is None else port)
381
+
382
+ def is_secure_origin(self, location: Link) -> bool:
383
+ # Determine if this url used a secure transport mechanism
384
+ parsed = urllib.parse.urlparse(str(location))
385
+ origin_protocol, origin_host, origin_port = (
386
+ parsed.scheme,
387
+ parsed.hostname,
388
+ parsed.port,
389
+ )
390
+
391
+ # The protocol to use to see if the protocol matches.
392
+ # Don't count the repository type as part of the protocol: in
393
+ # cases such as "git+ssh", only use "ssh". (I.e., Only verify against
394
+ # the last scheme.)
395
+ origin_protocol = origin_protocol.rsplit("+", 1)[-1]
396
+
397
+ # Determine if our origin is a secure origin by looking through our
398
+ # hardcoded list of secure origins, as well as any additional ones
399
+ # configured on this PackageFinder instance.
400
+ for secure_origin in self.iter_secure_origins():
401
+ secure_protocol, secure_host, secure_port = secure_origin
402
+ if origin_protocol != secure_protocol and secure_protocol != "*":
403
+ continue
404
+
405
+ try:
406
+ addr = ipaddress.ip_address(origin_host)
407
+ network = ipaddress.ip_network(secure_host)
408
+ except ValueError:
409
+ # We don't have both a valid address or a valid network, so
410
+ # we'll check this origin against hostnames.
411
+ if (
412
+ origin_host
413
+ and origin_host.lower() != secure_host.lower()
414
+ and secure_host != "*"
415
+ ):
416
+ continue
417
+ else:
418
+ # We have a valid address and network, so see if the address
419
+ # is contained within the network.
420
+ if addr not in network:
421
+ continue
422
+
423
+ # Check to see if the port matches.
424
+ if (
425
+ origin_port != secure_port
426
+ and secure_port != "*"
427
+ and secure_port is not None
428
+ ):
429
+ continue
430
+
431
+ # If we've gotten here, then this origin matches the current
432
+ # secure origin and we should return True
433
+ return True
434
+
435
+ # If we've gotten to this point, then the origin isn't secure and we
436
+ # will not accept it as a valid location to search. We will however
437
+ # log a warning that we are ignoring it.
438
+ logger.warning(
439
+ "The repository located at %s is not a trusted or secure host and "
440
+ "is being ignored. If this repository is available via HTTPS we "
441
+ "recommend you use HTTPS instead, otherwise you may silence "
442
+ "this warning and allow it anyway with '--trusted-host %s'.",
443
+ origin_host,
444
+ origin_host,
445
+ )
446
+
447
+ return False
448
+
449
+ def request(self, method: str, url: str, *args: Any, **kwargs: Any) -> Response:
450
+ # Allow setting a default timeout on a session
451
+ kwargs.setdefault("timeout", self.timeout)
452
+
453
+ # Dispatch the actual request
454
+ return super().request(method, url, *args, **kwargs)
scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/utils.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Iterator
2
+
3
+ from pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response
4
+
5
+ from pip._internal.exceptions import NetworkConnectionError
6
+
7
+ # The following comments and HTTP headers were originally added by
8
+ # Donald Stufft in git commit 22c562429a61bb77172039e480873fb239dd8c03.
9
+ #
10
+ # We use Accept-Encoding: identity here because requests defaults to
11
+ # accepting compressed responses. This breaks in a variety of ways
12
+ # depending on how the server is configured.
13
+ # - Some servers will notice that the file isn't a compressible file
14
+ # and will leave the file alone and with an empty Content-Encoding
15
+ # - Some servers will notice that the file is already compressed and
16
+ # will leave the file alone, adding a Content-Encoding: gzip header
17
+ # - Some servers won't notice anything at all and will take a file
18
+ # that's already been compressed and compress it again, and set
19
+ # the Content-Encoding: gzip header
20
+ # By setting this to request only the identity encoding we're hoping
21
+ # to eliminate the third case. Hopefully there does not exist a server
22
+ # which when given a file will notice it is already compressed and that
23
+ # you're not asking for a compressed file and will then decompress it
24
+ # before sending because if that's the case I don't think it'll ever be
25
+ # possible to make this work.
26
+ HEADERS: Dict[str, str] = {"Accept-Encoding": "identity"}
27
+
28
+
29
+ def raise_for_status(resp: Response) -> None:
30
+ http_error_msg = ""
31
+ if isinstance(resp.reason, bytes):
32
+ # We attempt to decode utf-8 first because some servers
33
+ # choose to localize their reason strings. If the string
34
+ # isn't utf-8, we fall back to iso-8859-1 for all other
35
+ # encodings.
36
+ try:
37
+ reason = resp.reason.decode("utf-8")
38
+ except UnicodeDecodeError:
39
+ reason = resp.reason.decode("iso-8859-1")
40
+ else:
41
+ reason = resp.reason
42
+
43
+ if 400 <= resp.status_code < 500:
44
+ http_error_msg = (
45
+ f"{resp.status_code} Client Error: {reason} for url: {resp.url}"
46
+ )
47
+
48
+ elif 500 <= resp.status_code < 600:
49
+ http_error_msg = (
50
+ f"{resp.status_code} Server Error: {reason} for url: {resp.url}"
51
+ )
52
+
53
+ if http_error_msg:
54
+ raise NetworkConnectionError(http_error_msg, response=resp)
55
+
56
+
57
+ def response_chunks(
58
+ response: Response, chunk_size: int = CONTENT_CHUNK_SIZE
59
+ ) -> Iterator[bytes]:
60
+ """Given a requests Response, provide the data chunks."""
61
+ try:
62
+ # Special case for urllib3.
63
+ for chunk in response.raw.stream(
64
+ chunk_size,
65
+ # We use decode_content=False here because we don't
66
+ # want urllib3 to mess with the raw bytes we get
67
+ # from the server. If we decompress inside of
68
+ # urllib3 then we cannot verify the checksum
69
+ # because the checksum will be of the compressed
70
+ # file. This breakage will only occur if the
71
+ # server adds a Content-Encoding header, which
72
+ # depends on how the server was configured:
73
+ # - Some servers will notice that the file isn't a
74
+ # compressible file and will leave the file alone
75
+ # and with an empty Content-Encoding
76
+ # - Some servers will notice that the file is
77
+ # already compressed and will leave the file
78
+ # alone and will add a Content-Encoding: gzip
79
+ # header
80
+ # - Some servers won't notice anything at all and
81
+ # will take a file that's already been compressed
82
+ # and compress it again and set the
83
+ # Content-Encoding: gzip header
84
+ #
85
+ # By setting this not to decode automatically we
86
+ # hope to eliminate problems with the second case.
87
+ decode_content=False,
88
+ ):
89
+ yield chunk
90
+ except AttributeError:
91
+ # Standard file-like object.
92
+ while True:
93
+ chunk = response.raw.read(chunk_size)
94
+ if not chunk:
95
+ break
96
+ yield chunk
scripts/myenv/lib/python3.10/site-packages/pip/_internal/network/xmlrpc.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """xmlrpclib.Transport implementation
2
+ """
3
+
4
+ import logging
5
+ import urllib.parse
6
+ import xmlrpc.client
7
+ from typing import TYPE_CHECKING, Tuple
8
+
9
+ from pip._internal.exceptions import NetworkConnectionError
10
+ from pip._internal.network.session import PipSession
11
+ from pip._internal.network.utils import raise_for_status
12
+
13
+ if TYPE_CHECKING:
14
+ from xmlrpc.client import _HostType, _Marshallable
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class PipXmlrpcTransport(xmlrpc.client.Transport):
20
+ """Provide a `xmlrpclib.Transport` implementation via a `PipSession`
21
+ object.
22
+ """
23
+
24
+ def __init__(
25
+ self, index_url: str, session: PipSession, use_datetime: bool = False
26
+ ) -> None:
27
+ super().__init__(use_datetime)
28
+ index_parts = urllib.parse.urlparse(index_url)
29
+ self._scheme = index_parts.scheme
30
+ self._session = session
31
+
32
+ def request(
33
+ self,
34
+ host: "_HostType",
35
+ handler: str,
36
+ request_body: bytes,
37
+ verbose: bool = False,
38
+ ) -> Tuple["_Marshallable", ...]:
39
+ assert isinstance(host, str)
40
+ parts = (self._scheme, host, handler, None, None, None)
41
+ url = urllib.parse.urlunparse(parts)
42
+ try:
43
+ headers = {"Content-Type": "text/xml"}
44
+ response = self._session.post(
45
+ url,
46
+ data=request_body,
47
+ headers=headers,
48
+ stream=True,
49
+ )
50
+ raise_for_status(response)
51
+ self.verbose = verbose
52
+ return self.parse_response(response.raw)
53
+ except NetworkConnectionError as exc:
54
+ assert exc.response
55
+ logger.critical(
56
+ "HTTP error %s while getting %s",
57
+ exc.response.status_code,
58
+ url,
59
+ )
60
+ raise
scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/__init__.py ADDED
File without changes
scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/__pycache__/freeze.cpython-310.pyc ADDED
Binary file (6.2 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/build/__init__.py ADDED
File without changes
scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (205 Bytes). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/metadata.cpython-310.pyc ADDED
Binary file (1.43 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/metadata_editable.cpython-310.pyc ADDED
Binary file (1.47 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/wheel.cpython-310.pyc ADDED
Binary file (1.22 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/wheel_legacy.cpython-310.pyc ADDED
Binary file (2.76 kB). View file
 
scripts/myenv/lib/python3.10/site-packages/pip/_internal/operations/build/metadata.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Metadata generation logic for source distributions.
2
+ """
3
+
4
+ import os
5
+
6
+ from pip._vendor.pep517.wrappers import Pep517HookCaller
7
+
8
+ from pip._internal.build_env import BuildEnvironment
9
+ from pip._internal.exceptions import (
10
+ InstallationSubprocessError,
11
+ MetadataGenerationFailed,
12
+ )
13
+ from pip._internal.utils.subprocess import runner_with_spinner_message
14
+ from pip._internal.utils.temp_dir import TempDirectory
15
+
16
+
17
+ def generate_metadata(
18
+ build_env: BuildEnvironment, backend: Pep517HookCaller, details: str
19
+ ) -> str:
20
+ """Generate metadata using mechanisms described in PEP 517.
21
+
22
+ Returns the generated metadata directory.
23
+ """
24
+ metadata_tmpdir = TempDirectory(kind="modern-metadata", globally_managed=True)
25
+
26
+ metadata_dir = metadata_tmpdir.path
27
+
28
+ with build_env:
29
+ # Note that Pep517HookCaller implements a fallback for
30
+ # prepare_metadata_for_build_wheel, so we don't have to
31
+ # consider the possibility that this hook doesn't exist.
32
+ runner = runner_with_spinner_message("Preparing metadata (pyproject.toml)")
33
+ with backend.subprocess_runner(runner):
34
+ try:
35
+ distinfo_dir = backend.prepare_metadata_for_build_wheel(metadata_dir)
36
+ except InstallationSubprocessError as error:
37
+ raise MetadataGenerationFailed(package_details=details) from error
38
+
39
+ return os.path.join(metadata_dir, distinfo_dir)