Tabassum Tanzim commited on
Commit
6167347
·
1 Parent(s): 3ad812a

all files added including req.txt

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .DS_Store +0 -0
  2. app.py +27 -0
  3. env/bin/Activate.ps1 +241 -0
  4. env/bin/activate +66 -0
  5. env/bin/activate.csh +25 -0
  6. env/bin/activate.fish +64 -0
  7. env/bin/pip +8 -0
  8. env/bin/pip3 +8 -0
  9. env/bin/pip3.11 +8 -0
  10. env/bin/pip3.9 +8 -0
  11. env/bin/python +1 -0
  12. env/bin/python3 +1 -0
  13. env/bin/python3.9 +1 -0
  14. env/lib/python3.9/site-packages/_distutils_hack/__init__.py +128 -0
  15. env/lib/python3.9/site-packages/_distutils_hack/override.py +1 -0
  16. env/lib/python3.9/site-packages/distutils-precedence.pth +3 -0
  17. env/lib/python3.9/site-packages/pip-23.3.2.dist-info/AUTHORS.txt +753 -0
  18. env/lib/python3.9/site-packages/pip-23.3.2.dist-info/INSTALLER +1 -0
  19. env/lib/python3.9/site-packages/pip-23.3.2.dist-info/LICENSE.txt +20 -0
  20. env/lib/python3.9/site-packages/pip-23.3.2.dist-info/METADATA +88 -0
  21. env/lib/python3.9/site-packages/pip-23.3.2.dist-info/RECORD +0 -0
  22. env/lib/python3.9/site-packages/pip-23.3.2.dist-info/REQUESTED +0 -0
  23. env/lib/python3.9/site-packages/pip-23.3.2.dist-info/WHEEL +5 -0
  24. env/lib/python3.9/site-packages/pip-23.3.2.dist-info/entry_points.txt +4 -0
  25. env/lib/python3.9/site-packages/pip-23.3.2.dist-info/top_level.txt +1 -0
  26. env/lib/python3.9/site-packages/pip/__init__.py +13 -0
  27. env/lib/python3.9/site-packages/pip/__main__.py +24 -0
  28. env/lib/python3.9/site-packages/pip/__pip-runner__.py +50 -0
  29. env/lib/python3.9/site-packages/pip/_internal/__init__.py +18 -0
  30. env/lib/python3.9/site-packages/pip/_internal/build_env.py +311 -0
  31. env/lib/python3.9/site-packages/pip/_internal/cache.py +290 -0
  32. env/lib/python3.9/site-packages/pip/_internal/cli/__init__.py +4 -0
  33. env/lib/python3.9/site-packages/pip/_internal/cli/autocompletion.py +172 -0
  34. env/lib/python3.9/site-packages/pip/_internal/cli/base_command.py +236 -0
  35. env/lib/python3.9/site-packages/pip/_internal/cli/cmdoptions.py +1077 -0
  36. env/lib/python3.9/site-packages/pip/_internal/cli/command_context.py +27 -0
  37. env/lib/python3.9/site-packages/pip/_internal/cli/main.py +79 -0
  38. env/lib/python3.9/site-packages/pip/_internal/cli/main_parser.py +134 -0
  39. env/lib/python3.9/site-packages/pip/_internal/cli/parser.py +294 -0
  40. env/lib/python3.9/site-packages/pip/_internal/cli/progress_bars.py +68 -0
  41. env/lib/python3.9/site-packages/pip/_internal/cli/req_command.py +505 -0
  42. env/lib/python3.9/site-packages/pip/_internal/cli/spinners.py +159 -0
  43. env/lib/python3.9/site-packages/pip/_internal/cli/status_codes.py +6 -0
  44. env/lib/python3.9/site-packages/pip/_internal/commands/__init__.py +132 -0
  45. env/lib/python3.9/site-packages/pip/_internal/commands/cache.py +225 -0
  46. env/lib/python3.9/site-packages/pip/_internal/commands/check.py +54 -0
  47. env/lib/python3.9/site-packages/pip/_internal/commands/completion.py +130 -0
  48. env/lib/python3.9/site-packages/pip/_internal/commands/configuration.py +282 -0
  49. env/lib/python3.9/site-packages/pip/_internal/commands/debug.py +203 -0
  50. env/lib/python3.9/site-packages/pip/_internal/commands/download.py +147 -0
.DS_Store ADDED
Binary file (6.15 kB). View file
 
app.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import onnxruntime as rt
3
+ from transformers import AutoTokenizer
4
+ import torch, json
5
+
6
+ tokenizer = AutoTokenizer.from_pretrained("distilroberta-base")
7
+
8
+ with open("task_types_encoded.json", "r") as fp:
9
+ encode_task_types = json.load(fp)
10
+
11
+ tasks = list(encode_task_types.keys())
12
+
13
+ inf_session = rt.InferenceSession('paper-classifier-quantized.onnx')
14
+ input_name = inf_session.get_inputs()[0].name
15
+ output_name = inf_session.get_outputs()[0].name
16
+
17
+ def classify_paper_task(abstract):
18
+ input_ids = tokenizer(abstract)['input_ids'][:512]
19
+ logits = inf_session.run([output_name], {input_name: [input_ids]})[0]
20
+ logits = torch.FloatTensor(logits)
21
+ probs = torch.sigmoid(logits)[0]
22
+ return dict(zip(tasks, map(float, probs)))
23
+
24
+ label = gr.outputs.Label(num_top_classes=5)
25
+ iface = gr.Interface(fn=classify_paper_task, inputs="text", outputs=label)
26
+ iface.launch(inline=False)
27
+
env/bin/Activate.ps1 ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <#
2
+ .Synopsis
3
+ Activate a Python virtual environment for the current PowerShell session.
4
+
5
+ .Description
6
+ Pushes the python executable for a virtual environment to the front of the
7
+ $Env:PATH environment variable and sets the prompt to signify that you are
8
+ in a Python virtual environment. Makes use of the command line switches as
9
+ well as the `pyvenv.cfg` file values present in the virtual environment.
10
+
11
+ .Parameter VenvDir
12
+ Path to the directory that contains the virtual environment to activate. The
13
+ default value for this is the parent of the directory that the Activate.ps1
14
+ script is located within.
15
+
16
+ .Parameter Prompt
17
+ The prompt prefix to display when this virtual environment is activated. By
18
+ default, this prompt is the name of the virtual environment folder (VenvDir)
19
+ surrounded by parentheses and followed by a single space (ie. '(.venv) ').
20
+
21
+ .Example
22
+ Activate.ps1
23
+ Activates the Python virtual environment that contains the Activate.ps1 script.
24
+
25
+ .Example
26
+ Activate.ps1 -Verbose
27
+ Activates the Python virtual environment that contains the Activate.ps1 script,
28
+ and shows extra information about the activation as it executes.
29
+
30
+ .Example
31
+ Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
32
+ Activates the Python virtual environment located in the specified location.
33
+
34
+ .Example
35
+ Activate.ps1 -Prompt "MyPython"
36
+ Activates the Python virtual environment that contains the Activate.ps1 script,
37
+ and prefixes the current prompt with the specified string (surrounded in
38
+ parentheses) while the virtual environment is active.
39
+
40
+ .Notes
41
+ On Windows, it may be required to enable this Activate.ps1 script by setting the
42
+ execution policy for the user. You can do this by issuing the following PowerShell
43
+ command:
44
+
45
+ PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
46
+
47
+ For more information on Execution Policies:
48
+ https://go.microsoft.com/fwlink/?LinkID=135170
49
+
50
+ #>
51
+ Param(
52
+ [Parameter(Mandatory = $false)]
53
+ [String]
54
+ $VenvDir,
55
+ [Parameter(Mandatory = $false)]
56
+ [String]
57
+ $Prompt
58
+ )
59
+
60
+ <# Function declarations --------------------------------------------------- #>
61
+
62
+ <#
63
+ .Synopsis
64
+ Remove all shell session elements added by the Activate script, including the
65
+ addition of the virtual environment's Python executable from the beginning of
66
+ the PATH variable.
67
+
68
+ .Parameter NonDestructive
69
+ If present, do not remove this function from the global namespace for the
70
+ session.
71
+
72
+ #>
73
+ function global:deactivate ([switch]$NonDestructive) {
74
+ # Revert to original values
75
+
76
+ # The prior prompt:
77
+ if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
78
+ Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
79
+ Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
80
+ }
81
+
82
+ # The prior PYTHONHOME:
83
+ if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
84
+ Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
85
+ Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
86
+ }
87
+
88
+ # The prior PATH:
89
+ if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
90
+ Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
91
+ Remove-Item -Path Env:_OLD_VIRTUAL_PATH
92
+ }
93
+
94
+ # Just remove the VIRTUAL_ENV altogether:
95
+ if (Test-Path -Path Env:VIRTUAL_ENV) {
96
+ Remove-Item -Path env:VIRTUAL_ENV
97
+ }
98
+
99
+ # Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
100
+ if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
101
+ Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
102
+ }
103
+
104
+ # Leave deactivate function in the global namespace if requested:
105
+ if (-not $NonDestructive) {
106
+ Remove-Item -Path function:deactivate
107
+ }
108
+ }
109
+
110
+ <#
111
+ .Description
112
+ Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
113
+ given folder, and returns them in a map.
114
+
115
+ For each line in the pyvenv.cfg file, if that line can be parsed into exactly
116
+ two strings separated by `=` (with any amount of whitespace surrounding the =)
117
+ then it is considered a `key = value` line. The left hand string is the key,
118
+ the right hand is the value.
119
+
120
+ If the value starts with a `'` or a `"` then the first and last character is
121
+ stripped from the value before being captured.
122
+
123
+ .Parameter ConfigDir
124
+ Path to the directory that contains the `pyvenv.cfg` file.
125
+ #>
126
+ function Get-PyVenvConfig(
127
+ [String]
128
+ $ConfigDir
129
+ ) {
130
+ Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
131
+
132
+ # Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
133
+ $pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
134
+
135
+ # An empty map will be returned if no config file is found.
136
+ $pyvenvConfig = @{ }
137
+
138
+ if ($pyvenvConfigPath) {
139
+
140
+ Write-Verbose "File exists, parse `key = value` lines"
141
+ $pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
142
+
143
+ $pyvenvConfigContent | ForEach-Object {
144
+ $keyval = $PSItem -split "\s*=\s*", 2
145
+ if ($keyval[0] -and $keyval[1]) {
146
+ $val = $keyval[1]
147
+
148
+ # Remove extraneous quotations around a string value.
149
+ if ("'""".Contains($val.Substring(0, 1))) {
150
+ $val = $val.Substring(1, $val.Length - 2)
151
+ }
152
+
153
+ $pyvenvConfig[$keyval[0]] = $val
154
+ Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
155
+ }
156
+ }
157
+ }
158
+ return $pyvenvConfig
159
+ }
160
+
161
+
162
+ <# Begin Activate script --------------------------------------------------- #>
163
+
164
+ # Determine the containing directory of this script
165
+ $VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
166
+ $VenvExecDir = Get-Item -Path $VenvExecPath
167
+
168
+ Write-Verbose "Activation script is located in path: '$VenvExecPath'"
169
+ Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
170
+ Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
171
+
172
+ # Set values required in priority: CmdLine, ConfigFile, Default
173
+ # First, get the location of the virtual environment, it might not be
174
+ # VenvExecDir if specified on the command line.
175
+ if ($VenvDir) {
176
+ Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
177
+ }
178
+ else {
179
+ Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
180
+ $VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
181
+ Write-Verbose "VenvDir=$VenvDir"
182
+ }
183
+
184
+ # Next, read the `pyvenv.cfg` file to determine any required value such
185
+ # as `prompt`.
186
+ $pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
187
+
188
+ # Next, set the prompt from the command line, or the config file, or
189
+ # just use the name of the virtual environment folder.
190
+ if ($Prompt) {
191
+ Write-Verbose "Prompt specified as argument, using '$Prompt'"
192
+ }
193
+ else {
194
+ Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
195
+ if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
196
+ Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
197
+ $Prompt = $pyvenvCfg['prompt'];
198
+ }
199
+ else {
200
+ Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virutal environment)"
201
+ Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
202
+ $Prompt = Split-Path -Path $venvDir -Leaf
203
+ }
204
+ }
205
+
206
+ Write-Verbose "Prompt = '$Prompt'"
207
+ Write-Verbose "VenvDir='$VenvDir'"
208
+
209
+ # Deactivate any currently active virtual environment, but leave the
210
+ # deactivate function in place.
211
+ deactivate -nondestructive
212
+
213
+ # Now set the environment variable VIRTUAL_ENV, used by many tools to determine
214
+ # that there is an activated venv.
215
+ $env:VIRTUAL_ENV = $VenvDir
216
+
217
+ if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
218
+
219
+ Write-Verbose "Setting prompt to '$Prompt'"
220
+
221
+ # Set the prompt to include the env name
222
+ # Make sure _OLD_VIRTUAL_PROMPT is global
223
+ function global:_OLD_VIRTUAL_PROMPT { "" }
224
+ Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
225
+ New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
226
+
227
+ function global:prompt {
228
+ Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
229
+ _OLD_VIRTUAL_PROMPT
230
+ }
231
+ }
232
+
233
+ # Clear PYTHONHOME
234
+ if (Test-Path -Path Env:PYTHONHOME) {
235
+ Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
236
+ Remove-Item -Path Env:PYTHONHOME
237
+ }
238
+
239
+ # Add the venv to the PATH
240
+ Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
241
+ $Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"
env/bin/activate ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file must be used with "source bin/activate" *from bash*
2
+ # you cannot run it directly
3
+
4
+ deactivate () {
5
+ # reset old environment variables
6
+ if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
7
+ PATH="${_OLD_VIRTUAL_PATH:-}"
8
+ export PATH
9
+ unset _OLD_VIRTUAL_PATH
10
+ fi
11
+ if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
12
+ PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
13
+ export PYTHONHOME
14
+ unset _OLD_VIRTUAL_PYTHONHOME
15
+ fi
16
+
17
+ # This should detect bash and zsh, which have a hash command that must
18
+ # be called to get it to forget past commands. Without forgetting
19
+ # past commands the $PATH changes we made may not be respected
20
+ if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
21
+ hash -r 2> /dev/null
22
+ fi
23
+
24
+ if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
25
+ PS1="${_OLD_VIRTUAL_PS1:-}"
26
+ export PS1
27
+ unset _OLD_VIRTUAL_PS1
28
+ fi
29
+
30
+ unset VIRTUAL_ENV
31
+ if [ ! "${1:-}" = "nondestructive" ] ; then
32
+ # Self destruct!
33
+ unset -f deactivate
34
+ fi
35
+ }
36
+
37
+ # unset irrelevant variables
38
+ deactivate nondestructive
39
+
40
+ VIRTUAL_ENV="/Users/tabassumtanzim/Downloads/MasterCourse/paper_classifier/env"
41
+ export VIRTUAL_ENV
42
+
43
+ _OLD_VIRTUAL_PATH="$PATH"
44
+ PATH="$VIRTUAL_ENV/bin:$PATH"
45
+ export PATH
46
+
47
+ # unset PYTHONHOME if set
48
+ # this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
49
+ # could use `if (set -u; : $PYTHONHOME) ;` in bash
50
+ if [ -n "${PYTHONHOME:-}" ] ; then
51
+ _OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
52
+ unset PYTHONHOME
53
+ fi
54
+
55
+ if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
56
+ _OLD_VIRTUAL_PS1="${PS1:-}"
57
+ PS1="(env) ${PS1:-}"
58
+ export PS1
59
+ fi
60
+
61
+ # This should detect bash and zsh, which have a hash command that must
62
+ # be called to get it to forget past commands. Without forgetting
63
+ # past commands the $PATH changes we made may not be respected
64
+ if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
65
+ hash -r 2> /dev/null
66
+ fi
env/bin/activate.csh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file must be used with "source bin/activate.csh" *from csh*.
2
+ # You cannot run it directly.
3
+ # Created by Davide Di Blasi <davidedb@gmail.com>.
4
+ # Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
5
+
6
+ alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; test "\!:*" != "nondestructive" && unalias deactivate'
7
+
8
+ # Unset irrelevant variables.
9
+ deactivate nondestructive
10
+
11
+ setenv VIRTUAL_ENV "/Users/tabassumtanzim/Downloads/MasterCourse/paper_classifier/env"
12
+
13
+ set _OLD_VIRTUAL_PATH="$PATH"
14
+ setenv PATH "$VIRTUAL_ENV/bin:$PATH"
15
+
16
+
17
+ set _OLD_VIRTUAL_PROMPT="$prompt"
18
+
19
+ if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
20
+ set prompt = "(env) $prompt"
21
+ endif
22
+
23
+ alias pydoc python -m pydoc
24
+
25
+ rehash
env/bin/activate.fish ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file must be used with "source <venv>/bin/activate.fish" *from fish*
2
+ # (https://fishshell.com/); you cannot run it directly.
3
+
4
+ function deactivate -d "Exit virtual environment and return to normal shell environment"
5
+ # reset old environment variables
6
+ if test -n "$_OLD_VIRTUAL_PATH"
7
+ set -gx PATH $_OLD_VIRTUAL_PATH
8
+ set -e _OLD_VIRTUAL_PATH
9
+ end
10
+ if test -n "$_OLD_VIRTUAL_PYTHONHOME"
11
+ set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME
12
+ set -e _OLD_VIRTUAL_PYTHONHOME
13
+ end
14
+
15
+ if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
16
+ functions -e fish_prompt
17
+ set -e _OLD_FISH_PROMPT_OVERRIDE
18
+ functions -c _old_fish_prompt fish_prompt
19
+ functions -e _old_fish_prompt
20
+ end
21
+
22
+ set -e VIRTUAL_ENV
23
+ if test "$argv[1]" != "nondestructive"
24
+ # Self-destruct!
25
+ functions -e deactivate
26
+ end
27
+ end
28
+
29
+ # Unset irrelevant variables.
30
+ deactivate nondestructive
31
+
32
+ set -gx VIRTUAL_ENV "/Users/tabassumtanzim/Downloads/MasterCourse/paper_classifier/env"
33
+
34
+ set -gx _OLD_VIRTUAL_PATH $PATH
35
+ set -gx PATH "$VIRTUAL_ENV/bin" $PATH
36
+
37
+ # Unset PYTHONHOME if set.
38
+ if set -q PYTHONHOME
39
+ set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
40
+ set -e PYTHONHOME
41
+ end
42
+
43
+ if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
44
+ # fish uses a function instead of an env var to generate the prompt.
45
+
46
+ # Save the current fish_prompt function as the function _old_fish_prompt.
47
+ functions -c fish_prompt _old_fish_prompt
48
+
49
+ # With the original prompt function renamed, we can override with our own.
50
+ function fish_prompt
51
+ # Save the return status of the last command.
52
+ set -l old_status $status
53
+
54
+ # Output the venv prompt; color taken from the blue of the Python logo.
55
+ printf "%s%s%s" (set_color 4B8BBE) "(env) " (set_color normal)
56
+
57
+ # Restore the return status of the previous command.
58
+ echo "exit $old_status" | .
59
+ # Output the original/"old" prompt.
60
+ _old_fish_prompt
61
+ end
62
+
63
+ set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
64
+ end
env/bin/pip ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/Users/tabassumtanzim/Downloads/MasterCourse/paper_classifier/env/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import re
4
+ import sys
5
+ from pip._internal.cli.main import main
6
+ if __name__ == '__main__':
7
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
+ sys.exit(main())
env/bin/pip3 ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/Users/tabassumtanzim/Downloads/MasterCourse/paper_classifier/env/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import re
4
+ import sys
5
+ from pip._internal.cli.main import main
6
+ if __name__ == '__main__':
7
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
+ sys.exit(main())
env/bin/pip3.11 ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/Users/tabassumtanzim/Downloads/MasterCourse/paper_classifier/env/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import re
4
+ import sys
5
+ from pip._internal.cli.main import main
6
+ if __name__ == '__main__':
7
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
+ sys.exit(main())
env/bin/pip3.9 ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/Users/tabassumtanzim/Downloads/MasterCourse/paper_classifier/env/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import re
4
+ import sys
5
+ from pip._internal.cli.main import main
6
+ if __name__ == '__main__':
7
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
+ sys.exit(main())
env/bin/python ADDED
@@ -0,0 +1 @@
 
 
1
+ python3
env/bin/python3 ADDED
@@ -0,0 +1 @@
 
 
1
+ /Library/Developer/CommandLineTools/usr/bin/python3
env/bin/python3.9 ADDED
@@ -0,0 +1 @@
 
 
1
+ python3
env/lib/python3.9/site-packages/_distutils_hack/__init__.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import re
4
+ import importlib
5
+ import warnings
6
+
7
+
8
+ is_pypy = '__pypy__' in sys.builtin_module_names
9
+
10
+
11
+ warnings.filterwarnings('ignore',
12
+ r'.+ distutils\b.+ deprecated',
13
+ DeprecationWarning)
14
+
15
+
16
+ def warn_distutils_present():
17
+ if 'distutils' not in sys.modules:
18
+ return
19
+ if is_pypy and sys.version_info < (3, 7):
20
+ # PyPy for 3.6 unconditionally imports distutils, so bypass the warning
21
+ # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250
22
+ return
23
+ warnings.warn(
24
+ "Distutils was imported before Setuptools, but importing Setuptools "
25
+ "also replaces the `distutils` module in `sys.modules`. This may lead "
26
+ "to undesirable behaviors or errors. To avoid these issues, avoid "
27
+ "using distutils directly, ensure that setuptools is installed in the "
28
+ "traditional way (e.g. not an editable install), and/or make sure "
29
+ "that setuptools is always imported before distutils.")
30
+
31
+
32
+ def clear_distutils():
33
+ if 'distutils' not in sys.modules:
34
+ return
35
+ warnings.warn("Setuptools is replacing distutils.")
36
+ mods = [name for name in sys.modules if re.match(r'distutils\b', name)]
37
+ for name in mods:
38
+ del sys.modules[name]
39
+
40
+
41
+ def enabled():
42
+ """
43
+ Allow selection of distutils by environment variable.
44
+ """
45
+ which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'stdlib')
46
+ return which == 'local'
47
+
48
+
49
+ def ensure_local_distutils():
50
+ clear_distutils()
51
+ distutils = importlib.import_module('setuptools._distutils')
52
+ distutils.__name__ = 'distutils'
53
+ sys.modules['distutils'] = distutils
54
+
55
+ # sanity check that submodules load as expected
56
+ core = importlib.import_module('distutils.core')
57
+ assert '_distutils' in core.__file__, core.__file__
58
+
59
+
60
+ def do_override():
61
+ """
62
+ Ensure that the local copy of distutils is preferred over stdlib.
63
+
64
+ See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
65
+ for more motivation.
66
+ """
67
+ if enabled():
68
+ warn_distutils_present()
69
+ ensure_local_distutils()
70
+
71
+
72
+ class DistutilsMetaFinder:
73
+ def find_spec(self, fullname, path, target=None):
74
+ if path is not None:
75
+ return
76
+
77
+ method_name = 'spec_for_{fullname}'.format(**locals())
78
+ method = getattr(self, method_name, lambda: None)
79
+ return method()
80
+
81
+ def spec_for_distutils(self):
82
+ import importlib.abc
83
+ import importlib.util
84
+
85
+ class DistutilsLoader(importlib.abc.Loader):
86
+
87
+ def create_module(self, spec):
88
+ return importlib.import_module('setuptools._distutils')
89
+
90
+ def exec_module(self, module):
91
+ pass
92
+
93
+ return importlib.util.spec_from_loader('distutils', DistutilsLoader())
94
+
95
+ def spec_for_pip(self):
96
+ """
97
+ Ensure stdlib distutils when running under pip.
98
+ See pypa/pip#8761 for rationale.
99
+ """
100
+ if self.pip_imported_during_build():
101
+ return
102
+ clear_distutils()
103
+ self.spec_for_distutils = lambda: None
104
+
105
+ @staticmethod
106
+ def pip_imported_during_build():
107
+ """
108
+ Detect if pip is being imported in a build script. Ref #2355.
109
+ """
110
+ import traceback
111
+ return any(
112
+ frame.f_globals['__file__'].endswith('setup.py')
113
+ for frame, line in traceback.walk_stack(None)
114
+ )
115
+
116
+
117
+ DISTUTILS_FINDER = DistutilsMetaFinder()
118
+
119
+
120
+ def add_shim():
121
+ sys.meta_path.insert(0, DISTUTILS_FINDER)
122
+
123
+
124
+ def remove_shim():
125
+ try:
126
+ sys.meta_path.remove(DISTUTILS_FINDER)
127
+ except ValueError:
128
+ pass
env/lib/python3.9/site-packages/_distutils_hack/override.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __import__('_distutils_hack').do_override()
env/lib/python3.9/site-packages/distutils-precedence.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ea7ffef3fe2a117ee12c68ed6553617f0d7fd2f0590257c25c484959a3b7373
3
+ size 152
env/lib/python3.9/site-packages/pip-23.3.2.dist-info/AUTHORS.txt ADDED
@@ -0,0 +1,753 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @Switch01
2
+ A_Rog
3
+ Aakanksha Agrawal
4
+ Abhinav Sagar
5
+ ABHYUDAY PRATAP SINGH
6
+ abs51295
7
+ AceGentile
8
+ Adam Chainz
9
+ Adam Tse
10
+ Adam Wentz
11
+ admin
12
+ Adrien Morison
13
+ ahayrapetyan
14
+ Ahilya
15
+ AinsworthK
16
+ Akash Srivastava
17
+ Alan Yee
18
+ Albert Tugushev
19
+ Albert-Guan
20
+ albertg
21
+ Alberto Sottile
22
+ Aleks Bunin
23
+ Ales Erjavec
24
+ Alethea Flowers
25
+ Alex Gaynor
26
+ Alex Grönholm
27
+ Alex Hedges
28
+ Alex Loosley
29
+ Alex Morega
30
+ Alex Stachowiak
31
+ Alexander Shtyrov
32
+ Alexandre Conrad
33
+ Alexey Popravka
34
+ Aleš Erjavec
35
+ Alli
36
+ Ami Fischman
37
+ Ananya Maiti
38
+ Anatoly Techtonik
39
+ Anders Kaseorg
40
+ Andre Aguiar
41
+ Andreas Lutro
42
+ Andrei Geacar
43
+ Andrew Gaul
44
+ Andrew Shymanel
45
+ Andrey Bienkowski
46
+ Andrey Bulgakov
47
+ Andrés Delfino
48
+ Andy Freeland
49
+ Andy Kluger
50
+ Ani Hayrapetyan
51
+ Aniruddha Basak
52
+ Anish Tambe
53
+ Anrs Hu
54
+ Anthony Sottile
55
+ Antoine Musso
56
+ Anton Ovchinnikov
57
+ Anton Patrushev
58
+ Antonio Alvarado Hernandez
59
+ Antony Lee
60
+ Antti Kaihola
61
+ Anubhav Patel
62
+ Anudit Nagar
63
+ Anuj Godase
64
+ AQNOUCH Mohammed
65
+ AraHaan
66
+ Arindam Choudhury
67
+ Armin Ronacher
68
+ Artem
69
+ Arun Babu Neelicattu
70
+ Ashley Manton
71
+ Ashwin Ramaswami
72
+ atse
73
+ Atsushi Odagiri
74
+ Avinash Karhana
75
+ Avner Cohen
76
+ Awit (Ah-Wit) Ghirmai
77
+ Baptiste Mispelon
78
+ Barney Gale
79
+ barneygale
80
+ Bartek Ogryczak
81
+ Bastian Venthur
82
+ Ben Bodenmiller
83
+ Ben Darnell
84
+ Ben Hoyt
85
+ Ben Mares
86
+ Ben Rosser
87
+ Bence Nagy
88
+ Benjamin Peterson
89
+ Benjamin VanEvery
90
+ Benoit Pierre
91
+ Berker Peksag
92
+ Bernard
93
+ Bernard Tyers
94
+ Bernardo B. Marques
95
+ Bernhard M. Wiedemann
96
+ Bertil Hatt
97
+ Bhavam Vidyarthi
98
+ Blazej Michalik
99
+ Bogdan Opanchuk
100
+ BorisZZZ
101
+ Brad Erickson
102
+ Bradley Ayers
103
+ Brandon L. Reiss
104
+ Brandt Bucher
105
+ Brett Randall
106
+ Brett Rosen
107
+ Brian Cristante
108
+ Brian Rosner
109
+ briantracy
110
+ BrownTruck
111
+ Bruno Oliveira
112
+ Bruno Renié
113
+ Bruno S
114
+ Bstrdsmkr
115
+ Buck Golemon
116
+ burrows
117
+ Bussonnier Matthias
118
+ bwoodsend
119
+ c22
120
+ Caleb Martinez
121
+ Calvin Smith
122
+ Carl Meyer
123
+ Carlos Liam
124
+ Carol Willing
125
+ Carter Thayer
126
+ Cass
127
+ Chandrasekhar Atina
128
+ Chih-Hsuan Yen
129
+ Chris Brinker
130
+ Chris Hunt
131
+ Chris Jerdonek
132
+ Chris Kuehl
133
+ Chris McDonough
134
+ Chris Pawley
135
+ Chris Pryer
136
+ Chris Wolfe
137
+ Christian Clauss
138
+ Christian Heimes
139
+ Christian Oudard
140
+ Christoph Reiter
141
+ Christopher Hunt
142
+ Christopher Snyder
143
+ cjc7373
144
+ Clark Boylan
145
+ Claudio Jolowicz
146
+ Clay McClure
147
+ Cody
148
+ Cody Soyland
149
+ Colin Watson
150
+ Collin Anderson
151
+ Connor Osborn
152
+ Cooper Lees
153
+ Cooper Ry Lees
154
+ Cory Benfield
155
+ Cory Wright
156
+ Craig Kerstiens
157
+ Cristian Sorinel
158
+ Cristina
159
+ Cristina Muñoz
160
+ Curtis Doty
161
+ cytolentino
162
+ Daan De Meyer
163
+ Damian
164
+ Damian Quiroga
165
+ Damian Shaw
166
+ Dan Black
167
+ Dan Savilonis
168
+ Dan Sully
169
+ Dane Hillard
170
+ daniel
171
+ Daniel Collins
172
+ Daniel Hahler
173
+ Daniel Holth
174
+ Daniel Jost
175
+ Daniel Katz
176
+ Daniel Shaulov
177
+ Daniele Esposti
178
+ Daniele Nicolodi
179
+ Daniele Procida
180
+ Daniil Konovalenko
181
+ Danny Hermes
182
+ Danny McClanahan
183
+ Darren Kavanagh
184
+ Dav Clark
185
+ Dave Abrahams
186
+ Dave Jones
187
+ David Aguilar
188
+ David Black
189
+ David Bordeynik
190
+ David Caro
191
+ David D Lowe
192
+ David Evans
193
+ David Hewitt
194
+ David Linke
195
+ David Poggi
196
+ David Pursehouse
197
+ David Runge
198
+ David Tucker
199
+ David Wales
200
+ Davidovich
201
+ ddelange
202
+ Deepak Sharma
203
+ Deepyaman Datta
204
+ Denise Yu
205
+ dependabot[bot]
206
+ derwolfe
207
+ Desetude
208
+ Devesh Kumar Singh
209
+ Diego Caraballo
210
+ Diego Ramirez
211
+ DiegoCaraballo
212
+ Dimitri Merejkowsky
213
+ Dimitri Papadopoulos
214
+ Dirk Stolle
215
+ Dmitry Gladkov
216
+ Dmitry Volodin
217
+ Domen Kožar
218
+ Dominic Davis-Foster
219
+ Donald Stufft
220
+ Dongweiming
221
+ doron zarhi
222
+ Dos Moonen
223
+ Douglas Thor
224
+ DrFeathers
225
+ Dustin Ingram
226
+ Dwayne Bailey
227
+ Ed Morley
228
+ Edgar Ramírez
229
+ Ee Durbin
230
+ Efflam Lemaillet
231
+ efflamlemaillet
232
+ Eitan Adler
233
+ ekristina
234
+ elainechan
235
+ Eli Schwartz
236
+ Elisha Hollander
237
+ Ellen Marie Dash
238
+ Emil Burzo
239
+ Emil Styrke
240
+ Emmanuel Arias
241
+ Endoh Takanao
242
+ enoch
243
+ Erdinc Mutlu
244
+ Eric Cousineau
245
+ Eric Gillingham
246
+ Eric Hanchrow
247
+ Eric Hopper
248
+ Erik M. Bray
249
+ Erik Rose
250
+ Erwin Janssen
251
+ Eugene Vereshchagin
252
+ everdimension
253
+ Federico
254
+ Felipe Peter
255
+ Felix Yan
256
+ fiber-space
257
+ Filip Kokosiński
258
+ Filipe Laíns
259
+ Finn Womack
260
+ finnagin
261
+ Florian Briand
262
+ Florian Rathgeber
263
+ Francesco
264
+ Francesco Montesano
265
+ Frost Ming
266
+ Gabriel Curio
267
+ Gabriel de Perthuis
268
+ Garry Polley
269
+ gavin
270
+ gdanielson
271
+ Geoffrey Sneddon
272
+ George Song
273
+ Georgi Valkov
274
+ Georgy Pchelkin
275
+ ghost
276
+ Giftlin Rajaiah
277
+ gizmoguy1
278
+ gkdoc
279
+ Godefroid Chapelle
280
+ Gopinath M
281
+ GOTO Hayato
282
+ gousaiyang
283
+ gpiks
284
+ Greg Roodt
285
+ Greg Ward
286
+ Guilherme Espada
287
+ Guillaume Seguin
288
+ gutsytechster
289
+ Guy Rozendorn
290
+ Guy Tuval
291
+ gzpan123
292
+ Hanjun Kim
293
+ Hari Charan
294
+ Harsh Vardhan
295
+ harupy
296
+ Harutaka Kawamura
297
+ hauntsaninja
298
+ Henrich Hartzer
299
+ Henry Schreiner
300
+ Herbert Pfennig
301
+ Holly Stotelmyer
302
+ Honnix
303
+ Hsiaoming Yang
304
+ Hugo Lopes Tavares
305
+ Hugo van Kemenade
306
+ Hugues Bruant
307
+ Hynek Schlawack
308
+ Ian Bicking
309
+ Ian Cordasco
310
+ Ian Lee
311
+ Ian Stapleton Cordasco
312
+ Ian Wienand
313
+ Igor Kuzmitshov
314
+ Igor Sobreira
315
+ Ilan Schnell
316
+ Illia Volochii
317
+ Ilya Baryshev
318
+ Inada Naoki
319
+ Ionel Cristian Mărieș
320
+ Ionel Maries Cristian
321
+ Itamar Turner-Trauring
322
+ Ivan Pozdeev
323
+ Jacob Kim
324
+ Jacob Walls
325
+ Jaime Sanz
326
+ jakirkham
327
+ Jakub Kuczys
328
+ Jakub Stasiak
329
+ Jakub Vysoky
330
+ Jakub Wilk
331
+ James Cleveland
332
+ James Curtin
333
+ James Firth
334
+ James Gerity
335
+ James Polley
336
+ Jan Pokorný
337
+ Jannis Leidel
338
+ Jarek Potiuk
339
+ jarondl
340
+ Jason Curtis
341
+ Jason R. Coombs
342
+ JasonMo
343
+ JasonMo1
344
+ Jay Graves
345
+ Jean-Christophe Fillion-Robin
346
+ Jeff Barber
347
+ Jeff Dairiki
348
+ Jeff Widman
349
+ Jelmer Vernooij
350
+ jenix21
351
+ Jeremy Stanley
352
+ Jeremy Zafran
353
+ Jesse Rittner
354
+ Jiashuo Li
355
+ Jim Fisher
356
+ Jim Garrison
357
+ Jiun Bae
358
+ Jivan Amara
359
+ Joe Bylund
360
+ Joe Michelini
361
+ John Paton
362
+ John T. Wodder II
363
+ John-Scott Atlakson
364
+ johnthagen
365
+ Jon Banafato
366
+ Jon Dufresne
367
+ Jon Parise
368
+ Jonas Nockert
369
+ Jonathan Herbert
370
+ Joonatan Partanen
371
+ Joost Molenaar
372
+ Jorge Niedbalski
373
+ Joseph Bylund
374
+ Joseph Long
375
+ Josh Bronson
376
+ Josh Hansen
377
+ Josh Schneier
378
+ Joshua
379
+ Juan Luis Cano Rodríguez
380
+ Juanjo Bazán
381
+ Judah Rand
382
+ Julian Berman
383
+ Julian Gethmann
384
+ Julien Demoor
385
+ Jussi Kukkonen
386
+ jwg4
387
+ Jyrki Pulliainen
388
+ Kai Chen
389
+ Kai Mueller
390
+ Kamal Bin Mustafa
391
+ kasium
392
+ kaustav haldar
393
+ keanemind
394
+ Keith Maxwell
395
+ Kelsey Hightower
396
+ Kenneth Belitzky
397
+ Kenneth Reitz
398
+ Kevin Burke
399
+ Kevin Carter
400
+ Kevin Frommelt
401
+ Kevin R Patterson
402
+ Kexuan Sun
403
+ Kit Randel
404
+ Klaas van Schelven
405
+ KOLANICH
406
+ kpinc
407
+ Krishna Oza
408
+ Kumar McMillan
409
+ Kurt McKee
410
+ Kyle Persohn
411
+ lakshmanaram
412
+ Laszlo Kiss-Kollar
413
+ Laurent Bristiel
414
+ Laurent LAPORTE
415
+ Laurie O
416
+ Laurie Opperman
417
+ layday
418
+ Leon Sasson
419
+ Lev Givon
420
+ Lincoln de Sousa
421
+ Lipis
422
+ lorddavidiii
423
+ Loren Carvalho
424
+ Lucas Cimon
425
+ Ludovic Gasc
426
+ Lukas Geiger
427
+ Lukas Juhrich
428
+ Luke Macken
429
+ Luo Jiebin
430
+ luojiebin
431
+ luz.paz
432
+ László Kiss Kollár
433
+ M00nL1ght
434
+ Marc Abramowitz
435
+ Marc Tamlyn
436
+ Marcus Smith
437
+ Mariatta
438
+ Mark Kohler
439
+ Mark Williams
440
+ Markus Hametner
441
+ Martey Dodoo
442
+ Martin Fischer
443
+ Martin Häcker
444
+ Martin Pavlasek
445
+ Masaki
446
+ Masklinn
447
+ Matej Stuchlik
448
+ Mathew Jennings
449
+ Mathieu Bridon
450
+ Mathieu Kniewallner
451
+ Matt Bacchi
452
+ Matt Good
453
+ Matt Maker
454
+ Matt Robenolt
455
+ matthew
456
+ Matthew Einhorn
457
+ Matthew Feickert
458
+ Matthew Gilliard
459
+ Matthew Iversen
460
+ Matthew Treinish
461
+ Matthew Trumbell
462
+ Matthew Willson
463
+ Matthias Bussonnier
464
+ mattip
465
+ Maurits van Rees
466
+ Max W Chase
467
+ Maxim Kurnikov
468
+ Maxime Rouyrre
469
+ mayeut
470
+ mbaluna
471
+ mdebi
472
+ memoselyk
473
+ meowmeowcat
474
+ Michael
475
+ Michael Aquilina
476
+ Michael E. Karpeles
477
+ Michael Klich
478
+ Michael Mintz
479
+ Michael Williamson
480
+ michaelpacer
481
+ Michał Górny
482
+ Mickaël Schoentgen
483
+ Miguel Araujo Perez
484
+ Mihir Singh
485
+ Mike
486
+ Mike Hendricks
487
+ Min RK
488
+ MinRK
489
+ Miro Hrončok
490
+ Monica Baluna
491
+ montefra
492
+ Monty Taylor
493
+ Muha Ajjan‮
494
+ Nadav Wexler
495
+ Nahuel Ambrosini
496
+ Nate Coraor
497
+ Nate Prewitt
498
+ Nathan Houghton
499
+ Nathaniel J. Smith
500
+ Nehal J Wani
501
+ Neil Botelho
502
+ Nguyễn Gia Phong
503
+ Nicholas Serra
504
+ Nick Coghlan
505
+ Nick Stenning
506
+ Nick Timkovich
507
+ Nicolas Bock
508
+ Nicole Harris
509
+ Nikhil Benesch
510
+ Nikhil Ladha
511
+ Nikita Chepanov
512
+ Nikolay Korolev
513
+ Nipunn Koorapati
514
+ Nitesh Sharma
515
+ Niyas Sait
516
+ Noah
517
+ Noah Gorny
518
+ Nowell Strite
519
+ NtaleGrey
520
+ nvdv
521
+ OBITORASU
522
+ Ofek Lev
523
+ ofrinevo
524
+ Oliver Freund
525
+ Oliver Jeeves
526
+ Oliver Mannion
527
+ Oliver Tonnhofer
528
+ Olivier Girardot
529
+ Olivier Grisel
530
+ Ollie Rutherfurd
531
+ OMOTO Kenji
532
+ Omry Yadan
533
+ onlinejudge95
534
+ Oren Held
535
+ Oscar Benjamin
536
+ Oz N Tiram
537
+ Pachwenko
538
+ Patrick Dubroy
539
+ Patrick Jenkins
540
+ Patrick Lawson
541
+ patricktokeeffe
542
+ Patrik Kopkan
543
+ Paul Ganssle
544
+ Paul Kehrer
545
+ Paul Moore
546
+ Paul Nasrat
547
+ Paul Oswald
548
+ Paul van der Linden
549
+ Paulus Schoutsen
550
+ Pavel Safronov
551
+ Pavithra Eswaramoorthy
552
+ Pawel Jasinski
553
+ Paweł Szramowski
554
+ Pekka Klärck
555
+ Peter Gessler
556
+ Peter Lisák
557
+ Peter Waller
558
+ petr-tik
559
+ Phaneendra Chiruvella
560
+ Phil Elson
561
+ Phil Freo
562
+ Phil Pennock
563
+ Phil Whelan
564
+ Philip Jägenstedt
565
+ Philip Molloy
566
+ Philippe Ombredanne
567
+ Pi Delport
568
+ Pierre-Yves Rofes
569
+ Pieter Degroote
570
+ pip
571
+ Prabakaran Kumaresshan
572
+ Prabhjyotsing Surjit Singh Sodhi
573
+ Prabhu Marappan
574
+ Pradyun Gedam
575
+ Prashant Sharma
576
+ Pratik Mallya
577
+ pre-commit-ci[bot]
578
+ Preet Thakkar
579
+ Preston Holmes
580
+ Przemek Wrzos
581
+ Pulkit Goyal
582
+ q0w
583
+ Qiangning Hong
584
+ Quentin Lee
585
+ Quentin Pradet
586
+ R. David Murray
587
+ Rafael Caricio
588
+ Ralf Schmitt
589
+ Razzi Abuissa
590
+ rdb
591
+ Reece Dunham
592
+ Remi Rampin
593
+ Rene Dudfield
594
+ Riccardo Magliocchetti
595
+ Riccardo Schirone
596
+ Richard Jones
597
+ Richard Si
598
+ Ricky Ng-Adam
599
+ Rishi
600
+ RobberPhex
601
+ Robert Collins
602
+ Robert McGibbon
603
+ Robert Pollak
604
+ Robert T. McGibbon
605
+ robin elisha robinson
606
+ Roey Berman
607
+ Rohan Jain
608
+ Roman Bogorodskiy
609
+ Roman Donchenko
610
+ Romuald Brunet
611
+ ronaudinho
612
+ Ronny Pfannschmidt
613
+ Rory McCann
614
+ Ross Brattain
615
+ Roy Wellington Ⅳ
616
+ Ruairidh MacLeod
617
+ Russell Keith-Magee
618
+ Ryan Shepherd
619
+ Ryan Wooden
620
+ ryneeverett
621
+ Sachi King
622
+ Salvatore Rinchiera
623
+ sandeepkiran-js
624
+ Sander Van Balen
625
+ Savio Jomton
626
+ schlamar
627
+ Scott Kitterman
628
+ Sean
629
+ seanj
630
+ Sebastian Jordan
631
+ Sebastian Schaetz
632
+ Segev Finer
633
+ SeongSoo Cho
634
+ Sergey Vasilyev
635
+ Seth Michael Larson
636
+ Seth Woodworth
637
+ Shahar Epstein
638
+ Shantanu
639
+ shireenrao
640
+ Shivansh-007
641
+ Shlomi Fish
642
+ Shovan Maity
643
+ Simeon Visser
644
+ Simon Cross
645
+ Simon Pichugin
646
+ sinoroc
647
+ sinscary
648
+ snook92
649
+ socketubs
650
+ Sorin Sbarnea
651
+ Srinivas Nyayapati
652
+ Stavros Korokithakis
653
+ Stefan Scherfke
654
+ Stefano Rivera
655
+ Stephan Erb
656
+ Stephen Rosen
657
+ stepshal
658
+ Steve (Gadget) Barnes
659
+ Steve Barnes
660
+ Steve Dower
661
+ Steve Kowalik
662
+ Steven Myint
663
+ Steven Silvester
664
+ stonebig
665
+ studioj
666
+ Stéphane Bidoul
667
+ Stéphane Bidoul (ACSONE)
668
+ Stéphane Klein
669
+ Sumana Harihareswara
670
+ Surbhi Sharma
671
+ Sviatoslav Sydorenko
672
+ Swat009
673
+ Sylvain
674
+ Takayuki SHIMIZUKAWA
675
+ Taneli Hukkinen
676
+ tbeswick
677
+ Thiago
678
+ Thijs Triemstra
679
+ Thomas Fenzl
680
+ Thomas Grainger
681
+ Thomas Guettler
682
+ Thomas Johansson
683
+ Thomas Kluyver
684
+ Thomas Smith
685
+ Thomas VINCENT
686
+ Tim D. Smith
687
+ Tim Gates
688
+ Tim Harder
689
+ Tim Heap
690
+ tim smith
691
+ tinruufu
692
+ Tobias Hermann
693
+ Tom Forbes
694
+ Tom Freudenheim
695
+ Tom V
696
+ Tomas Hrnciar
697
+ Tomas Orsava
698
+ Tomer Chachamu
699
+ Tommi Enenkel | AnB
700
+ Tomá�� Hrnčiar
701
+ Tony Beswick
702
+ Tony Narlock
703
+ Tony Zhaocheng Tan
704
+ TonyBeswick
705
+ toonarmycaptain
706
+ Toshio Kuratomi
707
+ toxinu
708
+ Travis Swicegood
709
+ Tushar Sadhwani
710
+ Tzu-ping Chung
711
+ Valentin Haenel
712
+ Victor Stinner
713
+ victorvpaulo
714
+ Vikram - Google
715
+ Viktor Szépe
716
+ Ville Skyttä
717
+ Vinay Sajip
718
+ Vincent Philippon
719
+ Vinicyus Macedo
720
+ Vipul Kumar
721
+ Vitaly Babiy
722
+ Vladimir Rutsky
723
+ W. Trevor King
724
+ Wil Tan
725
+ Wilfred Hughes
726
+ William Edwards
727
+ William ML Leslie
728
+ William T Olson
729
+ William Woodruff
730
+ Wilson Mo
731
+ wim glenn
732
+ Winson Luk
733
+ Wolfgang Maier
734
+ Wu Zhenyu
735
+ XAMES3
736
+ Xavier Fernandez
737
+ xoviat
738
+ xtreak
739
+ YAMAMOTO Takashi
740
+ Yen Chi Hsuan
741
+ Yeray Diaz Diaz
742
+ Yoval P
743
+ Yu Jian
744
+ Yuan Jing Vincent Yan
745
+ Yusuke Hayashi
746
+ Zearin
747
+ Zhiping Deng
748
+ ziebam
749
+ Zvezdan Petkovic
750
+ Łukasz Langa
751
+ Роман Донченко
752
+ Семён Марьясин
753
+ ‮rekcäH nitraM‮
env/lib/python3.9/site-packages/pip-23.3.2.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
env/lib/python3.9/site-packages/pip-23.3.2.dist-info/LICENSE.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2008-present The pip developers (see AUTHORS.txt file)
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
env/lib/python3.9/site-packages/pip-23.3.2.dist-info/METADATA ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: pip
3
+ Version: 23.3.2
4
+ Summary: The PyPA recommended tool for installing Python packages.
5
+ Home-page: https://pip.pypa.io/
6
+ Author: The pip developers
7
+ Author-email: distutils-sig@python.org
8
+ License: MIT
9
+ Project-URL: Documentation, https://pip.pypa.io
10
+ Project-URL: Source, https://github.com/pypa/pip
11
+ Project-URL: Changelog, https://pip.pypa.io/en/stable/news/
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Topic :: Software Development :: Build Tools
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.7
20
+ Classifier: Programming Language :: Python :: 3.8
21
+ Classifier: Programming Language :: Python :: 3.9
22
+ Classifier: Programming Language :: Python :: 3.10
23
+ Classifier: Programming Language :: Python :: 3.11
24
+ Classifier: Programming Language :: Python :: 3.12
25
+ Classifier: Programming Language :: Python :: Implementation :: CPython
26
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
27
+ Requires-Python: >=3.7
28
+ License-File: LICENSE.txt
29
+ License-File: AUTHORS.txt
30
+
31
+ pip - The Python Package Installer
32
+ ==================================
33
+
34
+ .. image:: https://img.shields.io/pypi/v/pip.svg
35
+ :target: https://pypi.org/project/pip/
36
+ :alt: PyPI
37
+
38
+ .. image:: https://img.shields.io/pypi/pyversions/pip
39
+ :target: https://pypi.org/project/pip
40
+ :alt: PyPI - Python Version
41
+
42
+ .. image:: https://readthedocs.org/projects/pip/badge/?version=latest
43
+ :target: https://pip.pypa.io/en/latest
44
+ :alt: Documentation
45
+
46
+ pip is the `package installer`_ for Python. You can use pip to install packages from the `Python Package Index`_ and other indexes.
47
+
48
+ Please take a look at our documentation for how to install and use pip:
49
+
50
+ * `Installation`_
51
+ * `Usage`_
52
+
53
+ We release updates regularly, with a new version every 3 months. Find more details in our documentation:
54
+
55
+ * `Release notes`_
56
+ * `Release process`_
57
+
58
+ If you find bugs, need help, or want to talk to the developers, please use our mailing lists or chat rooms:
59
+
60
+ * `Issue tracking`_
61
+ * `Discourse channel`_
62
+ * `User IRC`_
63
+
64
+ If you want to get involved head over to GitHub to get the source code, look at our development documentation and feel free to jump on the developer mailing lists and chat rooms:
65
+
66
+ * `GitHub page`_
67
+ * `Development documentation`_
68
+ * `Development IRC`_
69
+
70
+ Code of Conduct
71
+ ---------------
72
+
73
+ Everyone interacting in the pip project's codebases, issue trackers, chat
74
+ rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
75
+
76
+ .. _package installer: https://packaging.python.org/guides/tool-recommendations/
77
+ .. _Python Package Index: https://pypi.org
78
+ .. _Installation: https://pip.pypa.io/en/stable/installation/
79
+ .. _Usage: https://pip.pypa.io/en/stable/
80
+ .. _Release notes: https://pip.pypa.io/en/stable/news.html
81
+ .. _Release process: https://pip.pypa.io/en/latest/development/release-process/
82
+ .. _GitHub page: https://github.com/pypa/pip
83
+ .. _Development documentation: https://pip.pypa.io/en/latest/development
84
+ .. _Issue tracking: https://github.com/pypa/pip/issues
85
+ .. _Discourse channel: https://discuss.python.org/c/packaging
86
+ .. _User IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa
87
+ .. _Development IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev
88
+ .. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
env/lib/python3.9/site-packages/pip-23.3.2.dist-info/RECORD ADDED
The diff for this file is too large to render. See raw diff
 
env/lib/python3.9/site-packages/pip-23.3.2.dist-info/REQUESTED ADDED
File without changes
env/lib/python3.9/site-packages/pip-23.3.2.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.42.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
env/lib/python3.9/site-packages/pip-23.3.2.dist-info/entry_points.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [console_scripts]
2
+ pip = pip._internal.cli.main:main
3
+ pip3 = pip._internal.cli.main:main
4
+ pip3.11 = pip._internal.cli.main:main
env/lib/python3.9/site-packages/pip-23.3.2.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
env/lib/python3.9/site-packages/pip/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+
3
+ __version__ = "23.3.2"
4
+
5
+
6
+ def main(args: Optional[List[str]] = None) -> int:
7
+ """This is an internal API only meant for use by pip's own console scripts.
8
+
9
+ For additional details, see https://github.com/pypa/pip/issues/7498.
10
+ """
11
+ from pip._internal.utils.entrypoints import _wrapper
12
+
13
+ return _wrapper(args)
env/lib/python3.9/site-packages/pip/__main__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ # Remove '' and current working directory from the first entry
5
+ # of sys.path, if present to avoid using current directory
6
+ # in pip commands check, freeze, install, list and show,
7
+ # when invoked as python -m pip <command>
8
+ if sys.path[0] in ("", os.getcwd()):
9
+ sys.path.pop(0)
10
+
11
+ # If we are running from a wheel, add the wheel to sys.path
12
+ # This allows the usage python pip-*.whl/pip install pip-*.whl
13
+ if __package__ == "":
14
+ # __file__ is pip-*.whl/pip/__main__.py
15
+ # first dirname call strips of '/__main__.py', second strips off '/pip'
16
+ # Resulting path is the name of the wheel itself
17
+ # Add that to sys.path so we can import pip
18
+ path = os.path.dirname(os.path.dirname(__file__))
19
+ sys.path.insert(0, path)
20
+
21
+ if __name__ == "__main__":
22
+ from pip._internal.cli.main import main as _main
23
+
24
+ sys.exit(_main())
env/lib/python3.9/site-packages/pip/__pip-runner__.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Execute exactly this copy of pip, within a different environment.
2
+
3
+ This file is named as it is, to ensure that this module can't be imported via
4
+ an import statement.
5
+ """
6
+
7
+ # /!\ This version compatibility check section must be Python 2 compatible. /!\
8
+
9
+ import sys
10
+
11
+ # Copied from setup.py
12
+ PYTHON_REQUIRES = (3, 7)
13
+
14
+
15
+ def version_str(version): # type: ignore
16
+ return ".".join(str(v) for v in version)
17
+
18
+
19
+ if sys.version_info[:2] < PYTHON_REQUIRES:
20
+ raise SystemExit(
21
+ "This version of pip does not support python {} (requires >={}).".format(
22
+ version_str(sys.version_info[:2]), version_str(PYTHON_REQUIRES)
23
+ )
24
+ )
25
+
26
+ # From here on, we can use Python 3 features, but the syntax must remain
27
+ # Python 2 compatible.
28
+
29
+ import runpy # noqa: E402
30
+ from importlib.machinery import PathFinder # noqa: E402
31
+ from os.path import dirname # noqa: E402
32
+
33
+ PIP_SOURCES_ROOT = dirname(dirname(__file__))
34
+
35
+
36
+ class PipImportRedirectingFinder:
37
+ @classmethod
38
+ def find_spec(self, fullname, path=None, target=None): # type: ignore
39
+ if fullname != "pip":
40
+ return None
41
+
42
+ spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target)
43
+ assert spec, (PIP_SOURCES_ROOT, fullname)
44
+ return spec
45
+
46
+
47
+ sys.meta_path.insert(0, PipImportRedirectingFinder())
48
+
49
+ assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module"
50
+ runpy.run_module("pip", run_name="__main__", alter_sys=True)
env/lib/python3.9/site-packages/pip/_internal/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+
3
+ from pip._internal.utils import _log
4
+
5
+ # init_logging() must be called before any call to logging.getLogger()
6
+ # which happens at import of most modules.
7
+ _log.init_logging()
8
+
9
+
10
+ def main(args: (Optional[List[str]]) = None) -> int:
11
+ """This is preserved for old console scripts that may still be referencing
12
+ it.
13
+
14
+ For additional details, see https://github.com/pypa/pip/issues/7498.
15
+ """
16
+ from pip._internal.utils.entrypoints import _wrapper
17
+
18
+ return _wrapper(args)
env/lib/python3.9/site-packages/pip/_internal/build_env.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build Environment used for isolation during sdist building
2
+ """
3
+
4
+ import logging
5
+ import os
6
+ import pathlib
7
+ import site
8
+ import sys
9
+ import textwrap
10
+ from collections import OrderedDict
11
+ from types import TracebackType
12
+ from typing import TYPE_CHECKING, Iterable, List, Optional, Set, Tuple, Type, Union
13
+
14
+ from pip._vendor.certifi import where
15
+ from pip._vendor.packaging.requirements import Requirement
16
+ from pip._vendor.packaging.version import Version
17
+
18
+ from pip import __file__ as pip_location
19
+ from pip._internal.cli.spinners import open_spinner
20
+ from pip._internal.locations import get_platlib, get_purelib, get_scheme
21
+ from pip._internal.metadata import get_default_environment, get_environment
22
+ from pip._internal.utils.subprocess import call_subprocess
23
+ from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
24
+
25
+ if TYPE_CHECKING:
26
+ from pip._internal.index.package_finder import PackageFinder
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ def _dedup(a: str, b: str) -> Union[Tuple[str], Tuple[str, str]]:
32
+ return (a, b) if a != b else (a,)
33
+
34
+
35
+ class _Prefix:
36
+ def __init__(self, path: str) -> None:
37
+ self.path = path
38
+ self.setup = False
39
+ scheme = get_scheme("", prefix=path)
40
+ self.bin_dir = scheme.scripts
41
+ self.lib_dirs = _dedup(scheme.purelib, scheme.platlib)
42
+
43
+
44
+ def get_runnable_pip() -> str:
45
+ """Get a file to pass to a Python executable, to run the currently-running pip.
46
+
47
+ This is used to run a pip subprocess, for installing requirements into the build
48
+ environment.
49
+ """
50
+ source = pathlib.Path(pip_location).resolve().parent
51
+
52
+ if not source.is_dir():
53
+ # This would happen if someone is using pip from inside a zip file. In that
54
+ # case, we can use that directly.
55
+ return str(source)
56
+
57
+ return os.fsdecode(source / "__pip-runner__.py")
58
+
59
+
60
+ def _get_system_sitepackages() -> Set[str]:
61
+ """Get system site packages
62
+
63
+ Usually from site.getsitepackages,
64
+ but fallback on `get_purelib()/get_platlib()` if unavailable
65
+ (e.g. in a virtualenv created by virtualenv<20)
66
+
67
+ Returns normalized set of strings.
68
+ """
69
+ if hasattr(site, "getsitepackages"):
70
+ system_sites = site.getsitepackages()
71
+ else:
72
+ # virtualenv < 20 overwrites site.py without getsitepackages
73
+ # fallback on get_purelib/get_platlib.
74
+ # this is known to miss things, but shouldn't in the cases
75
+ # where getsitepackages() has been removed (inside a virtualenv)
76
+ system_sites = [get_purelib(), get_platlib()]
77
+ return {os.path.normcase(path) for path in system_sites}
78
+
79
+
80
+ class BuildEnvironment:
81
+ """Creates and manages an isolated environment to install build deps"""
82
+
83
+ def __init__(self) -> None:
84
+ temp_dir = TempDirectory(kind=tempdir_kinds.BUILD_ENV, globally_managed=True)
85
+
86
+ self._prefixes = OrderedDict(
87
+ (name, _Prefix(os.path.join(temp_dir.path, name)))
88
+ for name in ("normal", "overlay")
89
+ )
90
+
91
+ self._bin_dirs: List[str] = []
92
+ self._lib_dirs: List[str] = []
93
+ for prefix in reversed(list(self._prefixes.values())):
94
+ self._bin_dirs.append(prefix.bin_dir)
95
+ self._lib_dirs.extend(prefix.lib_dirs)
96
+
97
+ # Customize site to:
98
+ # - ensure .pth files are honored
99
+ # - prevent access to system site packages
100
+ system_sites = _get_system_sitepackages()
101
+
102
+ self._site_dir = os.path.join(temp_dir.path, "site")
103
+ if not os.path.exists(self._site_dir):
104
+ os.mkdir(self._site_dir)
105
+ with open(
106
+ os.path.join(self._site_dir, "sitecustomize.py"), "w", encoding="utf-8"
107
+ ) as fp:
108
+ fp.write(
109
+ textwrap.dedent(
110
+ """
111
+ import os, site, sys
112
+
113
+ # First, drop system-sites related paths.
114
+ original_sys_path = sys.path[:]
115
+ known_paths = set()
116
+ for path in {system_sites!r}:
117
+ site.addsitedir(path, known_paths=known_paths)
118
+ system_paths = set(
119
+ os.path.normcase(path)
120
+ for path in sys.path[len(original_sys_path):]
121
+ )
122
+ original_sys_path = [
123
+ path for path in original_sys_path
124
+ if os.path.normcase(path) not in system_paths
125
+ ]
126
+ sys.path = original_sys_path
127
+
128
+ # Second, add lib directories.
129
+ # ensuring .pth file are processed.
130
+ for path in {lib_dirs!r}:
131
+ assert not path in sys.path
132
+ site.addsitedir(path)
133
+ """
134
+ ).format(system_sites=system_sites, lib_dirs=self._lib_dirs)
135
+ )
136
+
137
+ def __enter__(self) -> None:
138
+ self._save_env = {
139
+ name: os.environ.get(name, None)
140
+ for name in ("PATH", "PYTHONNOUSERSITE", "PYTHONPATH")
141
+ }
142
+
143
+ path = self._bin_dirs[:]
144
+ old_path = self._save_env["PATH"]
145
+ if old_path:
146
+ path.extend(old_path.split(os.pathsep))
147
+
148
+ pythonpath = [self._site_dir]
149
+
150
+ os.environ.update(
151
+ {
152
+ "PATH": os.pathsep.join(path),
153
+ "PYTHONNOUSERSITE": "1",
154
+ "PYTHONPATH": os.pathsep.join(pythonpath),
155
+ }
156
+ )
157
+
158
+ def __exit__(
159
+ self,
160
+ exc_type: Optional[Type[BaseException]],
161
+ exc_val: Optional[BaseException],
162
+ exc_tb: Optional[TracebackType],
163
+ ) -> None:
164
+ for varname, old_value in self._save_env.items():
165
+ if old_value is None:
166
+ os.environ.pop(varname, None)
167
+ else:
168
+ os.environ[varname] = old_value
169
+
170
+ def check_requirements(
171
+ self, reqs: Iterable[str]
172
+ ) -> Tuple[Set[Tuple[str, str]], Set[str]]:
173
+ """Return 2 sets:
174
+ - conflicting requirements: set of (installed, wanted) reqs tuples
175
+ - missing requirements: set of reqs
176
+ """
177
+ missing = set()
178
+ conflicting = set()
179
+ if reqs:
180
+ env = (
181
+ get_environment(self._lib_dirs)
182
+ if hasattr(self, "_lib_dirs")
183
+ else get_default_environment()
184
+ )
185
+ for req_str in reqs:
186
+ req = Requirement(req_str)
187
+ # We're explicitly evaluating with an empty extra value, since build
188
+ # environments are not provided any mechanism to select specific extras.
189
+ if req.marker is not None and not req.marker.evaluate({"extra": ""}):
190
+ continue
191
+ dist = env.get_distribution(req.name)
192
+ if not dist:
193
+ missing.add(req_str)
194
+ continue
195
+ if isinstance(dist.version, Version):
196
+ installed_req_str = f"{req.name}=={dist.version}"
197
+ else:
198
+ installed_req_str = f"{req.name}==={dist.version}"
199
+ if not req.specifier.contains(dist.version, prereleases=True):
200
+ conflicting.add((installed_req_str, req_str))
201
+ # FIXME: Consider direct URL?
202
+ return conflicting, missing
203
+
204
+ def install_requirements(
205
+ self,
206
+ finder: "PackageFinder",
207
+ requirements: Iterable[str],
208
+ prefix_as_string: str,
209
+ *,
210
+ kind: str,
211
+ ) -> None:
212
+ prefix = self._prefixes[prefix_as_string]
213
+ assert not prefix.setup
214
+ prefix.setup = True
215
+ if not requirements:
216
+ return
217
+ self._install_requirements(
218
+ get_runnable_pip(),
219
+ finder,
220
+ requirements,
221
+ prefix,
222
+ kind=kind,
223
+ )
224
+
225
+ @staticmethod
226
+ def _install_requirements(
227
+ pip_runnable: str,
228
+ finder: "PackageFinder",
229
+ requirements: Iterable[str],
230
+ prefix: _Prefix,
231
+ *,
232
+ kind: str,
233
+ ) -> None:
234
+ args: List[str] = [
235
+ sys.executable,
236
+ pip_runnable,
237
+ "install",
238
+ "--ignore-installed",
239
+ "--no-user",
240
+ "--prefix",
241
+ prefix.path,
242
+ "--no-warn-script-location",
243
+ ]
244
+ if logger.getEffectiveLevel() <= logging.DEBUG:
245
+ args.append("-v")
246
+ for format_control in ("no_binary", "only_binary"):
247
+ formats = getattr(finder.format_control, format_control)
248
+ args.extend(
249
+ (
250
+ "--" + format_control.replace("_", "-"),
251
+ ",".join(sorted(formats or {":none:"})),
252
+ )
253
+ )
254
+
255
+ index_urls = finder.index_urls
256
+ if index_urls:
257
+ args.extend(["-i", index_urls[0]])
258
+ for extra_index in index_urls[1:]:
259
+ args.extend(["--extra-index-url", extra_index])
260
+ else:
261
+ args.append("--no-index")
262
+ for link in finder.find_links:
263
+ args.extend(["--find-links", link])
264
+
265
+ for host in finder.trusted_hosts:
266
+ args.extend(["--trusted-host", host])
267
+ if finder.allow_all_prereleases:
268
+ args.append("--pre")
269
+ if finder.prefer_binary:
270
+ args.append("--prefer-binary")
271
+ args.append("--")
272
+ args.extend(requirements)
273
+ extra_environ = {"_PIP_STANDALONE_CERT": where()}
274
+ with open_spinner(f"Installing {kind}") as spinner:
275
+ call_subprocess(
276
+ args,
277
+ command_desc=f"pip subprocess to install {kind}",
278
+ spinner=spinner,
279
+ extra_environ=extra_environ,
280
+ )
281
+
282
+
283
+ class NoOpBuildEnvironment(BuildEnvironment):
284
+ """A no-op drop-in replacement for BuildEnvironment"""
285
+
286
+ def __init__(self) -> None:
287
+ pass
288
+
289
+ def __enter__(self) -> None:
290
+ pass
291
+
292
+ def __exit__(
293
+ self,
294
+ exc_type: Optional[Type[BaseException]],
295
+ exc_val: Optional[BaseException],
296
+ exc_tb: Optional[TracebackType],
297
+ ) -> None:
298
+ pass
299
+
300
+ def cleanup(self) -> None:
301
+ pass
302
+
303
+ def install_requirements(
304
+ self,
305
+ finder: "PackageFinder",
306
+ requirements: Iterable[str],
307
+ prefix_as_string: str,
308
+ *,
309
+ kind: str,
310
+ ) -> None:
311
+ raise NotImplementedError()
env/lib/python3.9/site-packages/pip/_internal/cache.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cache Management
2
+ """
3
+
4
+ import hashlib
5
+ import json
6
+ import logging
7
+ import os
8
+ from pathlib import Path
9
+ from typing import Any, Dict, List, Optional
10
+
11
+ from pip._vendor.packaging.tags import Tag, interpreter_name, interpreter_version
12
+ from pip._vendor.packaging.utils import canonicalize_name
13
+
14
+ from pip._internal.exceptions import InvalidWheelFilename
15
+ from pip._internal.models.direct_url import DirectUrl
16
+ from pip._internal.models.link import Link
17
+ from pip._internal.models.wheel import Wheel
18
+ from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
19
+ from pip._internal.utils.urls import path_to_url
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ ORIGIN_JSON_NAME = "origin.json"
24
+
25
+
26
+ def _hash_dict(d: Dict[str, str]) -> str:
27
+ """Return a stable sha224 of a dictionary."""
28
+ s = json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
29
+ return hashlib.sha224(s.encode("ascii")).hexdigest()
30
+
31
+
32
+ class Cache:
33
+ """An abstract class - provides cache directories for data from links
34
+
35
+ :param cache_dir: The root of the cache.
36
+ """
37
+
38
+ def __init__(self, cache_dir: str) -> None:
39
+ super().__init__()
40
+ assert not cache_dir or os.path.isabs(cache_dir)
41
+ self.cache_dir = cache_dir or None
42
+
43
+ def _get_cache_path_parts(self, link: Link) -> List[str]:
44
+ """Get parts of part that must be os.path.joined with cache_dir"""
45
+
46
+ # We want to generate an url to use as our cache key, we don't want to
47
+ # just re-use the URL because it might have other items in the fragment
48
+ # and we don't care about those.
49
+ key_parts = {"url": link.url_without_fragment}
50
+ if link.hash_name is not None and link.hash is not None:
51
+ key_parts[link.hash_name] = link.hash
52
+ if link.subdirectory_fragment:
53
+ key_parts["subdirectory"] = link.subdirectory_fragment
54
+
55
+ # Include interpreter name, major and minor version in cache key
56
+ # to cope with ill-behaved sdists that build a different wheel
57
+ # depending on the python version their setup.py is being run on,
58
+ # and don't encode the difference in compatibility tags.
59
+ # https://github.com/pypa/pip/issues/7296
60
+ key_parts["interpreter_name"] = interpreter_name()
61
+ key_parts["interpreter_version"] = interpreter_version()
62
+
63
+ # Encode our key url with sha224, we'll use this because it has similar
64
+ # security properties to sha256, but with a shorter total output (and
65
+ # thus less secure). However the differences don't make a lot of
66
+ # difference for our use case here.
67
+ hashed = _hash_dict(key_parts)
68
+
69
+ # We want to nest the directories some to prevent having a ton of top
70
+ # level directories where we might run out of sub directories on some
71
+ # FS.
72
+ parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
73
+
74
+ return parts
75
+
76
+ def _get_candidates(self, link: Link, canonical_package_name: str) -> List[Any]:
77
+ can_not_cache = not self.cache_dir or not canonical_package_name or not link
78
+ if can_not_cache:
79
+ return []
80
+
81
+ path = self.get_path_for_link(link)
82
+ if os.path.isdir(path):
83
+ return [(candidate, path) for candidate in os.listdir(path)]
84
+ return []
85
+
86
+ def get_path_for_link(self, link: Link) -> str:
87
+ """Return a directory to store cached items in for link."""
88
+ raise NotImplementedError()
89
+
90
+ def get(
91
+ self,
92
+ link: Link,
93
+ package_name: Optional[str],
94
+ supported_tags: List[Tag],
95
+ ) -> Link:
96
+ """Returns a link to a cached item if it exists, otherwise returns the
97
+ passed link.
98
+ """
99
+ raise NotImplementedError()
100
+
101
+
102
+ class SimpleWheelCache(Cache):
103
+ """A cache of wheels for future installs."""
104
+
105
+ def __init__(self, cache_dir: str) -> None:
106
+ super().__init__(cache_dir)
107
+
108
+ def get_path_for_link(self, link: Link) -> str:
109
+ """Return a directory to store cached wheels for link
110
+
111
+ Because there are M wheels for any one sdist, we provide a directory
112
+ to cache them in, and then consult that directory when looking up
113
+ cache hits.
114
+
115
+ We only insert things into the cache if they have plausible version
116
+ numbers, so that we don't contaminate the cache with things that were
117
+ not unique. E.g. ./package might have dozens of installs done for it
118
+ and build a version of 0.0...and if we built and cached a wheel, we'd
119
+ end up using the same wheel even if the source has been edited.
120
+
121
+ :param link: The link of the sdist for which this will cache wheels.
122
+ """
123
+ parts = self._get_cache_path_parts(link)
124
+ assert self.cache_dir
125
+ # Store wheels within the root cache_dir
126
+ return os.path.join(self.cache_dir, "wheels", *parts)
127
+
128
+ def get(
129
+ self,
130
+ link: Link,
131
+ package_name: Optional[str],
132
+ supported_tags: List[Tag],
133
+ ) -> Link:
134
+ candidates = []
135
+
136
+ if not package_name:
137
+ return link
138
+
139
+ canonical_package_name = canonicalize_name(package_name)
140
+ for wheel_name, wheel_dir in self._get_candidates(link, canonical_package_name):
141
+ try:
142
+ wheel = Wheel(wheel_name)
143
+ except InvalidWheelFilename:
144
+ continue
145
+ if canonicalize_name(wheel.name) != canonical_package_name:
146
+ logger.debug(
147
+ "Ignoring cached wheel %s for %s as it "
148
+ "does not match the expected distribution name %s.",
149
+ wheel_name,
150
+ link,
151
+ package_name,
152
+ )
153
+ continue
154
+ if not wheel.supported(supported_tags):
155
+ # Built for a different python/arch/etc
156
+ continue
157
+ candidates.append(
158
+ (
159
+ wheel.support_index_min(supported_tags),
160
+ wheel_name,
161
+ wheel_dir,
162
+ )
163
+ )
164
+
165
+ if not candidates:
166
+ return link
167
+
168
+ _, wheel_name, wheel_dir = min(candidates)
169
+ return Link(path_to_url(os.path.join(wheel_dir, wheel_name)))
170
+
171
+
172
+ class EphemWheelCache(SimpleWheelCache):
173
+ """A SimpleWheelCache that creates it's own temporary cache directory"""
174
+
175
+ def __init__(self) -> None:
176
+ self._temp_dir = TempDirectory(
177
+ kind=tempdir_kinds.EPHEM_WHEEL_CACHE,
178
+ globally_managed=True,
179
+ )
180
+
181
+ super().__init__(self._temp_dir.path)
182
+
183
+
184
+ class CacheEntry:
185
+ def __init__(
186
+ self,
187
+ link: Link,
188
+ persistent: bool,
189
+ ):
190
+ self.link = link
191
+ self.persistent = persistent
192
+ self.origin: Optional[DirectUrl] = None
193
+ origin_direct_url_path = Path(self.link.file_path).parent / ORIGIN_JSON_NAME
194
+ if origin_direct_url_path.exists():
195
+ try:
196
+ self.origin = DirectUrl.from_json(
197
+ origin_direct_url_path.read_text(encoding="utf-8")
198
+ )
199
+ except Exception as e:
200
+ logger.warning(
201
+ "Ignoring invalid cache entry origin file %s for %s (%s)",
202
+ origin_direct_url_path,
203
+ link.filename,
204
+ e,
205
+ )
206
+
207
+
208
+ class WheelCache(Cache):
209
+ """Wraps EphemWheelCache and SimpleWheelCache into a single Cache
210
+
211
+ This Cache allows for gracefully degradation, using the ephem wheel cache
212
+ when a certain link is not found in the simple wheel cache first.
213
+ """
214
+
215
+ def __init__(self, cache_dir: str) -> None:
216
+ super().__init__(cache_dir)
217
+ self._wheel_cache = SimpleWheelCache(cache_dir)
218
+ self._ephem_cache = EphemWheelCache()
219
+
220
+ def get_path_for_link(self, link: Link) -> str:
221
+ return self._wheel_cache.get_path_for_link(link)
222
+
223
+ def get_ephem_path_for_link(self, link: Link) -> str:
224
+ return self._ephem_cache.get_path_for_link(link)
225
+
226
+ def get(
227
+ self,
228
+ link: Link,
229
+ package_name: Optional[str],
230
+ supported_tags: List[Tag],
231
+ ) -> Link:
232
+ cache_entry = self.get_cache_entry(link, package_name, supported_tags)
233
+ if cache_entry is None:
234
+ return link
235
+ return cache_entry.link
236
+
237
+ def get_cache_entry(
238
+ self,
239
+ link: Link,
240
+ package_name: Optional[str],
241
+ supported_tags: List[Tag],
242
+ ) -> Optional[CacheEntry]:
243
+ """Returns a CacheEntry with a link to a cached item if it exists or
244
+ None. The cache entry indicates if the item was found in the persistent
245
+ or ephemeral cache.
246
+ """
247
+ retval = self._wheel_cache.get(
248
+ link=link,
249
+ package_name=package_name,
250
+ supported_tags=supported_tags,
251
+ )
252
+ if retval is not link:
253
+ return CacheEntry(retval, persistent=True)
254
+
255
+ retval = self._ephem_cache.get(
256
+ link=link,
257
+ package_name=package_name,
258
+ supported_tags=supported_tags,
259
+ )
260
+ if retval is not link:
261
+ return CacheEntry(retval, persistent=False)
262
+
263
+ return None
264
+
265
+ @staticmethod
266
+ def record_download_origin(cache_dir: str, download_info: DirectUrl) -> None:
267
+ origin_path = Path(cache_dir) / ORIGIN_JSON_NAME
268
+ if origin_path.exists():
269
+ try:
270
+ origin = DirectUrl.from_json(origin_path.read_text(encoding="utf-8"))
271
+ except Exception as e:
272
+ logger.warning(
273
+ "Could not read origin file %s in cache entry (%s). "
274
+ "Will attempt to overwrite it.",
275
+ origin_path,
276
+ e,
277
+ )
278
+ else:
279
+ # TODO: use DirectUrl.equivalent when
280
+ # https://github.com/pypa/pip/pull/10564 is merged.
281
+ if origin.url != download_info.url:
282
+ logger.warning(
283
+ "Origin URL %s in cache entry %s does not match download URL "
284
+ "%s. This is likely a pip bug or a cache corruption issue. "
285
+ "Will overwrite it with the new value.",
286
+ origin.url,
287
+ cache_dir,
288
+ download_info.url,
289
+ )
290
+ origin_path.write_text(download_info.to_json(), encoding="utf-8")
env/lib/python3.9/site-packages/pip/_internal/cli/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """Subpackage containing all of pip's command line interface related code
2
+ """
3
+
4
+ # This file intentionally does not import submodules
env/lib/python3.9/site-packages/pip/_internal/cli/autocompletion.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ options += [
75
+ (opt_str, opt.nargs) for opt_str in opt._long_opts + opt._short_opts
76
+ ]
77
+
78
+ # filter out previously specified options from available options
79
+ prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]]
80
+ options = [(x, v) for (x, v) in options if x not in prev_opts]
81
+ # filter options by current input
82
+ options = [(k, v) for k, v in options if k.startswith(current)]
83
+ # get completion type given cwords and available subcommand options
84
+ completion_type = get_path_completion_type(
85
+ cwords,
86
+ cword,
87
+ subcommand.parser.option_list_all,
88
+ )
89
+ # get completion files and directories if ``completion_type`` is
90
+ # ``<file>``, ``<dir>`` or ``<path>``
91
+ if completion_type:
92
+ paths = auto_complete_paths(current, completion_type)
93
+ options = [(path, 0) for path in paths]
94
+ for option in options:
95
+ opt_label = option[0]
96
+ # append '=' to options which require args
97
+ if option[1] and option[0][:2] == "--":
98
+ opt_label += "="
99
+ print(opt_label)
100
+ else:
101
+ # show main parser options only when necessary
102
+
103
+ opts = [i.option_list for i in parser.option_groups]
104
+ opts.append(parser.option_list)
105
+ flattened_opts = chain.from_iterable(opts)
106
+ if current.startswith("-"):
107
+ for opt in flattened_opts:
108
+ if opt.help != optparse.SUPPRESS_HELP:
109
+ subcommands += opt._long_opts + opt._short_opts
110
+ else:
111
+ # get completion type given cwords and all available options
112
+ completion_type = get_path_completion_type(cwords, cword, flattened_opts)
113
+ if completion_type:
114
+ subcommands = list(auto_complete_paths(current, completion_type))
115
+
116
+ print(" ".join([x for x in subcommands if x.startswith(current)]))
117
+ sys.exit(1)
118
+
119
+
120
+ def get_path_completion_type(
121
+ cwords: List[str], cword: int, opts: Iterable[Any]
122
+ ) -> Optional[str]:
123
+ """Get the type of path completion (``file``, ``dir``, ``path`` or None)
124
+
125
+ :param cwords: same as the environmental variable ``COMP_WORDS``
126
+ :param cword: same as the environmental variable ``COMP_CWORD``
127
+ :param opts: The available options to check
128
+ :return: path completion type (``file``, ``dir``, ``path`` or None)
129
+ """
130
+ if cword < 2 or not cwords[cword - 2].startswith("-"):
131
+ return None
132
+ for opt in opts:
133
+ if opt.help == optparse.SUPPRESS_HELP:
134
+ continue
135
+ for o in str(opt).split("/"):
136
+ if cwords[cword - 2].split("=")[0] == o:
137
+ if not opt.metavar or any(
138
+ x in ("path", "file", "dir") for x in opt.metavar.split("/")
139
+ ):
140
+ return opt.metavar
141
+ return None
142
+
143
+
144
+ def auto_complete_paths(current: str, completion_type: str) -> Iterable[str]:
145
+ """If ``completion_type`` is ``file`` or ``path``, list all regular files
146
+ and directories starting with ``current``; otherwise only list directories
147
+ starting with ``current``.
148
+
149
+ :param current: The word to be completed
150
+ :param completion_type: path completion type(``file``, ``path`` or ``dir``)
151
+ :return: A generator of regular files and/or directories
152
+ """
153
+ directory, filename = os.path.split(current)
154
+ current_path = os.path.abspath(directory)
155
+ # Don't complete paths if they can't be accessed
156
+ if not os.access(current_path, os.R_OK):
157
+ return
158
+ filename = os.path.normcase(filename)
159
+ # list all files that start with ``filename``
160
+ file_list = (
161
+ x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)
162
+ )
163
+ for f in file_list:
164
+ opt = os.path.join(current_path, f)
165
+ comp_file = os.path.normcase(os.path.join(directory, f))
166
+ # complete regular files when there is not ``<dir>`` after option
167
+ # complete directories when there is ``<file>``, ``<path>`` or
168
+ # ``<dir>``after option
169
+ if completion_type != "dir" and os.path.isfile(opt):
170
+ yield comp_file
171
+ elif os.path.isdir(opt):
172
+ yield os.path.join(comp_file, "")
env/lib/python3.9/site-packages/pip/_internal/cli/base_command.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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._vendor.rich import traceback as rich_traceback
14
+
15
+ from pip._internal.cli import cmdoptions
16
+ from pip._internal.cli.command_context import CommandContextMixIn
17
+ from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
18
+ from pip._internal.cli.status_codes import (
19
+ ERROR,
20
+ PREVIOUS_BUILD_DIR_ERROR,
21
+ UNKNOWN_ERROR,
22
+ VIRTUALENV_NOT_FOUND,
23
+ )
24
+ from pip._internal.exceptions import (
25
+ BadCommand,
26
+ CommandError,
27
+ DiagnosticPipError,
28
+ InstallationError,
29
+ NetworkConnectionError,
30
+ PreviousBuildDirError,
31
+ UninstallationError,
32
+ )
33
+ from pip._internal.utils.filesystem import check_path_owner
34
+ from pip._internal.utils.logging import BrokenStdoutLoggingError, setup_logging
35
+ from pip._internal.utils.misc import get_prog, normalize_path
36
+ from pip._internal.utils.temp_dir import TempDirectoryTypeRegistry as TempDirRegistry
37
+ from pip._internal.utils.temp_dir import global_tempdir_manager, tempdir_registry
38
+ from pip._internal.utils.virtualenv import running_under_virtualenv
39
+
40
+ __all__ = ["Command"]
41
+
42
+ logger = logging.getLogger(__name__)
43
+
44
+
45
+ class Command(CommandContextMixIn):
46
+ usage: str = ""
47
+ ignore_require_venv: bool = False
48
+
49
+ def __init__(self, name: str, summary: str, isolated: bool = False) -> None:
50
+ super().__init__()
51
+
52
+ self.name = name
53
+ self.summary = summary
54
+ self.parser = ConfigOptionParser(
55
+ usage=self.usage,
56
+ prog=f"{get_prog()} {name}",
57
+ formatter=UpdatingDefaultsHelpFormatter(),
58
+ add_help_option=False,
59
+ name=name,
60
+ description=self.__doc__,
61
+ isolated=isolated,
62
+ )
63
+
64
+ self.tempdir_registry: Optional[TempDirRegistry] = None
65
+
66
+ # Commands should add options to this option group
67
+ optgroup_name = f"{self.name.capitalize()} Options"
68
+ self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)
69
+
70
+ # Add the general options
71
+ gen_opts = cmdoptions.make_option_group(
72
+ cmdoptions.general_group,
73
+ self.parser,
74
+ )
75
+ self.parser.add_option_group(gen_opts)
76
+
77
+ self.add_options()
78
+
79
+ def add_options(self) -> None:
80
+ pass
81
+
82
+ def handle_pip_version_check(self, options: Values) -> None:
83
+ """
84
+ This is a no-op so that commands by default do not do the pip version
85
+ check.
86
+ """
87
+ # Make sure we do the pip version check if the index_group options
88
+ # are present.
89
+ assert not hasattr(options, "no_index")
90
+
91
+ def run(self, options: Values, args: List[str]) -> int:
92
+ raise NotImplementedError
93
+
94
+ def parse_args(self, args: List[str]) -> Tuple[Values, List[str]]:
95
+ # factored out for testability
96
+ return self.parser.parse_args(args)
97
+
98
+ def main(self, args: List[str]) -> int:
99
+ try:
100
+ with self.main_context():
101
+ return self._main(args)
102
+ finally:
103
+ logging.shutdown()
104
+
105
+ def _main(self, args: List[str]) -> int:
106
+ # We must initialize this before the tempdir manager, otherwise the
107
+ # configuration would not be accessible by the time we clean up the
108
+ # tempdir manager.
109
+ self.tempdir_registry = self.enter_context(tempdir_registry())
110
+ # Intentionally set as early as possible so globally-managed temporary
111
+ # directories are available to the rest of the code.
112
+ self.enter_context(global_tempdir_manager())
113
+
114
+ options, args = self.parse_args(args)
115
+
116
+ # Set verbosity so that it can be used elsewhere.
117
+ self.verbosity = options.verbose - options.quiet
118
+
119
+ level_number = setup_logging(
120
+ verbosity=self.verbosity,
121
+ no_color=options.no_color,
122
+ user_log_file=options.log,
123
+ )
124
+
125
+ always_enabled_features = set(options.features_enabled) & set(
126
+ cmdoptions.ALWAYS_ENABLED_FEATURES
127
+ )
128
+ if always_enabled_features:
129
+ logger.warning(
130
+ "The following features are always enabled: %s. ",
131
+ ", ".join(sorted(always_enabled_features)),
132
+ )
133
+
134
+ # Make sure that the --python argument isn't specified after the
135
+ # subcommand. We can tell, because if --python was specified,
136
+ # we should only reach this point if we're running in the created
137
+ # subprocess, which has the _PIP_RUNNING_IN_SUBPROCESS environment
138
+ # variable set.
139
+ if options.python and "_PIP_RUNNING_IN_SUBPROCESS" not in os.environ:
140
+ logger.critical(
141
+ "The --python option must be placed before the pip subcommand name"
142
+ )
143
+ sys.exit(ERROR)
144
+
145
+ # TODO: Try to get these passing down from the command?
146
+ # without resorting to os.environ to hold these.
147
+ # This also affects isolated builds and it should.
148
+
149
+ if options.no_input:
150
+ os.environ["PIP_NO_INPUT"] = "1"
151
+
152
+ if options.exists_action:
153
+ os.environ["PIP_EXISTS_ACTION"] = " ".join(options.exists_action)
154
+
155
+ if options.require_venv and not self.ignore_require_venv:
156
+ # If a venv is required check if it can really be found
157
+ if not running_under_virtualenv():
158
+ logger.critical("Could not find an activated virtualenv (required).")
159
+ sys.exit(VIRTUALENV_NOT_FOUND)
160
+
161
+ if options.cache_dir:
162
+ options.cache_dir = normalize_path(options.cache_dir)
163
+ if not check_path_owner(options.cache_dir):
164
+ logger.warning(
165
+ "The directory '%s' or its parent directory is not owned "
166
+ "or is not writable by the current user. The cache "
167
+ "has been disabled. Check the permissions and owner of "
168
+ "that directory. If executing pip with sudo, you should "
169
+ "use sudo's -H flag.",
170
+ options.cache_dir,
171
+ )
172
+ options.cache_dir = None
173
+
174
+ def intercepts_unhandled_exc(
175
+ run_func: Callable[..., int]
176
+ ) -> Callable[..., int]:
177
+ @functools.wraps(run_func)
178
+ def exc_logging_wrapper(*args: Any) -> int:
179
+ try:
180
+ status = run_func(*args)
181
+ assert isinstance(status, int)
182
+ return status
183
+ except DiagnosticPipError as exc:
184
+ logger.error("%s", exc, extra={"rich": True})
185
+ logger.debug("Exception information:", exc_info=True)
186
+
187
+ return ERROR
188
+ except PreviousBuildDirError as exc:
189
+ logger.critical(str(exc))
190
+ logger.debug("Exception information:", exc_info=True)
191
+
192
+ return PREVIOUS_BUILD_DIR_ERROR
193
+ except (
194
+ InstallationError,
195
+ UninstallationError,
196
+ BadCommand,
197
+ NetworkConnectionError,
198
+ ) as exc:
199
+ logger.critical(str(exc))
200
+ logger.debug("Exception information:", exc_info=True)
201
+
202
+ return ERROR
203
+ except CommandError as exc:
204
+ logger.critical("%s", exc)
205
+ logger.debug("Exception information:", exc_info=True)
206
+
207
+ return ERROR
208
+ except BrokenStdoutLoggingError:
209
+ # Bypass our logger and write any remaining messages to
210
+ # stderr because stdout no longer works.
211
+ print("ERROR: Pipe to stdout was broken", file=sys.stderr)
212
+ if level_number <= logging.DEBUG:
213
+ traceback.print_exc(file=sys.stderr)
214
+
215
+ return ERROR
216
+ except KeyboardInterrupt:
217
+ logger.critical("Operation cancelled by user")
218
+ logger.debug("Exception information:", exc_info=True)
219
+
220
+ return ERROR
221
+ except BaseException:
222
+ logger.critical("Exception:", exc_info=True)
223
+
224
+ return UNKNOWN_ERROR
225
+
226
+ return exc_logging_wrapper
227
+
228
+ try:
229
+ if not options.debug_mode:
230
+ run = intercepts_unhandled_exc(self.run)
231
+ else:
232
+ run = self.run
233
+ rich_traceback.install(show_locals=True)
234
+ return run(options, args)
235
+ finally:
236
+ self.handle_pip_version_check(options)
env/lib/python3.9/site-packages/pip/_internal/cli/cmdoptions.py ADDED
@@ -0,0 +1,1077 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 importlib.util
14
+ import logging
15
+ import os
16
+ import textwrap
17
+ from functools import partial
18
+ from optparse import SUPPRESS_HELP, Option, OptionGroup, OptionParser, Values
19
+ from textwrap import dedent
20
+ from typing import Any, Callable, Dict, Optional, Tuple
21
+
22
+ from pip._vendor.packaging.utils import canonicalize_name
23
+
24
+ from pip._internal.cli.parser import ConfigOptionParser
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_dist_restriction(options: Values, check_target: bool = False) -> None:
63
+ """Function for determining if custom platform options are allowed.
64
+
65
+ :param options: The OptionParser options.
66
+ :param check_target: Whether or not to check if --target is being used.
67
+ """
68
+ dist_restriction_set = any(
69
+ [
70
+ options.python_version,
71
+ options.platforms,
72
+ options.abis,
73
+ options.implementation,
74
+ ]
75
+ )
76
+
77
+ binary_only = FormatControl(set(), {":all:"})
78
+ sdist_dependencies_allowed = (
79
+ options.format_control != binary_only and not options.ignore_dependencies
80
+ )
81
+
82
+ # Installations or downloads using dist restrictions must not combine
83
+ # source distributions and dist-specific wheels, as they are not
84
+ # guaranteed to be locally compatible.
85
+ if dist_restriction_set and sdist_dependencies_allowed:
86
+ raise CommandError(
87
+ "When restricting platform and interpreter constraints using "
88
+ "--python-version, --platform, --abi, or --implementation, "
89
+ "either --no-deps must be set, or --only-binary=:all: must be "
90
+ "set and --no-binary must not be set (or must be set to "
91
+ ":none:)."
92
+ )
93
+
94
+ if check_target:
95
+ if not options.dry_run and dist_restriction_set and not options.target_dir:
96
+ raise CommandError(
97
+ "Can not use any platform or abi specific options unless "
98
+ "installing via '--target' or using '--dry-run'"
99
+ )
100
+
101
+
102
+ def _path_option_check(option: Option, opt: str, value: str) -> str:
103
+ return os.path.expanduser(value)
104
+
105
+
106
+ def _package_name_option_check(option: Option, opt: str, value: str) -> str:
107
+ return canonicalize_name(value)
108
+
109
+
110
+ class PipOption(Option):
111
+ TYPES = Option.TYPES + ("path", "package_name")
112
+ TYPE_CHECKER = Option.TYPE_CHECKER.copy()
113
+ TYPE_CHECKER["package_name"] = _package_name_option_check
114
+ TYPE_CHECKER["path"] = _path_option_check
115
+
116
+
117
+ ###########
118
+ # options #
119
+ ###########
120
+
121
+ help_: Callable[..., Option] = partial(
122
+ Option,
123
+ "-h",
124
+ "--help",
125
+ dest="help",
126
+ action="help",
127
+ help="Show help.",
128
+ )
129
+
130
+ debug_mode: Callable[..., Option] = partial(
131
+ Option,
132
+ "--debug",
133
+ dest="debug_mode",
134
+ action="store_true",
135
+ default=False,
136
+ help=(
137
+ "Let unhandled exceptions propagate outside the main subroutine, "
138
+ "instead of logging them to stderr."
139
+ ),
140
+ )
141
+
142
+ isolated_mode: Callable[..., Option] = partial(
143
+ Option,
144
+ "--isolated",
145
+ dest="isolated_mode",
146
+ action="store_true",
147
+ default=False,
148
+ help=(
149
+ "Run pip in an isolated mode, ignoring environment variables and user "
150
+ "configuration."
151
+ ),
152
+ )
153
+
154
+ require_virtualenv: Callable[..., Option] = partial(
155
+ Option,
156
+ "--require-virtualenv",
157
+ "--require-venv",
158
+ dest="require_venv",
159
+ action="store_true",
160
+ default=False,
161
+ help=(
162
+ "Allow pip to only run in a virtual environment; "
163
+ "exit with an error otherwise."
164
+ ),
165
+ )
166
+
167
+ override_externally_managed: Callable[..., Option] = partial(
168
+ Option,
169
+ "--break-system-packages",
170
+ dest="override_externally_managed",
171
+ action="store_true",
172
+ help="Allow pip to modify an EXTERNALLY-MANAGED Python installation",
173
+ )
174
+
175
+ python: Callable[..., Option] = partial(
176
+ Option,
177
+ "--python",
178
+ dest="python",
179
+ help="Run pip with the specified Python interpreter.",
180
+ )
181
+
182
+ verbose: Callable[..., Option] = partial(
183
+ Option,
184
+ "-v",
185
+ "--verbose",
186
+ dest="verbose",
187
+ action="count",
188
+ default=0,
189
+ help="Give more output. Option is additive, and can be used up to 3 times.",
190
+ )
191
+
192
+ no_color: Callable[..., Option] = partial(
193
+ Option,
194
+ "--no-color",
195
+ dest="no_color",
196
+ action="store_true",
197
+ default=False,
198
+ help="Suppress colored output.",
199
+ )
200
+
201
+ version: Callable[..., Option] = partial(
202
+ Option,
203
+ "-V",
204
+ "--version",
205
+ dest="version",
206
+ action="store_true",
207
+ help="Show version and exit.",
208
+ )
209
+
210
+ quiet: Callable[..., Option] = partial(
211
+ Option,
212
+ "-q",
213
+ "--quiet",
214
+ dest="quiet",
215
+ action="count",
216
+ default=0,
217
+ help=(
218
+ "Give less output. Option is additive, and can be used up to 3"
219
+ " times (corresponding to WARNING, ERROR, and CRITICAL logging"
220
+ " levels)."
221
+ ),
222
+ )
223
+
224
+ progress_bar: Callable[..., Option] = partial(
225
+ Option,
226
+ "--progress-bar",
227
+ dest="progress_bar",
228
+ type="choice",
229
+ choices=["on", "off"],
230
+ default="on",
231
+ help="Specify whether the progress bar should be used [on, off] (default: on)",
232
+ )
233
+
234
+ log: Callable[..., Option] = partial(
235
+ PipOption,
236
+ "--log",
237
+ "--log-file",
238
+ "--local-log",
239
+ dest="log",
240
+ metavar="path",
241
+ type="path",
242
+ help="Path to a verbose appending log.",
243
+ )
244
+
245
+ no_input: Callable[..., Option] = partial(
246
+ Option,
247
+ # Don't ask for input
248
+ "--no-input",
249
+ dest="no_input",
250
+ action="store_true",
251
+ default=False,
252
+ help="Disable prompting for input.",
253
+ )
254
+
255
+ keyring_provider: Callable[..., Option] = partial(
256
+ Option,
257
+ "--keyring-provider",
258
+ dest="keyring_provider",
259
+ choices=["auto", "disabled", "import", "subprocess"],
260
+ default="auto",
261
+ help=(
262
+ "Enable the credential lookup via the keyring library if user input is allowed."
263
+ " Specify which mechanism to use [disabled, import, subprocess]."
264
+ " (default: disabled)"
265
+ ),
266
+ )
267
+
268
+ proxy: Callable[..., Option] = partial(
269
+ Option,
270
+ "--proxy",
271
+ dest="proxy",
272
+ type="str",
273
+ default="",
274
+ help="Specify a proxy in the form scheme://[user:passwd@]proxy.server:port.",
275
+ )
276
+
277
+ retries: Callable[..., Option] = partial(
278
+ Option,
279
+ "--retries",
280
+ dest="retries",
281
+ type="int",
282
+ default=5,
283
+ help="Maximum number of retries each connection should attempt "
284
+ "(default %default times).",
285
+ )
286
+
287
+ timeout: Callable[..., Option] = partial(
288
+ Option,
289
+ "--timeout",
290
+ "--default-timeout",
291
+ metavar="sec",
292
+ dest="timeout",
293
+ type="float",
294
+ default=15,
295
+ help="Set the socket timeout (default %default seconds).",
296
+ )
297
+
298
+
299
+ def exists_action() -> Option:
300
+ return Option(
301
+ # Option when path already exist
302
+ "--exists-action",
303
+ dest="exists_action",
304
+ type="choice",
305
+ choices=["s", "i", "w", "b", "a"],
306
+ default=[],
307
+ action="append",
308
+ metavar="action",
309
+ help="Default action when a path already exists: "
310
+ "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.",
311
+ )
312
+
313
+
314
+ cert: Callable[..., Option] = partial(
315
+ PipOption,
316
+ "--cert",
317
+ dest="cert",
318
+ type="path",
319
+ metavar="path",
320
+ help=(
321
+ "Path to PEM-encoded CA certificate bundle. "
322
+ "If provided, overrides the default. "
323
+ "See 'SSL Certificate Verification' in pip documentation "
324
+ "for more information."
325
+ ),
326
+ )
327
+
328
+ client_cert: Callable[..., Option] = partial(
329
+ PipOption,
330
+ "--client-cert",
331
+ dest="client_cert",
332
+ type="path",
333
+ default=None,
334
+ metavar="path",
335
+ help="Path to SSL client certificate, a single file containing the "
336
+ "private key and the certificate in PEM format.",
337
+ )
338
+
339
+ index_url: Callable[..., Option] = partial(
340
+ Option,
341
+ "-i",
342
+ "--index-url",
343
+ "--pypi-url",
344
+ dest="index_url",
345
+ metavar="URL",
346
+ default=PyPI.simple_url,
347
+ help="Base URL of the Python Package Index (default %default). "
348
+ "This should point to a repository compliant with PEP 503 "
349
+ "(the simple repository API) or a local directory laid out "
350
+ "in the same format.",
351
+ )
352
+
353
+
354
+ def extra_index_url() -> Option:
355
+ return Option(
356
+ "--extra-index-url",
357
+ dest="extra_index_urls",
358
+ metavar="URL",
359
+ action="append",
360
+ default=[],
361
+ help="Extra URLs of package indexes to use in addition to "
362
+ "--index-url. Should follow the same rules as "
363
+ "--index-url.",
364
+ )
365
+
366
+
367
+ no_index: Callable[..., Option] = partial(
368
+ Option,
369
+ "--no-index",
370
+ dest="no_index",
371
+ action="store_true",
372
+ default=False,
373
+ help="Ignore package index (only looking at --find-links URLs instead).",
374
+ )
375
+
376
+
377
+ def find_links() -> Option:
378
+ return Option(
379
+ "-f",
380
+ "--find-links",
381
+ dest="find_links",
382
+ action="append",
383
+ default=[],
384
+ metavar="url",
385
+ help="If a URL or path to an html file, then parse for links to "
386
+ "archives such as sdist (.tar.gz) or wheel (.whl) files. "
387
+ "If a local path or file:// URL that's a directory, "
388
+ "then look for archives in the directory listing. "
389
+ "Links to VCS project URLs are not supported.",
390
+ )
391
+
392
+
393
+ def trusted_host() -> Option:
394
+ return Option(
395
+ "--trusted-host",
396
+ dest="trusted_hosts",
397
+ action="append",
398
+ metavar="HOSTNAME",
399
+ default=[],
400
+ help="Mark this host or host:port pair as trusted, even though it "
401
+ "does not have valid or any HTTPS.",
402
+ )
403
+
404
+
405
+ def constraints() -> Option:
406
+ return Option(
407
+ "-c",
408
+ "--constraint",
409
+ dest="constraints",
410
+ action="append",
411
+ default=[],
412
+ metavar="file",
413
+ help="Constrain versions using the given constraints file. "
414
+ "This option can be used multiple times.",
415
+ )
416
+
417
+
418
+ def requirements() -> Option:
419
+ return Option(
420
+ "-r",
421
+ "--requirement",
422
+ dest="requirements",
423
+ action="append",
424
+ default=[],
425
+ metavar="file",
426
+ help="Install from the given requirements file. "
427
+ "This option can be used multiple times.",
428
+ )
429
+
430
+
431
+ def editable() -> Option:
432
+ return Option(
433
+ "-e",
434
+ "--editable",
435
+ dest="editables",
436
+ action="append",
437
+ default=[],
438
+ metavar="path/url",
439
+ help=(
440
+ "Install a project in editable mode (i.e. setuptools "
441
+ '"develop mode") from a local project path or a VCS url.'
442
+ ),
443
+ )
444
+
445
+
446
+ def _handle_src(option: Option, opt_str: str, value: str, parser: OptionParser) -> None:
447
+ value = os.path.abspath(value)
448
+ setattr(parser.values, option.dest, value)
449
+
450
+
451
+ src: Callable[..., Option] = partial(
452
+ PipOption,
453
+ "--src",
454
+ "--source",
455
+ "--source-dir",
456
+ "--source-directory",
457
+ dest="src_dir",
458
+ type="path",
459
+ metavar="dir",
460
+ default=get_src_prefix(),
461
+ action="callback",
462
+ callback=_handle_src,
463
+ help="Directory to check out editable projects into. "
464
+ 'The default in a virtualenv is "<venv path>/src". '
465
+ 'The default for global installs is "<current dir>/src".',
466
+ )
467
+
468
+
469
+ def _get_format_control(values: Values, option: Option) -> Any:
470
+ """Get a format_control object."""
471
+ return getattr(values, option.dest)
472
+
473
+
474
+ def _handle_no_binary(
475
+ option: Option, opt_str: str, value: str, parser: OptionParser
476
+ ) -> None:
477
+ existing = _get_format_control(parser.values, option)
478
+ FormatControl.handle_mutual_excludes(
479
+ value,
480
+ existing.no_binary,
481
+ existing.only_binary,
482
+ )
483
+
484
+
485
+ def _handle_only_binary(
486
+ option: Option, opt_str: str, value: str, parser: OptionParser
487
+ ) -> None:
488
+ existing = _get_format_control(parser.values, option)
489
+ FormatControl.handle_mutual_excludes(
490
+ value,
491
+ existing.only_binary,
492
+ existing.no_binary,
493
+ )
494
+
495
+
496
+ def no_binary() -> Option:
497
+ format_control = FormatControl(set(), set())
498
+ return Option(
499
+ "--no-binary",
500
+ dest="format_control",
501
+ action="callback",
502
+ callback=_handle_no_binary,
503
+ type="str",
504
+ default=format_control,
505
+ help="Do not use binary packages. Can be supplied multiple times, and "
506
+ 'each time adds to the existing value. Accepts either ":all:" to '
507
+ 'disable all binary packages, ":none:" to empty the set (notice '
508
+ "the colons), or one or more package names with commas between "
509
+ "them (no colons). Note that some packages are tricky to compile "
510
+ "and may fail to install when this option is used on them.",
511
+ )
512
+
513
+
514
+ def only_binary() -> Option:
515
+ format_control = FormatControl(set(), set())
516
+ return Option(
517
+ "--only-binary",
518
+ dest="format_control",
519
+ action="callback",
520
+ callback=_handle_only_binary,
521
+ type="str",
522
+ default=format_control,
523
+ help="Do not use source packages. Can be supplied multiple times, and "
524
+ 'each time adds to the existing value. Accepts either ":all:" to '
525
+ 'disable all source packages, ":none:" to empty the set, or one '
526
+ "or more package names with commas between them. Packages "
527
+ "without binary distributions will fail to install when this "
528
+ "option is used on them.",
529
+ )
530
+
531
+
532
+ platforms: Callable[..., Option] = partial(
533
+ Option,
534
+ "--platform",
535
+ dest="platforms",
536
+ metavar="platform",
537
+ action="append",
538
+ default=None,
539
+ help=(
540
+ "Only use wheels compatible with <platform>. Defaults to the "
541
+ "platform of the running system. Use this option multiple times to "
542
+ "specify multiple platforms supported by the target interpreter."
543
+ ),
544
+ )
545
+
546
+
547
+ # This was made a separate function for unit-testing purposes.
548
+ def _convert_python_version(value: str) -> Tuple[Tuple[int, ...], Optional[str]]:
549
+ """
550
+ Convert a version string like "3", "37", or "3.7.3" into a tuple of ints.
551
+
552
+ :return: A 2-tuple (version_info, error_msg), where `error_msg` is
553
+ non-None if and only if there was a parsing error.
554
+ """
555
+ if not value:
556
+ # The empty string is the same as not providing a value.
557
+ return (None, None)
558
+
559
+ parts = value.split(".")
560
+ if len(parts) > 3:
561
+ return ((), "at most three version parts are allowed")
562
+
563
+ if len(parts) == 1:
564
+ # Then we are in the case of "3" or "37".
565
+ value = parts[0]
566
+ if len(value) > 1:
567
+ parts = [value[0], value[1:]]
568
+
569
+ try:
570
+ version_info = tuple(int(part) for part in parts)
571
+ except ValueError:
572
+ return ((), "each version part must be an integer")
573
+
574
+ return (version_info, None)
575
+
576
+
577
+ def _handle_python_version(
578
+ option: Option, opt_str: str, value: str, parser: OptionParser
579
+ ) -> None:
580
+ """
581
+ Handle a provided --python-version value.
582
+ """
583
+ version_info, error_msg = _convert_python_version(value)
584
+ if error_msg is not None:
585
+ msg = "invalid --python-version value: {!r}: {}".format(
586
+ value,
587
+ error_msg,
588
+ )
589
+ raise_option_error(parser, option=option, msg=msg)
590
+
591
+ parser.values.python_version = version_info
592
+
593
+
594
+ python_version: Callable[..., Option] = partial(
595
+ Option,
596
+ "--python-version",
597
+ dest="python_version",
598
+ metavar="python_version",
599
+ action="callback",
600
+ callback=_handle_python_version,
601
+ type="str",
602
+ default=None,
603
+ help=dedent(
604
+ """\
605
+ The Python interpreter version to use for wheel and "Requires-Python"
606
+ compatibility checks. Defaults to a version derived from the running
607
+ interpreter. The version can be specified using up to three dot-separated
608
+ integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor
609
+ version can also be given as a string without dots (e.g. "37" for 3.7.0).
610
+ """
611
+ ),
612
+ )
613
+
614
+
615
+ implementation: Callable[..., Option] = partial(
616
+ Option,
617
+ "--implementation",
618
+ dest="implementation",
619
+ metavar="implementation",
620
+ default=None,
621
+ help=(
622
+ "Only use wheels compatible with Python "
623
+ "implementation <implementation>, e.g. 'pp', 'jy', 'cp', "
624
+ " or 'ip'. If not specified, then the current "
625
+ "interpreter implementation is used. Use 'py' to force "
626
+ "implementation-agnostic wheels."
627
+ ),
628
+ )
629
+
630
+
631
+ abis: Callable[..., Option] = partial(
632
+ Option,
633
+ "--abi",
634
+ dest="abis",
635
+ metavar="abi",
636
+ action="append",
637
+ default=None,
638
+ help=(
639
+ "Only use wheels compatible with Python abi <abi>, e.g. 'pypy_41'. "
640
+ "If not specified, then the current interpreter abi tag is used. "
641
+ "Use this option multiple times to specify multiple abis supported "
642
+ "by the target interpreter. Generally you will need to specify "
643
+ "--implementation, --platform, and --python-version when using this "
644
+ "option."
645
+ ),
646
+ )
647
+
648
+
649
+ def add_target_python_options(cmd_opts: OptionGroup) -> None:
650
+ cmd_opts.add_option(platforms())
651
+ cmd_opts.add_option(python_version())
652
+ cmd_opts.add_option(implementation())
653
+ cmd_opts.add_option(abis())
654
+
655
+
656
+ def make_target_python(options: Values) -> TargetPython:
657
+ target_python = TargetPython(
658
+ platforms=options.platforms,
659
+ py_version_info=options.python_version,
660
+ abis=options.abis,
661
+ implementation=options.implementation,
662
+ )
663
+
664
+ return target_python
665
+
666
+
667
+ def prefer_binary() -> Option:
668
+ return Option(
669
+ "--prefer-binary",
670
+ dest="prefer_binary",
671
+ action="store_true",
672
+ default=False,
673
+ help=(
674
+ "Prefer binary packages over source packages, even if the "
675
+ "source packages are newer."
676
+ ),
677
+ )
678
+
679
+
680
+ cache_dir: Callable[..., Option] = partial(
681
+ PipOption,
682
+ "--cache-dir",
683
+ dest="cache_dir",
684
+ default=USER_CACHE_DIR,
685
+ metavar="dir",
686
+ type="path",
687
+ help="Store the cache data in <dir>.",
688
+ )
689
+
690
+
691
+ def _handle_no_cache_dir(
692
+ option: Option, opt: str, value: str, parser: OptionParser
693
+ ) -> None:
694
+ """
695
+ Process a value provided for the --no-cache-dir option.
696
+
697
+ This is an optparse.Option callback for the --no-cache-dir option.
698
+ """
699
+ # The value argument will be None if --no-cache-dir is passed via the
700
+ # command-line, since the option doesn't accept arguments. However,
701
+ # the value can be non-None if the option is triggered e.g. by an
702
+ # environment variable, like PIP_NO_CACHE_DIR=true.
703
+ if value is not None:
704
+ # Then parse the string value to get argument error-checking.
705
+ try:
706
+ strtobool(value)
707
+ except ValueError as exc:
708
+ raise_option_error(parser, option=option, msg=str(exc))
709
+
710
+ # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool()
711
+ # converted to 0 (like "false" or "no") caused cache_dir to be disabled
712
+ # rather than enabled (logic would say the latter). Thus, we disable
713
+ # the cache directory not just on values that parse to True, but (for
714
+ # backwards compatibility reasons) also on values that parse to False.
715
+ # In other words, always set it to False if the option is provided in
716
+ # some (valid) form.
717
+ parser.values.cache_dir = False
718
+
719
+
720
+ no_cache: Callable[..., Option] = partial(
721
+ Option,
722
+ "--no-cache-dir",
723
+ dest="cache_dir",
724
+ action="callback",
725
+ callback=_handle_no_cache_dir,
726
+ help="Disable the cache.",
727
+ )
728
+
729
+ no_deps: Callable[..., Option] = partial(
730
+ Option,
731
+ "--no-deps",
732
+ "--no-dependencies",
733
+ dest="ignore_dependencies",
734
+ action="store_true",
735
+ default=False,
736
+ help="Don't install package dependencies.",
737
+ )
738
+
739
+ ignore_requires_python: Callable[..., Option] = partial(
740
+ Option,
741
+ "--ignore-requires-python",
742
+ dest="ignore_requires_python",
743
+ action="store_true",
744
+ help="Ignore the Requires-Python information.",
745
+ )
746
+
747
+ no_build_isolation: Callable[..., Option] = partial(
748
+ Option,
749
+ "--no-build-isolation",
750
+ dest="build_isolation",
751
+ action="store_false",
752
+ default=True,
753
+ help="Disable isolation when building a modern source distribution. "
754
+ "Build dependencies specified by PEP 518 must be already installed "
755
+ "if this option is used.",
756
+ )
757
+
758
+ check_build_deps: Callable[..., Option] = partial(
759
+ Option,
760
+ "--check-build-dependencies",
761
+ dest="check_build_deps",
762
+ action="store_true",
763
+ default=False,
764
+ help="Check the build dependencies when PEP517 is used.",
765
+ )
766
+
767
+
768
+ def _handle_no_use_pep517(
769
+ option: Option, opt: str, value: str, parser: OptionParser
770
+ ) -> None:
771
+ """
772
+ Process a value provided for the --no-use-pep517 option.
773
+
774
+ This is an optparse.Option callback for the no_use_pep517 option.
775
+ """
776
+ # Since --no-use-pep517 doesn't accept arguments, the value argument
777
+ # will be None if --no-use-pep517 is passed via the command-line.
778
+ # However, the value can be non-None if the option is triggered e.g.
779
+ # by an environment variable, for example "PIP_NO_USE_PEP517=true".
780
+ if value is not None:
781
+ msg = """A value was passed for --no-use-pep517,
782
+ probably using either the PIP_NO_USE_PEP517 environment variable
783
+ or the "no-use-pep517" config file option. Use an appropriate value
784
+ of the PIP_USE_PEP517 environment variable or the "use-pep517"
785
+ config file option instead.
786
+ """
787
+ raise_option_error(parser, option=option, msg=msg)
788
+
789
+ # If user doesn't wish to use pep517, we check if setuptools and wheel are installed
790
+ # and raise error if it is not.
791
+ packages = ("setuptools", "wheel")
792
+ if not all(importlib.util.find_spec(package) for package in packages):
793
+ msg = (
794
+ f"It is not possible to use --no-use-pep517 "
795
+ f"without {' and '.join(packages)} installed."
796
+ )
797
+ raise_option_error(parser, option=option, msg=msg)
798
+
799
+ # Otherwise, --no-use-pep517 was passed via the command-line.
800
+ parser.values.use_pep517 = False
801
+
802
+
803
+ use_pep517: Any = partial(
804
+ Option,
805
+ "--use-pep517",
806
+ dest="use_pep517",
807
+ action="store_true",
808
+ default=None,
809
+ help="Use PEP 517 for building source distributions "
810
+ "(use --no-use-pep517 to force legacy behaviour).",
811
+ )
812
+
813
+ no_use_pep517: Any = partial(
814
+ Option,
815
+ "--no-use-pep517",
816
+ dest="use_pep517",
817
+ action="callback",
818
+ callback=_handle_no_use_pep517,
819
+ default=None,
820
+ help=SUPPRESS_HELP,
821
+ )
822
+
823
+
824
+ def _handle_config_settings(
825
+ option: Option, opt_str: str, value: str, parser: OptionParser
826
+ ) -> None:
827
+ key, sep, val = value.partition("=")
828
+ if sep != "=":
829
+ parser.error(f"Arguments to {opt_str} must be of the form KEY=VAL")
830
+ dest = getattr(parser.values, option.dest)
831
+ if dest is None:
832
+ dest = {}
833
+ setattr(parser.values, option.dest, dest)
834
+ if key in dest:
835
+ if isinstance(dest[key], list):
836
+ dest[key].append(val)
837
+ else:
838
+ dest[key] = [dest[key], val]
839
+ else:
840
+ dest[key] = val
841
+
842
+
843
+ config_settings: Callable[..., Option] = partial(
844
+ Option,
845
+ "-C",
846
+ "--config-settings",
847
+ dest="config_settings",
848
+ type=str,
849
+ action="callback",
850
+ callback=_handle_config_settings,
851
+ metavar="settings",
852
+ help="Configuration settings to be passed to the PEP 517 build backend. "
853
+ "Settings take the form KEY=VALUE. Use multiple --config-settings options "
854
+ "to pass multiple keys to the backend.",
855
+ )
856
+
857
+ build_options: Callable[..., Option] = partial(
858
+ Option,
859
+ "--build-option",
860
+ dest="build_options",
861
+ metavar="options",
862
+ action="append",
863
+ help="Extra arguments to be supplied to 'setup.py bdist_wheel'.",
864
+ )
865
+
866
+ global_options: Callable[..., Option] = partial(
867
+ Option,
868
+ "--global-option",
869
+ dest="global_options",
870
+ action="append",
871
+ metavar="options",
872
+ help="Extra global options to be supplied to the setup.py "
873
+ "call before the install or bdist_wheel command.",
874
+ )
875
+
876
+ no_clean: Callable[..., Option] = partial(
877
+ Option,
878
+ "--no-clean",
879
+ action="store_true",
880
+ default=False,
881
+ help="Don't clean up build directories.",
882
+ )
883
+
884
+ pre: Callable[..., Option] = partial(
885
+ Option,
886
+ "--pre",
887
+ action="store_true",
888
+ default=False,
889
+ help="Include pre-release and development versions. By default, "
890
+ "pip only finds stable versions.",
891
+ )
892
+
893
+ disable_pip_version_check: Callable[..., Option] = partial(
894
+ Option,
895
+ "--disable-pip-version-check",
896
+ dest="disable_pip_version_check",
897
+ action="store_true",
898
+ default=False,
899
+ help="Don't periodically check PyPI to determine whether a new version "
900
+ "of pip is available for download. Implied with --no-index.",
901
+ )
902
+
903
+ root_user_action: Callable[..., Option] = partial(
904
+ Option,
905
+ "--root-user-action",
906
+ dest="root_user_action",
907
+ default="warn",
908
+ choices=["warn", "ignore"],
909
+ help="Action if pip is run as a root user. By default, a warning message is shown.",
910
+ )
911
+
912
+
913
+ def _handle_merge_hash(
914
+ option: Option, opt_str: str, value: str, parser: OptionParser
915
+ ) -> None:
916
+ """Given a value spelled "algo:digest", append the digest to a list
917
+ pointed to in a dict by the algo name."""
918
+ if not parser.values.hashes:
919
+ parser.values.hashes = {}
920
+ try:
921
+ algo, digest = value.split(":", 1)
922
+ except ValueError:
923
+ parser.error(
924
+ "Arguments to {} must be a hash name "
925
+ "followed by a value, like --hash=sha256:"
926
+ "abcde...".format(opt_str)
927
+ )
928
+ if algo not in STRONG_HASHES:
929
+ parser.error(
930
+ "Allowed hash algorithms for {} are {}.".format(
931
+ opt_str, ", ".join(STRONG_HASHES)
932
+ )
933
+ )
934
+ parser.values.hashes.setdefault(algo, []).append(digest)
935
+
936
+
937
+ hash: Callable[..., Option] = partial(
938
+ Option,
939
+ "--hash",
940
+ # Hash values eventually end up in InstallRequirement.hashes due to
941
+ # __dict__ copying in process_line().
942
+ dest="hashes",
943
+ action="callback",
944
+ callback=_handle_merge_hash,
945
+ type="string",
946
+ help="Verify that the package's archive matches this "
947
+ "hash before installing. Example: --hash=sha256:abcdef...",
948
+ )
949
+
950
+
951
+ require_hashes: Callable[..., Option] = partial(
952
+ Option,
953
+ "--require-hashes",
954
+ dest="require_hashes",
955
+ action="store_true",
956
+ default=False,
957
+ help="Require a hash to check each requirement against, for "
958
+ "repeatable installs. This option is implied when any package in a "
959
+ "requirements file has a --hash option.",
960
+ )
961
+
962
+
963
+ list_path: Callable[..., Option] = partial(
964
+ PipOption,
965
+ "--path",
966
+ dest="path",
967
+ type="path",
968
+ action="append",
969
+ help="Restrict to the specified installation path for listing "
970
+ "packages (can be used multiple times).",
971
+ )
972
+
973
+
974
+ def check_list_path_option(options: Values) -> None:
975
+ if options.path and (options.user or options.local):
976
+ raise CommandError("Cannot combine '--path' with '--user' or '--local'")
977
+
978
+
979
+ list_exclude: Callable[..., Option] = partial(
980
+ PipOption,
981
+ "--exclude",
982
+ dest="excludes",
983
+ action="append",
984
+ metavar="package",
985
+ type="package_name",
986
+ help="Exclude specified package from the output",
987
+ )
988
+
989
+
990
+ no_python_version_warning: Callable[..., Option] = partial(
991
+ Option,
992
+ "--no-python-version-warning",
993
+ dest="no_python_version_warning",
994
+ action="store_true",
995
+ default=False,
996
+ help="Silence deprecation warnings for upcoming unsupported Pythons.",
997
+ )
998
+
999
+
1000
+ # Features that are now always on. A warning is printed if they are used.
1001
+ ALWAYS_ENABLED_FEATURES = [
1002
+ "no-binary-enable-wheel-cache", # always on since 23.1
1003
+ ]
1004
+
1005
+ use_new_feature: Callable[..., Option] = partial(
1006
+ Option,
1007
+ "--use-feature",
1008
+ dest="features_enabled",
1009
+ metavar="feature",
1010
+ action="append",
1011
+ default=[],
1012
+ choices=[
1013
+ "fast-deps",
1014
+ "truststore",
1015
+ ]
1016
+ + ALWAYS_ENABLED_FEATURES,
1017
+ help="Enable new functionality, that may be backward incompatible.",
1018
+ )
1019
+
1020
+ use_deprecated_feature: Callable[..., Option] = partial(
1021
+ Option,
1022
+ "--use-deprecated",
1023
+ dest="deprecated_features_enabled",
1024
+ metavar="feature",
1025
+ action="append",
1026
+ default=[],
1027
+ choices=[
1028
+ "legacy-resolver",
1029
+ ],
1030
+ help=("Enable deprecated functionality, that will be removed in the future."),
1031
+ )
1032
+
1033
+
1034
+ ##########
1035
+ # groups #
1036
+ ##########
1037
+
1038
+ general_group: Dict[str, Any] = {
1039
+ "name": "General Options",
1040
+ "options": [
1041
+ help_,
1042
+ debug_mode,
1043
+ isolated_mode,
1044
+ require_virtualenv,
1045
+ python,
1046
+ verbose,
1047
+ version,
1048
+ quiet,
1049
+ log,
1050
+ no_input,
1051
+ keyring_provider,
1052
+ proxy,
1053
+ retries,
1054
+ timeout,
1055
+ exists_action,
1056
+ trusted_host,
1057
+ cert,
1058
+ client_cert,
1059
+ cache_dir,
1060
+ no_cache,
1061
+ disable_pip_version_check,
1062
+ no_color,
1063
+ no_python_version_warning,
1064
+ use_new_feature,
1065
+ use_deprecated_feature,
1066
+ ],
1067
+ }
1068
+
1069
+ index_group: Dict[str, Any] = {
1070
+ "name": "Package Index Options",
1071
+ "options": [
1072
+ index_url,
1073
+ extra_index_url,
1074
+ no_index,
1075
+ find_links,
1076
+ ],
1077
+ }
env/lib/python3.9/site-packages/pip/_internal/cli/command_context.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import ExitStack, contextmanager
2
+ from typing import ContextManager, Generator, 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) -> Generator[None, None, 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)
env/lib/python3.9/site-packages/pip/_internal/cli/main.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Primary application entrypoint.
2
+ """
3
+ import locale
4
+ import logging
5
+ import os
6
+ import sys
7
+ import warnings
8
+ from typing import List, Optional
9
+
10
+ from pip._internal.cli.autocompletion import autocomplete
11
+ from pip._internal.cli.main_parser import parse_command
12
+ from pip._internal.commands import create_command
13
+ from pip._internal.exceptions import PipError
14
+ from pip._internal.utils import deprecation
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ # Do not import and use main() directly! Using it directly is actively
20
+ # discouraged by pip's maintainers. The name, location and behavior of
21
+ # this function is subject to change, so calling it directly is not
22
+ # portable across different pip versions.
23
+
24
+ # In addition, running pip in-process is unsupported and unsafe. This is
25
+ # elaborated in detail at
26
+ # https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program.
27
+ # That document also provides suggestions that should work for nearly
28
+ # all users that are considering importing and using main() directly.
29
+
30
+ # However, we know that certain users will still want to invoke pip
31
+ # in-process. If you understand and accept the implications of using pip
32
+ # in an unsupported manner, the best approach is to use runpy to avoid
33
+ # depending on the exact location of this entry point.
34
+
35
+ # The following example shows how to use runpy to invoke pip in that
36
+ # case:
37
+ #
38
+ # sys.argv = ["pip", your, args, here]
39
+ # runpy.run_module("pip", run_name="__main__")
40
+ #
41
+ # Note that this will exit the process after running, unlike a direct
42
+ # call to main. As it is not safe to do any processing after calling
43
+ # main, this should not be an issue in practice.
44
+
45
+
46
+ def main(args: Optional[List[str]] = None) -> int:
47
+ if args is None:
48
+ args = sys.argv[1:]
49
+
50
+ # Suppress the pkg_resources deprecation warning
51
+ # Note - we use a module of .*pkg_resources to cover
52
+ # the normal case (pip._vendor.pkg_resources) and the
53
+ # devendored case (a bare pkg_resources)
54
+ warnings.filterwarnings(
55
+ action="ignore", category=DeprecationWarning, module=".*pkg_resources"
56
+ )
57
+
58
+ # Configure our deprecation warnings to be sent through loggers
59
+ deprecation.install_warning_logger()
60
+
61
+ autocomplete()
62
+
63
+ try:
64
+ cmd_name, cmd_args = parse_command(args)
65
+ except PipError as exc:
66
+ sys.stderr.write(f"ERROR: {exc}")
67
+ sys.stderr.write(os.linesep)
68
+ sys.exit(1)
69
+
70
+ # Needed for locale.getpreferredencoding(False) to work
71
+ # in pip._internal.utils.encoding.auto_decode
72
+ try:
73
+ locale.setlocale(locale.LC_ALL, "")
74
+ except locale.Error as e:
75
+ # setlocale can apparently crash if locale are uninitialized
76
+ logger.debug("Ignoring error %s when setting locale", e)
77
+ command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
78
+
79
+ return command.main(cmd_args)
env/lib/python3.9/site-packages/pip/_internal/cli/main_parser.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A single place for constructing and exposing the main parser
2
+ """
3
+
4
+ import os
5
+ import subprocess
6
+ import sys
7
+ from typing import List, Optional, Tuple
8
+
9
+ from pip._internal.build_env import get_runnable_pip
10
+ from pip._internal.cli import cmdoptions
11
+ from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
12
+ from pip._internal.commands import commands_dict, get_similar_commands
13
+ from pip._internal.exceptions import CommandError
14
+ from pip._internal.utils.misc import get_pip_version, get_prog
15
+
16
+ __all__ = ["create_main_parser", "parse_command"]
17
+
18
+
19
+ def create_main_parser() -> ConfigOptionParser:
20
+ """Creates and returns the main parser for pip's CLI"""
21
+
22
+ parser = ConfigOptionParser(
23
+ usage="\n%prog <command> [options]",
24
+ add_help_option=False,
25
+ formatter=UpdatingDefaultsHelpFormatter(),
26
+ name="global",
27
+ prog=get_prog(),
28
+ )
29
+ parser.disable_interspersed_args()
30
+
31
+ parser.version = get_pip_version()
32
+
33
+ # add the general options
34
+ gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)
35
+ parser.add_option_group(gen_opts)
36
+
37
+ # so the help formatter knows
38
+ parser.main = True # type: ignore
39
+
40
+ # create command listing for description
41
+ description = [""] + [
42
+ f"{name:27} {command_info.summary}"
43
+ for name, command_info in commands_dict.items()
44
+ ]
45
+ parser.description = "\n".join(description)
46
+
47
+ return parser
48
+
49
+
50
+ def identify_python_interpreter(python: str) -> Optional[str]:
51
+ # If the named file exists, use it.
52
+ # If it's a directory, assume it's a virtual environment and
53
+ # look for the environment's Python executable.
54
+ if os.path.exists(python):
55
+ if os.path.isdir(python):
56
+ # bin/python for Unix, Scripts/python.exe for Windows
57
+ # Try both in case of odd cases like cygwin.
58
+ for exe in ("bin/python", "Scripts/python.exe"):
59
+ py = os.path.join(python, exe)
60
+ if os.path.exists(py):
61
+ return py
62
+ else:
63
+ return python
64
+
65
+ # Could not find the interpreter specified
66
+ return None
67
+
68
+
69
+ def parse_command(args: List[str]) -> Tuple[str, List[str]]:
70
+ parser = create_main_parser()
71
+
72
+ # Note: parser calls disable_interspersed_args(), so the result of this
73
+ # call is to split the initial args into the general options before the
74
+ # subcommand and everything else.
75
+ # For example:
76
+ # args: ['--timeout=5', 'install', '--user', 'INITools']
77
+ # general_options: ['--timeout==5']
78
+ # args_else: ['install', '--user', 'INITools']
79
+ general_options, args_else = parser.parse_args(args)
80
+
81
+ # --python
82
+ if general_options.python and "_PIP_RUNNING_IN_SUBPROCESS" not in os.environ:
83
+ # Re-invoke pip using the specified Python interpreter
84
+ interpreter = identify_python_interpreter(general_options.python)
85
+ if interpreter is None:
86
+ raise CommandError(
87
+ f"Could not locate Python interpreter {general_options.python}"
88
+ )
89
+
90
+ pip_cmd = [
91
+ interpreter,
92
+ get_runnable_pip(),
93
+ ]
94
+ pip_cmd.extend(args)
95
+
96
+ # Set a flag so the child doesn't re-invoke itself, causing
97
+ # an infinite loop.
98
+ os.environ["_PIP_RUNNING_IN_SUBPROCESS"] = "1"
99
+ returncode = 0
100
+ try:
101
+ proc = subprocess.run(pip_cmd)
102
+ returncode = proc.returncode
103
+ except (subprocess.SubprocessError, OSError) as exc:
104
+ raise CommandError(f"Failed to run pip under {interpreter}: {exc}")
105
+ sys.exit(returncode)
106
+
107
+ # --version
108
+ if general_options.version:
109
+ sys.stdout.write(parser.version)
110
+ sys.stdout.write(os.linesep)
111
+ sys.exit()
112
+
113
+ # pip || pip help -> print_help()
114
+ if not args_else or (args_else[0] == "help" and len(args_else) == 1):
115
+ parser.print_help()
116
+ sys.exit()
117
+
118
+ # the subcommand name
119
+ cmd_name = args_else[0]
120
+
121
+ if cmd_name not in commands_dict:
122
+ guess = get_similar_commands(cmd_name)
123
+
124
+ msg = [f'unknown command "{cmd_name}"']
125
+ if guess:
126
+ msg.append(f'maybe you meant "{guess}"')
127
+
128
+ raise CommandError(" - ".join(msg))
129
+
130
+ # all the args without the subcommand
131
+ cmd_args = args[:]
132
+ cmd_args.remove(cmd_name)
133
+
134
+ return cmd_name, cmd_args
env/lib/python3.9/site-packages/pip/_internal/cli/parser.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, Generator, 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(
179
+ self,
180
+ ) -> Generator[Tuple[str, Any], None, None]:
181
+ # Configuration gives keys in an unordered manner. Order them.
182
+ override_order = ["global", self.name, ":env:"]
183
+
184
+ # Pool the options into different groups
185
+ section_items: Dict[str, List[Tuple[str, Any]]] = {
186
+ name: [] for name in override_order
187
+ }
188
+ for section_key, val in self.config.items():
189
+ # ignore empty values
190
+ if not val:
191
+ logger.debug(
192
+ "Ignoring configuration key '%s' as it's value is empty.",
193
+ section_key,
194
+ )
195
+ continue
196
+
197
+ section, key = section_key.split(".", 1)
198
+ if section in override_order:
199
+ section_items[section].append((key, val))
200
+
201
+ # Yield each group in their override order
202
+ for section in override_order:
203
+ for key, val in section_items[section]:
204
+ yield key, val
205
+
206
+ def _update_defaults(self, defaults: Dict[str, Any]) -> Dict[str, Any]:
207
+ """Updates the given defaults with values from the config files and
208
+ the environ. Does a little special handling for certain types of
209
+ options (lists)."""
210
+
211
+ # Accumulate complex default state.
212
+ self.values = optparse.Values(self.defaults)
213
+ late_eval = set()
214
+ # Then set the options with those values
215
+ for key, val in self._get_ordered_configuration_items():
216
+ # '--' because configuration supports only long names
217
+ option = self.get_option("--" + key)
218
+
219
+ # Ignore options not present in this parser. E.g. non-globals put
220
+ # in [global] by users that want them to apply to all applicable
221
+ # commands.
222
+ if option is None:
223
+ continue
224
+
225
+ assert option.dest is not None
226
+
227
+ if option.action in ("store_true", "store_false"):
228
+ try:
229
+ val = strtobool(val)
230
+ except ValueError:
231
+ self.error(
232
+ "{} is not a valid value for {} option, "
233
+ "please specify a boolean value like yes/no, "
234
+ "true/false or 1/0 instead.".format(val, key)
235
+ )
236
+ elif option.action == "count":
237
+ with suppress(ValueError):
238
+ val = strtobool(val)
239
+ with suppress(ValueError):
240
+ val = int(val)
241
+ if not isinstance(val, int) or val < 0:
242
+ self.error(
243
+ "{} is not a valid value for {} option, "
244
+ "please instead specify either a non-negative integer "
245
+ "or a boolean value like yes/no or false/true "
246
+ "which is equivalent to 1/0.".format(val, key)
247
+ )
248
+ elif option.action == "append":
249
+ val = val.split()
250
+ val = [self.check_default(option, key, v) for v in val]
251
+ elif option.action == "callback":
252
+ assert option.callback is not None
253
+ late_eval.add(option.dest)
254
+ opt_str = option.get_opt_string()
255
+ val = option.convert_value(opt_str, val)
256
+ # From take_action
257
+ args = option.callback_args or ()
258
+ kwargs = option.callback_kwargs or {}
259
+ option.callback(option, opt_str, val, self, *args, **kwargs)
260
+ else:
261
+ val = self.check_default(option, key, val)
262
+
263
+ defaults[option.dest] = val
264
+
265
+ for key in late_eval:
266
+ defaults[key] = getattr(self.values, key)
267
+ self.values = None
268
+ return defaults
269
+
270
+ def get_default_values(self) -> optparse.Values:
271
+ """Overriding to make updating the defaults after instantiation of
272
+ the option parser possible, _update_defaults() does the dirty work."""
273
+ if not self.process_default_values:
274
+ # Old, pre-Optik 1.5 behaviour.
275
+ return optparse.Values(self.defaults)
276
+
277
+ # Load the configuration, or error out in case of an error
278
+ try:
279
+ self.config.load()
280
+ except ConfigurationError as err:
281
+ self.exit(UNKNOWN_ERROR, str(err))
282
+
283
+ defaults = self._update_defaults(self.defaults.copy()) # ours
284
+ for option in self._get_all_options():
285
+ assert option.dest is not None
286
+ default = defaults.get(option.dest)
287
+ if isinstance(default, str):
288
+ opt_str = option.get_opt_string()
289
+ defaults[option.dest] = option.check_value(opt_str, default)
290
+ return optparse.Values(defaults)
291
+
292
+ def error(self, msg: str) -> None:
293
+ self.print_usage(sys.stderr)
294
+ self.exit(UNKNOWN_ERROR, f"{msg}\n")
env/lib/python3.9/site-packages/pip/_internal/cli/progress_bars.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ from typing import Callable, Generator, Iterable, Iterator, Optional, Tuple
3
+
4
+ from pip._vendor.rich.progress import (
5
+ BarColumn,
6
+ DownloadColumn,
7
+ FileSizeColumn,
8
+ Progress,
9
+ ProgressColumn,
10
+ SpinnerColumn,
11
+ TextColumn,
12
+ TimeElapsedColumn,
13
+ TimeRemainingColumn,
14
+ TransferSpeedColumn,
15
+ )
16
+
17
+ from pip._internal.utils.logging import get_indentation
18
+
19
+ DownloadProgressRenderer = Callable[[Iterable[bytes]], Iterator[bytes]]
20
+
21
+
22
+ def _rich_progress_bar(
23
+ iterable: Iterable[bytes],
24
+ *,
25
+ bar_type: str,
26
+ size: int,
27
+ ) -> Generator[bytes, None, None]:
28
+ assert bar_type == "on", "This should only be used in the default mode."
29
+
30
+ if not size:
31
+ total = float("inf")
32
+ columns: Tuple[ProgressColumn, ...] = (
33
+ TextColumn("[progress.description]{task.description}"),
34
+ SpinnerColumn("line", speed=1.5),
35
+ FileSizeColumn(),
36
+ TransferSpeedColumn(),
37
+ TimeElapsedColumn(),
38
+ )
39
+ else:
40
+ total = size
41
+ columns = (
42
+ TextColumn("[progress.description]{task.description}"),
43
+ BarColumn(),
44
+ DownloadColumn(),
45
+ TransferSpeedColumn(),
46
+ TextColumn("eta"),
47
+ TimeRemainingColumn(),
48
+ )
49
+
50
+ progress = Progress(*columns, refresh_per_second=30)
51
+ task_id = progress.add_task(" " * (get_indentation() + 2), total=total)
52
+ with progress:
53
+ for chunk in iterable:
54
+ yield chunk
55
+ progress.update(task_id, advance=len(chunk))
56
+
57
+
58
+ def get_download_progress_renderer(
59
+ *, bar_type: str, size: Optional[int] = None
60
+ ) -> DownloadProgressRenderer:
61
+ """Get an object that can be used to render the download progress.
62
+
63
+ Returns a callable, that takes an iterable to "wrap".
64
+ """
65
+ if bar_type == "on":
66
+ return functools.partial(_rich_progress_bar, bar_type=bar_type, size=size)
67
+ else:
68
+ return iter # no-op, when passed an iterator
env/lib/python3.9/site-packages/pip/_internal/cli/req_command.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contains the Command base classes that depend on PipSession.
2
+
3
+ The classes in this module are in a separate module so the commands not
4
+ needing download / PackageFinder capability don't unnecessarily import the
5
+ PackageFinder machinery and all its vendored dependencies, etc.
6
+ """
7
+
8
+ import logging
9
+ import os
10
+ import sys
11
+ from functools import partial
12
+ from optparse import Values
13
+ from typing import TYPE_CHECKING, Any, List, Optional, Tuple
14
+
15
+ from pip._internal.cache import WheelCache
16
+ from pip._internal.cli import cmdoptions
17
+ from pip._internal.cli.base_command import Command
18
+ from pip._internal.cli.command_context import CommandContextMixIn
19
+ from pip._internal.exceptions import CommandError, PreviousBuildDirError
20
+ from pip._internal.index.collector import LinkCollector
21
+ from pip._internal.index.package_finder import PackageFinder
22
+ from pip._internal.models.selection_prefs import SelectionPreferences
23
+ from pip._internal.models.target_python import TargetPython
24
+ from pip._internal.network.session import PipSession
25
+ from pip._internal.operations.build.build_tracker import BuildTracker
26
+ from pip._internal.operations.prepare import RequirementPreparer
27
+ from pip._internal.req.constructors import (
28
+ install_req_from_editable,
29
+ install_req_from_line,
30
+ install_req_from_parsed_requirement,
31
+ install_req_from_req_string,
32
+ )
33
+ from pip._internal.req.req_file import parse_requirements
34
+ from pip._internal.req.req_install import InstallRequirement
35
+ from pip._internal.resolution.base import BaseResolver
36
+ from pip._internal.self_outdated_check import pip_self_version_check
37
+ from pip._internal.utils.temp_dir import (
38
+ TempDirectory,
39
+ TempDirectoryTypeRegistry,
40
+ tempdir_kinds,
41
+ )
42
+ from pip._internal.utils.virtualenv import running_under_virtualenv
43
+
44
+ if TYPE_CHECKING:
45
+ from ssl import SSLContext
46
+
47
+ logger = logging.getLogger(__name__)
48
+
49
+
50
+ def _create_truststore_ssl_context() -> Optional["SSLContext"]:
51
+ if sys.version_info < (3, 10):
52
+ raise CommandError("The truststore feature is only available for Python 3.10+")
53
+
54
+ try:
55
+ import ssl
56
+ except ImportError:
57
+ logger.warning("Disabling truststore since ssl support is missing")
58
+ return None
59
+
60
+ try:
61
+ from pip._vendor import truststore
62
+ except ImportError as e:
63
+ raise CommandError(f"The truststore feature is unavailable: {e}")
64
+
65
+ return truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
66
+
67
+
68
+ class SessionCommandMixin(CommandContextMixIn):
69
+
70
+ """
71
+ A class mixin for command classes needing _build_session().
72
+ """
73
+
74
+ def __init__(self) -> None:
75
+ super().__init__()
76
+ self._session: Optional[PipSession] = None
77
+
78
+ @classmethod
79
+ def _get_index_urls(cls, options: Values) -> Optional[List[str]]:
80
+ """Return a list of index urls from user-provided options."""
81
+ index_urls = []
82
+ if not getattr(options, "no_index", False):
83
+ url = getattr(options, "index_url", None)
84
+ if url:
85
+ index_urls.append(url)
86
+ urls = getattr(options, "extra_index_urls", None)
87
+ if urls:
88
+ index_urls.extend(urls)
89
+ # Return None rather than an empty list
90
+ return index_urls or None
91
+
92
+ def get_default_session(self, options: Values) -> PipSession:
93
+ """Get a default-managed session."""
94
+ if self._session is None:
95
+ self._session = self.enter_context(self._build_session(options))
96
+ # there's no type annotation on requests.Session, so it's
97
+ # automatically ContextManager[Any] and self._session becomes Any,
98
+ # then https://github.com/python/mypy/issues/7696 kicks in
99
+ assert self._session is not None
100
+ return self._session
101
+
102
+ def _build_session(
103
+ self,
104
+ options: Values,
105
+ retries: Optional[int] = None,
106
+ timeout: Optional[int] = None,
107
+ fallback_to_certifi: bool = False,
108
+ ) -> PipSession:
109
+ cache_dir = options.cache_dir
110
+ assert not cache_dir or os.path.isabs(cache_dir)
111
+
112
+ if "truststore" in options.features_enabled:
113
+ try:
114
+ ssl_context = _create_truststore_ssl_context()
115
+ except Exception:
116
+ if not fallback_to_certifi:
117
+ raise
118
+ ssl_context = None
119
+ else:
120
+ ssl_context = None
121
+
122
+ session = PipSession(
123
+ cache=os.path.join(cache_dir, "http-v2") if cache_dir else None,
124
+ retries=retries if retries is not None else options.retries,
125
+ trusted_hosts=options.trusted_hosts,
126
+ index_urls=self._get_index_urls(options),
127
+ ssl_context=ssl_context,
128
+ )
129
+
130
+ # Handle custom ca-bundles from the user
131
+ if options.cert:
132
+ session.verify = options.cert
133
+
134
+ # Handle SSL client certificate
135
+ if options.client_cert:
136
+ session.cert = options.client_cert
137
+
138
+ # Handle timeouts
139
+ if options.timeout or timeout:
140
+ session.timeout = timeout if timeout is not None else options.timeout
141
+
142
+ # Handle configured proxies
143
+ if options.proxy:
144
+ session.proxies = {
145
+ "http": options.proxy,
146
+ "https": options.proxy,
147
+ }
148
+
149
+ # Determine if we can prompt the user for authentication or not
150
+ session.auth.prompting = not options.no_input
151
+ session.auth.keyring_provider = options.keyring_provider
152
+
153
+ return session
154
+
155
+
156
+ class IndexGroupCommand(Command, SessionCommandMixin):
157
+
158
+ """
159
+ Abstract base class for commands with the index_group options.
160
+
161
+ This also corresponds to the commands that permit the pip version check.
162
+ """
163
+
164
+ def handle_pip_version_check(self, options: Values) -> None:
165
+ """
166
+ Do the pip version check if not disabled.
167
+
168
+ This overrides the default behavior of not doing the check.
169
+ """
170
+ # Make sure the index_group options are present.
171
+ assert hasattr(options, "no_index")
172
+
173
+ if options.disable_pip_version_check or options.no_index:
174
+ return
175
+
176
+ # Otherwise, check if we're using the latest version of pip available.
177
+ session = self._build_session(
178
+ options,
179
+ retries=0,
180
+ timeout=min(5, options.timeout),
181
+ # This is set to ensure the function does not fail when truststore is
182
+ # specified in use-feature but cannot be loaded. This usually raises a
183
+ # CommandError and shows a nice user-facing error, but this function is not
184
+ # called in that try-except block.
185
+ fallback_to_certifi=True,
186
+ )
187
+ with session:
188
+ pip_self_version_check(session, options)
189
+
190
+
191
+ KEEPABLE_TEMPDIR_TYPES = [
192
+ tempdir_kinds.BUILD_ENV,
193
+ tempdir_kinds.EPHEM_WHEEL_CACHE,
194
+ tempdir_kinds.REQ_BUILD,
195
+ ]
196
+
197
+
198
+ def warn_if_run_as_root() -> None:
199
+ """Output a warning for sudo users on Unix.
200
+
201
+ In a virtual environment, sudo pip still writes to virtualenv.
202
+ On Windows, users may run pip as Administrator without issues.
203
+ This warning only applies to Unix root users outside of virtualenv.
204
+ """
205
+ if running_under_virtualenv():
206
+ return
207
+ if not hasattr(os, "getuid"):
208
+ return
209
+ # On Windows, there are no "system managed" Python packages. Installing as
210
+ # Administrator via pip is the correct way of updating system environments.
211
+ #
212
+ # We choose sys.platform over utils.compat.WINDOWS here to enable Mypy platform
213
+ # checks: https://mypy.readthedocs.io/en/stable/common_issues.html
214
+ if sys.platform == "win32" or sys.platform == "cygwin":
215
+ return
216
+
217
+ if os.getuid() != 0:
218
+ return
219
+
220
+ logger.warning(
221
+ "Running pip as the 'root' user can result in broken permissions and "
222
+ "conflicting behaviour with the system package manager. "
223
+ "It is recommended to use a virtual environment instead: "
224
+ "https://pip.pypa.io/warnings/venv"
225
+ )
226
+
227
+
228
+ def with_cleanup(func: Any) -> Any:
229
+ """Decorator for common logic related to managing temporary
230
+ directories.
231
+ """
232
+
233
+ def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None:
234
+ for t in KEEPABLE_TEMPDIR_TYPES:
235
+ registry.set_delete(t, False)
236
+
237
+ def wrapper(
238
+ self: RequirementCommand, options: Values, args: List[Any]
239
+ ) -> Optional[int]:
240
+ assert self.tempdir_registry is not None
241
+ if options.no_clean:
242
+ configure_tempdir_registry(self.tempdir_registry)
243
+
244
+ try:
245
+ return func(self, options, args)
246
+ except PreviousBuildDirError:
247
+ # This kind of conflict can occur when the user passes an explicit
248
+ # build directory with a pre-existing folder. In that case we do
249
+ # not want to accidentally remove it.
250
+ configure_tempdir_registry(self.tempdir_registry)
251
+ raise
252
+
253
+ return wrapper
254
+
255
+
256
+ class RequirementCommand(IndexGroupCommand):
257
+ def __init__(self, *args: Any, **kw: Any) -> None:
258
+ super().__init__(*args, **kw)
259
+
260
+ self.cmd_opts.add_option(cmdoptions.no_clean())
261
+
262
+ @staticmethod
263
+ def determine_resolver_variant(options: Values) -> str:
264
+ """Determines which resolver should be used, based on the given options."""
265
+ if "legacy-resolver" in options.deprecated_features_enabled:
266
+ return "legacy"
267
+
268
+ return "resolvelib"
269
+
270
+ @classmethod
271
+ def make_requirement_preparer(
272
+ cls,
273
+ temp_build_dir: TempDirectory,
274
+ options: Values,
275
+ build_tracker: BuildTracker,
276
+ session: PipSession,
277
+ finder: PackageFinder,
278
+ use_user_site: bool,
279
+ download_dir: Optional[str] = None,
280
+ verbosity: int = 0,
281
+ ) -> RequirementPreparer:
282
+ """
283
+ Create a RequirementPreparer instance for the given parameters.
284
+ """
285
+ temp_build_dir_path = temp_build_dir.path
286
+ assert temp_build_dir_path is not None
287
+ legacy_resolver = False
288
+
289
+ resolver_variant = cls.determine_resolver_variant(options)
290
+ if resolver_variant == "resolvelib":
291
+ lazy_wheel = "fast-deps" in options.features_enabled
292
+ if lazy_wheel:
293
+ logger.warning(
294
+ "pip is using lazily downloaded wheels using HTTP "
295
+ "range requests to obtain dependency information. "
296
+ "This experimental feature is enabled through "
297
+ "--use-feature=fast-deps and it is not ready for "
298
+ "production."
299
+ )
300
+ else:
301
+ legacy_resolver = True
302
+ lazy_wheel = False
303
+ if "fast-deps" in options.features_enabled:
304
+ logger.warning(
305
+ "fast-deps has no effect when used with the legacy resolver."
306
+ )
307
+
308
+ return RequirementPreparer(
309
+ build_dir=temp_build_dir_path,
310
+ src_dir=options.src_dir,
311
+ download_dir=download_dir,
312
+ build_isolation=options.build_isolation,
313
+ check_build_deps=options.check_build_deps,
314
+ build_tracker=build_tracker,
315
+ session=session,
316
+ progress_bar=options.progress_bar,
317
+ finder=finder,
318
+ require_hashes=options.require_hashes,
319
+ use_user_site=use_user_site,
320
+ lazy_wheel=lazy_wheel,
321
+ verbosity=verbosity,
322
+ legacy_resolver=legacy_resolver,
323
+ )
324
+
325
+ @classmethod
326
+ def make_resolver(
327
+ cls,
328
+ preparer: RequirementPreparer,
329
+ finder: PackageFinder,
330
+ options: Values,
331
+ wheel_cache: Optional[WheelCache] = None,
332
+ use_user_site: bool = False,
333
+ ignore_installed: bool = True,
334
+ ignore_requires_python: bool = False,
335
+ force_reinstall: bool = False,
336
+ upgrade_strategy: str = "to-satisfy-only",
337
+ use_pep517: Optional[bool] = None,
338
+ py_version_info: Optional[Tuple[int, ...]] = None,
339
+ ) -> BaseResolver:
340
+ """
341
+ Create a Resolver instance for the given parameters.
342
+ """
343
+ make_install_req = partial(
344
+ install_req_from_req_string,
345
+ isolated=options.isolated_mode,
346
+ use_pep517=use_pep517,
347
+ )
348
+ resolver_variant = cls.determine_resolver_variant(options)
349
+ # The long import name and duplicated invocation is needed to convince
350
+ # Mypy into correctly typechecking. Otherwise it would complain the
351
+ # "Resolver" class being redefined.
352
+ if resolver_variant == "resolvelib":
353
+ import pip._internal.resolution.resolvelib.resolver
354
+
355
+ return pip._internal.resolution.resolvelib.resolver.Resolver(
356
+ preparer=preparer,
357
+ finder=finder,
358
+ wheel_cache=wheel_cache,
359
+ make_install_req=make_install_req,
360
+ use_user_site=use_user_site,
361
+ ignore_dependencies=options.ignore_dependencies,
362
+ ignore_installed=ignore_installed,
363
+ ignore_requires_python=ignore_requires_python,
364
+ force_reinstall=force_reinstall,
365
+ upgrade_strategy=upgrade_strategy,
366
+ py_version_info=py_version_info,
367
+ )
368
+ import pip._internal.resolution.legacy.resolver
369
+
370
+ return pip._internal.resolution.legacy.resolver.Resolver(
371
+ preparer=preparer,
372
+ finder=finder,
373
+ wheel_cache=wheel_cache,
374
+ make_install_req=make_install_req,
375
+ use_user_site=use_user_site,
376
+ ignore_dependencies=options.ignore_dependencies,
377
+ ignore_installed=ignore_installed,
378
+ ignore_requires_python=ignore_requires_python,
379
+ force_reinstall=force_reinstall,
380
+ upgrade_strategy=upgrade_strategy,
381
+ py_version_info=py_version_info,
382
+ )
383
+
384
+ def get_requirements(
385
+ self,
386
+ args: List[str],
387
+ options: Values,
388
+ finder: PackageFinder,
389
+ session: PipSession,
390
+ ) -> List[InstallRequirement]:
391
+ """
392
+ Parse command-line arguments into the corresponding requirements.
393
+ """
394
+ requirements: List[InstallRequirement] = []
395
+ for filename in options.constraints:
396
+ for parsed_req in parse_requirements(
397
+ filename,
398
+ constraint=True,
399
+ finder=finder,
400
+ options=options,
401
+ session=session,
402
+ ):
403
+ req_to_add = install_req_from_parsed_requirement(
404
+ parsed_req,
405
+ isolated=options.isolated_mode,
406
+ user_supplied=False,
407
+ )
408
+ requirements.append(req_to_add)
409
+
410
+ for req in args:
411
+ req_to_add = install_req_from_line(
412
+ req,
413
+ comes_from=None,
414
+ isolated=options.isolated_mode,
415
+ use_pep517=options.use_pep517,
416
+ user_supplied=True,
417
+ config_settings=getattr(options, "config_settings", None),
418
+ )
419
+ requirements.append(req_to_add)
420
+
421
+ for req in options.editables:
422
+ req_to_add = install_req_from_editable(
423
+ req,
424
+ user_supplied=True,
425
+ isolated=options.isolated_mode,
426
+ use_pep517=options.use_pep517,
427
+ config_settings=getattr(options, "config_settings", None),
428
+ )
429
+ requirements.append(req_to_add)
430
+
431
+ # NOTE: options.require_hashes may be set if --require-hashes is True
432
+ for filename in options.requirements:
433
+ for parsed_req in parse_requirements(
434
+ filename, finder=finder, options=options, session=session
435
+ ):
436
+ req_to_add = install_req_from_parsed_requirement(
437
+ parsed_req,
438
+ isolated=options.isolated_mode,
439
+ use_pep517=options.use_pep517,
440
+ user_supplied=True,
441
+ config_settings=parsed_req.options.get("config_settings")
442
+ if parsed_req.options
443
+ else None,
444
+ )
445
+ requirements.append(req_to_add)
446
+
447
+ # If any requirement has hash options, enable hash checking.
448
+ if any(req.has_hash_options for req in requirements):
449
+ options.require_hashes = True
450
+
451
+ if not (args or options.editables or options.requirements):
452
+ opts = {"name": self.name}
453
+ if options.find_links:
454
+ raise CommandError(
455
+ "You must give at least one requirement to {name} "
456
+ '(maybe you meant "pip {name} {links}"?)'.format(
457
+ **dict(opts, links=" ".join(options.find_links))
458
+ )
459
+ )
460
+ else:
461
+ raise CommandError(
462
+ "You must give at least one requirement to {name} "
463
+ '(see "pip help {name}")'.format(**opts)
464
+ )
465
+
466
+ return requirements
467
+
468
+ @staticmethod
469
+ def trace_basic_info(finder: PackageFinder) -> None:
470
+ """
471
+ Trace basic information about the provided objects.
472
+ """
473
+ # Display where finder is looking for packages
474
+ search_scope = finder.search_scope
475
+ locations = search_scope.get_formatted_locations()
476
+ if locations:
477
+ logger.info(locations)
478
+
479
+ def _build_package_finder(
480
+ self,
481
+ options: Values,
482
+ session: PipSession,
483
+ target_python: Optional[TargetPython] = None,
484
+ ignore_requires_python: Optional[bool] = None,
485
+ ) -> PackageFinder:
486
+ """
487
+ Create a package finder appropriate to this requirement command.
488
+
489
+ :param ignore_requires_python: Whether to ignore incompatible
490
+ "Requires-Python" values in links. Defaults to False.
491
+ """
492
+ link_collector = LinkCollector.create(session, options=options)
493
+ selection_prefs = SelectionPreferences(
494
+ allow_yanked=True,
495
+ format_control=options.format_control,
496
+ allow_all_prereleases=options.pre,
497
+ prefer_binary=options.prefer_binary,
498
+ ignore_requires_python=ignore_requires_python,
499
+ )
500
+
501
+ return PackageFinder.create(
502
+ link_collector=link_collector,
503
+ selection_prefs=selection_prefs,
504
+ target_python=target_python,
505
+ )
env/lib/python3.9/site-packages/pip/_internal/cli/spinners.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import itertools
3
+ import logging
4
+ import sys
5
+ import time
6
+ from typing import IO, Generator, Optional
7
+
8
+ from pip._internal.utils.compat import WINDOWS
9
+ from pip._internal.utils.logging import get_indentation
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class SpinnerInterface:
15
+ def spin(self) -> None:
16
+ raise NotImplementedError()
17
+
18
+ def finish(self, final_status: str) -> None:
19
+ raise NotImplementedError()
20
+
21
+
22
+ class InteractiveSpinner(SpinnerInterface):
23
+ def __init__(
24
+ self,
25
+ message: str,
26
+ file: Optional[IO[str]] = None,
27
+ spin_chars: str = "-\\|/",
28
+ # Empirically, 8 updates/second looks nice
29
+ min_update_interval_seconds: float = 0.125,
30
+ ):
31
+ self._message = message
32
+ if file is None:
33
+ file = sys.stdout
34
+ self._file = file
35
+ self._rate_limiter = RateLimiter(min_update_interval_seconds)
36
+ self._finished = False
37
+
38
+ self._spin_cycle = itertools.cycle(spin_chars)
39
+
40
+ self._file.write(" " * get_indentation() + self._message + " ... ")
41
+ self._width = 0
42
+
43
+ def _write(self, status: str) -> None:
44
+ assert not self._finished
45
+ # Erase what we wrote before by backspacing to the beginning, writing
46
+ # spaces to overwrite the old text, and then backspacing again
47
+ backup = "\b" * self._width
48
+ self._file.write(backup + " " * self._width + backup)
49
+ # Now we have a blank slate to add our status
50
+ self._file.write(status)
51
+ self._width = len(status)
52
+ self._file.flush()
53
+ self._rate_limiter.reset()
54
+
55
+ def spin(self) -> None:
56
+ if self._finished:
57
+ return
58
+ if not self._rate_limiter.ready():
59
+ return
60
+ self._write(next(self._spin_cycle))
61
+
62
+ def finish(self, final_status: str) -> None:
63
+ if self._finished:
64
+ return
65
+ self._write(final_status)
66
+ self._file.write("\n")
67
+ self._file.flush()
68
+ self._finished = True
69
+
70
+
71
+ # Used for dumb terminals, non-interactive installs (no tty), etc.
72
+ # We still print updates occasionally (once every 60 seconds by default) to
73
+ # act as a keep-alive for systems like Travis-CI that take lack-of-output as
74
+ # an indication that a task has frozen.
75
+ class NonInteractiveSpinner(SpinnerInterface):
76
+ def __init__(self, message: str, min_update_interval_seconds: float = 60.0) -> None:
77
+ self._message = message
78
+ self._finished = False
79
+ self._rate_limiter = RateLimiter(min_update_interval_seconds)
80
+ self._update("started")
81
+
82
+ def _update(self, status: str) -> None:
83
+ assert not self._finished
84
+ self._rate_limiter.reset()
85
+ logger.info("%s: %s", self._message, status)
86
+
87
+ def spin(self) -> None:
88
+ if self._finished:
89
+ return
90
+ if not self._rate_limiter.ready():
91
+ return
92
+ self._update("still running...")
93
+
94
+ def finish(self, final_status: str) -> None:
95
+ if self._finished:
96
+ return
97
+ self._update(f"finished with status '{final_status}'")
98
+ self._finished = True
99
+
100
+
101
+ class RateLimiter:
102
+ def __init__(self, min_update_interval_seconds: float) -> None:
103
+ self._min_update_interval_seconds = min_update_interval_seconds
104
+ self._last_update: float = 0
105
+
106
+ def ready(self) -> bool:
107
+ now = time.time()
108
+ delta = now - self._last_update
109
+ return delta >= self._min_update_interval_seconds
110
+
111
+ def reset(self) -> None:
112
+ self._last_update = time.time()
113
+
114
+
115
+ @contextlib.contextmanager
116
+ def open_spinner(message: str) -> Generator[SpinnerInterface, None, None]:
117
+ # Interactive spinner goes directly to sys.stdout rather than being routed
118
+ # through the logging system, but it acts like it has level INFO,
119
+ # i.e. it's only displayed if we're at level INFO or better.
120
+ # Non-interactive spinner goes through the logging system, so it is always
121
+ # in sync with logging configuration.
122
+ if sys.stdout.isatty() and logger.getEffectiveLevel() <= logging.INFO:
123
+ spinner: SpinnerInterface = InteractiveSpinner(message)
124
+ else:
125
+ spinner = NonInteractiveSpinner(message)
126
+ try:
127
+ with hidden_cursor(sys.stdout):
128
+ yield spinner
129
+ except KeyboardInterrupt:
130
+ spinner.finish("canceled")
131
+ raise
132
+ except Exception:
133
+ spinner.finish("error")
134
+ raise
135
+ else:
136
+ spinner.finish("done")
137
+
138
+
139
+ HIDE_CURSOR = "\x1b[?25l"
140
+ SHOW_CURSOR = "\x1b[?25h"
141
+
142
+
143
+ @contextlib.contextmanager
144
+ def hidden_cursor(file: IO[str]) -> Generator[None, None, None]:
145
+ # The Windows terminal does not support the hide/show cursor ANSI codes,
146
+ # even via colorama. So don't even try.
147
+ if WINDOWS:
148
+ yield
149
+ # We don't want to clutter the output with control characters if we're
150
+ # writing to a file, or if the user is running with --quiet.
151
+ # See https://github.com/pypa/pip/issues/3418
152
+ elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO:
153
+ yield
154
+ else:
155
+ file.write(HIDE_CURSOR)
156
+ try:
157
+ yield
158
+ finally:
159
+ file.write(SHOW_CURSOR)
env/lib/python3.9/site-packages/pip/_internal/cli/status_codes.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ SUCCESS = 0
2
+ ERROR = 1
3
+ UNKNOWN_ERROR = 2
4
+ VIRTUALENV_NOT_FOUND = 3
5
+ PREVIOUS_BUILD_DIR_ERROR = 4
6
+ NO_MATCHES_FOUND = 23
env/lib/python3.9/site-packages/pip/_internal/commands/__init__.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Package containing all pip commands
3
+ """
4
+
5
+ import importlib
6
+ from collections import namedtuple
7
+ from typing import Any, Dict, Optional
8
+
9
+ from pip._internal.cli.base_command import Command
10
+
11
+ CommandInfo = namedtuple("CommandInfo", "module_path, class_name, summary")
12
+
13
+ # This dictionary does a bunch of heavy lifting for help output:
14
+ # - Enables avoiding additional (costly) imports for presenting `--help`.
15
+ # - The ordering matters for help display.
16
+ #
17
+ # Even though the module path starts with the same "pip._internal.commands"
18
+ # prefix, the full path makes testing easier (specifically when modifying
19
+ # `commands_dict` in test setup / teardown).
20
+ commands_dict: Dict[str, CommandInfo] = {
21
+ "install": CommandInfo(
22
+ "pip._internal.commands.install",
23
+ "InstallCommand",
24
+ "Install packages.",
25
+ ),
26
+ "download": CommandInfo(
27
+ "pip._internal.commands.download",
28
+ "DownloadCommand",
29
+ "Download packages.",
30
+ ),
31
+ "uninstall": CommandInfo(
32
+ "pip._internal.commands.uninstall",
33
+ "UninstallCommand",
34
+ "Uninstall packages.",
35
+ ),
36
+ "freeze": CommandInfo(
37
+ "pip._internal.commands.freeze",
38
+ "FreezeCommand",
39
+ "Output installed packages in requirements format.",
40
+ ),
41
+ "inspect": CommandInfo(
42
+ "pip._internal.commands.inspect",
43
+ "InspectCommand",
44
+ "Inspect the python environment.",
45
+ ),
46
+ "list": CommandInfo(
47
+ "pip._internal.commands.list",
48
+ "ListCommand",
49
+ "List installed packages.",
50
+ ),
51
+ "show": CommandInfo(
52
+ "pip._internal.commands.show",
53
+ "ShowCommand",
54
+ "Show information about installed packages.",
55
+ ),
56
+ "check": CommandInfo(
57
+ "pip._internal.commands.check",
58
+ "CheckCommand",
59
+ "Verify installed packages have compatible dependencies.",
60
+ ),
61
+ "config": CommandInfo(
62
+ "pip._internal.commands.configuration",
63
+ "ConfigurationCommand",
64
+ "Manage local and global configuration.",
65
+ ),
66
+ "search": CommandInfo(
67
+ "pip._internal.commands.search",
68
+ "SearchCommand",
69
+ "Search PyPI for packages.",
70
+ ),
71
+ "cache": CommandInfo(
72
+ "pip._internal.commands.cache",
73
+ "CacheCommand",
74
+ "Inspect and manage pip's wheel cache.",
75
+ ),
76
+ "index": CommandInfo(
77
+ "pip._internal.commands.index",
78
+ "IndexCommand",
79
+ "Inspect information available from package indexes.",
80
+ ),
81
+ "wheel": CommandInfo(
82
+ "pip._internal.commands.wheel",
83
+ "WheelCommand",
84
+ "Build wheels from your requirements.",
85
+ ),
86
+ "hash": CommandInfo(
87
+ "pip._internal.commands.hash",
88
+ "HashCommand",
89
+ "Compute hashes of package archives.",
90
+ ),
91
+ "completion": CommandInfo(
92
+ "pip._internal.commands.completion",
93
+ "CompletionCommand",
94
+ "A helper command used for command completion.",
95
+ ),
96
+ "debug": CommandInfo(
97
+ "pip._internal.commands.debug",
98
+ "DebugCommand",
99
+ "Show information useful for debugging.",
100
+ ),
101
+ "help": CommandInfo(
102
+ "pip._internal.commands.help",
103
+ "HelpCommand",
104
+ "Show help for commands.",
105
+ ),
106
+ }
107
+
108
+
109
+ def create_command(name: str, **kwargs: Any) -> Command:
110
+ """
111
+ Create an instance of the Command class with the given name.
112
+ """
113
+ module_path, class_name, summary = commands_dict[name]
114
+ module = importlib.import_module(module_path)
115
+ command_class = getattr(module, class_name)
116
+ command = command_class(name=name, summary=summary, **kwargs)
117
+
118
+ return command
119
+
120
+
121
+ def get_similar_commands(name: str) -> Optional[str]:
122
+ """Command name auto-correct."""
123
+ from difflib import get_close_matches
124
+
125
+ name = name.lower()
126
+
127
+ close_commands = get_close_matches(name, commands_dict.keys())
128
+
129
+ if close_commands:
130
+ return close_commands[0]
131
+ else:
132
+ return None
env/lib/python3.9/site-packages/pip/_internal/commands/cache.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import textwrap
3
+ from optparse import Values
4
+ from typing import Any, List
5
+
6
+ from pip._internal.cli.base_command import Command
7
+ from pip._internal.cli.status_codes import ERROR, SUCCESS
8
+ from pip._internal.exceptions import CommandError, PipError
9
+ from pip._internal.utils import filesystem
10
+ from pip._internal.utils.logging import getLogger
11
+
12
+ logger = getLogger(__name__)
13
+
14
+
15
+ class CacheCommand(Command):
16
+ """
17
+ Inspect and manage pip's wheel cache.
18
+
19
+ Subcommands:
20
+
21
+ - dir: Show the cache directory.
22
+ - info: Show information about the cache.
23
+ - list: List filenames of packages stored in the cache.
24
+ - remove: Remove one or more package from the cache.
25
+ - purge: Remove all items from the cache.
26
+
27
+ ``<pattern>`` can be a glob expression or a package name.
28
+ """
29
+
30
+ ignore_require_venv = True
31
+ usage = """
32
+ %prog dir
33
+ %prog info
34
+ %prog list [<pattern>] [--format=[human, abspath]]
35
+ %prog remove <pattern>
36
+ %prog purge
37
+ """
38
+
39
+ def add_options(self) -> None:
40
+ self.cmd_opts.add_option(
41
+ "--format",
42
+ action="store",
43
+ dest="list_format",
44
+ default="human",
45
+ choices=("human", "abspath"),
46
+ help="Select the output format among: human (default) or abspath",
47
+ )
48
+
49
+ self.parser.insert_option_group(0, self.cmd_opts)
50
+
51
+ def run(self, options: Values, args: List[str]) -> int:
52
+ handlers = {
53
+ "dir": self.get_cache_dir,
54
+ "info": self.get_cache_info,
55
+ "list": self.list_cache_items,
56
+ "remove": self.remove_cache_items,
57
+ "purge": self.purge_cache,
58
+ }
59
+
60
+ if not options.cache_dir:
61
+ logger.error("pip cache commands can not function since cache is disabled.")
62
+ return ERROR
63
+
64
+ # Determine action
65
+ if not args or args[0] not in handlers:
66
+ logger.error(
67
+ "Need an action (%s) to perform.",
68
+ ", ".join(sorted(handlers)),
69
+ )
70
+ return ERROR
71
+
72
+ action = args[0]
73
+
74
+ # Error handling happens here, not in the action-handlers.
75
+ try:
76
+ handlers[action](options, args[1:])
77
+ except PipError as e:
78
+ logger.error(e.args[0])
79
+ return ERROR
80
+
81
+ return SUCCESS
82
+
83
+ def get_cache_dir(self, options: Values, args: List[Any]) -> None:
84
+ if args:
85
+ raise CommandError("Too many arguments")
86
+
87
+ logger.info(options.cache_dir)
88
+
89
+ def get_cache_info(self, options: Values, args: List[Any]) -> None:
90
+ if args:
91
+ raise CommandError("Too many arguments")
92
+
93
+ num_http_files = len(self._find_http_files(options))
94
+ num_packages = len(self._find_wheels(options, "*"))
95
+
96
+ http_cache_location = self._cache_dir(options, "http-v2")
97
+ old_http_cache_location = self._cache_dir(options, "http")
98
+ wheels_cache_location = self._cache_dir(options, "wheels")
99
+ http_cache_size = filesystem.format_size(
100
+ filesystem.directory_size(http_cache_location)
101
+ + filesystem.directory_size(old_http_cache_location)
102
+ )
103
+ wheels_cache_size = filesystem.format_directory_size(wheels_cache_location)
104
+
105
+ message = (
106
+ textwrap.dedent(
107
+ """
108
+ Package index page cache location (pip v23.3+): {http_cache_location}
109
+ Package index page cache location (older pips): {old_http_cache_location}
110
+ Package index page cache size: {http_cache_size}
111
+ Number of HTTP files: {num_http_files}
112
+ Locally built wheels location: {wheels_cache_location}
113
+ Locally built wheels size: {wheels_cache_size}
114
+ Number of locally built wheels: {package_count}
115
+ """ # noqa: E501
116
+ )
117
+ .format(
118
+ http_cache_location=http_cache_location,
119
+ old_http_cache_location=old_http_cache_location,
120
+ http_cache_size=http_cache_size,
121
+ num_http_files=num_http_files,
122
+ wheels_cache_location=wheels_cache_location,
123
+ package_count=num_packages,
124
+ wheels_cache_size=wheels_cache_size,
125
+ )
126
+ .strip()
127
+ )
128
+
129
+ logger.info(message)
130
+
131
+ def list_cache_items(self, options: Values, args: List[Any]) -> None:
132
+ if len(args) > 1:
133
+ raise CommandError("Too many arguments")
134
+
135
+ if args:
136
+ pattern = args[0]
137
+ else:
138
+ pattern = "*"
139
+
140
+ files = self._find_wheels(options, pattern)
141
+ if options.list_format == "human":
142
+ self.format_for_human(files)
143
+ else:
144
+ self.format_for_abspath(files)
145
+
146
+ def format_for_human(self, files: List[str]) -> None:
147
+ if not files:
148
+ logger.info("No locally built wheels cached.")
149
+ return
150
+
151
+ results = []
152
+ for filename in files:
153
+ wheel = os.path.basename(filename)
154
+ size = filesystem.format_file_size(filename)
155
+ results.append(f" - {wheel} ({size})")
156
+ logger.info("Cache contents:\n")
157
+ logger.info("\n".join(sorted(results)))
158
+
159
+ def format_for_abspath(self, files: List[str]) -> None:
160
+ if files:
161
+ logger.info("\n".join(sorted(files)))
162
+
163
+ def remove_cache_items(self, options: Values, args: List[Any]) -> None:
164
+ if len(args) > 1:
165
+ raise CommandError("Too many arguments")
166
+
167
+ if not args:
168
+ raise CommandError("Please provide a pattern")
169
+
170
+ files = self._find_wheels(options, args[0])
171
+
172
+ no_matching_msg = "No matching packages"
173
+ if args[0] == "*":
174
+ # Only fetch http files if no specific pattern given
175
+ files += self._find_http_files(options)
176
+ else:
177
+ # Add the pattern to the log message
178
+ no_matching_msg += ' for pattern "{}"'.format(args[0])
179
+
180
+ if not files:
181
+ logger.warning(no_matching_msg)
182
+
183
+ for filename in files:
184
+ os.unlink(filename)
185
+ logger.verbose("Removed %s", filename)
186
+ logger.info("Files removed: %s", len(files))
187
+
188
+ def purge_cache(self, options: Values, args: List[Any]) -> None:
189
+ if args:
190
+ raise CommandError("Too many arguments")
191
+
192
+ return self.remove_cache_items(options, ["*"])
193
+
194
+ def _cache_dir(self, options: Values, subdir: str) -> str:
195
+ return os.path.join(options.cache_dir, subdir)
196
+
197
+ def _find_http_files(self, options: Values) -> List[str]:
198
+ old_http_dir = self._cache_dir(options, "http")
199
+ new_http_dir = self._cache_dir(options, "http-v2")
200
+ return filesystem.find_files(old_http_dir, "*") + filesystem.find_files(
201
+ new_http_dir, "*"
202
+ )
203
+
204
+ def _find_wheels(self, options: Values, pattern: str) -> List[str]:
205
+ wheel_dir = self._cache_dir(options, "wheels")
206
+
207
+ # The wheel filename format, as specified in PEP 427, is:
208
+ # {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl
209
+ #
210
+ # Additionally, non-alphanumeric values in the distribution are
211
+ # normalized to underscores (_), meaning hyphens can never occur
212
+ # before `-{version}`.
213
+ #
214
+ # Given that information:
215
+ # - If the pattern we're given contains a hyphen (-), the user is
216
+ # providing at least the version. Thus, we can just append `*.whl`
217
+ # to match the rest of it.
218
+ # - If the pattern we're given doesn't contain a hyphen (-), the
219
+ # user is only providing the name. Thus, we append `-*.whl` to
220
+ # match the hyphen before the version, followed by anything else.
221
+ #
222
+ # PEP 427: https://www.python.org/dev/peps/pep-0427/
223
+ pattern = pattern + ("*.whl" if "-" in pattern else "-*.whl")
224
+
225
+ return filesystem.find_files(wheel_dir, pattern)
env/lib/python3.9/site-packages/pip/_internal/commands/check.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from optparse import Values
3
+ from typing import List
4
+
5
+ from pip._internal.cli.base_command import Command
6
+ from pip._internal.cli.status_codes import ERROR, SUCCESS
7
+ from pip._internal.operations.check import (
8
+ check_package_set,
9
+ create_package_set_from_installed,
10
+ warn_legacy_versions_and_specifiers,
11
+ )
12
+ from pip._internal.utils.misc import write_output
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class CheckCommand(Command):
18
+ """Verify installed packages have compatible dependencies."""
19
+
20
+ usage = """
21
+ %prog [options]"""
22
+
23
+ def run(self, options: Values, args: List[str]) -> int:
24
+ package_set, parsing_probs = create_package_set_from_installed()
25
+ warn_legacy_versions_and_specifiers(package_set)
26
+ missing, conflicting = check_package_set(package_set)
27
+
28
+ for project_name in missing:
29
+ version = package_set[project_name].version
30
+ for dependency in missing[project_name]:
31
+ write_output(
32
+ "%s %s requires %s, which is not installed.",
33
+ project_name,
34
+ version,
35
+ dependency[0],
36
+ )
37
+
38
+ for project_name in conflicting:
39
+ version = package_set[project_name].version
40
+ for dep_name, dep_version, req in conflicting[project_name]:
41
+ write_output(
42
+ "%s %s has requirement %s, but you have %s %s.",
43
+ project_name,
44
+ version,
45
+ req,
46
+ dep_name,
47
+ dep_version,
48
+ )
49
+
50
+ if missing or conflicting or parsing_probs:
51
+ return ERROR
52
+ else:
53
+ write_output("No broken requirements found.")
54
+ return SUCCESS
env/lib/python3.9/site-packages/pip/_internal/commands/completion.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import textwrap
3
+ from optparse import Values
4
+ from typing import List
5
+
6
+ from pip._internal.cli.base_command import Command
7
+ from pip._internal.cli.status_codes import SUCCESS
8
+ from pip._internal.utils.misc import get_prog
9
+
10
+ BASE_COMPLETION = """
11
+ # pip {shell} completion start{script}# pip {shell} completion end
12
+ """
13
+
14
+ COMPLETION_SCRIPTS = {
15
+ "bash": """
16
+ _pip_completion()
17
+ {{
18
+ COMPREPLY=( $( COMP_WORDS="${{COMP_WORDS[*]}}" \\
19
+ COMP_CWORD=$COMP_CWORD \\
20
+ PIP_AUTO_COMPLETE=1 $1 2>/dev/null ) )
21
+ }}
22
+ complete -o default -F _pip_completion {prog}
23
+ """,
24
+ "zsh": """
25
+ #compdef -P pip[0-9.]#
26
+ __pip() {{
27
+ compadd $( COMP_WORDS="$words[*]" \\
28
+ COMP_CWORD=$((CURRENT-1)) \\
29
+ PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null )
30
+ }}
31
+ if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
32
+ # autoload from fpath, call function directly
33
+ __pip "$@"
34
+ else
35
+ # eval/source/. command, register function for later
36
+ compdef __pip -P 'pip[0-9.]#'
37
+ fi
38
+ """,
39
+ "fish": """
40
+ function __fish_complete_pip
41
+ set -lx COMP_WORDS (commandline -o) ""
42
+ set -lx COMP_CWORD ( \\
43
+ math (contains -i -- (commandline -t) $COMP_WORDS)-1 \\
44
+ )
45
+ set -lx PIP_AUTO_COMPLETE 1
46
+ string split \\ -- (eval $COMP_WORDS[1])
47
+ end
48
+ complete -fa "(__fish_complete_pip)" -c {prog}
49
+ """,
50
+ "powershell": """
51
+ if ((Test-Path Function:\\TabExpansion) -and -not `
52
+ (Test-Path Function:\\_pip_completeBackup)) {{
53
+ Rename-Item Function:\\TabExpansion _pip_completeBackup
54
+ }}
55
+ function TabExpansion($line, $lastWord) {{
56
+ $lastBlock = [regex]::Split($line, '[|;]')[-1].TrimStart()
57
+ if ($lastBlock.StartsWith("{prog} ")) {{
58
+ $Env:COMP_WORDS=$lastBlock
59
+ $Env:COMP_CWORD=$lastBlock.Split().Length - 1
60
+ $Env:PIP_AUTO_COMPLETE=1
61
+ (& {prog}).Split()
62
+ Remove-Item Env:COMP_WORDS
63
+ Remove-Item Env:COMP_CWORD
64
+ Remove-Item Env:PIP_AUTO_COMPLETE
65
+ }}
66
+ elseif (Test-Path Function:\\_pip_completeBackup) {{
67
+ # Fall back on existing tab expansion
68
+ _pip_completeBackup $line $lastWord
69
+ }}
70
+ }}
71
+ """,
72
+ }
73
+
74
+
75
+ class CompletionCommand(Command):
76
+ """A helper command to be used for command completion."""
77
+
78
+ ignore_require_venv = True
79
+
80
+ def add_options(self) -> None:
81
+ self.cmd_opts.add_option(
82
+ "--bash",
83
+ "-b",
84
+ action="store_const",
85
+ const="bash",
86
+ dest="shell",
87
+ help="Emit completion code for bash",
88
+ )
89
+ self.cmd_opts.add_option(
90
+ "--zsh",
91
+ "-z",
92
+ action="store_const",
93
+ const="zsh",
94
+ dest="shell",
95
+ help="Emit completion code for zsh",
96
+ )
97
+ self.cmd_opts.add_option(
98
+ "--fish",
99
+ "-f",
100
+ action="store_const",
101
+ const="fish",
102
+ dest="shell",
103
+ help="Emit completion code for fish",
104
+ )
105
+ self.cmd_opts.add_option(
106
+ "--powershell",
107
+ "-p",
108
+ action="store_const",
109
+ const="powershell",
110
+ dest="shell",
111
+ help="Emit completion code for powershell",
112
+ )
113
+
114
+ self.parser.insert_option_group(0, self.cmd_opts)
115
+
116
+ def run(self, options: Values, args: List[str]) -> int:
117
+ """Prints the completion code of the given shell"""
118
+ shells = COMPLETION_SCRIPTS.keys()
119
+ shell_options = ["--" + shell for shell in sorted(shells)]
120
+ if options.shell in shells:
121
+ script = textwrap.dedent(
122
+ COMPLETION_SCRIPTS.get(options.shell, "").format(prog=get_prog())
123
+ )
124
+ print(BASE_COMPLETION.format(script=script, shell=options.shell))
125
+ return SUCCESS
126
+ else:
127
+ sys.stderr.write(
128
+ "ERROR: You must pass {}\n".format(" or ".join(shell_options))
129
+ )
130
+ return SUCCESS
env/lib/python3.9/site-packages/pip/_internal/commands/configuration.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import subprocess
4
+ from optparse import Values
5
+ from typing import Any, List, Optional
6
+
7
+ from pip._internal.cli.base_command import Command
8
+ from pip._internal.cli.status_codes import ERROR, SUCCESS
9
+ from pip._internal.configuration import (
10
+ Configuration,
11
+ Kind,
12
+ get_configuration_files,
13
+ kinds,
14
+ )
15
+ from pip._internal.exceptions import PipError
16
+ from pip._internal.utils.logging import indent_log
17
+ from pip._internal.utils.misc import get_prog, write_output
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ class ConfigurationCommand(Command):
23
+ """
24
+ Manage local and global configuration.
25
+
26
+ Subcommands:
27
+
28
+ - list: List the active configuration (or from the file specified)
29
+ - edit: Edit the configuration file in an editor
30
+ - get: Get the value associated with command.option
31
+ - set: Set the command.option=value
32
+ - unset: Unset the value associated with command.option
33
+ - debug: List the configuration files and values defined under them
34
+
35
+ Configuration keys should be dot separated command and option name,
36
+ with the special prefix "global" affecting any command. For example,
37
+ "pip config set global.index-url https://example.org/" would configure
38
+ the index url for all commands, but "pip config set download.timeout 10"
39
+ would configure a 10 second timeout only for "pip download" commands.
40
+
41
+ If none of --user, --global and --site are passed, a virtual
42
+ environment configuration file is used if one is active and the file
43
+ exists. Otherwise, all modifications happen to the user file by
44
+ default.
45
+ """
46
+
47
+ ignore_require_venv = True
48
+ usage = """
49
+ %prog [<file-option>] list
50
+ %prog [<file-option>] [--editor <editor-path>] edit
51
+
52
+ %prog [<file-option>] get command.option
53
+ %prog [<file-option>] set command.option value
54
+ %prog [<file-option>] unset command.option
55
+ %prog [<file-option>] debug
56
+ """
57
+
58
+ def add_options(self) -> None:
59
+ self.cmd_opts.add_option(
60
+ "--editor",
61
+ dest="editor",
62
+ action="store",
63
+ default=None,
64
+ help=(
65
+ "Editor to use to edit the file. Uses VISUAL or EDITOR "
66
+ "environment variables if not provided."
67
+ ),
68
+ )
69
+
70
+ self.cmd_opts.add_option(
71
+ "--global",
72
+ dest="global_file",
73
+ action="store_true",
74
+ default=False,
75
+ help="Use the system-wide configuration file only",
76
+ )
77
+
78
+ self.cmd_opts.add_option(
79
+ "--user",
80
+ dest="user_file",
81
+ action="store_true",
82
+ default=False,
83
+ help="Use the user configuration file only",
84
+ )
85
+
86
+ self.cmd_opts.add_option(
87
+ "--site",
88
+ dest="site_file",
89
+ action="store_true",
90
+ default=False,
91
+ help="Use the current environment configuration file only",
92
+ )
93
+
94
+ self.parser.insert_option_group(0, self.cmd_opts)
95
+
96
+ def run(self, options: Values, args: List[str]) -> int:
97
+ handlers = {
98
+ "list": self.list_values,
99
+ "edit": self.open_in_editor,
100
+ "get": self.get_name,
101
+ "set": self.set_name_value,
102
+ "unset": self.unset_name,
103
+ "debug": self.list_config_values,
104
+ }
105
+
106
+ # Determine action
107
+ if not args or args[0] not in handlers:
108
+ logger.error(
109
+ "Need an action (%s) to perform.",
110
+ ", ".join(sorted(handlers)),
111
+ )
112
+ return ERROR
113
+
114
+ action = args[0]
115
+
116
+ # Determine which configuration files are to be loaded
117
+ # Depends on whether the command is modifying.
118
+ try:
119
+ load_only = self._determine_file(
120
+ options, need_value=(action in ["get", "set", "unset", "edit"])
121
+ )
122
+ except PipError as e:
123
+ logger.error(e.args[0])
124
+ return ERROR
125
+
126
+ # Load a new configuration
127
+ self.configuration = Configuration(
128
+ isolated=options.isolated_mode, load_only=load_only
129
+ )
130
+ self.configuration.load()
131
+
132
+ # Error handling happens here, not in the action-handlers.
133
+ try:
134
+ handlers[action](options, args[1:])
135
+ except PipError as e:
136
+ logger.error(e.args[0])
137
+ return ERROR
138
+
139
+ return SUCCESS
140
+
141
+ def _determine_file(self, options: Values, need_value: bool) -> Optional[Kind]:
142
+ file_options = [
143
+ key
144
+ for key, value in (
145
+ (kinds.USER, options.user_file),
146
+ (kinds.GLOBAL, options.global_file),
147
+ (kinds.SITE, options.site_file),
148
+ )
149
+ if value
150
+ ]
151
+
152
+ if not file_options:
153
+ if not need_value:
154
+ return None
155
+ # Default to user, unless there's a site file.
156
+ elif any(
157
+ os.path.exists(site_config_file)
158
+ for site_config_file in get_configuration_files()[kinds.SITE]
159
+ ):
160
+ return kinds.SITE
161
+ else:
162
+ return kinds.USER
163
+ elif len(file_options) == 1:
164
+ return file_options[0]
165
+
166
+ raise PipError(
167
+ "Need exactly one file to operate upon "
168
+ "(--user, --site, --global) to perform."
169
+ )
170
+
171
+ def list_values(self, options: Values, args: List[str]) -> None:
172
+ self._get_n_args(args, "list", n=0)
173
+
174
+ for key, value in sorted(self.configuration.items()):
175
+ write_output("%s=%r", key, value)
176
+
177
+ def get_name(self, options: Values, args: List[str]) -> None:
178
+ key = self._get_n_args(args, "get [name]", n=1)
179
+ value = self.configuration.get_value(key)
180
+
181
+ write_output("%s", value)
182
+
183
+ def set_name_value(self, options: Values, args: List[str]) -> None:
184
+ key, value = self._get_n_args(args, "set [name] [value]", n=2)
185
+ self.configuration.set_value(key, value)
186
+
187
+ self._save_configuration()
188
+
189
+ def unset_name(self, options: Values, args: List[str]) -> None:
190
+ key = self._get_n_args(args, "unset [name]", n=1)
191
+ self.configuration.unset_value(key)
192
+
193
+ self._save_configuration()
194
+
195
+ def list_config_values(self, options: Values, args: List[str]) -> None:
196
+ """List config key-value pairs across different config files"""
197
+ self._get_n_args(args, "debug", n=0)
198
+
199
+ self.print_env_var_values()
200
+ # Iterate over config files and print if they exist, and the
201
+ # key-value pairs present in them if they do
202
+ for variant, files in sorted(self.configuration.iter_config_files()):
203
+ write_output("%s:", variant)
204
+ for fname in files:
205
+ with indent_log():
206
+ file_exists = os.path.exists(fname)
207
+ write_output("%s, exists: %r", fname, file_exists)
208
+ if file_exists:
209
+ self.print_config_file_values(variant)
210
+
211
+ def print_config_file_values(self, variant: Kind) -> None:
212
+ """Get key-value pairs from the file of a variant"""
213
+ for name, value in self.configuration.get_values_in_config(variant).items():
214
+ with indent_log():
215
+ write_output("%s: %s", name, value)
216
+
217
+ def print_env_var_values(self) -> None:
218
+ """Get key-values pairs present as environment variables"""
219
+ write_output("%s:", "env_var")
220
+ with indent_log():
221
+ for key, value in sorted(self.configuration.get_environ_vars()):
222
+ env_var = f"PIP_{key.upper()}"
223
+ write_output("%s=%r", env_var, value)
224
+
225
+ def open_in_editor(self, options: Values, args: List[str]) -> None:
226
+ editor = self._determine_editor(options)
227
+
228
+ fname = self.configuration.get_file_to_edit()
229
+ if fname is None:
230
+ raise PipError("Could not determine appropriate file.")
231
+ elif '"' in fname:
232
+ # This shouldn't happen, unless we see a username like that.
233
+ # If that happens, we'd appreciate a pull request fixing this.
234
+ raise PipError(
235
+ f'Can not open an editor for a file name containing "\n{fname}'
236
+ )
237
+
238
+ try:
239
+ subprocess.check_call(f'{editor} "{fname}"', shell=True)
240
+ except FileNotFoundError as e:
241
+ if not e.filename:
242
+ e.filename = editor
243
+ raise
244
+ except subprocess.CalledProcessError as e:
245
+ raise PipError(
246
+ "Editor Subprocess exited with exit code {}".format(e.returncode)
247
+ )
248
+
249
+ def _get_n_args(self, args: List[str], example: str, n: int) -> Any:
250
+ """Helper to make sure the command got the right number of arguments"""
251
+ if len(args) != n:
252
+ msg = (
253
+ "Got unexpected number of arguments, expected {}. "
254
+ '(example: "{} config {}")'
255
+ ).format(n, get_prog(), example)
256
+ raise PipError(msg)
257
+
258
+ if n == 1:
259
+ return args[0]
260
+ else:
261
+ return args
262
+
263
+ def _save_configuration(self) -> None:
264
+ # We successfully ran a modifying command. Need to save the
265
+ # configuration.
266
+ try:
267
+ self.configuration.save()
268
+ except Exception:
269
+ logger.exception(
270
+ "Unable to save configuration. Please report this as a bug."
271
+ )
272
+ raise PipError("Internal Error.")
273
+
274
+ def _determine_editor(self, options: Values) -> str:
275
+ if options.editor is not None:
276
+ return options.editor
277
+ elif "VISUAL" in os.environ:
278
+ return os.environ["VISUAL"]
279
+ elif "EDITOR" in os.environ:
280
+ return os.environ["EDITOR"]
281
+ else:
282
+ raise PipError("Could not determine editor to use.")
env/lib/python3.9/site-packages/pip/_internal/commands/debug.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.resources
2
+ import locale
3
+ import logging
4
+ import os
5
+ import sys
6
+ from optparse import Values
7
+ from types import ModuleType
8
+ from typing import Any, Dict, List, Optional
9
+
10
+ import pip._vendor
11
+ from pip._vendor.certifi import where
12
+ from pip._vendor.packaging.version import parse as parse_version
13
+
14
+ from pip._internal.cli import cmdoptions
15
+ from pip._internal.cli.base_command import Command
16
+ from pip._internal.cli.cmdoptions import make_target_python
17
+ from pip._internal.cli.status_codes import SUCCESS
18
+ from pip._internal.configuration import Configuration
19
+ from pip._internal.metadata import get_environment
20
+ from pip._internal.utils.logging import indent_log
21
+ from pip._internal.utils.misc import get_pip_version
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ def show_value(name: str, value: Any) -> None:
27
+ logger.info("%s: %s", name, value)
28
+
29
+
30
+ def show_sys_implementation() -> None:
31
+ logger.info("sys.implementation:")
32
+ implementation_name = sys.implementation.name
33
+ with indent_log():
34
+ show_value("name", implementation_name)
35
+
36
+
37
+ def create_vendor_txt_map() -> Dict[str, str]:
38
+ with importlib.resources.open_text("pip._vendor", "vendor.txt") as f:
39
+ # Purge non version specifying lines.
40
+ # Also, remove any space prefix or suffixes (including comments).
41
+ lines = [
42
+ line.strip().split(" ", 1)[0] for line in f.readlines() if "==" in line
43
+ ]
44
+
45
+ # Transform into "module" -> version dict.
46
+ return dict(line.split("==", 1) for line in lines)
47
+
48
+
49
+ def get_module_from_module_name(module_name: str) -> Optional[ModuleType]:
50
+ # Module name can be uppercase in vendor.txt for some reason...
51
+ module_name = module_name.lower().replace("-", "_")
52
+ # PATCH: setuptools is actually only pkg_resources.
53
+ if module_name == "setuptools":
54
+ module_name = "pkg_resources"
55
+
56
+ try:
57
+ __import__(f"pip._vendor.{module_name}", globals(), locals(), level=0)
58
+ return getattr(pip._vendor, module_name)
59
+ except ImportError:
60
+ # We allow 'truststore' to fail to import due
61
+ # to being unavailable on Python 3.9 and earlier.
62
+ if module_name == "truststore" and sys.version_info < (3, 10):
63
+ return None
64
+ raise
65
+
66
+
67
+ def get_vendor_version_from_module(module_name: str) -> Optional[str]:
68
+ module = get_module_from_module_name(module_name)
69
+ version = getattr(module, "__version__", None)
70
+
71
+ if module and not version:
72
+ # Try to find version in debundled module info.
73
+ assert module.__file__ is not None
74
+ env = get_environment([os.path.dirname(module.__file__)])
75
+ dist = env.get_distribution(module_name)
76
+ if dist:
77
+ version = str(dist.version)
78
+
79
+ return version
80
+
81
+
82
+ def show_actual_vendor_versions(vendor_txt_versions: Dict[str, str]) -> None:
83
+ """Log the actual version and print extra info if there is
84
+ a conflict or if the actual version could not be imported.
85
+ """
86
+ for module_name, expected_version in vendor_txt_versions.items():
87
+ extra_message = ""
88
+ actual_version = get_vendor_version_from_module(module_name)
89
+ if not actual_version:
90
+ extra_message = (
91
+ " (Unable to locate actual module version, using"
92
+ " vendor.txt specified version)"
93
+ )
94
+ actual_version = expected_version
95
+ elif parse_version(actual_version) != parse_version(expected_version):
96
+ extra_message = (
97
+ " (CONFLICT: vendor.txt suggests version should"
98
+ " be {})".format(expected_version)
99
+ )
100
+ logger.info("%s==%s%s", module_name, actual_version, extra_message)
101
+
102
+
103
+ def show_vendor_versions() -> None:
104
+ logger.info("vendored library versions:")
105
+
106
+ vendor_txt_versions = create_vendor_txt_map()
107
+ with indent_log():
108
+ show_actual_vendor_versions(vendor_txt_versions)
109
+
110
+
111
+ def show_tags(options: Values) -> None:
112
+ tag_limit = 10
113
+
114
+ target_python = make_target_python(options)
115
+ tags = target_python.get_sorted_tags()
116
+
117
+ # Display the target options that were explicitly provided.
118
+ formatted_target = target_python.format_given()
119
+ suffix = ""
120
+ if formatted_target:
121
+ suffix = f" (target: {formatted_target})"
122
+
123
+ msg = "Compatible tags: {}{}".format(len(tags), suffix)
124
+ logger.info(msg)
125
+
126
+ if options.verbose < 1 and len(tags) > tag_limit:
127
+ tags_limited = True
128
+ tags = tags[:tag_limit]
129
+ else:
130
+ tags_limited = False
131
+
132
+ with indent_log():
133
+ for tag in tags:
134
+ logger.info(str(tag))
135
+
136
+ if tags_limited:
137
+ msg = (
138
+ "...\n[First {tag_limit} tags shown. Pass --verbose to show all.]"
139
+ ).format(tag_limit=tag_limit)
140
+ logger.info(msg)
141
+
142
+
143
+ def ca_bundle_info(config: Configuration) -> str:
144
+ levels = {key.split(".", 1)[0] for key, _ in config.items()}
145
+ if not levels:
146
+ return "Not specified"
147
+
148
+ levels_that_override_global = ["install", "wheel", "download"]
149
+ global_overriding_level = [
150
+ level for level in levels if level in levels_that_override_global
151
+ ]
152
+ if not global_overriding_level:
153
+ return "global"
154
+
155
+ if "global" in levels:
156
+ levels.remove("global")
157
+ return ", ".join(levels)
158
+
159
+
160
+ class DebugCommand(Command):
161
+ """
162
+ Display debug information.
163
+ """
164
+
165
+ usage = """
166
+ %prog <options>"""
167
+ ignore_require_venv = True
168
+
169
+ def add_options(self) -> None:
170
+ cmdoptions.add_target_python_options(self.cmd_opts)
171
+ self.parser.insert_option_group(0, self.cmd_opts)
172
+ self.parser.config.load()
173
+
174
+ def run(self, options: Values, args: List[str]) -> int:
175
+ logger.warning(
176
+ "This command is only meant for debugging. "
177
+ "Do not use this with automation for parsing and getting these "
178
+ "details, since the output and options of this command may "
179
+ "change without notice."
180
+ )
181
+ show_value("pip version", get_pip_version())
182
+ show_value("sys.version", sys.version)
183
+ show_value("sys.executable", sys.executable)
184
+ show_value("sys.getdefaultencoding", sys.getdefaultencoding())
185
+ show_value("sys.getfilesystemencoding", sys.getfilesystemencoding())
186
+ show_value(
187
+ "locale.getpreferredencoding",
188
+ locale.getpreferredencoding(),
189
+ )
190
+ show_value("sys.platform", sys.platform)
191
+ show_sys_implementation()
192
+
193
+ show_value("'cert' config value", ca_bundle_info(self.parser.config))
194
+ show_value("REQUESTS_CA_BUNDLE", os.environ.get("REQUESTS_CA_BUNDLE"))
195
+ show_value("CURL_CA_BUNDLE", os.environ.get("CURL_CA_BUNDLE"))
196
+ show_value("pip._vendor.certifi.where()", where())
197
+ show_value("pip._vendor.DEBUNDLED", pip._vendor.DEBUNDLED)
198
+
199
+ show_vendor_versions()
200
+
201
+ show_tags(options)
202
+
203
+ return SUCCESS
env/lib/python3.9/site-packages/pip/_internal/commands/download.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ from optparse import Values
4
+ from typing import List
5
+
6
+ from pip._internal.cli import cmdoptions
7
+ from pip._internal.cli.cmdoptions import make_target_python
8
+ from pip._internal.cli.req_command import RequirementCommand, with_cleanup
9
+ from pip._internal.cli.status_codes import SUCCESS
10
+ from pip._internal.operations.build.build_tracker import get_build_tracker
11
+ from pip._internal.req.req_install import check_legacy_setup_py_options
12
+ from pip._internal.utils.misc import ensure_dir, normalize_path, write_output
13
+ from pip._internal.utils.temp_dir import TempDirectory
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class DownloadCommand(RequirementCommand):
19
+ """
20
+ Download packages from:
21
+
22
+ - PyPI (and other indexes) using requirement specifiers.
23
+ - VCS project urls.
24
+ - Local project directories.
25
+ - Local or remote source archives.
26
+
27
+ pip also supports downloading from "requirements files", which provide
28
+ an easy way to specify a whole environment to be downloaded.
29
+ """
30
+
31
+ usage = """
32
+ %prog [options] <requirement specifier> [package-index-options] ...
33
+ %prog [options] -r <requirements file> [package-index-options] ...
34
+ %prog [options] <vcs project url> ...
35
+ %prog [options] <local project path> ...
36
+ %prog [options] <archive url/path> ..."""
37
+
38
+ def add_options(self) -> None:
39
+ self.cmd_opts.add_option(cmdoptions.constraints())
40
+ self.cmd_opts.add_option(cmdoptions.requirements())
41
+ self.cmd_opts.add_option(cmdoptions.no_deps())
42
+ self.cmd_opts.add_option(cmdoptions.global_options())
43
+ self.cmd_opts.add_option(cmdoptions.no_binary())
44
+ self.cmd_opts.add_option(cmdoptions.only_binary())
45
+ self.cmd_opts.add_option(cmdoptions.prefer_binary())
46
+ self.cmd_opts.add_option(cmdoptions.src())
47
+ self.cmd_opts.add_option(cmdoptions.pre())
48
+ self.cmd_opts.add_option(cmdoptions.require_hashes())
49
+ self.cmd_opts.add_option(cmdoptions.progress_bar())
50
+ self.cmd_opts.add_option(cmdoptions.no_build_isolation())
51
+ self.cmd_opts.add_option(cmdoptions.use_pep517())
52
+ self.cmd_opts.add_option(cmdoptions.no_use_pep517())
53
+ self.cmd_opts.add_option(cmdoptions.check_build_deps())
54
+ self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
55
+
56
+ self.cmd_opts.add_option(
57
+ "-d",
58
+ "--dest",
59
+ "--destination-dir",
60
+ "--destination-directory",
61
+ dest="download_dir",
62
+ metavar="dir",
63
+ default=os.curdir,
64
+ help="Download packages into <dir>.",
65
+ )
66
+
67
+ cmdoptions.add_target_python_options(self.cmd_opts)
68
+
69
+ index_opts = cmdoptions.make_option_group(
70
+ cmdoptions.index_group,
71
+ self.parser,
72
+ )
73
+
74
+ self.parser.insert_option_group(0, index_opts)
75
+ self.parser.insert_option_group(0, self.cmd_opts)
76
+
77
+ @with_cleanup
78
+ def run(self, options: Values, args: List[str]) -> int:
79
+ options.ignore_installed = True
80
+ # editable doesn't really make sense for `pip download`, but the bowels
81
+ # of the RequirementSet code require that property.
82
+ options.editables = []
83
+
84
+ cmdoptions.check_dist_restriction(options)
85
+
86
+ options.download_dir = normalize_path(options.download_dir)
87
+ ensure_dir(options.download_dir)
88
+
89
+ session = self.get_default_session(options)
90
+
91
+ target_python = make_target_python(options)
92
+ finder = self._build_package_finder(
93
+ options=options,
94
+ session=session,
95
+ target_python=target_python,
96
+ ignore_requires_python=options.ignore_requires_python,
97
+ )
98
+
99
+ build_tracker = self.enter_context(get_build_tracker())
100
+
101
+ directory = TempDirectory(
102
+ delete=not options.no_clean,
103
+ kind="download",
104
+ globally_managed=True,
105
+ )
106
+
107
+ reqs = self.get_requirements(args, options, finder, session)
108
+ check_legacy_setup_py_options(options, reqs)
109
+
110
+ preparer = self.make_requirement_preparer(
111
+ temp_build_dir=directory,
112
+ options=options,
113
+ build_tracker=build_tracker,
114
+ session=session,
115
+ finder=finder,
116
+ download_dir=options.download_dir,
117
+ use_user_site=False,
118
+ verbosity=self.verbosity,
119
+ )
120
+
121
+ resolver = self.make_resolver(
122
+ preparer=preparer,
123
+ finder=finder,
124
+ options=options,
125
+ ignore_requires_python=options.ignore_requires_python,
126
+ use_pep517=options.use_pep517,
127
+ py_version_info=options.python_version,
128
+ )
129
+
130
+ self.trace_basic_info(finder)
131
+
132
+ requirement_set = resolver.resolve(reqs, check_supported_wheels=True)
133
+
134
+ downloaded: List[str] = []
135
+ for req in requirement_set.requirements.values():
136
+ if req.satisfied_by is None:
137
+ assert req.name is not None
138
+ preparer.save_linked_requirement(req)
139
+ downloaded.append(req.name)
140
+
141
+ preparer.prepare_linked_requirements_more(requirement_set.requirements.values())
142
+ requirement_set.warn_legacy_versions_and_specifiers()
143
+
144
+ if downloaded:
145
+ write_output("Successfully downloaded %s", " ".join(downloaded))
146
+
147
+ return SUCCESS