Tekrox commited on
Commit
758cd30
·
verified ·
1 Parent(s): 0e64e3b

Initial upload: Upcycle Things

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. .env.example +4 -0
  3. .gitattributes +4 -0
  4. .venv/bin/Activate.ps1 +241 -0
  5. .venv/bin/activate +66 -0
  6. .venv/bin/activate.csh +25 -0
  7. .venv/bin/activate.fish +64 -0
  8. .venv/bin/pip +10 -0
  9. .venv/bin/pip3 +10 -0
  10. .venv/bin/pip3.9 +10 -0
  11. .venv/bin/python +3 -0
  12. .venv/bin/python3 +3 -0
  13. .venv/bin/python3.9 +3 -0
  14. .venv/lib/python3.9/site-packages/_distutils_hack/__init__.py +128 -0
  15. .venv/lib/python3.9/site-packages/_distutils_hack/override.py +1 -0
  16. .venv/lib/python3.9/site-packages/distutils-precedence.pth +3 -0
  17. .venv/lib/python3.9/site-packages/pip-21.2.4.dist-info/INSTALLER +1 -0
  18. .venv/lib/python3.9/site-packages/pip-21.2.4.dist-info/LICENSE.txt +20 -0
  19. .venv/lib/python3.9/site-packages/pip-21.2.4.dist-info/METADATA +92 -0
  20. .venv/lib/python3.9/site-packages/pip-21.2.4.dist-info/RECORD +0 -0
  21. .venv/lib/python3.9/site-packages/pip-21.2.4.dist-info/REQUESTED +0 -0
  22. .venv/lib/python3.9/site-packages/pip-21.2.4.dist-info/WHEEL +5 -0
  23. .venv/lib/python3.9/site-packages/pip-21.2.4.dist-info/entry_points.txt +5 -0
  24. .venv/lib/python3.9/site-packages/pip-21.2.4.dist-info/top_level.txt +1 -0
  25. .venv/lib/python3.9/site-packages/pip/__init__.py +13 -0
  26. .venv/lib/python3.9/site-packages/pip/__main__.py +31 -0
  27. .venv/lib/python3.9/site-packages/pip/_internal/__init__.py +19 -0
  28. .venv/lib/python3.9/site-packages/pip/_internal/build_env.py +294 -0
  29. .venv/lib/python3.9/site-packages/pip/_internal/cache.py +287 -0
  30. .venv/lib/python3.9/site-packages/pip/_internal/cli/__init__.py +4 -0
  31. .venv/lib/python3.9/site-packages/pip/_internal/cli/autocompletion.py +163 -0
  32. .venv/lib/python3.9/site-packages/pip/_internal/cli/base_command.py +214 -0
  33. .venv/lib/python3.9/site-packages/pip/_internal/cli/cmdoptions.py +1009 -0
  34. .venv/lib/python3.9/site-packages/pip/_internal/cli/command_context.py +27 -0
  35. .venv/lib/python3.9/site-packages/pip/_internal/cli/main.py +70 -0
  36. .venv/lib/python3.9/site-packages/pip/_internal/cli/main_parser.py +87 -0
  37. .venv/lib/python3.9/site-packages/pip/_internal/cli/parser.py +292 -0
  38. .venv/lib/python3.9/site-packages/pip/_internal/cli/progress_bars.py +250 -0
  39. .venv/lib/python3.9/site-packages/pip/_internal/cli/req_command.py +453 -0
  40. .venv/lib/python3.9/site-packages/pip/_internal/cli/spinners.py +157 -0
  41. .venv/lib/python3.9/site-packages/pip/_internal/cli/status_codes.py +6 -0
  42. .venv/lib/python3.9/site-packages/pip/_internal/commands/__init__.py +112 -0
  43. .venv/lib/python3.9/site-packages/pip/_internal/commands/cache.py +216 -0
  44. .venv/lib/python3.9/site-packages/pip/_internal/commands/check.py +47 -0
  45. .venv/lib/python3.9/site-packages/pip/_internal/commands/completion.py +91 -0
  46. .venv/lib/python3.9/site-packages/pip/_internal/commands/configuration.py +266 -0
  47. .venv/lib/python3.9/site-packages/pip/_internal/commands/debug.py +204 -0
  48. .venv/lib/python3.9/site-packages/pip/_internal/commands/download.py +139 -0
  49. .venv/lib/python3.9/site-packages/pip/_internal/commands/freeze.py +84 -0
  50. .venv/lib/python3.9/site-packages/pip/_internal/commands/hash.py +55 -0
.DS_Store ADDED
Binary file (6.15 kB). View file
 
.env.example ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ HF_TOKEN= # Hugging Face write token (for dataset repo)
2
+ MODAL_TOKEN_ID= # Modal auth — from modal.com/settings
3
+ MODAL_TOKEN_SECRET= # Modal auth — from modal.com/settings
4
+ HF_DATASET_REPO= # e.g. your-username/museum-of-things
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ .venv/bin/python filter=lfs diff=lfs merge=lfs -text
37
+ .venv/bin/python3 filter=lfs diff=lfs merge=lfs -text
38
+ .venv/bin/python3.9 filter=lfs diff=lfs merge=lfs -text
39
+ .venv/lib/python3.9/site-packages/pip/_vendor/distlib/t64.exe filter=lfs diff=lfs merge=lfs -text
.venv/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"
.venv/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/miha/Code/Museum of Things/.venv"
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="(.venv) ${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
.venv/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/miha/Code/Museum of Things/.venv"
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 = "(.venv) $prompt"
21
+ endif
22
+
23
+ alias pydoc python -m pydoc
24
+
25
+ rehash
.venv/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/miha/Code/Museum of Things/.venv"
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) "(.venv) " (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
.venv/bin/pip ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ '''exec' "/Users/miha/Code/Museum of Things/.venv/bin/python3" "$0" "$@"
3
+ ' '''
4
+ # -*- coding: utf-8 -*-
5
+ import re
6
+ import sys
7
+ from pip._internal.cli.main import main
8
+ if __name__ == '__main__':
9
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
10
+ sys.exit(main())
.venv/bin/pip3 ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ '''exec' "/Users/miha/Code/Museum of Things/.venv/bin/python3" "$0" "$@"
3
+ ' '''
4
+ # -*- coding: utf-8 -*-
5
+ import re
6
+ import sys
7
+ from pip._internal.cli.main import main
8
+ if __name__ == '__main__':
9
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
10
+ sys.exit(main())
.venv/bin/pip3.9 ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ '''exec' "/Users/miha/Code/Museum of Things/.venv/bin/python3" "$0" "$@"
3
+ ' '''
4
+ # -*- coding: utf-8 -*-
5
+ import re
6
+ import sys
7
+ from pip._internal.cli.main import main
8
+ if __name__ == '__main__':
9
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
10
+ sys.exit(main())
.venv/bin/python ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b42b1a117605cafc8607b67b0892a609c2cd125012dd56288abeed8c89cdfb1
3
+ size 102352
.venv/bin/python3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b42b1a117605cafc8607b67b0892a609c2cd125012dd56288abeed8c89cdfb1
3
+ size 102352
.venv/bin/python3.9 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b42b1a117605cafc8607b67b0892a609c2cd125012dd56288abeed8c89cdfb1
3
+ size 102352
.venv/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
.venv/lib/python3.9/site-packages/_distutils_hack/override.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __import__('_distutils_hack').do_override()
.venv/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
.venv/lib/python3.9/site-packages/pip-21.2.4.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
.venv/lib/python3.9/site-packages/pip-21.2.4.dist-info/LICENSE.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2008-2021 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.
.venv/lib/python3.9/site-packages/pip-21.2.4.dist-info/METADATA ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: pip
3
+ Version: 21.2.4
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
+ Platform: UNKNOWN
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Topic :: Software Development :: Build Tools
17
+ Classifier: Programming Language :: Python
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.6
21
+ Classifier: Programming Language :: Python :: 3.7
22
+ Classifier: Programming Language :: Python :: 3.8
23
+ Classifier: Programming Language :: Python :: 3.9
24
+ Classifier: Programming Language :: Python :: Implementation :: CPython
25
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
26
+ Requires-Python: >=3.6
27
+ License-File: LICENSE.txt
28
+
29
+ pip - The Python Package Installer
30
+ ==================================
31
+
32
+ .. image:: https://img.shields.io/pypi/v/pip.svg
33
+ :target: https://pypi.org/project/pip/
34
+
35
+ .. image:: https://readthedocs.org/projects/pip/badge/?version=latest
36
+ :target: https://pip.pypa.io/en/latest
37
+
38
+ pip is the `package installer`_ for Python. You can use pip to install packages from the `Python Package Index`_ and other indexes.
39
+
40
+ Please take a look at our documentation for how to install and use pip:
41
+
42
+ * `Installation`_
43
+ * `Usage`_
44
+
45
+ We release updates regularly, with a new version every 3 months. Find more details in our documentation:
46
+
47
+ * `Release notes`_
48
+ * `Release process`_
49
+
50
+ In pip 20.3, we've `made a big improvement to the heart of pip`_; `learn more`_. We want your input, so `sign up for our user experience research studies`_ to help us do it right.
51
+
52
+ **Note**: pip 21.0, in January 2021, removed Python 2 support, per pip's `Python 2 support policy`_. Please migrate to Python 3.
53
+
54
+ If you find bugs, need help, or want to talk to the developers, please use our mailing lists or chat rooms:
55
+
56
+ * `Issue tracking`_
57
+ * `Discourse channel`_
58
+ * `User IRC`_
59
+
60
+ 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:
61
+
62
+ * `GitHub page`_
63
+ * `Development documentation`_
64
+ * `Development mailing list`_
65
+ * `Development IRC`_
66
+
67
+ Code of Conduct
68
+ ---------------
69
+
70
+ Everyone interacting in the pip project's codebases, issue trackers, chat
71
+ rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
72
+
73
+ .. _package installer: https://packaging.python.org/guides/tool-recommendations/
74
+ .. _Python Package Index: https://pypi.org
75
+ .. _Installation: https://pip.pypa.io/en/stable/installation/
76
+ .. _Usage: https://pip.pypa.io/en/stable/
77
+ .. _Release notes: https://pip.pypa.io/en/stable/news.html
78
+ .. _Release process: https://pip.pypa.io/en/latest/development/release-process/
79
+ .. _GitHub page: https://github.com/pypa/pip
80
+ .. _Development documentation: https://pip.pypa.io/en/latest/development
81
+ .. _made a big improvement to the heart of pip: https://pyfound.blogspot.com/2020/11/pip-20-3-new-resolver.html
82
+ .. _learn more: https://pip.pypa.io/en/latest/user_guide/#changes-to-the-pip-dependency-resolver-in-20-3-2020
83
+ .. _sign up for our user experience research studies: https://pyfound.blogspot.com/2020/03/new-pip-resolver-to-roll-out-this-year.html
84
+ .. _Python 2 support policy: https://pip.pypa.io/en/latest/development/release-process/#python-2-support
85
+ .. _Issue tracking: https://github.com/pypa/pip/issues
86
+ .. _Discourse channel: https://discuss.python.org/c/packaging
87
+ .. _Development mailing list: https://mail.python.org/mailman3/lists/distutils-sig.python.org/
88
+ .. _User IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa
89
+ .. _Development IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev
90
+ .. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
91
+
92
+
.venv/lib/python3.9/site-packages/pip-21.2.4.dist-info/RECORD ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.9/site-packages/pip-21.2.4.dist-info/REQUESTED ADDED
File without changes
.venv/lib/python3.9/site-packages/pip-21.2.4.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.36.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
.venv/lib/python3.9/site-packages/pip-21.2.4.dist-info/entry_points.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ [console_scripts]
2
+ pip = pip._internal.cli.main:main
3
+ pip3 = pip._internal.cli.main:main
4
+ pip3.9 = pip._internal.cli.main:main
5
+
.venv/lib/python3.9/site-packages/pip-21.2.4.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
.venv/lib/python3.9/site-packages/pip/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+
3
+ __version__ = "21.2.4"
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)
.venv/lib/python3.9/site-packages/pip/__main__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import warnings
4
+
5
+ # Remove '' and current working directory from the first entry
6
+ # of sys.path, if present to avoid using current directory
7
+ # in pip commands check, freeze, install, list and show,
8
+ # when invoked as python -m pip <command>
9
+ if sys.path[0] in ("", os.getcwd()):
10
+ sys.path.pop(0)
11
+
12
+ # If we are running from a wheel, add the wheel to sys.path
13
+ # This allows the usage python pip-*.whl/pip install pip-*.whl
14
+ if __package__ == "":
15
+ # __file__ is pip-*.whl/pip/__main__.py
16
+ # first dirname call strips of '/__main__.py', second strips off '/pip'
17
+ # Resulting path is the name of the wheel itself
18
+ # Add that to sys.path so we can import pip
19
+ path = os.path.dirname(os.path.dirname(__file__))
20
+ sys.path.insert(0, path)
21
+
22
+ if __name__ == "__main__":
23
+ # Work around the error reported in #9540, pending a proper fix.
24
+ # Note: It is essential the warning filter is set *before* importing
25
+ # pip, as the deprecation happens at import time, not runtime.
26
+ warnings.filterwarnings(
27
+ "ignore", category=DeprecationWarning, module=".*packaging\\.version"
28
+ )
29
+ from pip._internal.cli.main import main as _main
30
+
31
+ sys.exit(_main())
.venv/lib/python3.9/site-packages/pip/_internal/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+
3
+ import pip._internal.utils.inject_securetransport # noqa
4
+ from pip._internal.utils import _log
5
+
6
+ # init_logging() must be called before any call to logging.getLogger()
7
+ # which happens at import of most modules.
8
+ _log.init_logging()
9
+
10
+
11
+ def main(args: (Optional[List[str]]) = None) -> int:
12
+ """This is preserved for old console scripts that may still be referencing
13
+ it.
14
+
15
+ For additional details, see https://github.com/pypa/pip/issues/7498.
16
+ """
17
+ from pip._internal.utils.entrypoints import _wrapper
18
+
19
+ return _wrapper(args)
.venv/lib/python3.9/site-packages/pip/_internal/build_env.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build Environment used for isolation during sdist building
2
+ """
3
+
4
+ import contextlib
5
+ import logging
6
+ import os
7
+ import pathlib
8
+ import sys
9
+ import textwrap
10
+ import zipfile
11
+ from collections import OrderedDict
12
+ from sysconfig import get_paths
13
+ from types import TracebackType
14
+ from typing import TYPE_CHECKING, Iterable, Iterator, List, Optional, Set, Tuple, Type
15
+
16
+ from pip._vendor.certifi import where
17
+ from pip._vendor.packaging.requirements import Requirement
18
+ from pip._vendor.packaging.version import Version
19
+
20
+ from pip import __file__ as pip_location
21
+ from pip._internal.cli.spinners import open_spinner
22
+ from pip._internal.locations import get_platlib, get_prefixed_libs, get_purelib
23
+ from pip._internal.metadata import get_environment
24
+ from pip._internal.utils.subprocess import call_subprocess
25
+ from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
26
+
27
+ if TYPE_CHECKING:
28
+ from pip._internal.index.package_finder import PackageFinder
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ class _Prefix:
34
+
35
+ def __init__(self, path):
36
+ # type: (str) -> None
37
+ self.path = path
38
+ self.setup = False
39
+ self.bin_dir = get_paths(
40
+ 'nt' if os.name == 'nt' else 'posix_prefix',
41
+ vars={'base': path, 'platbase': path}
42
+ )['scripts']
43
+ self.lib_dirs = get_prefixed_libs(path)
44
+
45
+
46
+ @contextlib.contextmanager
47
+ def _create_standalone_pip() -> Iterator[str]:
48
+ """Create a "standalone pip" zip file.
49
+
50
+ The zip file's content is identical to the currently-running pip.
51
+ It will be used to install requirements into the build environment.
52
+ """
53
+ source = pathlib.Path(pip_location).resolve().parent
54
+
55
+ # Return the current instance if `source` is not a directory. We can't build
56
+ # a zip from this, and it likely means the instance is already standalone.
57
+ if not source.is_dir():
58
+ yield str(source)
59
+ return
60
+
61
+ with TempDirectory(kind="standalone-pip") as tmp_dir:
62
+ pip_zip = os.path.join(tmp_dir.path, "__env_pip__.zip")
63
+ kwargs = {}
64
+ if sys.version_info >= (3, 8):
65
+ kwargs["strict_timestamps"] = False
66
+ with zipfile.ZipFile(pip_zip, "w", **kwargs) as zf:
67
+ for child in source.rglob("*"):
68
+ zf.write(child, child.relative_to(source.parent).as_posix())
69
+ yield os.path.join(pip_zip, "pip")
70
+
71
+
72
+ class BuildEnvironment:
73
+ """Creates and manages an isolated environment to install build deps
74
+ """
75
+
76
+ def __init__(self):
77
+ # type: () -> None
78
+ temp_dir = TempDirectory(
79
+ kind=tempdir_kinds.BUILD_ENV, globally_managed=True
80
+ )
81
+
82
+ self._prefixes = OrderedDict(
83
+ (name, _Prefix(os.path.join(temp_dir.path, name)))
84
+ for name in ('normal', 'overlay')
85
+ )
86
+
87
+ self._bin_dirs = [] # type: List[str]
88
+ self._lib_dirs = [] # type: List[str]
89
+ for prefix in reversed(list(self._prefixes.values())):
90
+ self._bin_dirs.append(prefix.bin_dir)
91
+ self._lib_dirs.extend(prefix.lib_dirs)
92
+
93
+ # Customize site to:
94
+ # - ensure .pth files are honored
95
+ # - prevent access to system site packages
96
+ system_sites = {
97
+ os.path.normcase(site) for site in (get_purelib(), get_platlib())
98
+ }
99
+ self._site_dir = os.path.join(temp_dir.path, 'site')
100
+ if not os.path.exists(self._site_dir):
101
+ os.mkdir(self._site_dir)
102
+ with open(os.path.join(self._site_dir, 'sitecustomize.py'), 'w') as fp:
103
+ fp.write(textwrap.dedent(
104
+ '''
105
+ import os, site, sys
106
+
107
+ # First, drop system-sites related paths.
108
+ original_sys_path = sys.path[:]
109
+ known_paths = set()
110
+ for path in {system_sites!r}:
111
+ site.addsitedir(path, known_paths=known_paths)
112
+ system_paths = set(
113
+ os.path.normcase(path)
114
+ for path in sys.path[len(original_sys_path):]
115
+ )
116
+ original_sys_path = [
117
+ path for path in original_sys_path
118
+ if os.path.normcase(path) not in system_paths
119
+ ]
120
+ sys.path = original_sys_path
121
+
122
+ # Second, add lib directories.
123
+ # ensuring .pth file are processed.
124
+ for path in {lib_dirs!r}:
125
+ assert not path in sys.path
126
+ site.addsitedir(path)
127
+ '''
128
+ ).format(system_sites=system_sites, lib_dirs=self._lib_dirs))
129
+
130
+ def __enter__(self):
131
+ # type: () -> None
132
+ self._save_env = {
133
+ name: os.environ.get(name, None)
134
+ for name in ('PATH', 'PYTHONNOUSERSITE', 'PYTHONPATH')
135
+ }
136
+
137
+ path = self._bin_dirs[:]
138
+ old_path = self._save_env['PATH']
139
+ if old_path:
140
+ path.extend(old_path.split(os.pathsep))
141
+
142
+ pythonpath = [self._site_dir]
143
+
144
+ os.environ.update({
145
+ 'PATH': os.pathsep.join(path),
146
+ 'PYTHONNOUSERSITE': '1',
147
+ 'PYTHONPATH': os.pathsep.join(pythonpath),
148
+ })
149
+
150
+ def __exit__(
151
+ self,
152
+ exc_type, # type: Optional[Type[BaseException]]
153
+ exc_val, # type: Optional[BaseException]
154
+ exc_tb # type: Optional[TracebackType]
155
+ ):
156
+ # type: (...) -> None
157
+ for varname, old_value in self._save_env.items():
158
+ if old_value is None:
159
+ os.environ.pop(varname, None)
160
+ else:
161
+ os.environ[varname] = old_value
162
+
163
+ def check_requirements(self, reqs):
164
+ # type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]]
165
+ """Return 2 sets:
166
+ - conflicting requirements: set of (installed, wanted) reqs tuples
167
+ - missing requirements: set of reqs
168
+ """
169
+ missing = set()
170
+ conflicting = set()
171
+ if reqs:
172
+ env = get_environment(self._lib_dirs)
173
+ for req_str in reqs:
174
+ req = Requirement(req_str)
175
+ dist = env.get_distribution(req.name)
176
+ if not dist:
177
+ missing.add(req_str)
178
+ continue
179
+ if isinstance(dist.version, Version):
180
+ installed_req_str = f"{req.name}=={dist.version}"
181
+ else:
182
+ installed_req_str = f"{req.name}==={dist.version}"
183
+ if dist.version not in req.specifier:
184
+ conflicting.add((installed_req_str, req_str))
185
+ # FIXME: Consider direct URL?
186
+ return conflicting, missing
187
+
188
+ def install_requirements(
189
+ self,
190
+ finder, # type: PackageFinder
191
+ requirements, # type: Iterable[str]
192
+ prefix_as_string, # type: str
193
+ message # type: str
194
+ ):
195
+ # type: (...) -> None
196
+ prefix = self._prefixes[prefix_as_string]
197
+ assert not prefix.setup
198
+ prefix.setup = True
199
+ if not requirements:
200
+ return
201
+ with contextlib.ExitStack() as ctx:
202
+ # TODO: Remove this block when dropping 3.6 support. Python 3.6
203
+ # lacks importlib.resources and pep517 has issues loading files in
204
+ # a zip, so we fallback to the "old" method by adding the current
205
+ # pip directory to the child process's sys.path.
206
+ if sys.version_info < (3, 7):
207
+ pip_runnable = os.path.dirname(pip_location)
208
+ else:
209
+ pip_runnable = ctx.enter_context(_create_standalone_pip())
210
+ self._install_requirements(
211
+ pip_runnable,
212
+ finder,
213
+ requirements,
214
+ prefix,
215
+ message,
216
+ )
217
+
218
+ @staticmethod
219
+ def _install_requirements(
220
+ pip_runnable: str,
221
+ finder: "PackageFinder",
222
+ requirements: Iterable[str],
223
+ prefix: _Prefix,
224
+ message: str,
225
+ ) -> None:
226
+ args = [
227
+ sys.executable, pip_runnable, 'install',
228
+ '--ignore-installed', '--no-user', '--prefix', prefix.path,
229
+ '--no-warn-script-location',
230
+ ] # type: List[str]
231
+ if logger.getEffectiveLevel() <= logging.DEBUG:
232
+ args.append('-v')
233
+ for format_control in ('no_binary', 'only_binary'):
234
+ formats = getattr(finder.format_control, format_control)
235
+ args.extend(('--' + format_control.replace('_', '-'),
236
+ ','.join(sorted(formats or {':none:'}))))
237
+
238
+ index_urls = finder.index_urls
239
+ if index_urls:
240
+ args.extend(['-i', index_urls[0]])
241
+ for extra_index in index_urls[1:]:
242
+ args.extend(['--extra-index-url', extra_index])
243
+ else:
244
+ args.append('--no-index')
245
+ for link in finder.find_links:
246
+ args.extend(['--find-links', link])
247
+
248
+ for host in finder.trusted_hosts:
249
+ args.extend(['--trusted-host', host])
250
+ if finder.allow_all_prereleases:
251
+ args.append('--pre')
252
+ if finder.prefer_binary:
253
+ args.append('--prefer-binary')
254
+ args.append('--')
255
+ args.extend(requirements)
256
+ extra_environ = {"_PIP_STANDALONE_CERT": where()}
257
+ with open_spinner(message) as spinner:
258
+ call_subprocess(args, spinner=spinner, extra_environ=extra_environ)
259
+
260
+
261
+ class NoOpBuildEnvironment(BuildEnvironment):
262
+ """A no-op drop-in replacement for BuildEnvironment
263
+ """
264
+
265
+ def __init__(self):
266
+ # type: () -> None
267
+ pass
268
+
269
+ def __enter__(self):
270
+ # type: () -> None
271
+ pass
272
+
273
+ def __exit__(
274
+ self,
275
+ exc_type, # type: Optional[Type[BaseException]]
276
+ exc_val, # type: Optional[BaseException]
277
+ exc_tb # type: Optional[TracebackType]
278
+ ):
279
+ # type: (...) -> None
280
+ pass
281
+
282
+ def cleanup(self):
283
+ # type: () -> None
284
+ pass
285
+
286
+ def install_requirements(
287
+ self,
288
+ finder, # type: PackageFinder
289
+ requirements, # type: Iterable[str]
290
+ prefix_as_string, # type: str
291
+ message # type: str
292
+ ):
293
+ # type: (...) -> None
294
+ raise NotImplementedError()
.venv/lib/python3.9/site-packages/pip/_internal/cache.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cache Management
2
+ """
3
+
4
+ import hashlib
5
+ import json
6
+ import logging
7
+ import os
8
+ from typing import Any, Dict, List, Optional, Set
9
+
10
+ from pip._vendor.packaging.tags import Tag, interpreter_name, interpreter_version
11
+ from pip._vendor.packaging.utils import canonicalize_name
12
+
13
+ from pip._internal.exceptions import InvalidWheelFilename
14
+ from pip._internal.models.format_control import FormatControl
15
+ from pip._internal.models.link import Link
16
+ from pip._internal.models.wheel import Wheel
17
+ from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
18
+ from pip._internal.utils.urls import path_to_url
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ def _hash_dict(d):
24
+ # type: (Dict[str, str]) -> str
25
+ """Return a stable sha224 of a dictionary."""
26
+ s = json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
27
+ return hashlib.sha224(s.encode("ascii")).hexdigest()
28
+
29
+
30
+ class Cache:
31
+ """An abstract class - provides cache directories for data from links
32
+
33
+
34
+ :param cache_dir: The root of the cache.
35
+ :param format_control: An object of FormatControl class to limit
36
+ binaries being read from the cache.
37
+ :param allowed_formats: which formats of files the cache should store.
38
+ ('binary' and 'source' are the only allowed values)
39
+ """
40
+
41
+ def __init__(self, cache_dir, format_control, allowed_formats):
42
+ # type: (str, FormatControl, Set[str]) -> None
43
+ super().__init__()
44
+ assert not cache_dir or os.path.isabs(cache_dir)
45
+ self.cache_dir = cache_dir or None
46
+ self.format_control = format_control
47
+ self.allowed_formats = allowed_formats
48
+
49
+ _valid_formats = {"source", "binary"}
50
+ assert self.allowed_formats.union(_valid_formats) == _valid_formats
51
+
52
+ def _get_cache_path_parts(self, link):
53
+ # type: (Link) -> List[str]
54
+ """Get parts of part that must be os.path.joined with cache_dir
55
+ """
56
+
57
+ # We want to generate an url to use as our cache key, we don't want to
58
+ # just re-use the URL because it might have other items in the fragment
59
+ # and we don't care about those.
60
+ key_parts = {"url": link.url_without_fragment}
61
+ if link.hash_name is not None and link.hash is not None:
62
+ key_parts[link.hash_name] = link.hash
63
+ if link.subdirectory_fragment:
64
+ key_parts["subdirectory"] = link.subdirectory_fragment
65
+
66
+ # Include interpreter name, major and minor version in cache key
67
+ # to cope with ill-behaved sdists that build a different wheel
68
+ # depending on the python version their setup.py is being run on,
69
+ # and don't encode the difference in compatibility tags.
70
+ # https://github.com/pypa/pip/issues/7296
71
+ key_parts["interpreter_name"] = interpreter_name()
72
+ key_parts["interpreter_version"] = interpreter_version()
73
+
74
+ # Encode our key url with sha224, we'll use this because it has similar
75
+ # security properties to sha256, but with a shorter total output (and
76
+ # thus less secure). However the differences don't make a lot of
77
+ # difference for our use case here.
78
+ hashed = _hash_dict(key_parts)
79
+
80
+ # We want to nest the directories some to prevent having a ton of top
81
+ # level directories where we might run out of sub directories on some
82
+ # FS.
83
+ parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
84
+
85
+ return parts
86
+
87
+ def _get_candidates(self, link, canonical_package_name):
88
+ # type: (Link, str) -> List[Any]
89
+ can_not_cache = (
90
+ not self.cache_dir or
91
+ not canonical_package_name or
92
+ not link
93
+ )
94
+ if can_not_cache:
95
+ return []
96
+
97
+ formats = self.format_control.get_allowed_formats(
98
+ canonical_package_name
99
+ )
100
+ if not self.allowed_formats.intersection(formats):
101
+ return []
102
+
103
+ candidates = []
104
+ path = self.get_path_for_link(link)
105
+ if os.path.isdir(path):
106
+ for candidate in os.listdir(path):
107
+ candidates.append((candidate, path))
108
+ return candidates
109
+
110
+ def get_path_for_link(self, link):
111
+ # type: (Link) -> str
112
+ """Return a directory to store cached items in for link.
113
+ """
114
+ raise NotImplementedError()
115
+
116
+ def get(
117
+ self,
118
+ link, # type: Link
119
+ package_name, # type: Optional[str]
120
+ supported_tags, # type: List[Tag]
121
+ ):
122
+ # type: (...) -> Link
123
+ """Returns a link to a cached item if it exists, otherwise returns the
124
+ passed link.
125
+ """
126
+ raise NotImplementedError()
127
+
128
+
129
+ class SimpleWheelCache(Cache):
130
+ """A cache of wheels for future installs.
131
+ """
132
+
133
+ def __init__(self, cache_dir, format_control):
134
+ # type: (str, FormatControl) -> None
135
+ super().__init__(cache_dir, format_control, {"binary"})
136
+
137
+ def get_path_for_link(self, link):
138
+ # type: (Link) -> str
139
+ """Return a directory to store cached wheels for link
140
+
141
+ Because there are M wheels for any one sdist, we provide a directory
142
+ to cache them in, and then consult that directory when looking up
143
+ cache hits.
144
+
145
+ We only insert things into the cache if they have plausible version
146
+ numbers, so that we don't contaminate the cache with things that were
147
+ not unique. E.g. ./package might have dozens of installs done for it
148
+ and build a version of 0.0...and if we built and cached a wheel, we'd
149
+ end up using the same wheel even if the source has been edited.
150
+
151
+ :param link: The link of the sdist for which this will cache wheels.
152
+ """
153
+ parts = self._get_cache_path_parts(link)
154
+ assert self.cache_dir
155
+ # Store wheels within the root cache_dir
156
+ return os.path.join(self.cache_dir, "wheels", *parts)
157
+
158
+ def get(
159
+ self,
160
+ link, # type: Link
161
+ package_name, # type: Optional[str]
162
+ supported_tags, # type: List[Tag]
163
+ ):
164
+ # type: (...) -> Link
165
+ candidates = []
166
+
167
+ if not package_name:
168
+ return link
169
+
170
+ canonical_package_name = canonicalize_name(package_name)
171
+ for wheel_name, wheel_dir in self._get_candidates(
172
+ link, canonical_package_name
173
+ ):
174
+ try:
175
+ wheel = Wheel(wheel_name)
176
+ except InvalidWheelFilename:
177
+ continue
178
+ if canonicalize_name(wheel.name) != canonical_package_name:
179
+ logger.debug(
180
+ "Ignoring cached wheel %s for %s as it "
181
+ "does not match the expected distribution name %s.",
182
+ wheel_name, link, package_name,
183
+ )
184
+ continue
185
+ if not wheel.supported(supported_tags):
186
+ # Built for a different python/arch/etc
187
+ continue
188
+ candidates.append(
189
+ (
190
+ wheel.support_index_min(supported_tags),
191
+ wheel_name,
192
+ wheel_dir,
193
+ )
194
+ )
195
+
196
+ if not candidates:
197
+ return link
198
+
199
+ _, wheel_name, wheel_dir = min(candidates)
200
+ return Link(path_to_url(os.path.join(wheel_dir, wheel_name)))
201
+
202
+
203
+ class EphemWheelCache(SimpleWheelCache):
204
+ """A SimpleWheelCache that creates it's own temporary cache directory
205
+ """
206
+
207
+ def __init__(self, format_control):
208
+ # type: (FormatControl) -> None
209
+ self._temp_dir = TempDirectory(
210
+ kind=tempdir_kinds.EPHEM_WHEEL_CACHE,
211
+ globally_managed=True,
212
+ )
213
+
214
+ super().__init__(self._temp_dir.path, format_control)
215
+
216
+
217
+ class CacheEntry:
218
+ def __init__(
219
+ self,
220
+ link, # type: Link
221
+ persistent, # type: bool
222
+ ):
223
+ self.link = link
224
+ self.persistent = persistent
225
+
226
+
227
+ class WheelCache(Cache):
228
+ """Wraps EphemWheelCache and SimpleWheelCache into a single Cache
229
+
230
+ This Cache allows for gracefully degradation, using the ephem wheel cache
231
+ when a certain link is not found in the simple wheel cache first.
232
+ """
233
+
234
+ def __init__(self, cache_dir, format_control):
235
+ # type: (str, FormatControl) -> None
236
+ super().__init__(cache_dir, format_control, {'binary'})
237
+ self._wheel_cache = SimpleWheelCache(cache_dir, format_control)
238
+ self._ephem_cache = EphemWheelCache(format_control)
239
+
240
+ def get_path_for_link(self, link):
241
+ # type: (Link) -> str
242
+ return self._wheel_cache.get_path_for_link(link)
243
+
244
+ def get_ephem_path_for_link(self, link):
245
+ # type: (Link) -> str
246
+ return self._ephem_cache.get_path_for_link(link)
247
+
248
+ def get(
249
+ self,
250
+ link, # type: Link
251
+ package_name, # type: Optional[str]
252
+ supported_tags, # type: List[Tag]
253
+ ):
254
+ # type: (...) -> Link
255
+ cache_entry = self.get_cache_entry(link, package_name, supported_tags)
256
+ if cache_entry is None:
257
+ return link
258
+ return cache_entry.link
259
+
260
+ def get_cache_entry(
261
+ self,
262
+ link, # type: Link
263
+ package_name, # type: Optional[str]
264
+ supported_tags, # type: List[Tag]
265
+ ):
266
+ # type: (...) -> Optional[CacheEntry]
267
+ """Returns a CacheEntry with a link to a cached item if it exists or
268
+ None. The cache entry indicates if the item was found in the persistent
269
+ or ephemeral cache.
270
+ """
271
+ retval = self._wheel_cache.get(
272
+ link=link,
273
+ package_name=package_name,
274
+ supported_tags=supported_tags,
275
+ )
276
+ if retval is not link:
277
+ return CacheEntry(retval, persistent=True)
278
+
279
+ retval = self._ephem_cache.get(
280
+ link=link,
281
+ package_name=package_name,
282
+ supported_tags=supported_tags,
283
+ )
284
+ if retval is not link:
285
+ return CacheEntry(retval, persistent=False)
286
+
287
+ return None
.venv/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
.venv/lib/python3.9/site-packages/pip/_internal/cli/autocompletion.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ subcommand = create_command(subcommand_name)
63
+
64
+ for opt in subcommand.parser.option_list_all:
65
+ if opt.help != optparse.SUPPRESS_HELP:
66
+ for opt_str in opt._long_opts + opt._short_opts:
67
+ options.append((opt_str, opt.nargs))
68
+
69
+ # filter out previously specified options from available options
70
+ prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]]
71
+ options = [(x, v) for (x, v) in options if x not in prev_opts]
72
+ # filter options by current input
73
+ options = [(k, v) for k, v in options if k.startswith(current)]
74
+ # get completion type given cwords and available subcommand options
75
+ completion_type = get_path_completion_type(
76
+ cwords,
77
+ cword,
78
+ subcommand.parser.option_list_all,
79
+ )
80
+ # get completion files and directories if ``completion_type`` is
81
+ # ``<file>``, ``<dir>`` or ``<path>``
82
+ if completion_type:
83
+ paths = auto_complete_paths(current, completion_type)
84
+ options = [(path, 0) for path in paths]
85
+ for option in options:
86
+ opt_label = option[0]
87
+ # append '=' to options which require args
88
+ if option[1] and option[0][:2] == "--":
89
+ opt_label += "="
90
+ print(opt_label)
91
+ else:
92
+ # show main parser options only when necessary
93
+
94
+ opts = [i.option_list for i in parser.option_groups]
95
+ opts.append(parser.option_list)
96
+ flattened_opts = chain.from_iterable(opts)
97
+ if current.startswith("-"):
98
+ for opt in flattened_opts:
99
+ if opt.help != optparse.SUPPRESS_HELP:
100
+ subcommands += opt._long_opts + opt._short_opts
101
+ else:
102
+ # get completion type given cwords and all available options
103
+ completion_type = get_path_completion_type(cwords, cword, flattened_opts)
104
+ if completion_type:
105
+ subcommands = list(auto_complete_paths(current, completion_type))
106
+
107
+ print(" ".join([x for x in subcommands if x.startswith(current)]))
108
+ sys.exit(1)
109
+
110
+
111
+ def get_path_completion_type(
112
+ cwords: List[str], cword: int, opts: Iterable[Any]
113
+ ) -> Optional[str]:
114
+ """Get the type of path completion (``file``, ``dir``, ``path`` or None)
115
+
116
+ :param cwords: same as the environmental variable ``COMP_WORDS``
117
+ :param cword: same as the environmental variable ``COMP_CWORD``
118
+ :param opts: The available options to check
119
+ :return: path completion type (``file``, ``dir``, ``path`` or None)
120
+ """
121
+ if cword < 2 or not cwords[cword - 2].startswith("-"):
122
+ return None
123
+ for opt in opts:
124
+ if opt.help == optparse.SUPPRESS_HELP:
125
+ continue
126
+ for o in str(opt).split("/"):
127
+ if cwords[cword - 2].split("=")[0] == o:
128
+ if not opt.metavar or any(
129
+ x in ("path", "file", "dir") for x in opt.metavar.split("/")
130
+ ):
131
+ return opt.metavar
132
+ return None
133
+
134
+
135
+ def auto_complete_paths(current: str, completion_type: str) -> Iterable[str]:
136
+ """If ``completion_type`` is ``file`` or ``path``, list all regular files
137
+ and directories starting with ``current``; otherwise only list directories
138
+ starting with ``current``.
139
+
140
+ :param current: The word to be completed
141
+ :param completion_type: path completion type(`file`, `path` or `dir`)i
142
+ :return: A generator of regular files and/or directories
143
+ """
144
+ directory, filename = os.path.split(current)
145
+ current_path = os.path.abspath(directory)
146
+ # Don't complete paths if they can't be accessed
147
+ if not os.access(current_path, os.R_OK):
148
+ return
149
+ filename = os.path.normcase(filename)
150
+ # list all files that start with ``filename``
151
+ file_list = (
152
+ x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)
153
+ )
154
+ for f in file_list:
155
+ opt = os.path.join(current_path, f)
156
+ comp_file = os.path.normcase(os.path.join(directory, f))
157
+ # complete regular files when there is not ``<dir>`` after option
158
+ # complete directories when there is ``<file>``, ``<path>`` or
159
+ # ``<dir>``after option
160
+ if completion_type != "dir" and os.path.isfile(opt):
161
+ yield comp_file
162
+ elif os.path.isdir(opt):
163
+ yield os.path.join(comp_file, "")
.venv/lib/python3.9/site-packages/pip/_internal/cli/base_command.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base Command class, and related routines"""
2
+
3
+ import logging
4
+ import logging.config
5
+ import optparse
6
+ import os
7
+ import sys
8
+ import traceback
9
+ from optparse import Values
10
+ from typing import Any, List, Optional, Tuple
11
+
12
+ from pip._internal.cli import cmdoptions
13
+ from pip._internal.cli.command_context import CommandContextMixIn
14
+ from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
15
+ from pip._internal.cli.status_codes import (
16
+ ERROR,
17
+ PREVIOUS_BUILD_DIR_ERROR,
18
+ UNKNOWN_ERROR,
19
+ VIRTUALENV_NOT_FOUND,
20
+ )
21
+ from pip._internal.exceptions import (
22
+ BadCommand,
23
+ CommandError,
24
+ InstallationError,
25
+ NetworkConnectionError,
26
+ PreviousBuildDirError,
27
+ UninstallationError,
28
+ )
29
+ from pip._internal.utils.deprecation import deprecated
30
+ from pip._internal.utils.filesystem import check_path_owner
31
+ from pip._internal.utils.logging import BrokenStdoutLoggingError, setup_logging
32
+ from pip._internal.utils.misc import get_prog, normalize_path
33
+ from pip._internal.utils.temp_dir import TempDirectoryTypeRegistry as TempDirRegistry
34
+ from pip._internal.utils.temp_dir import global_tempdir_manager, tempdir_registry
35
+ from pip._internal.utils.virtualenv import running_under_virtualenv
36
+
37
+ __all__ = ["Command"]
38
+
39
+ logger = logging.getLogger(__name__)
40
+
41
+
42
+ class Command(CommandContextMixIn):
43
+ usage: str = ""
44
+ ignore_require_venv: bool = False
45
+
46
+ def __init__(self, name: str, summary: str, isolated: bool = False) -> None:
47
+ super().__init__()
48
+
49
+ self.name = name
50
+ self.summary = summary
51
+ self.parser = ConfigOptionParser(
52
+ usage=self.usage,
53
+ prog=f"{get_prog()} {name}",
54
+ formatter=UpdatingDefaultsHelpFormatter(),
55
+ add_help_option=False,
56
+ name=name,
57
+ description=self.__doc__,
58
+ isolated=isolated,
59
+ )
60
+
61
+ self.tempdir_registry: Optional[TempDirRegistry] = None
62
+
63
+ # Commands should add options to this option group
64
+ optgroup_name = f"{self.name.capitalize()} Options"
65
+ self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)
66
+
67
+ # Add the general options
68
+ gen_opts = cmdoptions.make_option_group(
69
+ cmdoptions.general_group,
70
+ self.parser,
71
+ )
72
+ self.parser.add_option_group(gen_opts)
73
+
74
+ self.add_options()
75
+
76
+ def add_options(self) -> None:
77
+ pass
78
+
79
+ def handle_pip_version_check(self, options: Values) -> None:
80
+ """
81
+ This is a no-op so that commands by default do not do the pip version
82
+ check.
83
+ """
84
+ # Make sure we do the pip version check if the index_group options
85
+ # are present.
86
+ assert not hasattr(options, "no_index")
87
+
88
+ def run(self, options: Values, args: List[Any]) -> int:
89
+ raise NotImplementedError
90
+
91
+ def parse_args(self, args: List[str]) -> Tuple[Any, Any]:
92
+ # factored out for testability
93
+ return self.parser.parse_args(args)
94
+
95
+ def main(self, args: List[str]) -> int:
96
+ try:
97
+ with self.main_context():
98
+ return self._main(args)
99
+ finally:
100
+ logging.shutdown()
101
+
102
+ def _main(self, args: List[str]) -> int:
103
+ # We must initialize this before the tempdir manager, otherwise the
104
+ # configuration would not be accessible by the time we clean up the
105
+ # tempdir manager.
106
+ self.tempdir_registry = self.enter_context(tempdir_registry())
107
+ # Intentionally set as early as possible so globally-managed temporary
108
+ # directories are available to the rest of the code.
109
+ self.enter_context(global_tempdir_manager())
110
+
111
+ options, args = self.parse_args(args)
112
+
113
+ # Set verbosity so that it can be used elsewhere.
114
+ self.verbosity = options.verbose - options.quiet
115
+
116
+ level_number = setup_logging(
117
+ verbosity=self.verbosity,
118
+ no_color=options.no_color,
119
+ user_log_file=options.log,
120
+ )
121
+
122
+ # TODO: Try to get these passing down from the command?
123
+ # without resorting to os.environ to hold these.
124
+ # This also affects isolated builds and it should.
125
+
126
+ if options.no_input:
127
+ os.environ["PIP_NO_INPUT"] = "1"
128
+
129
+ if options.exists_action:
130
+ os.environ["PIP_EXISTS_ACTION"] = " ".join(options.exists_action)
131
+
132
+ if options.require_venv and not self.ignore_require_venv:
133
+ # If a venv is required check if it can really be found
134
+ if not running_under_virtualenv():
135
+ logger.critical("Could not find an activated virtualenv (required).")
136
+ sys.exit(VIRTUALENV_NOT_FOUND)
137
+
138
+ if options.cache_dir:
139
+ options.cache_dir = normalize_path(options.cache_dir)
140
+ if not check_path_owner(options.cache_dir):
141
+ logger.warning(
142
+ "The directory '%s' or its parent directory is not owned "
143
+ "or is not writable by the current user. The cache "
144
+ "has been disabled. Check the permissions and owner of "
145
+ "that directory. If executing pip with sudo, you should "
146
+ "use sudo's -H flag.",
147
+ options.cache_dir,
148
+ )
149
+ options.cache_dir = None
150
+
151
+ if getattr(options, "build_dir", None):
152
+ deprecated(
153
+ reason=(
154
+ "The -b/--build/--build-dir/--build-directory "
155
+ "option is deprecated and has no effect anymore."
156
+ ),
157
+ replacement=(
158
+ "use the TMPDIR/TEMP/TMP environment variable, "
159
+ "possibly combined with --no-clean"
160
+ ),
161
+ gone_in="21.3",
162
+ issue=8333,
163
+ )
164
+
165
+ if "2020-resolver" in options.features_enabled:
166
+ logger.warning(
167
+ "--use-feature=2020-resolver no longer has any effect, "
168
+ "since it is now the default dependency resolver in pip. "
169
+ "This will become an error in pip 21.0."
170
+ )
171
+
172
+ try:
173
+ status = self.run(options, args)
174
+ assert isinstance(status, int)
175
+ return status
176
+ except PreviousBuildDirError as exc:
177
+ logger.critical(str(exc))
178
+ logger.debug("Exception information:", exc_info=True)
179
+
180
+ return PREVIOUS_BUILD_DIR_ERROR
181
+ except (
182
+ InstallationError,
183
+ UninstallationError,
184
+ BadCommand,
185
+ NetworkConnectionError,
186
+ ) as exc:
187
+ logger.critical(str(exc))
188
+ logger.debug("Exception information:", exc_info=True)
189
+
190
+ return ERROR
191
+ except CommandError as exc:
192
+ logger.critical("%s", exc)
193
+ logger.debug("Exception information:", exc_info=True)
194
+
195
+ return ERROR
196
+ except BrokenStdoutLoggingError:
197
+ # Bypass our logger and write any remaining messages to stderr
198
+ # because stdout no longer works.
199
+ print("ERROR: Pipe to stdout was broken", file=sys.stderr)
200
+ if level_number <= logging.DEBUG:
201
+ traceback.print_exc(file=sys.stderr)
202
+
203
+ return ERROR
204
+ except KeyboardInterrupt:
205
+ logger.critical("Operation cancelled by user")
206
+ logger.debug("Exception information:", exc_info=True)
207
+
208
+ return ERROR
209
+ except BaseException:
210
+ logger.critical("Exception:", exc_info=True)
211
+
212
+ return UNKNOWN_ERROR
213
+ finally:
214
+ self.handle_pip_version_check(options)
.venv/lib/python3.9/site-packages/pip/_internal/cli/cmdoptions.py ADDED
@@ -0,0 +1,1009 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 os
14
+ import textwrap
15
+ import warnings
16
+ from functools import partial
17
+ from optparse import SUPPRESS_HELP, Option, OptionGroup, OptionParser, Values
18
+ from textwrap import dedent
19
+ from typing import Any, Callable, Dict, Optional, Tuple
20
+
21
+ from pip._vendor.packaging.utils import canonicalize_name
22
+
23
+ from pip._internal.cli.parser import ConfigOptionParser
24
+ from pip._internal.cli.progress_bars import BAR_TYPES
25
+ from pip._internal.exceptions import CommandError
26
+ from pip._internal.locations import USER_CACHE_DIR, get_src_prefix
27
+ from pip._internal.models.format_control import FormatControl
28
+ from pip._internal.models.index import PyPI
29
+ from pip._internal.models.target_python import TargetPython
30
+ from pip._internal.utils.hashes import STRONG_HASHES
31
+ from pip._internal.utils.misc import strtobool
32
+
33
+
34
+ def raise_option_error(parser: OptionParser, option: Option, msg: str) -> None:
35
+ """
36
+ Raise an option parsing error using parser.error().
37
+
38
+ Args:
39
+ parser: an OptionParser instance.
40
+ option: an Option instance.
41
+ msg: the error text.
42
+ """
43
+ msg = f"{option} error: {msg}"
44
+ msg = textwrap.fill(" ".join(msg.split()))
45
+ parser.error(msg)
46
+
47
+
48
+ def make_option_group(group: Dict[str, Any], parser: ConfigOptionParser) -> OptionGroup:
49
+ """
50
+ Return an OptionGroup object
51
+ group -- assumed to be dict with 'name' and 'options' keys
52
+ parser -- an optparse Parser
53
+ """
54
+ option_group = OptionGroup(parser, group["name"])
55
+ for option in group["options"]:
56
+ option_group.add_option(option())
57
+ return option_group
58
+
59
+
60
+ def check_install_build_global(
61
+ options: Values, check_options: Optional[Values] = None
62
+ ) -> None:
63
+ """Disable wheels if per-setup.py call options are set.
64
+
65
+ :param options: The OptionParser options to update.
66
+ :param check_options: The options to check, if not supplied defaults to
67
+ options.
68
+ """
69
+ if check_options is None:
70
+ check_options = options
71
+
72
+ def getname(n: str) -> Optional[Any]:
73
+ return getattr(check_options, n, None)
74
+
75
+ names = ["build_options", "global_options", "install_options"]
76
+ if any(map(getname, names)):
77
+ control = options.format_control
78
+ control.disallow_binaries()
79
+ warnings.warn(
80
+ "Disabling all use of wheels due to the use of --build-option "
81
+ "/ --global-option / --install-option.",
82
+ stacklevel=2,
83
+ )
84
+
85
+
86
+ def check_dist_restriction(options: Values, check_target: bool = False) -> None:
87
+ """Function for determining if custom platform options are allowed.
88
+
89
+ :param options: The OptionParser options.
90
+ :param check_target: Whether or not to check if --target is being used.
91
+ """
92
+ dist_restriction_set = any(
93
+ [
94
+ options.python_version,
95
+ options.platforms,
96
+ options.abis,
97
+ options.implementation,
98
+ ]
99
+ )
100
+
101
+ binary_only = FormatControl(set(), {":all:"})
102
+ sdist_dependencies_allowed = (
103
+ options.format_control != binary_only and not options.ignore_dependencies
104
+ )
105
+
106
+ # Installations or downloads using dist restrictions must not combine
107
+ # source distributions and dist-specific wheels, as they are not
108
+ # guaranteed to be locally compatible.
109
+ if dist_restriction_set and sdist_dependencies_allowed:
110
+ raise CommandError(
111
+ "When restricting platform and interpreter constraints using "
112
+ "--python-version, --platform, --abi, or --implementation, "
113
+ "either --no-deps must be set, or --only-binary=:all: must be "
114
+ "set and --no-binary must not be set (or must be set to "
115
+ ":none:)."
116
+ )
117
+
118
+ if check_target:
119
+ if dist_restriction_set and not options.target_dir:
120
+ raise CommandError(
121
+ "Can not use any platform or abi specific options unless "
122
+ "installing via '--target'"
123
+ )
124
+
125
+
126
+ def _path_option_check(option: Option, opt: str, value: str) -> str:
127
+ return os.path.expanduser(value)
128
+
129
+
130
+ def _package_name_option_check(option: Option, opt: str, value: str) -> str:
131
+ return canonicalize_name(value)
132
+
133
+
134
+ class PipOption(Option):
135
+ TYPES = Option.TYPES + ("path", "package_name")
136
+ TYPE_CHECKER = Option.TYPE_CHECKER.copy()
137
+ TYPE_CHECKER["package_name"] = _package_name_option_check
138
+ TYPE_CHECKER["path"] = _path_option_check
139
+
140
+
141
+ ###########
142
+ # options #
143
+ ###########
144
+
145
+ help_: Callable[..., Option] = partial(
146
+ Option,
147
+ "-h",
148
+ "--help",
149
+ dest="help",
150
+ action="help",
151
+ help="Show help.",
152
+ )
153
+
154
+ isolated_mode: Callable[..., Option] = partial(
155
+ Option,
156
+ "--isolated",
157
+ dest="isolated_mode",
158
+ action="store_true",
159
+ default=False,
160
+ help=(
161
+ "Run pip in an isolated mode, ignoring environment variables and user "
162
+ "configuration."
163
+ ),
164
+ )
165
+
166
+ require_virtualenv: Callable[..., Option] = partial(
167
+ Option,
168
+ # Run only if inside a virtualenv, bail if not.
169
+ "--require-virtualenv",
170
+ "--require-venv",
171
+ dest="require_venv",
172
+ action="store_true",
173
+ default=False,
174
+ help=SUPPRESS_HELP,
175
+ )
176
+
177
+ verbose: Callable[..., Option] = partial(
178
+ Option,
179
+ "-v",
180
+ "--verbose",
181
+ dest="verbose",
182
+ action="count",
183
+ default=0,
184
+ help="Give more output. Option is additive, and can be used up to 3 times.",
185
+ )
186
+
187
+ no_color: Callable[..., Option] = partial(
188
+ Option,
189
+ "--no-color",
190
+ dest="no_color",
191
+ action="store_true",
192
+ default=False,
193
+ help="Suppress colored output.",
194
+ )
195
+
196
+ version: Callable[..., Option] = partial(
197
+ Option,
198
+ "-V",
199
+ "--version",
200
+ dest="version",
201
+ action="store_true",
202
+ help="Show version and exit.",
203
+ )
204
+
205
+ quiet: Callable[..., Option] = partial(
206
+ Option,
207
+ "-q",
208
+ "--quiet",
209
+ dest="quiet",
210
+ action="count",
211
+ default=0,
212
+ help=(
213
+ "Give less output. Option is additive, and can be used up to 3"
214
+ " times (corresponding to WARNING, ERROR, and CRITICAL logging"
215
+ " levels)."
216
+ ),
217
+ )
218
+
219
+ progress_bar: Callable[..., Option] = partial(
220
+ Option,
221
+ "--progress-bar",
222
+ dest="progress_bar",
223
+ type="choice",
224
+ choices=list(BAR_TYPES.keys()),
225
+ default="on",
226
+ help=(
227
+ "Specify type of progress to be displayed ["
228
+ + "|".join(BAR_TYPES.keys())
229
+ + "] (default: %default)"
230
+ ),
231
+ )
232
+
233
+ log: Callable[..., Option] = partial(
234
+ PipOption,
235
+ "--log",
236
+ "--log-file",
237
+ "--local-log",
238
+ dest="log",
239
+ metavar="path",
240
+ type="path",
241
+ help="Path to a verbose appending log.",
242
+ )
243
+
244
+ no_input: Callable[..., Option] = partial(
245
+ Option,
246
+ # Don't ask for input
247
+ "--no-input",
248
+ dest="no_input",
249
+ action="store_true",
250
+ default=False,
251
+ help="Disable prompting for input.",
252
+ )
253
+
254
+ proxy: Callable[..., Option] = partial(
255
+ Option,
256
+ "--proxy",
257
+ dest="proxy",
258
+ type="str",
259
+ default="",
260
+ help="Specify a proxy in the form [user:passwd@]proxy.server:port.",
261
+ )
262
+
263
+ retries: Callable[..., Option] = partial(
264
+ Option,
265
+ "--retries",
266
+ dest="retries",
267
+ type="int",
268
+ default=5,
269
+ help="Maximum number of retries each connection should attempt "
270
+ "(default %default times).",
271
+ )
272
+
273
+ timeout: Callable[..., Option] = partial(
274
+ Option,
275
+ "--timeout",
276
+ "--default-timeout",
277
+ metavar="sec",
278
+ dest="timeout",
279
+ type="float",
280
+ default=15,
281
+ help="Set the socket timeout (default %default seconds).",
282
+ )
283
+
284
+
285
+ def exists_action() -> Option:
286
+ return Option(
287
+ # Option when path already exist
288
+ "--exists-action",
289
+ dest="exists_action",
290
+ type="choice",
291
+ choices=["s", "i", "w", "b", "a"],
292
+ default=[],
293
+ action="append",
294
+ metavar="action",
295
+ help="Default action when a path already exists: "
296
+ "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.",
297
+ )
298
+
299
+
300
+ cert: Callable[..., Option] = partial(
301
+ PipOption,
302
+ "--cert",
303
+ dest="cert",
304
+ type="path",
305
+ metavar="path",
306
+ help=(
307
+ "Path to PEM-encoded CA certificate bundle. "
308
+ "If provided, overrides the default. "
309
+ "See 'SSL Certificate Verification' in pip documentation "
310
+ "for more information."
311
+ ),
312
+ )
313
+
314
+ client_cert: Callable[..., Option] = partial(
315
+ PipOption,
316
+ "--client-cert",
317
+ dest="client_cert",
318
+ type="path",
319
+ default=None,
320
+ metavar="path",
321
+ help="Path to SSL client certificate, a single file containing the "
322
+ "private key and the certificate in PEM format.",
323
+ )
324
+
325
+ index_url: Callable[..., Option] = partial(
326
+ Option,
327
+ "-i",
328
+ "--index-url",
329
+ "--pypi-url",
330
+ dest="index_url",
331
+ metavar="URL",
332
+ default=PyPI.simple_url,
333
+ help="Base URL of the Python Package Index (default %default). "
334
+ "This should point to a repository compliant with PEP 503 "
335
+ "(the simple repository API) or a local directory laid out "
336
+ "in the same format.",
337
+ )
338
+
339
+
340
+ def extra_index_url() -> Option:
341
+ return Option(
342
+ "--extra-index-url",
343
+ dest="extra_index_urls",
344
+ metavar="URL",
345
+ action="append",
346
+ default=[],
347
+ help="Extra URLs of package indexes to use in addition to "
348
+ "--index-url. Should follow the same rules as "
349
+ "--index-url.",
350
+ )
351
+
352
+
353
+ no_index: Callable[..., Option] = partial(
354
+ Option,
355
+ "--no-index",
356
+ dest="no_index",
357
+ action="store_true",
358
+ default=False,
359
+ help="Ignore package index (only looking at --find-links URLs instead).",
360
+ )
361
+
362
+
363
+ def find_links() -> Option:
364
+ return Option(
365
+ "-f",
366
+ "--find-links",
367
+ dest="find_links",
368
+ action="append",
369
+ default=[],
370
+ metavar="url",
371
+ help="If a URL or path to an html file, then parse for links to "
372
+ "archives such as sdist (.tar.gz) or wheel (.whl) files. "
373
+ "If a local path or file:// URL that's a directory, "
374
+ "then look for archives in the directory listing. "
375
+ "Links to VCS project URLs are not supported.",
376
+ )
377
+
378
+
379
+ def trusted_host() -> Option:
380
+ return Option(
381
+ "--trusted-host",
382
+ dest="trusted_hosts",
383
+ action="append",
384
+ metavar="HOSTNAME",
385
+ default=[],
386
+ help="Mark this host or host:port pair as trusted, even though it "
387
+ "does not have valid or any HTTPS.",
388
+ )
389
+
390
+
391
+ def constraints() -> Option:
392
+ return Option(
393
+ "-c",
394
+ "--constraint",
395
+ dest="constraints",
396
+ action="append",
397
+ default=[],
398
+ metavar="file",
399
+ help="Constrain versions using the given constraints file. "
400
+ "This option can be used multiple times.",
401
+ )
402
+
403
+
404
+ def requirements() -> Option:
405
+ return Option(
406
+ "-r",
407
+ "--requirement",
408
+ dest="requirements",
409
+ action="append",
410
+ default=[],
411
+ metavar="file",
412
+ help="Install from the given requirements file. "
413
+ "This option can be used multiple times.",
414
+ )
415
+
416
+
417
+ def editable() -> Option:
418
+ return Option(
419
+ "-e",
420
+ "--editable",
421
+ dest="editables",
422
+ action="append",
423
+ default=[],
424
+ metavar="path/url",
425
+ help=(
426
+ "Install a project in editable mode (i.e. setuptools "
427
+ '"develop mode") from a local project path or a VCS url.'
428
+ ),
429
+ )
430
+
431
+
432
+ def _handle_src(option: Option, opt_str: str, value: str, parser: OptionParser) -> None:
433
+ value = os.path.abspath(value)
434
+ setattr(parser.values, option.dest, value)
435
+
436
+
437
+ src: Callable[..., Option] = partial(
438
+ PipOption,
439
+ "--src",
440
+ "--source",
441
+ "--source-dir",
442
+ "--source-directory",
443
+ dest="src_dir",
444
+ type="path",
445
+ metavar="dir",
446
+ default=get_src_prefix(),
447
+ action="callback",
448
+ callback=_handle_src,
449
+ help="Directory to check out editable projects into. "
450
+ 'The default in a virtualenv is "<venv path>/src". '
451
+ 'The default for global installs is "<current dir>/src".',
452
+ )
453
+
454
+
455
+ def _get_format_control(values: Values, option: Option) -> Any:
456
+ """Get a format_control object."""
457
+ return getattr(values, option.dest)
458
+
459
+
460
+ def _handle_no_binary(
461
+ option: Option, opt_str: str, value: str, parser: OptionParser
462
+ ) -> None:
463
+ existing = _get_format_control(parser.values, option)
464
+ FormatControl.handle_mutual_excludes(
465
+ value,
466
+ existing.no_binary,
467
+ existing.only_binary,
468
+ )
469
+
470
+
471
+ def _handle_only_binary(
472
+ option: Option, opt_str: str, value: str, parser: OptionParser
473
+ ) -> None:
474
+ existing = _get_format_control(parser.values, option)
475
+ FormatControl.handle_mutual_excludes(
476
+ value,
477
+ existing.only_binary,
478
+ existing.no_binary,
479
+ )
480
+
481
+
482
+ def no_binary() -> Option:
483
+ format_control = FormatControl(set(), set())
484
+ return Option(
485
+ "--no-binary",
486
+ dest="format_control",
487
+ action="callback",
488
+ callback=_handle_no_binary,
489
+ type="str",
490
+ default=format_control,
491
+ help="Do not use binary packages. Can be supplied multiple times, and "
492
+ 'each time adds to the existing value. Accepts either ":all:" to '
493
+ 'disable all binary packages, ":none:" to empty the set (notice '
494
+ "the colons), or one or more package names with commas between "
495
+ "them (no colons). Note that some packages are tricky to compile "
496
+ "and may fail to install when this option is used on them.",
497
+ )
498
+
499
+
500
+ def only_binary() -> Option:
501
+ format_control = FormatControl(set(), set())
502
+ return Option(
503
+ "--only-binary",
504
+ dest="format_control",
505
+ action="callback",
506
+ callback=_handle_only_binary,
507
+ type="str",
508
+ default=format_control,
509
+ help="Do not use source packages. Can be supplied multiple times, and "
510
+ 'each time adds to the existing value. Accepts either ":all:" to '
511
+ 'disable all source packages, ":none:" to empty the set, or one '
512
+ "or more package names with commas between them. Packages "
513
+ "without binary distributions will fail to install when this "
514
+ "option is used on them.",
515
+ )
516
+
517
+
518
+ platforms: Callable[..., Option] = partial(
519
+ Option,
520
+ "--platform",
521
+ dest="platforms",
522
+ metavar="platform",
523
+ action="append",
524
+ default=None,
525
+ help=(
526
+ "Only use wheels compatible with <platform>. Defaults to the "
527
+ "platform of the running system. Use this option multiple times to "
528
+ "specify multiple platforms supported by the target interpreter."
529
+ ),
530
+ )
531
+
532
+
533
+ # This was made a separate function for unit-testing purposes.
534
+ def _convert_python_version(value: str) -> Tuple[Tuple[int, ...], Optional[str]]:
535
+ """
536
+ Convert a version string like "3", "37", or "3.7.3" into a tuple of ints.
537
+
538
+ :return: A 2-tuple (version_info, error_msg), where `error_msg` is
539
+ non-None if and only if there was a parsing error.
540
+ """
541
+ if not value:
542
+ # The empty string is the same as not providing a value.
543
+ return (None, None)
544
+
545
+ parts = value.split(".")
546
+ if len(parts) > 3:
547
+ return ((), "at most three version parts are allowed")
548
+
549
+ if len(parts) == 1:
550
+ # Then we are in the case of "3" or "37".
551
+ value = parts[0]
552
+ if len(value) > 1:
553
+ parts = [value[0], value[1:]]
554
+
555
+ try:
556
+ version_info = tuple(int(part) for part in parts)
557
+ except ValueError:
558
+ return ((), "each version part must be an integer")
559
+
560
+ return (version_info, None)
561
+
562
+
563
+ def _handle_python_version(
564
+ option: Option, opt_str: str, value: str, parser: OptionParser
565
+ ) -> None:
566
+ """
567
+ Handle a provided --python-version value.
568
+ """
569
+ version_info, error_msg = _convert_python_version(value)
570
+ if error_msg is not None:
571
+ msg = "invalid --python-version value: {!r}: {}".format(
572
+ value,
573
+ error_msg,
574
+ )
575
+ raise_option_error(parser, option=option, msg=msg)
576
+
577
+ parser.values.python_version = version_info
578
+
579
+
580
+ python_version: Callable[..., Option] = partial(
581
+ Option,
582
+ "--python-version",
583
+ dest="python_version",
584
+ metavar="python_version",
585
+ action="callback",
586
+ callback=_handle_python_version,
587
+ type="str",
588
+ default=None,
589
+ help=dedent(
590
+ """\
591
+ The Python interpreter version to use for wheel and "Requires-Python"
592
+ compatibility checks. Defaults to a version derived from the running
593
+ interpreter. The version can be specified using up to three dot-separated
594
+ integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor
595
+ version can also be given as a string without dots (e.g. "37" for 3.7.0).
596
+ """
597
+ ),
598
+ )
599
+
600
+
601
+ implementation: Callable[..., Option] = partial(
602
+ Option,
603
+ "--implementation",
604
+ dest="implementation",
605
+ metavar="implementation",
606
+ default=None,
607
+ help=(
608
+ "Only use wheels compatible with Python "
609
+ "implementation <implementation>, e.g. 'pp', 'jy', 'cp', "
610
+ " or 'ip'. If not specified, then the current "
611
+ "interpreter implementation is used. Use 'py' to force "
612
+ "implementation-agnostic wheels."
613
+ ),
614
+ )
615
+
616
+
617
+ abis: Callable[..., Option] = partial(
618
+ Option,
619
+ "--abi",
620
+ dest="abis",
621
+ metavar="abi",
622
+ action="append",
623
+ default=None,
624
+ help=(
625
+ "Only use wheels compatible with Python abi <abi>, e.g. 'pypy_41'. "
626
+ "If not specified, then the current interpreter abi tag is used. "
627
+ "Use this option multiple times to specify multiple abis supported "
628
+ "by the target interpreter. Generally you will need to specify "
629
+ "--implementation, --platform, and --python-version when using this "
630
+ "option."
631
+ ),
632
+ )
633
+
634
+
635
+ def add_target_python_options(cmd_opts: OptionGroup) -> None:
636
+ cmd_opts.add_option(platforms())
637
+ cmd_opts.add_option(python_version())
638
+ cmd_opts.add_option(implementation())
639
+ cmd_opts.add_option(abis())
640
+
641
+
642
+ def make_target_python(options: Values) -> TargetPython:
643
+ target_python = TargetPython(
644
+ platforms=options.platforms,
645
+ py_version_info=options.python_version,
646
+ abis=options.abis,
647
+ implementation=options.implementation,
648
+ )
649
+
650
+ return target_python
651
+
652
+
653
+ def prefer_binary() -> Option:
654
+ return Option(
655
+ "--prefer-binary",
656
+ dest="prefer_binary",
657
+ action="store_true",
658
+ default=False,
659
+ help="Prefer older binary packages over newer source packages.",
660
+ )
661
+
662
+
663
+ cache_dir: Callable[..., Option] = partial(
664
+ PipOption,
665
+ "--cache-dir",
666
+ dest="cache_dir",
667
+ default=USER_CACHE_DIR,
668
+ metavar="dir",
669
+ type="path",
670
+ help="Store the cache data in <dir>.",
671
+ )
672
+
673
+
674
+ def _handle_no_cache_dir(
675
+ option: Option, opt: str, value: str, parser: OptionParser
676
+ ) -> None:
677
+ """
678
+ Process a value provided for the --no-cache-dir option.
679
+
680
+ This is an optparse.Option callback for the --no-cache-dir option.
681
+ """
682
+ # The value argument will be None if --no-cache-dir is passed via the
683
+ # command-line, since the option doesn't accept arguments. However,
684
+ # the value can be non-None if the option is triggered e.g. by an
685
+ # environment variable, like PIP_NO_CACHE_DIR=true.
686
+ if value is not None:
687
+ # Then parse the string value to get argument error-checking.
688
+ try:
689
+ strtobool(value)
690
+ except ValueError as exc:
691
+ raise_option_error(parser, option=option, msg=str(exc))
692
+
693
+ # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool()
694
+ # converted to 0 (like "false" or "no") caused cache_dir to be disabled
695
+ # rather than enabled (logic would say the latter). Thus, we disable
696
+ # the cache directory not just on values that parse to True, but (for
697
+ # backwards compatibility reasons) also on values that parse to False.
698
+ # In other words, always set it to False if the option is provided in
699
+ # some (valid) form.
700
+ parser.values.cache_dir = False
701
+
702
+
703
+ no_cache: Callable[..., Option] = partial(
704
+ Option,
705
+ "--no-cache-dir",
706
+ dest="cache_dir",
707
+ action="callback",
708
+ callback=_handle_no_cache_dir,
709
+ help="Disable the cache.",
710
+ )
711
+
712
+ no_deps: Callable[..., Option] = partial(
713
+ Option,
714
+ "--no-deps",
715
+ "--no-dependencies",
716
+ dest="ignore_dependencies",
717
+ action="store_true",
718
+ default=False,
719
+ help="Don't install package dependencies.",
720
+ )
721
+
722
+ build_dir: Callable[..., Option] = partial(
723
+ PipOption,
724
+ "-b",
725
+ "--build",
726
+ "--build-dir",
727
+ "--build-directory",
728
+ dest="build_dir",
729
+ type="path",
730
+ metavar="dir",
731
+ help=SUPPRESS_HELP,
732
+ )
733
+
734
+ ignore_requires_python: Callable[..., Option] = partial(
735
+ Option,
736
+ "--ignore-requires-python",
737
+ dest="ignore_requires_python",
738
+ action="store_true",
739
+ help="Ignore the Requires-Python information.",
740
+ )
741
+
742
+ no_build_isolation: Callable[..., Option] = partial(
743
+ Option,
744
+ "--no-build-isolation",
745
+ dest="build_isolation",
746
+ action="store_false",
747
+ default=True,
748
+ help="Disable isolation when building a modern source distribution. "
749
+ "Build dependencies specified by PEP 518 must be already installed "
750
+ "if this option is used.",
751
+ )
752
+
753
+
754
+ def _handle_no_use_pep517(
755
+ option: Option, opt: str, value: str, parser: OptionParser
756
+ ) -> None:
757
+ """
758
+ Process a value provided for the --no-use-pep517 option.
759
+
760
+ This is an optparse.Option callback for the no_use_pep517 option.
761
+ """
762
+ # Since --no-use-pep517 doesn't accept arguments, the value argument
763
+ # will be None if --no-use-pep517 is passed via the command-line.
764
+ # However, the value can be non-None if the option is triggered e.g.
765
+ # by an environment variable, for example "PIP_NO_USE_PEP517=true".
766
+ if value is not None:
767
+ msg = """A value was passed for --no-use-pep517,
768
+ probably using either the PIP_NO_USE_PEP517 environment variable
769
+ or the "no-use-pep517" config file option. Use an appropriate value
770
+ of the PIP_USE_PEP517 environment variable or the "use-pep517"
771
+ config file option instead.
772
+ """
773
+ raise_option_error(parser, option=option, msg=msg)
774
+
775
+ # Otherwise, --no-use-pep517 was passed via the command-line.
776
+ parser.values.use_pep517 = False
777
+
778
+
779
+ use_pep517: Any = partial(
780
+ Option,
781
+ "--use-pep517",
782
+ dest="use_pep517",
783
+ action="store_true",
784
+ default=None,
785
+ help="Use PEP 517 for building source distributions "
786
+ "(use --no-use-pep517 to force legacy behaviour).",
787
+ )
788
+
789
+ no_use_pep517: Any = partial(
790
+ Option,
791
+ "--no-use-pep517",
792
+ dest="use_pep517",
793
+ action="callback",
794
+ callback=_handle_no_use_pep517,
795
+ default=None,
796
+ help=SUPPRESS_HELP,
797
+ )
798
+
799
+ install_options: Callable[..., Option] = partial(
800
+ Option,
801
+ "--install-option",
802
+ dest="install_options",
803
+ action="append",
804
+ metavar="options",
805
+ help="Extra arguments to be supplied to the setup.py install "
806
+ 'command (use like --install-option="--install-scripts=/usr/local/'
807
+ 'bin"). Use multiple --install-option options to pass multiple '
808
+ "options to setup.py install. If you are using an option with a "
809
+ "directory path, be sure to use absolute path.",
810
+ )
811
+
812
+ build_options: Callable[..., Option] = partial(
813
+ Option,
814
+ "--build-option",
815
+ dest="build_options",
816
+ metavar="options",
817
+ action="append",
818
+ help="Extra arguments to be supplied to 'setup.py bdist_wheel'.",
819
+ )
820
+
821
+ global_options: Callable[..., Option] = partial(
822
+ Option,
823
+ "--global-option",
824
+ dest="global_options",
825
+ action="append",
826
+ metavar="options",
827
+ help="Extra global options to be supplied to the setup.py "
828
+ "call before the install or bdist_wheel command.",
829
+ )
830
+
831
+ no_clean: Callable[..., Option] = partial(
832
+ Option,
833
+ "--no-clean",
834
+ action="store_true",
835
+ default=False,
836
+ help="Don't clean up build directories.",
837
+ )
838
+
839
+ pre: Callable[..., Option] = partial(
840
+ Option,
841
+ "--pre",
842
+ action="store_true",
843
+ default=False,
844
+ help="Include pre-release and development versions. By default, "
845
+ "pip only finds stable versions.",
846
+ )
847
+
848
+ disable_pip_version_check: Callable[..., Option] = partial(
849
+ Option,
850
+ "--disable-pip-version-check",
851
+ dest="disable_pip_version_check",
852
+ action="store_true",
853
+ default=False,
854
+ help="Don't periodically check PyPI to determine whether a new version "
855
+ "of pip is available for download. Implied with --no-index.",
856
+ )
857
+
858
+
859
+ def _handle_merge_hash(
860
+ option: Option, opt_str: str, value: str, parser: OptionParser
861
+ ) -> None:
862
+ """Given a value spelled "algo:digest", append the digest to a list
863
+ pointed to in a dict by the algo name."""
864
+ if not parser.values.hashes:
865
+ parser.values.hashes = {}
866
+ try:
867
+ algo, digest = value.split(":", 1)
868
+ except ValueError:
869
+ parser.error(
870
+ "Arguments to {} must be a hash name " # noqa
871
+ "followed by a value, like --hash=sha256:"
872
+ "abcde...".format(opt_str)
873
+ )
874
+ if algo not in STRONG_HASHES:
875
+ parser.error(
876
+ "Allowed hash algorithms for {} are {}.".format( # noqa
877
+ opt_str, ", ".join(STRONG_HASHES)
878
+ )
879
+ )
880
+ parser.values.hashes.setdefault(algo, []).append(digest)
881
+
882
+
883
+ hash: Callable[..., Option] = partial(
884
+ Option,
885
+ "--hash",
886
+ # Hash values eventually end up in InstallRequirement.hashes due to
887
+ # __dict__ copying in process_line().
888
+ dest="hashes",
889
+ action="callback",
890
+ callback=_handle_merge_hash,
891
+ type="string",
892
+ help="Verify that the package's archive matches this "
893
+ "hash before installing. Example: --hash=sha256:abcdef...",
894
+ )
895
+
896
+
897
+ require_hashes: Callable[..., Option] = partial(
898
+ Option,
899
+ "--require-hashes",
900
+ dest="require_hashes",
901
+ action="store_true",
902
+ default=False,
903
+ help="Require a hash to check each requirement against, for "
904
+ "repeatable installs. This option is implied when any package in a "
905
+ "requirements file has a --hash option.",
906
+ )
907
+
908
+
909
+ list_path: Callable[..., Option] = partial(
910
+ PipOption,
911
+ "--path",
912
+ dest="path",
913
+ type="path",
914
+ action="append",
915
+ help="Restrict to the specified installation path for listing "
916
+ "packages (can be used multiple times).",
917
+ )
918
+
919
+
920
+ def check_list_path_option(options: Values) -> None:
921
+ if options.path and (options.user or options.local):
922
+ raise CommandError("Cannot combine '--path' with '--user' or '--local'")
923
+
924
+
925
+ list_exclude: Callable[..., Option] = partial(
926
+ PipOption,
927
+ "--exclude",
928
+ dest="excludes",
929
+ action="append",
930
+ metavar="package",
931
+ type="package_name",
932
+ help="Exclude specified package from the output",
933
+ )
934
+
935
+
936
+ no_python_version_warning: Callable[..., Option] = partial(
937
+ Option,
938
+ "--no-python-version-warning",
939
+ dest="no_python_version_warning",
940
+ action="store_true",
941
+ default=False,
942
+ help="Silence deprecation warnings for upcoming unsupported Pythons.",
943
+ )
944
+
945
+
946
+ use_new_feature: Callable[..., Option] = partial(
947
+ Option,
948
+ "--use-feature",
949
+ dest="features_enabled",
950
+ metavar="feature",
951
+ action="append",
952
+ default=[],
953
+ choices=["2020-resolver", "fast-deps", "in-tree-build"],
954
+ help="Enable new functionality, that may be backward incompatible.",
955
+ )
956
+
957
+ use_deprecated_feature: Callable[..., Option] = partial(
958
+ Option,
959
+ "--use-deprecated",
960
+ dest="deprecated_features_enabled",
961
+ metavar="feature",
962
+ action="append",
963
+ default=[],
964
+ choices=["legacy-resolver"],
965
+ help=("Enable deprecated functionality, that will be removed in the future."),
966
+ )
967
+
968
+
969
+ ##########
970
+ # groups #
971
+ ##########
972
+
973
+ general_group: Dict[str, Any] = {
974
+ "name": "General Options",
975
+ "options": [
976
+ help_,
977
+ isolated_mode,
978
+ require_virtualenv,
979
+ verbose,
980
+ version,
981
+ quiet,
982
+ log,
983
+ no_input,
984
+ proxy,
985
+ retries,
986
+ timeout,
987
+ exists_action,
988
+ trusted_host,
989
+ cert,
990
+ client_cert,
991
+ cache_dir,
992
+ no_cache,
993
+ disable_pip_version_check,
994
+ no_color,
995
+ no_python_version_warning,
996
+ use_new_feature,
997
+ use_deprecated_feature,
998
+ ],
999
+ }
1000
+
1001
+ index_group: Dict[str, Any] = {
1002
+ "name": "Package Index Options",
1003
+ "options": [
1004
+ index_url,
1005
+ extra_index_url,
1006
+ no_index,
1007
+ find_links,
1008
+ ],
1009
+ }
.venv/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, Iterator, TypeVar
3
+
4
+ _T = TypeVar("_T", covariant=True)
5
+
6
+
7
+ class CommandContextMixIn:
8
+ def __init__(self) -> None:
9
+ super().__init__()
10
+ self._in_main_context = False
11
+ self._main_context = ExitStack()
12
+
13
+ @contextmanager
14
+ def main_context(self) -> Iterator[None]:
15
+ assert not self._in_main_context
16
+
17
+ self._in_main_context = True
18
+ try:
19
+ with self._main_context:
20
+ yield
21
+ finally:
22
+ self._in_main_context = False
23
+
24
+ def enter_context(self, context_provider: ContextManager[_T]) -> _T:
25
+ assert self._in_main_context
26
+
27
+ return self._main_context.enter_context(context_provider)
.venv/lib/python3.9/site-packages/pip/_internal/cli/main.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Primary application entrypoint.
2
+ """
3
+ import locale
4
+ import logging
5
+ import os
6
+ import sys
7
+ from typing import List, Optional
8
+
9
+ from pip._internal.cli.autocompletion import autocomplete
10
+ from pip._internal.cli.main_parser import parse_command
11
+ from pip._internal.commands import create_command
12
+ from pip._internal.exceptions import PipError
13
+ from pip._internal.utils import deprecation
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ # Do not import and use main() directly! Using it directly is actively
19
+ # discouraged by pip's maintainers. The name, location and behavior of
20
+ # this function is subject to change, so calling it directly is not
21
+ # portable across different pip versions.
22
+
23
+ # In addition, running pip in-process is unsupported and unsafe. This is
24
+ # elaborated in detail at
25
+ # https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program.
26
+ # That document also provides suggestions that should work for nearly
27
+ # all users that are considering importing and using main() directly.
28
+
29
+ # However, we know that certain users will still want to invoke pip
30
+ # in-process. If you understand and accept the implications of using pip
31
+ # in an unsupported manner, the best approach is to use runpy to avoid
32
+ # depending on the exact location of this entry point.
33
+
34
+ # The following example shows how to use runpy to invoke pip in that
35
+ # case:
36
+ #
37
+ # sys.argv = ["pip", your, args, here]
38
+ # runpy.run_module("pip", run_name="__main__")
39
+ #
40
+ # Note that this will exit the process after running, unlike a direct
41
+ # call to main. As it is not safe to do any processing after calling
42
+ # main, this should not be an issue in practice.
43
+
44
+
45
+ def main(args: Optional[List[str]] = None) -> int:
46
+ if args is None:
47
+ args = sys.argv[1:]
48
+
49
+ # Configure our deprecation warnings to be sent through loggers
50
+ deprecation.install_warning_logger()
51
+
52
+ autocomplete()
53
+
54
+ try:
55
+ cmd_name, cmd_args = parse_command(args)
56
+ except PipError as exc:
57
+ sys.stderr.write(f"ERROR: {exc}")
58
+ sys.stderr.write(os.linesep)
59
+ sys.exit(1)
60
+
61
+ # Needed for locale.getpreferredencoding(False) to work
62
+ # in pip._internal.utils.encoding.auto_decode
63
+ try:
64
+ locale.setlocale(locale.LC_ALL, "")
65
+ except locale.Error as e:
66
+ # setlocale can apparently crash if locale are uninitialized
67
+ logger.debug("Ignoring error %s when setting locale", e)
68
+ command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
69
+
70
+ return command.main(cmd_args)
.venv/lib/python3.9/site-packages/pip/_internal/cli/main_parser.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A single place for constructing and exposing the main parser
2
+ """
3
+
4
+ import os
5
+ import sys
6
+ from typing import List, Tuple
7
+
8
+ from pip._internal.cli import cmdoptions
9
+ from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
10
+ from pip._internal.commands import commands_dict, get_similar_commands
11
+ from pip._internal.exceptions import CommandError
12
+ from pip._internal.utils.misc import get_pip_version, get_prog
13
+
14
+ __all__ = ["create_main_parser", "parse_command"]
15
+
16
+
17
+ def create_main_parser() -> ConfigOptionParser:
18
+ """Creates and returns the main parser for pip's CLI"""
19
+
20
+ parser = ConfigOptionParser(
21
+ usage="\n%prog <command> [options]",
22
+ add_help_option=False,
23
+ formatter=UpdatingDefaultsHelpFormatter(),
24
+ name="global",
25
+ prog=get_prog(),
26
+ )
27
+ parser.disable_interspersed_args()
28
+
29
+ parser.version = get_pip_version()
30
+
31
+ # add the general options
32
+ gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)
33
+ parser.add_option_group(gen_opts)
34
+
35
+ # so the help formatter knows
36
+ parser.main = True # type: ignore
37
+
38
+ # create command listing for description
39
+ description = [""] + [
40
+ f"{name:27} {command_info.summary}"
41
+ for name, command_info in commands_dict.items()
42
+ ]
43
+ parser.description = "\n".join(description)
44
+
45
+ return parser
46
+
47
+
48
+ def parse_command(args: List[str]) -> Tuple[str, List[str]]:
49
+ parser = create_main_parser()
50
+
51
+ # Note: parser calls disable_interspersed_args(), so the result of this
52
+ # call is to split the initial args into the general options before the
53
+ # subcommand and everything else.
54
+ # For example:
55
+ # args: ['--timeout=5', 'install', '--user', 'INITools']
56
+ # general_options: ['--timeout==5']
57
+ # args_else: ['install', '--user', 'INITools']
58
+ general_options, args_else = parser.parse_args(args)
59
+
60
+ # --version
61
+ if general_options.version:
62
+ sys.stdout.write(parser.version)
63
+ sys.stdout.write(os.linesep)
64
+ sys.exit()
65
+
66
+ # pip || pip help -> print_help()
67
+ if not args_else or (args_else[0] == "help" and len(args_else) == 1):
68
+ parser.print_help()
69
+ sys.exit()
70
+
71
+ # the subcommand name
72
+ cmd_name = args_else[0]
73
+
74
+ if cmd_name not in commands_dict:
75
+ guess = get_similar_commands(cmd_name)
76
+
77
+ msg = [f'unknown command "{cmd_name}"']
78
+ if guess:
79
+ msg.append(f'maybe you meant "{guess}"')
80
+
81
+ raise CommandError(" - ".join(msg))
82
+
83
+ # all the args without the subcommand
84
+ cmd_args = args[:]
85
+ cmd_args.remove(cmd_name)
86
+
87
+ return cmd_name, cmd_args
.venv/lib/python3.9/site-packages/pip/_internal/cli/parser.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base option parser setup"""
2
+
3
+ import logging
4
+ import optparse
5
+ import shutil
6
+ import sys
7
+ import textwrap
8
+ from contextlib import suppress
9
+ from typing import Any, Dict, Iterator, List, Tuple
10
+
11
+ from pip._internal.cli.status_codes import UNKNOWN_ERROR
12
+ from pip._internal.configuration import Configuration, ConfigurationError
13
+ from pip._internal.utils.misc import redact_auth_from_url, strtobool
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
19
+ """A prettier/less verbose help formatter for optparse."""
20
+
21
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
22
+ # help position must be aligned with __init__.parseopts.description
23
+ kwargs["max_help_position"] = 30
24
+ kwargs["indent_increment"] = 1
25
+ kwargs["width"] = shutil.get_terminal_size()[0] - 2
26
+ super().__init__(*args, **kwargs)
27
+
28
+ def format_option_strings(self, option: optparse.Option) -> str:
29
+ return self._format_option_strings(option)
30
+
31
+ def _format_option_strings(
32
+ self, option: optparse.Option, mvarfmt: str = " <{}>", optsep: str = ", "
33
+ ) -> str:
34
+ """
35
+ Return a comma-separated list of option strings and metavars.
36
+
37
+ :param option: tuple of (short opt, long opt), e.g: ('-f', '--format')
38
+ :param mvarfmt: metavar format string
39
+ :param optsep: separator
40
+ """
41
+ opts = []
42
+
43
+ if option._short_opts:
44
+ opts.append(option._short_opts[0])
45
+ if option._long_opts:
46
+ opts.append(option._long_opts[0])
47
+ if len(opts) > 1:
48
+ opts.insert(1, optsep)
49
+
50
+ if option.takes_value():
51
+ assert option.dest is not None
52
+ metavar = option.metavar or option.dest.lower()
53
+ opts.append(mvarfmt.format(metavar.lower()))
54
+
55
+ return "".join(opts)
56
+
57
+ def format_heading(self, heading: str) -> str:
58
+ if heading == "Options":
59
+ return ""
60
+ return heading + ":\n"
61
+
62
+ def format_usage(self, usage: str) -> str:
63
+ """
64
+ Ensure there is only one newline between usage and the first heading
65
+ if there is no description.
66
+ """
67
+ msg = "\nUsage: {}\n".format(self.indent_lines(textwrap.dedent(usage), " "))
68
+ return msg
69
+
70
+ def format_description(self, description: str) -> str:
71
+ # leave full control over description to us
72
+ if description:
73
+ if hasattr(self.parser, "main"):
74
+ label = "Commands"
75
+ else:
76
+ label = "Description"
77
+ # some doc strings have initial newlines, some don't
78
+ description = description.lstrip("\n")
79
+ # some doc strings have final newlines and spaces, some don't
80
+ description = description.rstrip()
81
+ # dedent, then reindent
82
+ description = self.indent_lines(textwrap.dedent(description), " ")
83
+ description = f"{label}:\n{description}\n"
84
+ return description
85
+ else:
86
+ return ""
87
+
88
+ def format_epilog(self, epilog: str) -> str:
89
+ # leave full control over epilog to us
90
+ if epilog:
91
+ return epilog
92
+ else:
93
+ return ""
94
+
95
+ def indent_lines(self, text: str, indent: str) -> str:
96
+ new_lines = [indent + line for line in text.split("\n")]
97
+ return "\n".join(new_lines)
98
+
99
+
100
+ class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):
101
+ """Custom help formatter for use in ConfigOptionParser.
102
+
103
+ This is updates the defaults before expanding them, allowing
104
+ them to show up correctly in the help listing.
105
+
106
+ Also redact auth from url type options
107
+ """
108
+
109
+ def expand_default(self, option: optparse.Option) -> str:
110
+ default_values = None
111
+ if self.parser is not None:
112
+ assert isinstance(self.parser, ConfigOptionParser)
113
+ self.parser._update_defaults(self.parser.defaults)
114
+ assert option.dest is not None
115
+ default_values = self.parser.defaults.get(option.dest)
116
+ help_text = super().expand_default(option)
117
+
118
+ if default_values and option.metavar == "URL":
119
+ if isinstance(default_values, str):
120
+ default_values = [default_values]
121
+
122
+ # If its not a list, we should abort and just return the help text
123
+ if not isinstance(default_values, list):
124
+ default_values = []
125
+
126
+ for val in default_values:
127
+ help_text = help_text.replace(val, redact_auth_from_url(val))
128
+
129
+ return help_text
130
+
131
+
132
+ class CustomOptionParser(optparse.OptionParser):
133
+ def insert_option_group(
134
+ self, idx: int, *args: Any, **kwargs: Any
135
+ ) -> optparse.OptionGroup:
136
+ """Insert an OptionGroup at a given position."""
137
+ group = self.add_option_group(*args, **kwargs)
138
+
139
+ self.option_groups.pop()
140
+ self.option_groups.insert(idx, group)
141
+
142
+ return group
143
+
144
+ @property
145
+ def option_list_all(self) -> List[optparse.Option]:
146
+ """Get a list of all options, including those in option groups."""
147
+ res = self.option_list[:]
148
+ for i in self.option_groups:
149
+ res.extend(i.option_list)
150
+
151
+ return res
152
+
153
+
154
+ class ConfigOptionParser(CustomOptionParser):
155
+ """Custom option parser which updates its defaults by checking the
156
+ configuration files and environmental variables"""
157
+
158
+ def __init__(
159
+ self,
160
+ *args: Any,
161
+ name: str,
162
+ isolated: bool = False,
163
+ **kwargs: Any,
164
+ ) -> None:
165
+ self.name = name
166
+ self.config = Configuration(isolated)
167
+
168
+ assert self.name
169
+ super().__init__(*args, **kwargs)
170
+
171
+ def check_default(self, option: optparse.Option, key: str, val: Any) -> Any:
172
+ try:
173
+ return option.check_value(key, val)
174
+ except optparse.OptionValueError as exc:
175
+ print(f"An error occurred during configuration: {exc}")
176
+ sys.exit(3)
177
+
178
+ def _get_ordered_configuration_items(self) -> Iterator[Tuple[str, Any]]:
179
+ # Configuration gives keys in an unordered manner. Order them.
180
+ override_order = ["global", self.name, ":env:"]
181
+
182
+ # Pool the options into different groups
183
+ section_items: Dict[str, List[Tuple[str, Any]]] = {
184
+ name: [] for name in override_order
185
+ }
186
+ for section_key, val in self.config.items():
187
+ # ignore empty values
188
+ if not val:
189
+ logger.debug(
190
+ "Ignoring configuration key '%s' as it's value is empty.",
191
+ section_key,
192
+ )
193
+ continue
194
+
195
+ section, key = section_key.split(".", 1)
196
+ if section in override_order:
197
+ section_items[section].append((key, val))
198
+
199
+ # Yield each group in their override order
200
+ for section in override_order:
201
+ for key, val in section_items[section]:
202
+ yield key, val
203
+
204
+ def _update_defaults(self, defaults: Dict[str, Any]) -> Dict[str, Any]:
205
+ """Updates the given defaults with values from the config files and
206
+ the environ. Does a little special handling for certain types of
207
+ options (lists)."""
208
+
209
+ # Accumulate complex default state.
210
+ self.values = optparse.Values(self.defaults)
211
+ late_eval = set()
212
+ # Then set the options with those values
213
+ for key, val in self._get_ordered_configuration_items():
214
+ # '--' because configuration supports only long names
215
+ option = self.get_option("--" + key)
216
+
217
+ # Ignore options not present in this parser. E.g. non-globals put
218
+ # in [global] by users that want them to apply to all applicable
219
+ # commands.
220
+ if option is None:
221
+ continue
222
+
223
+ assert option.dest is not None
224
+
225
+ if option.action in ("store_true", "store_false"):
226
+ try:
227
+ val = strtobool(val)
228
+ except ValueError:
229
+ self.error(
230
+ "{} is not a valid value for {} option, " # noqa
231
+ "please specify a boolean value like yes/no, "
232
+ "true/false or 1/0 instead.".format(val, key)
233
+ )
234
+ elif option.action == "count":
235
+ with suppress(ValueError):
236
+ val = strtobool(val)
237
+ with suppress(ValueError):
238
+ val = int(val)
239
+ if not isinstance(val, int) or val < 0:
240
+ self.error(
241
+ "{} is not a valid value for {} option, " # noqa
242
+ "please instead specify either a non-negative integer "
243
+ "or a boolean value like yes/no or false/true "
244
+ "which is equivalent to 1/0.".format(val, key)
245
+ )
246
+ elif option.action == "append":
247
+ val = val.split()
248
+ val = [self.check_default(option, key, v) for v in val]
249
+ elif option.action == "callback":
250
+ assert option.callback is not None
251
+ late_eval.add(option.dest)
252
+ opt_str = option.get_opt_string()
253
+ val = option.convert_value(opt_str, val)
254
+ # From take_action
255
+ args = option.callback_args or ()
256
+ kwargs = option.callback_kwargs or {}
257
+ option.callback(option, opt_str, val, self, *args, **kwargs)
258
+ else:
259
+ val = self.check_default(option, key, val)
260
+
261
+ defaults[option.dest] = val
262
+
263
+ for key in late_eval:
264
+ defaults[key] = getattr(self.values, key)
265
+ self.values = None
266
+ return defaults
267
+
268
+ def get_default_values(self) -> optparse.Values:
269
+ """Overriding to make updating the defaults after instantiation of
270
+ the option parser possible, _update_defaults() does the dirty work."""
271
+ if not self.process_default_values:
272
+ # Old, pre-Optik 1.5 behaviour.
273
+ return optparse.Values(self.defaults)
274
+
275
+ # Load the configuration, or error out in case of an error
276
+ try:
277
+ self.config.load()
278
+ except ConfigurationError as err:
279
+ self.exit(UNKNOWN_ERROR, str(err))
280
+
281
+ defaults = self._update_defaults(self.defaults.copy()) # ours
282
+ for option in self._get_all_options():
283
+ assert option.dest is not None
284
+ default = defaults.get(option.dest)
285
+ if isinstance(default, str):
286
+ opt_str = option.get_opt_string()
287
+ defaults[option.dest] = option.check_value(opt_str, default)
288
+ return optparse.Values(defaults)
289
+
290
+ def error(self, msg: str) -> None:
291
+ self.print_usage(sys.stderr)
292
+ self.exit(UNKNOWN_ERROR, f"{msg}\n")
.venv/lib/python3.9/site-packages/pip/_internal/cli/progress_bars.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import sys
3
+ from signal import SIGINT, default_int_handler, signal
4
+ from typing import Any
5
+
6
+ from pip._vendor.progress.bar import Bar, FillingCirclesBar, IncrementalBar
7
+ from pip._vendor.progress.spinner import Spinner
8
+
9
+ from pip._internal.utils.compat import WINDOWS
10
+ from pip._internal.utils.logging import get_indentation
11
+ from pip._internal.utils.misc import format_size
12
+
13
+ try:
14
+ from pip._vendor import colorama
15
+ # Lots of different errors can come from this, including SystemError and
16
+ # ImportError.
17
+ except Exception:
18
+ colorama = None
19
+
20
+
21
+ def _select_progress_class(preferred: Bar, fallback: Bar) -> Bar:
22
+ encoding = getattr(preferred.file, "encoding", None)
23
+
24
+ # If we don't know what encoding this file is in, then we'll just assume
25
+ # that it doesn't support unicode and use the ASCII bar.
26
+ if not encoding:
27
+ return fallback
28
+
29
+ # Collect all of the possible characters we want to use with the preferred
30
+ # bar.
31
+ characters = [
32
+ getattr(preferred, "empty_fill", ""),
33
+ getattr(preferred, "fill", ""),
34
+ ]
35
+ characters += list(getattr(preferred, "phases", []))
36
+
37
+ # Try to decode the characters we're using for the bar using the encoding
38
+ # of the given file, if this works then we'll assume that we can use the
39
+ # fancier bar and if not we'll fall back to the plaintext bar.
40
+ try:
41
+ "".join(characters).encode(encoding)
42
+ except UnicodeEncodeError:
43
+ return fallback
44
+ else:
45
+ return preferred
46
+
47
+
48
+ _BaseBar: Any = _select_progress_class(IncrementalBar, Bar)
49
+
50
+
51
+ class InterruptibleMixin:
52
+ """
53
+ Helper to ensure that self.finish() gets called on keyboard interrupt.
54
+
55
+ This allows downloads to be interrupted without leaving temporary state
56
+ (like hidden cursors) behind.
57
+
58
+ This class is similar to the progress library's existing SigIntMixin
59
+ helper, but as of version 1.2, that helper has the following problems:
60
+
61
+ 1. It calls sys.exit().
62
+ 2. It discards the existing SIGINT handler completely.
63
+ 3. It leaves its own handler in place even after an uninterrupted finish,
64
+ which will have unexpected delayed effects if the user triggers an
65
+ unrelated keyboard interrupt some time after a progress-displaying
66
+ download has already completed, for example.
67
+ """
68
+
69
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
70
+ """
71
+ Save the original SIGINT handler for later.
72
+ """
73
+ # https://github.com/python/mypy/issues/5887
74
+ super().__init__(*args, **kwargs) # type: ignore
75
+
76
+ self.original_handler = signal(SIGINT, self.handle_sigint)
77
+
78
+ # If signal() returns None, the previous handler was not installed from
79
+ # Python, and we cannot restore it. This probably should not happen,
80
+ # but if it does, we must restore something sensible instead, at least.
81
+ # The least bad option should be Python's default SIGINT handler, which
82
+ # just raises KeyboardInterrupt.
83
+ if self.original_handler is None:
84
+ self.original_handler = default_int_handler
85
+
86
+ def finish(self) -> None:
87
+ """
88
+ Restore the original SIGINT handler after finishing.
89
+
90
+ This should happen regardless of whether the progress display finishes
91
+ normally, or gets interrupted.
92
+ """
93
+ super().finish() # type: ignore
94
+ signal(SIGINT, self.original_handler)
95
+
96
+ def handle_sigint(self, signum, frame): # type: ignore
97
+ """
98
+ Call self.finish() before delegating to the original SIGINT handler.
99
+
100
+ This handler should only be in place while the progress display is
101
+ active.
102
+ """
103
+ self.finish()
104
+ self.original_handler(signum, frame)
105
+
106
+
107
+ class SilentBar(Bar):
108
+ def update(self) -> None:
109
+ pass
110
+
111
+
112
+ class BlueEmojiBar(IncrementalBar):
113
+
114
+ suffix = "%(percent)d%%"
115
+ bar_prefix = " "
116
+ bar_suffix = " "
117
+ phases = ("\U0001F539", "\U0001F537", "\U0001F535")
118
+
119
+
120
+ class DownloadProgressMixin:
121
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
122
+ # https://github.com/python/mypy/issues/5887
123
+ super().__init__(*args, **kwargs) # type: ignore
124
+ self.message: str = (" " * (get_indentation() + 2)) + self.message
125
+
126
+ @property
127
+ def downloaded(self) -> str:
128
+ return format_size(self.index) # type: ignore
129
+
130
+ @property
131
+ def download_speed(self) -> str:
132
+ # Avoid zero division errors...
133
+ if self.avg == 0.0: # type: ignore
134
+ return "..."
135
+ return format_size(1 / self.avg) + "/s" # type: ignore
136
+
137
+ @property
138
+ def pretty_eta(self) -> str:
139
+ if self.eta: # type: ignore
140
+ return f"eta {self.eta_td}" # type: ignore
141
+ return ""
142
+
143
+ def iter(self, it): # type: ignore
144
+ for x in it:
145
+ yield x
146
+ # B305 is incorrectly raised here
147
+ # https://github.com/PyCQA/flake8-bugbear/issues/59
148
+ self.next(len(x)) # noqa: B305
149
+ self.finish()
150
+
151
+
152
+ class WindowsMixin:
153
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
154
+ # The Windows terminal does not support the hide/show cursor ANSI codes
155
+ # even with colorama. So we'll ensure that hide_cursor is False on
156
+ # Windows.
157
+ # This call needs to go before the super() call, so that hide_cursor
158
+ # is set in time. The base progress bar class writes the "hide cursor"
159
+ # code to the terminal in its init, so if we don't set this soon
160
+ # enough, we get a "hide" with no corresponding "show"...
161
+ if WINDOWS and self.hide_cursor: # type: ignore
162
+ self.hide_cursor = False
163
+
164
+ # https://github.com/python/mypy/issues/5887
165
+ super().__init__(*args, **kwargs) # type: ignore
166
+
167
+ # Check if we are running on Windows and we have the colorama module,
168
+ # if we do then wrap our file with it.
169
+ if WINDOWS and colorama:
170
+ self.file = colorama.AnsiToWin32(self.file) # type: ignore
171
+ # The progress code expects to be able to call self.file.isatty()
172
+ # but the colorama.AnsiToWin32() object doesn't have that, so we'll
173
+ # add it.
174
+ self.file.isatty = lambda: self.file.wrapped.isatty()
175
+ # The progress code expects to be able to call self.file.flush()
176
+ # but the colorama.AnsiToWin32() object doesn't have that, so we'll
177
+ # add it.
178
+ self.file.flush = lambda: self.file.wrapped.flush()
179
+
180
+
181
+ class BaseDownloadProgressBar(WindowsMixin, InterruptibleMixin, DownloadProgressMixin):
182
+
183
+ file = sys.stdout
184
+ message = "%(percent)d%%"
185
+ suffix = "%(downloaded)s %(download_speed)s %(pretty_eta)s"
186
+
187
+
188
+ class DefaultDownloadProgressBar(BaseDownloadProgressBar, _BaseBar):
189
+ pass
190
+
191
+
192
+ class DownloadSilentBar(BaseDownloadProgressBar, SilentBar):
193
+ pass
194
+
195
+
196
+ class DownloadBar(BaseDownloadProgressBar, Bar):
197
+ pass
198
+
199
+
200
+ class DownloadFillingCirclesBar(BaseDownloadProgressBar, FillingCirclesBar):
201
+ pass
202
+
203
+
204
+ class DownloadBlueEmojiProgressBar(BaseDownloadProgressBar, BlueEmojiBar):
205
+ pass
206
+
207
+
208
+ class DownloadProgressSpinner(
209
+ WindowsMixin, InterruptibleMixin, DownloadProgressMixin, Spinner
210
+ ):
211
+
212
+ file = sys.stdout
213
+ suffix = "%(downloaded)s %(download_speed)s"
214
+
215
+ def next_phase(self) -> str:
216
+ if not hasattr(self, "_phaser"):
217
+ self._phaser = itertools.cycle(self.phases)
218
+ return next(self._phaser)
219
+
220
+ def update(self) -> None:
221
+ message = self.message % self
222
+ phase = self.next_phase()
223
+ suffix = self.suffix % self
224
+ line = "".join(
225
+ [
226
+ message,
227
+ " " if message else "",
228
+ phase,
229
+ " " if suffix else "",
230
+ suffix,
231
+ ]
232
+ )
233
+
234
+ self.writeln(line)
235
+
236
+
237
+ BAR_TYPES = {
238
+ "off": (DownloadSilentBar, DownloadSilentBar),
239
+ "on": (DefaultDownloadProgressBar, DownloadProgressSpinner),
240
+ "ascii": (DownloadBar, DownloadProgressSpinner),
241
+ "pretty": (DownloadFillingCirclesBar, DownloadProgressSpinner),
242
+ "emoji": (DownloadBlueEmojiProgressBar, DownloadProgressSpinner),
243
+ }
244
+
245
+
246
+ def DownloadProgressProvider(progress_bar, max=None): # type: ignore
247
+ if max is None or max == 0:
248
+ return BAR_TYPES[progress_bar][1]().iter
249
+ else:
250
+ return BAR_TYPES[progress_bar][0](max=max).iter
.venv/lib/python3.9/site-packages/pip/_internal/cli/req_command.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 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.prepare import RequirementPreparer
26
+ from pip._internal.req.constructors import (
27
+ install_req_from_editable,
28
+ install_req_from_line,
29
+ install_req_from_parsed_requirement,
30
+ install_req_from_req_string,
31
+ )
32
+ from pip._internal.req.req_file import parse_requirements
33
+ from pip._internal.req.req_install import InstallRequirement
34
+ from pip._internal.req.req_tracker import RequirementTracker
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
+ logger = logging.getLogger(__name__)
45
+
46
+
47
+ class SessionCommandMixin(CommandContextMixIn):
48
+
49
+ """
50
+ A class mixin for command classes needing _build_session().
51
+ """
52
+
53
+ def __init__(self) -> None:
54
+ super().__init__()
55
+ self._session: Optional[PipSession] = None
56
+
57
+ @classmethod
58
+ def _get_index_urls(cls, options: Values) -> Optional[List[str]]:
59
+ """Return a list of index urls from user-provided options."""
60
+ index_urls = []
61
+ if not getattr(options, "no_index", False):
62
+ url = getattr(options, "index_url", None)
63
+ if url:
64
+ index_urls.append(url)
65
+ urls = getattr(options, "extra_index_urls", None)
66
+ if urls:
67
+ index_urls.extend(urls)
68
+ # Return None rather than an empty list
69
+ return index_urls or None
70
+
71
+ def get_default_session(self, options: Values) -> PipSession:
72
+ """Get a default-managed session."""
73
+ if self._session is None:
74
+ self._session = self.enter_context(self._build_session(options))
75
+ # there's no type annotation on requests.Session, so it's
76
+ # automatically ContextManager[Any] and self._session becomes Any,
77
+ # then https://github.com/python/mypy/issues/7696 kicks in
78
+ assert self._session is not None
79
+ return self._session
80
+
81
+ def _build_session(
82
+ self,
83
+ options: Values,
84
+ retries: Optional[int] = None,
85
+ timeout: Optional[int] = None,
86
+ ) -> PipSession:
87
+ assert not options.cache_dir or os.path.isabs(options.cache_dir)
88
+ session = PipSession(
89
+ cache=(
90
+ os.path.join(options.cache_dir, "http") if options.cache_dir else None
91
+ ),
92
+ retries=retries if retries is not None else options.retries,
93
+ trusted_hosts=options.trusted_hosts,
94
+ index_urls=self._get_index_urls(options),
95
+ )
96
+
97
+ # Handle custom ca-bundles from the user
98
+ if options.cert:
99
+ session.verify = options.cert
100
+
101
+ # Handle SSL client certificate
102
+ if options.client_cert:
103
+ session.cert = options.client_cert
104
+
105
+ # Handle timeouts
106
+ if options.timeout or timeout:
107
+ session.timeout = timeout if timeout is not None else options.timeout
108
+
109
+ # Handle configured proxies
110
+ if options.proxy:
111
+ session.proxies = {
112
+ "http": options.proxy,
113
+ "https": options.proxy,
114
+ }
115
+
116
+ # Determine if we can prompt the user for authentication or not
117
+ session.auth.prompting = not options.no_input
118
+
119
+ return session
120
+
121
+
122
+ class IndexGroupCommand(Command, SessionCommandMixin):
123
+
124
+ """
125
+ Abstract base class for commands with the index_group options.
126
+
127
+ This also corresponds to the commands that permit the pip version check.
128
+ """
129
+
130
+ def handle_pip_version_check(self, options: Values) -> None:
131
+ """
132
+ Do the pip version check if not disabled.
133
+
134
+ This overrides the default behavior of not doing the check.
135
+ """
136
+ # Make sure the index_group options are present.
137
+ assert hasattr(options, "no_index")
138
+
139
+ if options.disable_pip_version_check or options.no_index:
140
+ return
141
+
142
+ # Otherwise, check if we're using the latest version of pip available.
143
+ session = self._build_session(
144
+ options, retries=0, timeout=min(5, options.timeout)
145
+ )
146
+ with session:
147
+ pip_self_version_check(session, options)
148
+
149
+
150
+ KEEPABLE_TEMPDIR_TYPES = [
151
+ tempdir_kinds.BUILD_ENV,
152
+ tempdir_kinds.EPHEM_WHEEL_CACHE,
153
+ tempdir_kinds.REQ_BUILD,
154
+ ]
155
+
156
+
157
+ def warn_if_run_as_root() -> None:
158
+ """Output a warning for sudo users on Unix.
159
+
160
+ In a virtual environment, sudo pip still writes to virtualenv.
161
+ On Windows, users may run pip as Administrator without issues.
162
+ This warning only applies to Unix root users outside of virtualenv.
163
+ """
164
+ if running_under_virtualenv():
165
+ return
166
+ if not hasattr(os, "getuid"):
167
+ return
168
+ # On Windows, there are no "system managed" Python packages. Installing as
169
+ # Administrator via pip is the correct way of updating system environments.
170
+ #
171
+ # We choose sys.platform over utils.compat.WINDOWS here to enable Mypy platform
172
+ # checks: https://mypy.readthedocs.io/en/stable/common_issues.html
173
+ if sys.platform == "win32" or sys.platform == "cygwin":
174
+ return
175
+ if sys.platform == "darwin" or sys.platform == "linux":
176
+ if os.getuid() != 0:
177
+ return
178
+ logger.warning(
179
+ "Running pip as the 'root' user can result in broken permissions and "
180
+ "conflicting behaviour with the system package manager. "
181
+ "It is recommended to use a virtual environment instead: "
182
+ "https://pip.pypa.io/warnings/venv"
183
+ )
184
+
185
+
186
+ def with_cleanup(func: Any) -> Any:
187
+ """Decorator for common logic related to managing temporary
188
+ directories.
189
+ """
190
+
191
+ def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None:
192
+ for t in KEEPABLE_TEMPDIR_TYPES:
193
+ registry.set_delete(t, False)
194
+
195
+ def wrapper(
196
+ self: RequirementCommand, options: Values, args: List[Any]
197
+ ) -> Optional[int]:
198
+ assert self.tempdir_registry is not None
199
+ if options.no_clean:
200
+ configure_tempdir_registry(self.tempdir_registry)
201
+
202
+ try:
203
+ return func(self, options, args)
204
+ except PreviousBuildDirError:
205
+ # This kind of conflict can occur when the user passes an explicit
206
+ # build directory with a pre-existing folder. In that case we do
207
+ # not want to accidentally remove it.
208
+ configure_tempdir_registry(self.tempdir_registry)
209
+ raise
210
+
211
+ return wrapper
212
+
213
+
214
+ class RequirementCommand(IndexGroupCommand):
215
+ def __init__(self, *args: Any, **kw: Any) -> None:
216
+ super().__init__(*args, **kw)
217
+
218
+ self.cmd_opts.add_option(cmdoptions.no_clean())
219
+
220
+ @staticmethod
221
+ def determine_resolver_variant(options: Values) -> str:
222
+ """Determines which resolver should be used, based on the given options."""
223
+ if "legacy-resolver" in options.deprecated_features_enabled:
224
+ return "legacy"
225
+
226
+ return "2020-resolver"
227
+
228
+ @classmethod
229
+ def make_requirement_preparer(
230
+ cls,
231
+ temp_build_dir: TempDirectory,
232
+ options: Values,
233
+ req_tracker: RequirementTracker,
234
+ session: PipSession,
235
+ finder: PackageFinder,
236
+ use_user_site: bool,
237
+ download_dir: Optional[str] = None,
238
+ ) -> RequirementPreparer:
239
+ """
240
+ Create a RequirementPreparer instance for the given parameters.
241
+ """
242
+ temp_build_dir_path = temp_build_dir.path
243
+ assert temp_build_dir_path is not None
244
+
245
+ resolver_variant = cls.determine_resolver_variant(options)
246
+ if resolver_variant == "2020-resolver":
247
+ lazy_wheel = "fast-deps" in options.features_enabled
248
+ if lazy_wheel:
249
+ logger.warning(
250
+ "pip is using lazily downloaded wheels using HTTP "
251
+ "range requests to obtain dependency information. "
252
+ "This experimental feature is enabled through "
253
+ "--use-feature=fast-deps and it is not ready for "
254
+ "production."
255
+ )
256
+ else:
257
+ lazy_wheel = False
258
+ if "fast-deps" in options.features_enabled:
259
+ logger.warning(
260
+ "fast-deps has no effect when used with the legacy resolver."
261
+ )
262
+
263
+ return RequirementPreparer(
264
+ build_dir=temp_build_dir_path,
265
+ src_dir=options.src_dir,
266
+ download_dir=download_dir,
267
+ build_isolation=options.build_isolation,
268
+ req_tracker=req_tracker,
269
+ session=session,
270
+ progress_bar=options.progress_bar,
271
+ finder=finder,
272
+ require_hashes=options.require_hashes,
273
+ use_user_site=use_user_site,
274
+ lazy_wheel=lazy_wheel,
275
+ in_tree_build="in-tree-build" in options.features_enabled,
276
+ )
277
+
278
+ @classmethod
279
+ def make_resolver(
280
+ cls,
281
+ preparer: RequirementPreparer,
282
+ finder: PackageFinder,
283
+ options: Values,
284
+ wheel_cache: Optional[WheelCache] = None,
285
+ use_user_site: bool = False,
286
+ ignore_installed: bool = True,
287
+ ignore_requires_python: bool = False,
288
+ force_reinstall: bool = False,
289
+ upgrade_strategy: str = "to-satisfy-only",
290
+ use_pep517: Optional[bool] = None,
291
+ py_version_info: Optional[Tuple[int, ...]] = None,
292
+ ) -> BaseResolver:
293
+ """
294
+ Create a Resolver instance for the given parameters.
295
+ """
296
+ make_install_req = partial(
297
+ install_req_from_req_string,
298
+ isolated=options.isolated_mode,
299
+ use_pep517=use_pep517,
300
+ )
301
+ resolver_variant = cls.determine_resolver_variant(options)
302
+ # The long import name and duplicated invocation is needed to convince
303
+ # Mypy into correctly typechecking. Otherwise it would complain the
304
+ # "Resolver" class being redefined.
305
+ if resolver_variant == "2020-resolver":
306
+ import pip._internal.resolution.resolvelib.resolver
307
+
308
+ return pip._internal.resolution.resolvelib.resolver.Resolver(
309
+ preparer=preparer,
310
+ finder=finder,
311
+ wheel_cache=wheel_cache,
312
+ make_install_req=make_install_req,
313
+ use_user_site=use_user_site,
314
+ ignore_dependencies=options.ignore_dependencies,
315
+ ignore_installed=ignore_installed,
316
+ ignore_requires_python=ignore_requires_python,
317
+ force_reinstall=force_reinstall,
318
+ upgrade_strategy=upgrade_strategy,
319
+ py_version_info=py_version_info,
320
+ )
321
+ import pip._internal.resolution.legacy.resolver
322
+
323
+ return pip._internal.resolution.legacy.resolver.Resolver(
324
+ preparer=preparer,
325
+ finder=finder,
326
+ wheel_cache=wheel_cache,
327
+ make_install_req=make_install_req,
328
+ use_user_site=use_user_site,
329
+ ignore_dependencies=options.ignore_dependencies,
330
+ ignore_installed=ignore_installed,
331
+ ignore_requires_python=ignore_requires_python,
332
+ force_reinstall=force_reinstall,
333
+ upgrade_strategy=upgrade_strategy,
334
+ py_version_info=py_version_info,
335
+ )
336
+
337
+ def get_requirements(
338
+ self,
339
+ args: List[str],
340
+ options: Values,
341
+ finder: PackageFinder,
342
+ session: PipSession,
343
+ ) -> List[InstallRequirement]:
344
+ """
345
+ Parse command-line arguments into the corresponding requirements.
346
+ """
347
+ requirements: List[InstallRequirement] = []
348
+ for filename in options.constraints:
349
+ for parsed_req in parse_requirements(
350
+ filename,
351
+ constraint=True,
352
+ finder=finder,
353
+ options=options,
354
+ session=session,
355
+ ):
356
+ req_to_add = install_req_from_parsed_requirement(
357
+ parsed_req,
358
+ isolated=options.isolated_mode,
359
+ user_supplied=False,
360
+ )
361
+ requirements.append(req_to_add)
362
+
363
+ for req in args:
364
+ req_to_add = install_req_from_line(
365
+ req,
366
+ None,
367
+ isolated=options.isolated_mode,
368
+ use_pep517=options.use_pep517,
369
+ user_supplied=True,
370
+ )
371
+ requirements.append(req_to_add)
372
+
373
+ for req in options.editables:
374
+ req_to_add = install_req_from_editable(
375
+ req,
376
+ user_supplied=True,
377
+ isolated=options.isolated_mode,
378
+ use_pep517=options.use_pep517,
379
+ )
380
+ requirements.append(req_to_add)
381
+
382
+ # NOTE: options.require_hashes may be set if --require-hashes is True
383
+ for filename in options.requirements:
384
+ for parsed_req in parse_requirements(
385
+ filename, finder=finder, options=options, session=session
386
+ ):
387
+ req_to_add = install_req_from_parsed_requirement(
388
+ parsed_req,
389
+ isolated=options.isolated_mode,
390
+ use_pep517=options.use_pep517,
391
+ user_supplied=True,
392
+ )
393
+ requirements.append(req_to_add)
394
+
395
+ # If any requirement has hash options, enable hash checking.
396
+ if any(req.has_hash_options for req in requirements):
397
+ options.require_hashes = True
398
+
399
+ if not (args or options.editables or options.requirements):
400
+ opts = {"name": self.name}
401
+ if options.find_links:
402
+ raise CommandError(
403
+ "You must give at least one requirement to {name} "
404
+ '(maybe you meant "pip {name} {links}"?)'.format(
405
+ **dict(opts, links=" ".join(options.find_links))
406
+ )
407
+ )
408
+ else:
409
+ raise CommandError(
410
+ "You must give at least one requirement to {name} "
411
+ '(see "pip help {name}")'.format(**opts)
412
+ )
413
+
414
+ return requirements
415
+
416
+ @staticmethod
417
+ def trace_basic_info(finder: PackageFinder) -> None:
418
+ """
419
+ Trace basic information about the provided objects.
420
+ """
421
+ # Display where finder is looking for packages
422
+ search_scope = finder.search_scope
423
+ locations = search_scope.get_formatted_locations()
424
+ if locations:
425
+ logger.info(locations)
426
+
427
+ def _build_package_finder(
428
+ self,
429
+ options: Values,
430
+ session: PipSession,
431
+ target_python: Optional[TargetPython] = None,
432
+ ignore_requires_python: Optional[bool] = None,
433
+ ) -> PackageFinder:
434
+ """
435
+ Create a package finder appropriate to this requirement command.
436
+
437
+ :param ignore_requires_python: Whether to ignore incompatible
438
+ "Requires-Python" values in links. Defaults to False.
439
+ """
440
+ link_collector = LinkCollector.create(session, options=options)
441
+ selection_prefs = SelectionPreferences(
442
+ allow_yanked=True,
443
+ format_control=options.format_control,
444
+ allow_all_prereleases=options.pre,
445
+ prefer_binary=options.prefer_binary,
446
+ ignore_requires_python=ignore_requires_python,
447
+ )
448
+
449
+ return PackageFinder.create(
450
+ link_collector=link_collector,
451
+ selection_prefs=selection_prefs,
452
+ target_python=target_python,
453
+ )
.venv/lib/python3.9/site-packages/pip/_internal/cli/spinners.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import itertools
3
+ import logging
4
+ import sys
5
+ import time
6
+ from typing import IO, Iterator
7
+
8
+ from pip._vendor.progress import HIDE_CURSOR, SHOW_CURSOR
9
+
10
+ from pip._internal.utils.compat import WINDOWS
11
+ from pip._internal.utils.logging import get_indentation
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class SpinnerInterface:
17
+ def spin(self) -> None:
18
+ raise NotImplementedError()
19
+
20
+ def finish(self, final_status: str) -> None:
21
+ raise NotImplementedError()
22
+
23
+
24
+ class InteractiveSpinner(SpinnerInterface):
25
+ def __init__(
26
+ self,
27
+ message: str,
28
+ file: IO[str] = None,
29
+ spin_chars: str = "-\\|/",
30
+ # Empirically, 8 updates/second looks nice
31
+ min_update_interval_seconds: float = 0.125,
32
+ ):
33
+ self._message = message
34
+ if file is None:
35
+ file = sys.stdout
36
+ self._file = file
37
+ self._rate_limiter = RateLimiter(min_update_interval_seconds)
38
+ self._finished = False
39
+
40
+ self._spin_cycle = itertools.cycle(spin_chars)
41
+
42
+ self._file.write(" " * get_indentation() + self._message + " ... ")
43
+ self._width = 0
44
+
45
+ def _write(self, status: str) -> None:
46
+ assert not self._finished
47
+ # Erase what we wrote before by backspacing to the beginning, writing
48
+ # spaces to overwrite the old text, and then backspacing again
49
+ backup = "\b" * self._width
50
+ self._file.write(backup + " " * self._width + backup)
51
+ # Now we have a blank slate to add our status
52
+ self._file.write(status)
53
+ self._width = len(status)
54
+ self._file.flush()
55
+ self._rate_limiter.reset()
56
+
57
+ def spin(self) -> None:
58
+ if self._finished:
59
+ return
60
+ if not self._rate_limiter.ready():
61
+ return
62
+ self._write(next(self._spin_cycle))
63
+
64
+ def finish(self, final_status: str) -> None:
65
+ if self._finished:
66
+ return
67
+ self._write(final_status)
68
+ self._file.write("\n")
69
+ self._file.flush()
70
+ self._finished = True
71
+
72
+
73
+ # Used for dumb terminals, non-interactive installs (no tty), etc.
74
+ # We still print updates occasionally (once every 60 seconds by default) to
75
+ # act as a keep-alive for systems like Travis-CI that take lack-of-output as
76
+ # an indication that a task has frozen.
77
+ class NonInteractiveSpinner(SpinnerInterface):
78
+ def __init__(self, message: str, min_update_interval_seconds: float = 60.0) -> None:
79
+ self._message = message
80
+ self._finished = False
81
+ self._rate_limiter = RateLimiter(min_update_interval_seconds)
82
+ self._update("started")
83
+
84
+ def _update(self, status: str) -> None:
85
+ assert not self._finished
86
+ self._rate_limiter.reset()
87
+ logger.info("%s: %s", self._message, status)
88
+
89
+ def spin(self) -> None:
90
+ if self._finished:
91
+ return
92
+ if not self._rate_limiter.ready():
93
+ return
94
+ self._update("still running...")
95
+
96
+ def finish(self, final_status: str) -> None:
97
+ if self._finished:
98
+ return
99
+ self._update(f"finished with status '{final_status}'")
100
+ self._finished = True
101
+
102
+
103
+ class RateLimiter:
104
+ def __init__(self, min_update_interval_seconds: float) -> None:
105
+ self._min_update_interval_seconds = min_update_interval_seconds
106
+ self._last_update: float = 0
107
+
108
+ def ready(self) -> bool:
109
+ now = time.time()
110
+ delta = now - self._last_update
111
+ return delta >= self._min_update_interval_seconds
112
+
113
+ def reset(self) -> None:
114
+ self._last_update = time.time()
115
+
116
+
117
+ @contextlib.contextmanager
118
+ def open_spinner(message: str) -> Iterator[SpinnerInterface]:
119
+ # Interactive spinner goes directly to sys.stdout rather than being routed
120
+ # through the logging system, but it acts like it has level INFO,
121
+ # i.e. it's only displayed if we're at level INFO or better.
122
+ # Non-interactive spinner goes through the logging system, so it is always
123
+ # in sync with logging configuration.
124
+ if sys.stdout.isatty() and logger.getEffectiveLevel() <= logging.INFO:
125
+ spinner: SpinnerInterface = InteractiveSpinner(message)
126
+ else:
127
+ spinner = NonInteractiveSpinner(message)
128
+ try:
129
+ with hidden_cursor(sys.stdout):
130
+ yield spinner
131
+ except KeyboardInterrupt:
132
+ spinner.finish("canceled")
133
+ raise
134
+ except Exception:
135
+ spinner.finish("error")
136
+ raise
137
+ else:
138
+ spinner.finish("done")
139
+
140
+
141
+ @contextlib.contextmanager
142
+ def hidden_cursor(file: IO[str]) -> Iterator[None]:
143
+ # The Windows terminal does not support the hide/show cursor ANSI codes,
144
+ # even via colorama. So don't even try.
145
+ if WINDOWS:
146
+ yield
147
+ # We don't want to clutter the output with control characters if we're
148
+ # writing to a file, or if the user is running with --quiet.
149
+ # See https://github.com/pypa/pip/issues/3418
150
+ elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO:
151
+ yield
152
+ else:
153
+ file.write(HIDE_CURSOR)
154
+ try:
155
+ yield
156
+ finally:
157
+ file.write(SHOW_CURSOR)
.venv/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
.venv/lib/python3.9/site-packages/pip/_internal/commands/__init__.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Package containing all pip commands
3
+ """
4
+
5
+ import importlib
6
+ from collections import OrderedDict, 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
+ # The ordering matters for help display.
14
+ # Also, even though the module path starts with the same
15
+ # "pip._internal.commands" prefix in each case, we include the full path
16
+ # because it makes testing easier (specifically when modifying commands_dict
17
+ # in test setup / teardown by adding info for a FakeCommand class defined
18
+ # in a test-related module).
19
+ # Finally, we need to pass an iterable of pairs here rather than a dict
20
+ # so that the ordering won't be lost when using Python 2.7.
21
+ commands_dict: Dict[str, CommandInfo] = OrderedDict([
22
+ ('install', CommandInfo(
23
+ 'pip._internal.commands.install', 'InstallCommand',
24
+ 'Install packages.',
25
+ )),
26
+ ('download', CommandInfo(
27
+ 'pip._internal.commands.download', 'DownloadCommand',
28
+ 'Download packages.',
29
+ )),
30
+ ('uninstall', CommandInfo(
31
+ 'pip._internal.commands.uninstall', 'UninstallCommand',
32
+ 'Uninstall packages.',
33
+ )),
34
+ ('freeze', CommandInfo(
35
+ 'pip._internal.commands.freeze', 'FreezeCommand',
36
+ 'Output installed packages in requirements format.',
37
+ )),
38
+ ('list', CommandInfo(
39
+ 'pip._internal.commands.list', 'ListCommand',
40
+ 'List installed packages.',
41
+ )),
42
+ ('show', CommandInfo(
43
+ 'pip._internal.commands.show', 'ShowCommand',
44
+ 'Show information about installed packages.',
45
+ )),
46
+ ('check', CommandInfo(
47
+ 'pip._internal.commands.check', 'CheckCommand',
48
+ 'Verify installed packages have compatible dependencies.',
49
+ )),
50
+ ('config', CommandInfo(
51
+ 'pip._internal.commands.configuration', 'ConfigurationCommand',
52
+ 'Manage local and global configuration.',
53
+ )),
54
+ ('search', CommandInfo(
55
+ 'pip._internal.commands.search', 'SearchCommand',
56
+ 'Search PyPI for packages.',
57
+ )),
58
+ ('cache', CommandInfo(
59
+ 'pip._internal.commands.cache', 'CacheCommand',
60
+ "Inspect and manage pip's wheel cache.",
61
+ )),
62
+ ('index', CommandInfo(
63
+ 'pip._internal.commands.index', 'IndexCommand',
64
+ "Inspect information available from package indexes.",
65
+ )),
66
+ ('wheel', CommandInfo(
67
+ 'pip._internal.commands.wheel', 'WheelCommand',
68
+ 'Build wheels from your requirements.',
69
+ )),
70
+ ('hash', CommandInfo(
71
+ 'pip._internal.commands.hash', 'HashCommand',
72
+ 'Compute hashes of package archives.',
73
+ )),
74
+ ('completion', CommandInfo(
75
+ 'pip._internal.commands.completion', 'CompletionCommand',
76
+ 'A helper command used for command completion.',
77
+ )),
78
+ ('debug', CommandInfo(
79
+ 'pip._internal.commands.debug', 'DebugCommand',
80
+ 'Show information useful for debugging.',
81
+ )),
82
+ ('help', CommandInfo(
83
+ 'pip._internal.commands.help', 'HelpCommand',
84
+ 'Show help for commands.',
85
+ )),
86
+ ])
87
+
88
+
89
+ def create_command(name: str, **kwargs: Any) -> Command:
90
+ """
91
+ Create an instance of the Command class with the given name.
92
+ """
93
+ module_path, class_name, summary = commands_dict[name]
94
+ module = importlib.import_module(module_path)
95
+ command_class = getattr(module, class_name)
96
+ command = command_class(name=name, summary=summary, **kwargs)
97
+
98
+ return command
99
+
100
+
101
+ def get_similar_commands(name: str) -> Optional[str]:
102
+ """Command name auto-correct."""
103
+ from difflib import get_close_matches
104
+
105
+ name = name.lower()
106
+
107
+ close_commands = get_close_matches(name, commands_dict.keys())
108
+
109
+ if close_commands:
110
+ return close_commands[0]
111
+ else:
112
+ return None
.venv/lib/python3.9/site-packages/pip/_internal/commands/cache.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import textwrap
3
+ from optparse import Values
4
+ from typing import Any, List
5
+
6
+ import pip._internal.utils.filesystem as filesystem
7
+ from pip._internal.cli.base_command import Command
8
+ from pip._internal.cli.status_codes import ERROR, SUCCESS
9
+ from pip._internal.exceptions import CommandError, PipError
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
+
41
+ self.cmd_opts.add_option(
42
+ '--format',
43
+ action='store',
44
+ dest='list_format',
45
+ default="human",
46
+ choices=('human', 'abspath'),
47
+ help="Select the output format among: human (default) or abspath"
48
+ )
49
+
50
+ self.parser.insert_option_group(0, self.cmd_opts)
51
+
52
+ def run(self, options: Values, args: List[Any]) -> int:
53
+ handlers = {
54
+ "dir": self.get_cache_dir,
55
+ "info": self.get_cache_info,
56
+ "list": self.list_cache_items,
57
+ "remove": self.remove_cache_items,
58
+ "purge": self.purge_cache,
59
+ }
60
+
61
+ if not options.cache_dir:
62
+ logger.error("pip cache commands can not "
63
+ "function since cache is disabled.")
64
+ return ERROR
65
+
66
+ # Determine action
67
+ if not args or args[0] not in handlers:
68
+ logger.error(
69
+ "Need an action (%s) to perform.",
70
+ ", ".join(sorted(handlers)),
71
+ )
72
+ return ERROR
73
+
74
+ action = args[0]
75
+
76
+ # Error handling happens here, not in the action-handlers.
77
+ try:
78
+ handlers[action](options, args[1:])
79
+ except PipError as e:
80
+ logger.error(e.args[0])
81
+ return ERROR
82
+
83
+ return SUCCESS
84
+
85
+ def get_cache_dir(self, options: Values, args: List[Any]) -> None:
86
+ if args:
87
+ raise CommandError('Too many arguments')
88
+
89
+ logger.info(options.cache_dir)
90
+
91
+ def get_cache_info(self, options: Values, args: List[Any]) -> None:
92
+ if args:
93
+ raise CommandError('Too many arguments')
94
+
95
+ num_http_files = len(self._find_http_files(options))
96
+ num_packages = len(self._find_wheels(options, '*'))
97
+
98
+ http_cache_location = self._cache_dir(options, 'http')
99
+ wheels_cache_location = self._cache_dir(options, 'wheels')
100
+ http_cache_size = filesystem.format_directory_size(http_cache_location)
101
+ wheels_cache_size = filesystem.format_directory_size(
102
+ wheels_cache_location
103
+ )
104
+
105
+ message = textwrap.dedent("""
106
+ Package index page cache location: {http_cache_location}
107
+ Package index page cache size: {http_cache_size}
108
+ Number of HTTP files: {num_http_files}
109
+ Wheels location: {wheels_cache_location}
110
+ Wheels size: {wheels_cache_size}
111
+ Number of wheels: {package_count}
112
+ """).format(
113
+ http_cache_location=http_cache_location,
114
+ http_cache_size=http_cache_size,
115
+ num_http_files=num_http_files,
116
+ wheels_cache_location=wheels_cache_location,
117
+ package_count=num_packages,
118
+ wheels_cache_size=wheels_cache_size,
119
+ ).strip()
120
+
121
+ logger.info(message)
122
+
123
+ def list_cache_items(self, options: Values, args: List[Any]) -> None:
124
+ if len(args) > 1:
125
+ raise CommandError('Too many arguments')
126
+
127
+ if args:
128
+ pattern = args[0]
129
+ else:
130
+ pattern = '*'
131
+
132
+ files = self._find_wheels(options, pattern)
133
+ if options.list_format == 'human':
134
+ self.format_for_human(files)
135
+ else:
136
+ self.format_for_abspath(files)
137
+
138
+ def format_for_human(self, files: List[str]) -> None:
139
+ if not files:
140
+ logger.info('Nothing cached.')
141
+ return
142
+
143
+ results = []
144
+ for filename in files:
145
+ wheel = os.path.basename(filename)
146
+ size = filesystem.format_file_size(filename)
147
+ results.append(f' - {wheel} ({size})')
148
+ logger.info('Cache contents:\n')
149
+ logger.info('\n'.join(sorted(results)))
150
+
151
+ def format_for_abspath(self, files: List[str]) -> None:
152
+ if not files:
153
+ return
154
+
155
+ results = []
156
+ for filename in files:
157
+ results.append(filename)
158
+
159
+ logger.info('\n'.join(sorted(results)))
160
+
161
+ def remove_cache_items(self, options: Values, args: List[Any]) -> None:
162
+ if len(args) > 1:
163
+ raise CommandError('Too many arguments')
164
+
165
+ if not args:
166
+ raise CommandError('Please provide a pattern')
167
+
168
+ files = self._find_wheels(options, args[0])
169
+
170
+ # Only fetch http files if no specific pattern given
171
+ if args[0] == '*':
172
+ files += self._find_http_files(options)
173
+
174
+ if not files:
175
+ raise CommandError('No matching packages')
176
+
177
+ for filename in files:
178
+ os.unlink(filename)
179
+ logger.verbose("Removed %s", filename)
180
+ logger.info("Files removed: %s", len(files))
181
+
182
+ def purge_cache(self, options: Values, args: List[Any]) -> None:
183
+ if args:
184
+ raise CommandError('Too many arguments')
185
+
186
+ return self.remove_cache_items(options, ['*'])
187
+
188
+ def _cache_dir(self, options: Values, subdir: str) -> str:
189
+ return os.path.join(options.cache_dir, subdir)
190
+
191
+ def _find_http_files(self, options: Values) -> List[str]:
192
+ http_dir = self._cache_dir(options, 'http')
193
+ return filesystem.find_files(http_dir, '*')
194
+
195
+ def _find_wheels(self, options: Values, pattern: str) -> List[str]:
196
+ wheel_dir = self._cache_dir(options, 'wheels')
197
+
198
+ # The wheel filename format, as specified in PEP 427, is:
199
+ # {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl
200
+ #
201
+ # Additionally, non-alphanumeric values in the distribution are
202
+ # normalized to underscores (_), meaning hyphens can never occur
203
+ # before `-{version}`.
204
+ #
205
+ # Given that information:
206
+ # - If the pattern we're given contains a hyphen (-), the user is
207
+ # providing at least the version. Thus, we can just append `*.whl`
208
+ # to match the rest of it.
209
+ # - If the pattern we're given doesn't contain a hyphen (-), the
210
+ # user is only providing the name. Thus, we append `-*.whl` to
211
+ # match the hyphen before the version, followed by anything else.
212
+ #
213
+ # PEP 427: https://www.python.org/dev/peps/pep-0427/
214
+ pattern = pattern + ("*.whl" if "-" in pattern else "-*.whl")
215
+
216
+ return filesystem.find_files(wheel_dir, pattern)
.venv/lib/python3.9/site-packages/pip/_internal/commands/check.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from optparse import Values
3
+ from typing import Any, 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
+ )
11
+ from pip._internal.utils.misc import write_output
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class CheckCommand(Command):
17
+ """Verify installed packages have compatible dependencies."""
18
+
19
+ usage = """
20
+ %prog [options]"""
21
+
22
+ def run(self, options: Values, args: List[Any]) -> int:
23
+
24
+ package_set, parsing_probs = create_package_set_from_installed()
25
+ missing, conflicting = check_package_set(package_set)
26
+
27
+ for project_name in missing:
28
+ version = package_set[project_name].version
29
+ for dependency in missing[project_name]:
30
+ write_output(
31
+ "%s %s requires %s, which is not installed.",
32
+ project_name, version, dependency[0],
33
+ )
34
+
35
+ for project_name in conflicting:
36
+ version = package_set[project_name].version
37
+ for dep_name, dep_version, req in conflicting[project_name]:
38
+ write_output(
39
+ "%s %s has requirement %s, but you have %s %s.",
40
+ project_name, version, req, dep_name, dep_version,
41
+ )
42
+
43
+ if missing or conflicting or parsing_probs:
44
+ return ERROR
45
+ else:
46
+ write_output("No broken requirements found.")
47
+ return SUCCESS
.venv/lib/python3.9/site-packages/pip/_internal/commands/completion.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ function _pip_completion {{
26
+ local words cword
27
+ read -Ac words
28
+ read -cn cword
29
+ reply=( $( COMP_WORDS="$words[*]" \\
30
+ COMP_CWORD=$(( cword-1 )) \\
31
+ PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null ))
32
+ }}
33
+ compctl -K _pip_completion {prog}
34
+ """,
35
+ 'fish': """
36
+ function __fish_complete_pip
37
+ set -lx COMP_WORDS (commandline -o) ""
38
+ set -lx COMP_CWORD ( \\
39
+ math (contains -i -- (commandline -t) $COMP_WORDS)-1 \\
40
+ )
41
+ set -lx PIP_AUTO_COMPLETE 1
42
+ string split \\ -- (eval $COMP_WORDS[1])
43
+ end
44
+ complete -fa "(__fish_complete_pip)" -c {prog}
45
+ """,
46
+ }
47
+
48
+
49
+ class CompletionCommand(Command):
50
+ """A helper command to be used for command completion."""
51
+
52
+ ignore_require_venv = True
53
+
54
+ def add_options(self) -> None:
55
+ self.cmd_opts.add_option(
56
+ '--bash', '-b',
57
+ action='store_const',
58
+ const='bash',
59
+ dest='shell',
60
+ help='Emit completion code for bash')
61
+ self.cmd_opts.add_option(
62
+ '--zsh', '-z',
63
+ action='store_const',
64
+ const='zsh',
65
+ dest='shell',
66
+ help='Emit completion code for zsh')
67
+ self.cmd_opts.add_option(
68
+ '--fish', '-f',
69
+ action='store_const',
70
+ const='fish',
71
+ dest='shell',
72
+ help='Emit completion code for fish')
73
+
74
+ self.parser.insert_option_group(0, self.cmd_opts)
75
+
76
+ def run(self, options: Values, args: List[str]) -> int:
77
+ """Prints the completion code of the given shell"""
78
+ shells = COMPLETION_SCRIPTS.keys()
79
+ shell_options = ['--' + shell for shell in sorted(shells)]
80
+ if options.shell in shells:
81
+ script = textwrap.dedent(
82
+ COMPLETION_SCRIPTS.get(options.shell, '').format(
83
+ prog=get_prog())
84
+ )
85
+ print(BASE_COMPLETION.format(script=script, shell=options.shell))
86
+ return SUCCESS
87
+ else:
88
+ sys.stderr.write(
89
+ 'ERROR: You must pass {}\n' .format(' or '.join(shell_options))
90
+ )
91
+ return SUCCESS
.venv/lib/python3.9/site-packages/pip/_internal/commands/configuration.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 name
31
+ - set: Set the name=value
32
+ - unset: Unset the value associated with name
33
+ - debug: List the configuration files and values defined under them
34
+
35
+ If none of --user, --global and --site are passed, a virtual
36
+ environment configuration file is used if one is active and the file
37
+ exists. Otherwise, all modifications happen on the to the user file by
38
+ default.
39
+ """
40
+
41
+ ignore_require_venv = True
42
+ usage = """
43
+ %prog [<file-option>] list
44
+ %prog [<file-option>] [--editor <editor-path>] edit
45
+
46
+ %prog [<file-option>] get name
47
+ %prog [<file-option>] set name value
48
+ %prog [<file-option>] unset name
49
+ %prog [<file-option>] debug
50
+ """
51
+
52
+ def add_options(self) -> None:
53
+ self.cmd_opts.add_option(
54
+ '--editor',
55
+ dest='editor',
56
+ action='store',
57
+ default=None,
58
+ help=(
59
+ 'Editor to use to edit the file. Uses VISUAL or EDITOR '
60
+ 'environment variables if not provided.'
61
+ )
62
+ )
63
+
64
+ self.cmd_opts.add_option(
65
+ '--global',
66
+ dest='global_file',
67
+ action='store_true',
68
+ default=False,
69
+ help='Use the system-wide configuration file only'
70
+ )
71
+
72
+ self.cmd_opts.add_option(
73
+ '--user',
74
+ dest='user_file',
75
+ action='store_true',
76
+ default=False,
77
+ help='Use the user configuration file only'
78
+ )
79
+
80
+ self.cmd_opts.add_option(
81
+ '--site',
82
+ dest='site_file',
83
+ action='store_true',
84
+ default=False,
85
+ help='Use the current environment configuration file only'
86
+ )
87
+
88
+ self.parser.insert_option_group(0, self.cmd_opts)
89
+
90
+ def run(self, options: Values, args: List[str]) -> int:
91
+ handlers = {
92
+ "list": self.list_values,
93
+ "edit": self.open_in_editor,
94
+ "get": self.get_name,
95
+ "set": self.set_name_value,
96
+ "unset": self.unset_name,
97
+ "debug": self.list_config_values,
98
+ }
99
+
100
+ # Determine action
101
+ if not args or args[0] not in handlers:
102
+ logger.error(
103
+ "Need an action (%s) to perform.",
104
+ ", ".join(sorted(handlers)),
105
+ )
106
+ return ERROR
107
+
108
+ action = args[0]
109
+
110
+ # Determine which configuration files are to be loaded
111
+ # Depends on whether the command is modifying.
112
+ try:
113
+ load_only = self._determine_file(
114
+ options, need_value=(action in ["get", "set", "unset", "edit"])
115
+ )
116
+ except PipError as e:
117
+ logger.error(e.args[0])
118
+ return ERROR
119
+
120
+ # Load a new configuration
121
+ self.configuration = Configuration(
122
+ isolated=options.isolated_mode, load_only=load_only
123
+ )
124
+ self.configuration.load()
125
+
126
+ # Error handling happens here, not in the action-handlers.
127
+ try:
128
+ handlers[action](options, args[1:])
129
+ except PipError as e:
130
+ logger.error(e.args[0])
131
+ return ERROR
132
+
133
+ return SUCCESS
134
+
135
+ def _determine_file(self, options: Values, need_value: bool) -> Optional[Kind]:
136
+ file_options = [key for key, value in (
137
+ (kinds.USER, options.user_file),
138
+ (kinds.GLOBAL, options.global_file),
139
+ (kinds.SITE, options.site_file),
140
+ ) if value]
141
+
142
+ if not file_options:
143
+ if not need_value:
144
+ return None
145
+ # Default to user, unless there's a site file.
146
+ elif any(
147
+ os.path.exists(site_config_file)
148
+ for site_config_file in get_configuration_files()[kinds.SITE]
149
+ ):
150
+ return kinds.SITE
151
+ else:
152
+ return kinds.USER
153
+ elif len(file_options) == 1:
154
+ return file_options[0]
155
+
156
+ raise PipError(
157
+ "Need exactly one file to operate upon "
158
+ "(--user, --site, --global) to perform."
159
+ )
160
+
161
+ def list_values(self, options: Values, args: List[str]) -> None:
162
+ self._get_n_args(args, "list", n=0)
163
+
164
+ for key, value in sorted(self.configuration.items()):
165
+ write_output("%s=%r", key, value)
166
+
167
+ def get_name(self, options: Values, args: List[str]) -> None:
168
+ key = self._get_n_args(args, "get [name]", n=1)
169
+ value = self.configuration.get_value(key)
170
+
171
+ write_output("%s", value)
172
+
173
+ def set_name_value(self, options: Values, args: List[str]) -> None:
174
+ key, value = self._get_n_args(args, "set [name] [value]", n=2)
175
+ self.configuration.set_value(key, value)
176
+
177
+ self._save_configuration()
178
+
179
+ def unset_name(self, options: Values, args: List[str]) -> None:
180
+ key = self._get_n_args(args, "unset [name]", n=1)
181
+ self.configuration.unset_value(key)
182
+
183
+ self._save_configuration()
184
+
185
+ def list_config_values(self, options: Values, args: List[str]) -> None:
186
+ """List config key-value pairs across different config files"""
187
+ self._get_n_args(args, "debug", n=0)
188
+
189
+ self.print_env_var_values()
190
+ # Iterate over config files and print if they exist, and the
191
+ # key-value pairs present in them if they do
192
+ for variant, files in sorted(self.configuration.iter_config_files()):
193
+ write_output("%s:", variant)
194
+ for fname in files:
195
+ with indent_log():
196
+ file_exists = os.path.exists(fname)
197
+ write_output("%s, exists: %r",
198
+ fname, file_exists)
199
+ if file_exists:
200
+ self.print_config_file_values(variant)
201
+
202
+ def print_config_file_values(self, variant: Kind) -> None:
203
+ """Get key-value pairs from the file of a variant"""
204
+ for name, value in self.configuration.\
205
+ get_values_in_config(variant).items():
206
+ with indent_log():
207
+ write_output("%s: %s", name, value)
208
+
209
+ def print_env_var_values(self) -> None:
210
+ """Get key-values pairs present as environment variables"""
211
+ write_output("%s:", 'env_var')
212
+ with indent_log():
213
+ for key, value in sorted(self.configuration.get_environ_vars()):
214
+ env_var = f'PIP_{key.upper()}'
215
+ write_output("%s=%r", env_var, value)
216
+
217
+ def open_in_editor(self, options: Values, args: List[str]) -> None:
218
+ editor = self._determine_editor(options)
219
+
220
+ fname = self.configuration.get_file_to_edit()
221
+ if fname is None:
222
+ raise PipError("Could not determine appropriate file.")
223
+
224
+ try:
225
+ subprocess.check_call([editor, fname])
226
+ except subprocess.CalledProcessError as e:
227
+ raise PipError(
228
+ "Editor Subprocess exited with exit code {}"
229
+ .format(e.returncode)
230
+ )
231
+
232
+ def _get_n_args(self, args: List[str], example: str, n: int) -> Any:
233
+ """Helper to make sure the command got the right number of arguments
234
+ """
235
+ if len(args) != n:
236
+ msg = (
237
+ 'Got unexpected number of arguments, expected {}. '
238
+ '(example: "{} config {}")'
239
+ ).format(n, get_prog(), example)
240
+ raise PipError(msg)
241
+
242
+ if n == 1:
243
+ return args[0]
244
+ else:
245
+ return args
246
+
247
+ def _save_configuration(self) -> None:
248
+ # We successfully ran a modifying command. Need to save the
249
+ # configuration.
250
+ try:
251
+ self.configuration.save()
252
+ except Exception:
253
+ logger.exception(
254
+ "Unable to save configuration. Please report this as a bug."
255
+ )
256
+ raise PipError("Internal Error.")
257
+
258
+ def _determine_editor(self, options: Values) -> str:
259
+ if options.editor is not None:
260
+ return options.editor
261
+ elif "VISUAL" in os.environ:
262
+ return os.environ["VISUAL"]
263
+ elif "EDITOR" in os.environ:
264
+ return os.environ["EDITOR"]
265
+ else:
266
+ raise PipError("Could not determine editor to use.")
.venv/lib/python3.9/site-packages/pip/_internal/commands/debug.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import locale
2
+ import logging
3
+ import os
4
+ import sys
5
+ from optparse import Values
6
+ from types import ModuleType
7
+ from typing import Any, Dict, List, Optional
8
+
9
+ import pip._vendor
10
+ from pip._vendor.certifi import where
11
+ from pip._vendor.packaging.version import parse as parse_version
12
+
13
+ from pip import __file__ as pip_location
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
+ vendor_txt_path = os.path.join(
39
+ os.path.dirname(pip_location),
40
+ '_vendor',
41
+ 'vendor.txt'
42
+ )
43
+
44
+ with open(vendor_txt_path) as f:
45
+ # Purge non version specifying lines.
46
+ # Also, remove any space prefix or suffixes (including comments).
47
+ lines = [line.strip().split(' ', 1)[0]
48
+ for line in f.readlines() if '==' in line]
49
+
50
+ # Transform into "module" -> version dict.
51
+ return dict(line.split('==', 1) for line in lines) # type: ignore
52
+
53
+
54
+ def get_module_from_module_name(module_name: str) -> ModuleType:
55
+ # Module name can be uppercase in vendor.txt for some reason...
56
+ module_name = module_name.lower()
57
+ # PATCH: setuptools is actually only pkg_resources.
58
+ if module_name == 'setuptools':
59
+ module_name = 'pkg_resources'
60
+
61
+ __import__(
62
+ f'pip._vendor.{module_name}',
63
+ globals(),
64
+ locals(),
65
+ level=0
66
+ )
67
+ return getattr(pip._vendor, module_name)
68
+
69
+
70
+ def get_vendor_version_from_module(module_name: str) -> Optional[str]:
71
+ module = get_module_from_module_name(module_name)
72
+ version = getattr(module, '__version__', None)
73
+
74
+ if not version:
75
+ # Try to find version in debundled module info.
76
+ env = get_environment([os.path.dirname(module.__file__)])
77
+ dist = env.get_distribution(module_name)
78
+ if dist:
79
+ version = str(dist.version)
80
+
81
+ return version
82
+
83
+
84
+ def show_actual_vendor_versions(vendor_txt_versions: Dict[str, str]) -> None:
85
+ """Log the actual version and print extra info if there is
86
+ a conflict or if the actual version could not be imported.
87
+ """
88
+ for module_name, expected_version in vendor_txt_versions.items():
89
+ extra_message = ''
90
+ actual_version = get_vendor_version_from_module(module_name)
91
+ if not actual_version:
92
+ extra_message = ' (Unable to locate actual module version, using'\
93
+ ' vendor.txt specified version)'
94
+ actual_version = expected_version
95
+ elif parse_version(actual_version) != parse_version(expected_version):
96
+ extra_message = ' (CONFLICT: vendor.txt suggests version should'\
97
+ ' be {})'.format(expected_version)
98
+ logger.info('%s==%s%s', module_name, actual_version, extra_message)
99
+
100
+
101
+ def show_vendor_versions() -> None:
102
+ logger.info('vendored library versions:')
103
+
104
+ vendor_txt_versions = create_vendor_txt_map()
105
+ with indent_log():
106
+ show_actual_vendor_versions(vendor_txt_versions)
107
+
108
+
109
+ def show_tags(options: Values) -> None:
110
+ tag_limit = 10
111
+
112
+ target_python = make_target_python(options)
113
+ tags = target_python.get_tags()
114
+
115
+ # Display the target options that were explicitly provided.
116
+ formatted_target = target_python.format_given()
117
+ suffix = ''
118
+ if formatted_target:
119
+ suffix = f' (target: {formatted_target})'
120
+
121
+ msg = 'Compatible tags: {}{}'.format(len(tags), suffix)
122
+ logger.info(msg)
123
+
124
+ if options.verbose < 1 and len(tags) > tag_limit:
125
+ tags_limited = True
126
+ tags = tags[:tag_limit]
127
+ else:
128
+ tags_limited = False
129
+
130
+ with indent_log():
131
+ for tag in tags:
132
+ logger.info(str(tag))
133
+
134
+ if tags_limited:
135
+ msg = (
136
+ '...\n'
137
+ '[First {tag_limit} tags shown. Pass --verbose to show all.]'
138
+ ).format(tag_limit=tag_limit)
139
+ logger.info(msg)
140
+
141
+
142
+ def ca_bundle_info(config: Configuration) -> str:
143
+ levels = set()
144
+ for key, _ in config.items():
145
+ levels.add(key.split('.')[0])
146
+
147
+ if not levels:
148
+ return "Not specified"
149
+
150
+ levels_that_override_global = ['install', 'wheel', 'download']
151
+ global_overriding_level = [
152
+ level for level in levels if level in levels_that_override_global
153
+ ]
154
+ if not global_overriding_level:
155
+ return 'global'
156
+
157
+ if 'global' in levels:
158
+ levels.remove('global')
159
+ return ", ".join(levels)
160
+
161
+
162
+ class DebugCommand(Command):
163
+ """
164
+ Display debug information.
165
+ """
166
+
167
+ usage = """
168
+ %prog <options>"""
169
+ ignore_require_venv = True
170
+
171
+ def add_options(self) -> None:
172
+ cmdoptions.add_target_python_options(self.cmd_opts)
173
+ self.parser.insert_option_group(0, self.cmd_opts)
174
+ self.parser.config.load()
175
+
176
+ def run(self, options: Values, args: List[str]) -> int:
177
+ logger.warning(
178
+ "This command is only meant for debugging. "
179
+ "Do not use this with automation for parsing and getting these "
180
+ "details, since the output and options of this command may "
181
+ "change without notice."
182
+ )
183
+ show_value('pip version', get_pip_version())
184
+ show_value('sys.version', sys.version)
185
+ show_value('sys.executable', sys.executable)
186
+ show_value('sys.getdefaultencoding', sys.getdefaultencoding())
187
+ show_value('sys.getfilesystemencoding', sys.getfilesystemencoding())
188
+ show_value(
189
+ 'locale.getpreferredencoding', locale.getpreferredencoding(),
190
+ )
191
+ show_value('sys.platform', sys.platform)
192
+ show_sys_implementation()
193
+
194
+ show_value("'cert' config value", ca_bundle_info(self.parser.config))
195
+ show_value("REQUESTS_CA_BUNDLE", os.environ.get('REQUESTS_CA_BUNDLE'))
196
+ show_value("CURL_CA_BUNDLE", os.environ.get('CURL_CA_BUNDLE'))
197
+ show_value("pip._vendor.certifi.where()", where())
198
+ show_value("pip._vendor.DEBUNDLED", pip._vendor.DEBUNDLED)
199
+
200
+ show_vendor_versions()
201
+
202
+ show_tags(options)
203
+
204
+ return SUCCESS
.venv/lib/python3.9/site-packages/pip/_internal/commands/download.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.req.req_tracker import get_requirement_tracker
11
+ from pip._internal.utils.misc import ensure_dir, normalize_path, write_output
12
+ from pip._internal.utils.temp_dir import TempDirectory
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class DownloadCommand(RequirementCommand):
18
+ """
19
+ Download packages from:
20
+
21
+ - PyPI (and other indexes) using requirement specifiers.
22
+ - VCS project urls.
23
+ - Local project directories.
24
+ - Local or remote source archives.
25
+
26
+ pip also supports downloading from "requirements files", which provide
27
+ an easy way to specify a whole environment to be downloaded.
28
+ """
29
+
30
+ usage = """
31
+ %prog [options] <requirement specifier> [package-index-options] ...
32
+ %prog [options] -r <requirements file> [package-index-options] ...
33
+ %prog [options] <vcs project url> ...
34
+ %prog [options] <local project path> ...
35
+ %prog [options] <archive url/path> ..."""
36
+
37
+ def add_options(self) -> None:
38
+ self.cmd_opts.add_option(cmdoptions.constraints())
39
+ self.cmd_opts.add_option(cmdoptions.requirements())
40
+ self.cmd_opts.add_option(cmdoptions.build_dir())
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.ignore_requires_python())
54
+
55
+ self.cmd_opts.add_option(
56
+ '-d', '--dest', '--destination-dir', '--destination-directory',
57
+ dest='download_dir',
58
+ metavar='dir',
59
+ default=os.curdir,
60
+ help=("Download packages into <dir>."),
61
+ )
62
+
63
+ cmdoptions.add_target_python_options(self.cmd_opts)
64
+
65
+ index_opts = cmdoptions.make_option_group(
66
+ cmdoptions.index_group,
67
+ self.parser,
68
+ )
69
+
70
+ self.parser.insert_option_group(0, index_opts)
71
+ self.parser.insert_option_group(0, self.cmd_opts)
72
+
73
+ @with_cleanup
74
+ def run(self, options: Values, args: List[str]) -> int:
75
+
76
+ options.ignore_installed = True
77
+ # editable doesn't really make sense for `pip download`, but the bowels
78
+ # of the RequirementSet code require that property.
79
+ options.editables = []
80
+
81
+ cmdoptions.check_dist_restriction(options)
82
+
83
+ options.download_dir = normalize_path(options.download_dir)
84
+ ensure_dir(options.download_dir)
85
+
86
+ session = self.get_default_session(options)
87
+
88
+ target_python = make_target_python(options)
89
+ finder = self._build_package_finder(
90
+ options=options,
91
+ session=session,
92
+ target_python=target_python,
93
+ ignore_requires_python=options.ignore_requires_python,
94
+ )
95
+
96
+ req_tracker = self.enter_context(get_requirement_tracker())
97
+
98
+ directory = TempDirectory(
99
+ delete=not options.no_clean,
100
+ kind="download",
101
+ globally_managed=True,
102
+ )
103
+
104
+ reqs = self.get_requirements(args, options, finder, session)
105
+
106
+ preparer = self.make_requirement_preparer(
107
+ temp_build_dir=directory,
108
+ options=options,
109
+ req_tracker=req_tracker,
110
+ session=session,
111
+ finder=finder,
112
+ download_dir=options.download_dir,
113
+ use_user_site=False,
114
+ )
115
+
116
+ resolver = self.make_resolver(
117
+ preparer=preparer,
118
+ finder=finder,
119
+ options=options,
120
+ ignore_requires_python=options.ignore_requires_python,
121
+ py_version_info=options.python_version,
122
+ )
123
+
124
+ self.trace_basic_info(finder)
125
+
126
+ requirement_set = resolver.resolve(
127
+ reqs, check_supported_wheels=True
128
+ )
129
+
130
+ downloaded: List[str] = []
131
+ for req in requirement_set.requirements.values():
132
+ if req.satisfied_by is None:
133
+ assert req.name is not None
134
+ preparer.save_linked_requirement(req)
135
+ downloaded.append(req.name)
136
+ if downloaded:
137
+ write_output('Successfully downloaded %s', ' '.join(downloaded))
138
+
139
+ return SUCCESS
.venv/lib/python3.9/site-packages/pip/_internal/commands/freeze.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from optparse import Values
3
+ from typing import List
4
+
5
+ from pip._internal.cli import cmdoptions
6
+ from pip._internal.cli.base_command import Command
7
+ from pip._internal.cli.status_codes import SUCCESS
8
+ from pip._internal.operations.freeze import freeze
9
+ from pip._internal.utils.compat import stdlib_pkgs
10
+
11
+ DEV_PKGS = {'pip', 'setuptools', 'distribute', 'wheel'}
12
+
13
+
14
+ class FreezeCommand(Command):
15
+ """
16
+ Output installed packages in requirements format.
17
+
18
+ packages are listed in a case-insensitive sorted order.
19
+ """
20
+
21
+ usage = """
22
+ %prog [options]"""
23
+ log_streams = ("ext://sys.stderr", "ext://sys.stderr")
24
+
25
+ def add_options(self) -> None:
26
+ self.cmd_opts.add_option(
27
+ '-r', '--requirement',
28
+ dest='requirements',
29
+ action='append',
30
+ default=[],
31
+ metavar='file',
32
+ help="Use the order in the given requirements file and its "
33
+ "comments when generating output. This option can be "
34
+ "used multiple times.")
35
+ self.cmd_opts.add_option(
36
+ '-l', '--local',
37
+ dest='local',
38
+ action='store_true',
39
+ default=False,
40
+ help='If in a virtualenv that has global access, do not output '
41
+ 'globally-installed packages.')
42
+ self.cmd_opts.add_option(
43
+ '--user',
44
+ dest='user',
45
+ action='store_true',
46
+ default=False,
47
+ help='Only output packages installed in user-site.')
48
+ self.cmd_opts.add_option(cmdoptions.list_path())
49
+ self.cmd_opts.add_option(
50
+ '--all',
51
+ dest='freeze_all',
52
+ action='store_true',
53
+ help='Do not skip these packages in the output:'
54
+ ' {}'.format(', '.join(DEV_PKGS)))
55
+ self.cmd_opts.add_option(
56
+ '--exclude-editable',
57
+ dest='exclude_editable',
58
+ action='store_true',
59
+ help='Exclude editable package from output.')
60
+ self.cmd_opts.add_option(cmdoptions.list_exclude())
61
+
62
+ self.parser.insert_option_group(0, self.cmd_opts)
63
+
64
+ def run(self, options: Values, args: List[str]) -> int:
65
+ skip = set(stdlib_pkgs)
66
+ if not options.freeze_all:
67
+ skip.update(DEV_PKGS)
68
+
69
+ if options.excludes:
70
+ skip.update(options.excludes)
71
+
72
+ cmdoptions.check_list_path_option(options)
73
+
74
+ for line in freeze(
75
+ requirement=options.requirements,
76
+ local_only=options.local,
77
+ user_only=options.user,
78
+ paths=options.path,
79
+ isolated=options.isolated_mode,
80
+ skip=skip,
81
+ exclude_editable=options.exclude_editable,
82
+ ):
83
+ sys.stdout.write(line + '\n')
84
+ return SUCCESS
.venv/lib/python3.9/site-packages/pip/_internal/commands/hash.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import logging
3
+ import sys
4
+ from optparse import Values
5
+ from typing import List
6
+
7
+ from pip._internal.cli.base_command import Command
8
+ from pip._internal.cli.status_codes import ERROR, SUCCESS
9
+ from pip._internal.utils.hashes import FAVORITE_HASH, STRONG_HASHES
10
+ from pip._internal.utils.misc import read_chunks, write_output
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class HashCommand(Command):
16
+ """
17
+ Compute a hash of a local package archive.
18
+
19
+ These can be used with --hash in a requirements file to do repeatable
20
+ installs.
21
+ """
22
+
23
+ usage = '%prog [options] <file> ...'
24
+ ignore_require_venv = True
25
+
26
+ def add_options(self) -> None:
27
+ self.cmd_opts.add_option(
28
+ '-a', '--algorithm',
29
+ dest='algorithm',
30
+ choices=STRONG_HASHES,
31
+ action='store',
32
+ default=FAVORITE_HASH,
33
+ help='The hash algorithm to use: one of {}'.format(
34
+ ', '.join(STRONG_HASHES)))
35
+ self.parser.insert_option_group(0, self.cmd_opts)
36
+
37
+ def run(self, options: Values, args: List[str]) -> int:
38
+ if not args:
39
+ self.parser.print_usage(sys.stderr)
40
+ return ERROR
41
+
42
+ algorithm = options.algorithm
43
+ for path in args:
44
+ write_output('%s:\n--hash=%s:%s',
45
+ path, algorithm, _hash_of_file(path, algorithm))
46
+ return SUCCESS
47
+
48
+
49
+ def _hash_of_file(path: str, algorithm: str) -> str:
50
+ """Return the hash digest of a file."""
51
+ with open(path, 'rb') as archive:
52
+ hash = hashlib.new(algorithm)
53
+ for chunk in read_chunks(archive):
54
+ hash.update(chunk)
55
+ return hash.hexdigest()