hxrron commited on
Commit
c2fbd85
·
verified ·
1 Parent(s): be11e7a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. python_embeded/Lib/site-packages/pip-25.1.1.dist-info/licenses/AUTHORS.txt +821 -0
  3. python_embeded/Lib/site-packages/pip-25.1.1.dist-info/licenses/LICENSE.txt +20 -0
  4. python_embeded/Lib/site-packages/pip/_internal/__init__.py +18 -0
  5. python_embeded/Lib/site-packages/pip/_internal/build_env.py +325 -0
  6. python_embeded/Lib/site-packages/pip/_internal/cache.py +289 -0
  7. python_embeded/Lib/site-packages/pip/_internal/cli/__init__.py +3 -0
  8. python_embeded/Lib/site-packages/pip/_internal/cli/autocompletion.py +175 -0
  9. python_embeded/Lib/site-packages/pip/_internal/cli/base_command.py +233 -0
  10. python_embeded/Lib/site-packages/pip/_internal/cli/cmdoptions.py +1133 -0
  11. python_embeded/Lib/site-packages/pip/_internal/cli/command_context.py +27 -0
  12. python_embeded/Lib/site-packages/pip/_internal/cli/index_command.py +173 -0
  13. python_embeded/Lib/site-packages/pip/_internal/cli/main.py +79 -0
  14. python_embeded/Lib/site-packages/pip/_internal/cli/main_parser.py +133 -0
  15. python_embeded/Lib/site-packages/pip/_internal/cli/parser.py +294 -0
  16. python_embeded/Lib/site-packages/pip/_internal/cli/progress_bars.py +144 -0
  17. python_embeded/Lib/site-packages/pip/_internal/cli/req_command.py +347 -0
  18. python_embeded/Lib/site-packages/pip/_internal/cli/spinners.py +159 -0
  19. python_embeded/Lib/site-packages/pip/_internal/cli/status_codes.py +6 -0
  20. python_embeded/Lib/site-packages/pip/_internal/commands/__init__.py +137 -0
  21. python_embeded/Lib/site-packages/pip/_internal/commands/cache.py +228 -0
  22. python_embeded/Lib/site-packages/pip/_internal/commands/check.py +67 -0
  23. python_embeded/Lib/site-packages/pip/_internal/commands/completion.py +136 -0
  24. python_embeded/Lib/site-packages/pip/_internal/commands/configuration.py +280 -0
  25. python_embeded/Lib/site-packages/pip/_internal/commands/debug.py +201 -0
  26. python_embeded/Lib/site-packages/pip/_internal/commands/download.py +146 -0
  27. python_embeded/Lib/site-packages/pip/_internal/commands/freeze.py +108 -0
  28. python_embeded/Lib/site-packages/pip/_internal/commands/hash.py +59 -0
  29. python_embeded/Lib/site-packages/pip/_internal/commands/help.py +41 -0
  30. python_embeded/Lib/site-packages/pip/_internal/commands/index.py +153 -0
  31. python_embeded/Lib/site-packages/pip/_internal/commands/inspect.py +92 -0
  32. python_embeded/Lib/site-packages/pip/_internal/commands/install.py +793 -0
  33. python_embeded/Lib/site-packages/pip/_internal/commands/list.py +391 -0
  34. python_embeded/Lib/site-packages/pip/_internal/commands/lock.py +171 -0
  35. python_embeded/Lib/site-packages/pip/_internal/commands/search.py +176 -0
  36. python_embeded/Lib/site-packages/pip/_internal/commands/show.py +228 -0
  37. python_embeded/Lib/site-packages/pip/_internal/commands/uninstall.py +114 -0
  38. python_embeded/Lib/site-packages/pip/_internal/commands/wheel.py +182 -0
  39. python_embeded/Lib/site-packages/pip/_internal/configuration.py +383 -0
  40. python_embeded/Lib/site-packages/pip/_internal/distributions/__init__.py +21 -0
  41. python_embeded/Lib/site-packages/pip/_internal/distributions/base.py +53 -0
  42. python_embeded/Lib/site-packages/pip/_internal/distributions/installed.py +29 -0
  43. python_embeded/Lib/site-packages/pip/_internal/distributions/sdist.py +158 -0
  44. python_embeded/Lib/site-packages/pip/_internal/distributions/wheel.py +42 -0
  45. python_embeded/Lib/site-packages/pip/_internal/exceptions.py +862 -0
  46. python_embeded/Lib/site-packages/pip/_internal/index/__init__.py +1 -0
  47. python_embeded/Lib/site-packages/pip/_internal/index/collector.py +494 -0
  48. python_embeded/Lib/site-packages/pip/_internal/index/package_finder.py +1050 -0
  49. python_embeded/Lib/site-packages/pip/_internal/index/sources.py +284 -0
  50. python_embeded/Lib/site-packages/pip/_internal/locations/__init__.py +439 -0
.gitattributes CHANGED
@@ -323,3 +323,5 @@ python_embeded/Lib/site-packages/skimage/data/retina.jpg filter=lfs diff=lfs mer
323
  python_embeded/Lib/site-packages/skimage/data/hubble_deep_field.jpg filter=lfs diff=lfs merge=lfs -text
324
  python_embeded/Lib/site-packages/skimage/data/rocket.jpg filter=lfs diff=lfs merge=lfs -text
325
  python_embeded/Lib/site-packages/skimage/data/camera.png filter=lfs diff=lfs merge=lfs -text
 
 
 
323
  python_embeded/Lib/site-packages/skimage/data/hubble_deep_field.jpg filter=lfs diff=lfs merge=lfs -text
324
  python_embeded/Lib/site-packages/skimage/data/rocket.jpg filter=lfs diff=lfs merge=lfs -text
325
  python_embeded/Lib/site-packages/skimage/data/camera.png filter=lfs diff=lfs merge=lfs -text
326
+ python_embeded/Lib/site-packages/scipy/special/libsf_error_state.dll filter=lfs diff=lfs merge=lfs -text
327
+ python_embeded/Lib/site-packages/pydantic_core/_pydantic_core.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
python_embeded/Lib/site-packages/pip-25.1.1.dist-info/licenses/AUTHORS.txt ADDED
@@ -0,0 +1,821 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @Switch01
2
+ A_Rog
3
+ Aakanksha Agrawal
4
+ Abhinav Sagar
5
+ ABHYUDAY PRATAP SINGH
6
+ abs51295
7
+ AceGentile
8
+ Adam Chainz
9
+ Adam Tse
10
+ Adam Turner
11
+ Adam Wentz
12
+ admin
13
+ Adolfo Ochagavía
14
+ Adrien Morison
15
+ Agus
16
+ ahayrapetyan
17
+ Ahilya
18
+ AinsworthK
19
+ Akash Srivastava
20
+ Alan Yee
21
+ Albert Tugushev
22
+ Albert-Guan
23
+ albertg
24
+ Alberto Sottile
25
+ Aleks Bunin
26
+ Ales Erjavec
27
+ Alethea Flowers
28
+ Alex Gaynor
29
+ Alex Grönholm
30
+ Alex Hedges
31
+ Alex Loosley
32
+ Alex Morega
33
+ Alex Stachowiak
34
+ Alexander Regueiro
35
+ Alexander Shtyrov
36
+ Alexandre Conrad
37
+ Alexey Popravka
38
+ Aleš Erjavec
39
+ Alli
40
+ Ami Fischman
41
+ Ananya Maiti
42
+ Anatoly Techtonik
43
+ Anders Kaseorg
44
+ Andre Aguiar
45
+ Andreas Lutro
46
+ Andrei Geacar
47
+ Andrew Gaul
48
+ Andrew Shymanel
49
+ Andrey Bienkowski
50
+ Andrey Bulgakov
51
+ Andrés Delfino
52
+ Andy Freeland
53
+ Andy Kluger
54
+ Ani Hayrapetyan
55
+ Aniruddha Basak
56
+ Anish Tambe
57
+ Anrs Hu
58
+ Anthony Sottile
59
+ Antoine Musso
60
+ Anton Ovchinnikov
61
+ Anton Patrushev
62
+ Anton Zelenov
63
+ Antonio Alvarado Hernandez
64
+ Antony Lee
65
+ Antti Kaihola
66
+ Anubhav Patel
67
+ Anudit Nagar
68
+ Anuj Godase
69
+ AQNOUCH Mohammed
70
+ AraHaan
71
+ arena
72
+ arenasys
73
+ Arindam Choudhury
74
+ Armin Ronacher
75
+ Arnon Yaari
76
+ Artem
77
+ Arun Babu Neelicattu
78
+ Ashley Manton
79
+ Ashwin Ramaswami
80
+ atse
81
+ Atsushi Odagiri
82
+ Avinash Karhana
83
+ Avner Cohen
84
+ Awit (Ah-Wit) Ghirmai
85
+ Baptiste Mispelon
86
+ Barney Gale
87
+ barneygale
88
+ Bartek Ogryczak
89
+ Bastian Venthur
90
+ Ben Bodenmiller
91
+ Ben Darnell
92
+ Ben Hoyt
93
+ Ben Mares
94
+ Ben Rosser
95
+ Bence Nagy
96
+ Benjamin Peterson
97
+ Benjamin VanEvery
98
+ Benoit Pierre
99
+ Berker Peksag
100
+ Bernard
101
+ Bernard Tyers
102
+ Bernardo B. Marques
103
+ Bernhard M. Wiedemann
104
+ Bertil Hatt
105
+ Bhavam Vidyarthi
106
+ Blazej Michalik
107
+ Bogdan Opanchuk
108
+ BorisZZZ
109
+ Brad Erickson
110
+ Bradley Ayers
111
+ Bradley Reynolds
112
+ Branch Vincent
113
+ Brandon L. Reiss
114
+ Brandt Bucher
115
+ Brannon Dorsey
116
+ Brett Randall
117
+ Brett Rosen
118
+ Brian Cristante
119
+ Brian Rosner
120
+ briantracy
121
+ BrownTruck
122
+ Bruno Oliveira
123
+ Bruno Renié
124
+ Bruno S
125
+ Bstrdsmkr
126
+ Buck Golemon
127
+ burrows
128
+ Bussonnier Matthias
129
+ bwoodsend
130
+ c22
131
+ Caleb Brown
132
+ Caleb Martinez
133
+ Calvin Smith
134
+ Carl Meyer
135
+ Carlos Liam
136
+ Carol Willing
137
+ Carter Thayer
138
+ Cass
139
+ Chandrasekhar Atina
140
+ Charlie Marsh
141
+ charwick
142
+ Chih-Hsuan Yen
143
+ Chris Brinker
144
+ Chris Hunt
145
+ Chris Jerdonek
146
+ Chris Kuehl
147
+ Chris Markiewicz
148
+ Chris McDonough
149
+ Chris Pawley
150
+ Chris Pryer
151
+ Chris Wolfe
152
+ Christian Clauss
153
+ Christian Heimes
154
+ Christian Oudard
155
+ Christoph Reiter
156
+ Christopher Hunt
157
+ Christopher Snyder
158
+ chrysle
159
+ cjc7373
160
+ Clark Boylan
161
+ Claudio Jolowicz
162
+ Clay McClure
163
+ Cody
164
+ Cody Soyland
165
+ Colin Watson
166
+ Collin Anderson
167
+ Connor Osborn
168
+ Cooper Lees
169
+ Cooper Ry Lees
170
+ Cory Benfield
171
+ Cory Wright
172
+ Craig Kerstiens
173
+ Cristian Sorinel
174
+ Cristina
175
+ Cristina Muñoz
176
+ ctg123
177
+ Curtis Doty
178
+ cytolentino
179
+ Daan De Meyer
180
+ Dale
181
+ Damian
182
+ Damian Quiroga
183
+ Damian Shaw
184
+ Dan Black
185
+ Dan Savilonis
186
+ Dan Sully
187
+ Dane Hillard
188
+ daniel
189
+ Daniel Collins
190
+ Daniel Hahler
191
+ Daniel Holth
192
+ Daniel Jost
193
+ Daniel Katz
194
+ Daniel Shaulov
195
+ Daniele Esposti
196
+ Daniele Nicolodi
197
+ Daniele Procida
198
+ Daniil Konovalenko
199
+ Danny Hermes
200
+ Danny McClanahan
201
+ Darren Kavanagh
202
+ Dav Clark
203
+ Dave Abrahams
204
+ Dave Jones
205
+ David Aguilar
206
+ David Black
207
+ David Bordeynik
208
+ David Caro
209
+ David D Lowe
210
+ David Evans
211
+ David Hewitt
212
+ David Linke
213
+ David Poggi
214
+ David Poznik
215
+ David Pursehouse
216
+ David Runge
217
+ David Tucker
218
+ David Wales
219
+ Davidovich
220
+ ddelange
221
+ Deepak Sharma
222
+ Deepyaman Datta
223
+ Denise Yu
224
+ dependabot[bot]
225
+ derwolfe
226
+ Desetude
227
+ developer
228
+ Devesh Kumar Singh
229
+ devsagul
230
+ Diego Caraballo
231
+ Diego Ramirez
232
+ DiegoCaraballo
233
+ Dimitri Merejkowsky
234
+ Dimitri Papadopoulos
235
+ Dimitri Papadopoulos Orfanos
236
+ Dirk Stolle
237
+ Dmitry Gladkov
238
+ Dmitry Volodin
239
+ Domen Kožar
240
+ Dominic Davis-Foster
241
+ Donald Stufft
242
+ Dongweiming
243
+ doron zarhi
244
+ Dos Moonen
245
+ Douglas Thor
246
+ DrFeathers
247
+ Dustin Ingram
248
+ Dustin Rodrigues
249
+ Dwayne Bailey
250
+ Ed Morley
251
+ Edgar Ramírez
252
+ Edgar Ramírez Mondragón
253
+ Ee Durbin
254
+ Efflam Lemaillet
255
+ efflamlemaillet
256
+ Eitan Adler
257
+ ekristina
258
+ elainechan
259
+ Eli Schwartz
260
+ Elisha Hollander
261
+ Ellen Marie Dash
262
+ Emil Burzo
263
+ Emil Styrke
264
+ Emmanuel Arias
265
+ Endoh Takanao
266
+ enoch
267
+ Erdinc Mutlu
268
+ Eric Cousineau
269
+ Eric Gillingham
270
+ Eric Hanchrow
271
+ Eric Hopper
272
+ Erik M. Bray
273
+ Erik Rose
274
+ Erwin Janssen
275
+ Eugene Vereshchagin
276
+ everdimension
277
+ Federico
278
+ Felipe Peter
279
+ Felix Yan
280
+ fiber-space
281
+ Filip Kokosiński
282
+ Filipe Laíns
283
+ Finn Womack
284
+ finnagin
285
+ Flavio Amurrio
286
+ Florian Briand
287
+ Florian Rathgeber
288
+ Francesco
289
+ Francesco Montesano
290
+ Fredrik Orderud
291
+ Fredrik Roubert
292
+ Frost Ming
293
+ Gabriel Curio
294
+ Gabriel de Perthuis
295
+ Garry Polley
296
+ gavin
297
+ gdanielson
298
+ Geoffrey Sneddon
299
+ George Margaritis
300
+ George Song
301
+ Georgi Valkov
302
+ Georgy Pchelkin
303
+ ghost
304
+ Giftlin Rajaiah
305
+ gizmoguy1
306
+ gkdoc
307
+ Godefroid Chapelle
308
+ Gopinath M
309
+ GOTO Hayato
310
+ gousaiyang
311
+ gpiks
312
+ Greg Roodt
313
+ Greg Ward
314
+ Guilherme Espada
315
+ Guillaume Seguin
316
+ gutsytechster
317
+ Guy Rozendorn
318
+ Guy Tuval
319
+ gzpan123
320
+ Hanjun Kim
321
+ Hari Charan
322
+ Harsh Vardhan
323
+ harupy
324
+ Harutaka Kawamura
325
+ hauntsaninja
326
+ Henrich Hartzer
327
+ Henry Schreiner
328
+ Herbert Pfennig
329
+ Holly Stotelmyer
330
+ Honnix
331
+ Hsiaoming Yang
332
+ Hugo Lopes Tavares
333
+ Hugo van Kemenade
334
+ Hugues Bruant
335
+ Hynek Schlawack
336
+ Ian Bicking
337
+ Ian Cordasco
338
+ Ian Lee
339
+ Ian Stapleton Cordasco
340
+ Ian Wienand
341
+ Igor Kuzmitshov
342
+ Igor Sobreira
343
+ Ikko Ashimine
344
+ Ilan Schnell
345
+ Illia Volochii
346
+ Ilya Baryshev
347
+ Inada Naoki
348
+ Ionel Cristian Mărieș
349
+ Ionel Maries Cristian
350
+ Itamar Turner-Trauring
351
+ iTrooz
352
+ Ivan Pozdeev
353
+ J. Nick Koston
354
+ Jacob Kim
355
+ Jacob Walls
356
+ Jaime Sanz
357
+ Jake Lishman
358
+ jakirkham
359
+ Jakub Kuczys
360
+ Jakub Stasiak
361
+ Jakub Vysoky
362
+ Jakub Wilk
363
+ James Cleveland
364
+ James Curtin
365
+ James Firth
366
+ James Gerity
367
+ James Polley
368
+ Jan Pokorný
369
+ Jannis Leidel
370
+ Jarek Potiuk
371
+ jarondl
372
+ Jason Curtis
373
+ Jason R. Coombs
374
+ JasonMo
375
+ JasonMo1
376
+ Jay Graves
377
+ Jean Abou Samra
378
+ Jean-Christophe Fillion-Robin
379
+ Jeff Barber
380
+ Jeff Dairiki
381
+ Jeff Widman
382
+ Jelmer Vernooij
383
+ jenix21
384
+ Jeremy Fleischman
385
+ Jeremy Stanley
386
+ Jeremy Zafran
387
+ Jesse Rittner
388
+ Jiashuo Li
389
+ Jim Fisher
390
+ Jim Garrison
391
+ Jinzhe Zeng
392
+ Jiun Bae
393
+ Jivan Amara
394
+ Joa
395
+ Joe Bylund
396
+ Joe Michelini
397
+ Johannes Altmanninger
398
+ John Paton
399
+ John Sirois
400
+ John T. Wodder II
401
+ John-Scott Atlakson
402
+ johnthagen
403
+ Jon Banafato
404
+ Jon Dufresne
405
+ Jon Parise
406
+ Jonas Nockert
407
+ Jonathan Herbert
408
+ Joonatan Partanen
409
+ Joost Molenaar
410
+ Jorge Niedbalski
411
+ Joseph Bylund
412
+ Joseph Long
413
+ Josh Bronson
414
+ Josh Cannon
415
+ Josh Hansen
416
+ Josh Schneier
417
+ Joshua
418
+ JoshuaPerdue
419
+ Juan Luis Cano Rodríguez
420
+ Juanjo Bazán
421
+ Judah Rand
422
+ Julian Berman
423
+ Julian Gethmann
424
+ Julien Demoor
425
+ July Tikhonov
426
+ Jussi Kukkonen
427
+ Justin van Heek
428
+ jwg4
429
+ Jyrki Pulliainen
430
+ Kai Chen
431
+ Kai Mueller
432
+ Kamal Bin Mustafa
433
+ Karolina Surma
434
+ kasium
435
+ kaustav haldar
436
+ keanemind
437
+ Keith Maxwell
438
+ Kelsey Hightower
439
+ Kenneth Belitzky
440
+ Kenneth Reitz
441
+ Kevin Burke
442
+ Kevin Carter
443
+ Kevin Frommelt
444
+ Kevin R Patterson
445
+ Kexuan Sun
446
+ Kit Randel
447
+ Klaas van Schelven
448
+ KOLANICH
449
+ konstin
450
+ kpinc
451
+ Krishan Bhasin
452
+ Krishna Oza
453
+ Kumar McMillan
454
+ Kuntal Majumder
455
+ Kurt McKee
456
+ Kyle Persohn
457
+ lakshmanaram
458
+ Laszlo Kiss-Kollar
459
+ Laurent Bristiel
460
+ Laurent LAPORTE
461
+ Laurie O
462
+ Laurie Opperman
463
+ layday
464
+ Leon Sasson
465
+ Lev Givon
466
+ Lincoln de Sousa
467
+ Lipis
468
+ lorddavidiii
469
+ Loren Carvalho
470
+ Lucas Cimon
471
+ Ludovic Gasc
472
+ Luis Medel
473
+ Lukas Geiger
474
+ Lukas Juhrich
475
+ Luke Macken
476
+ Luo Jiebin
477
+ luojiebin
478
+ luz.paz
479
+ László Kiss Kollár
480
+ M00nL1ght
481
+ Malcolm Smith
482
+ Marc Abramowitz
483
+ Marc Tamlyn
484
+ Marcus Smith
485
+ Mariatta
486
+ Mark Kohler
487
+ Mark McLoughlin
488
+ Mark Williams
489
+ Markus Hametner
490
+ Martey Dodoo
491
+ Martin Fischer
492
+ Martin Häcker
493
+ Martin Pavlasek
494
+ Masaki
495
+ Masklinn
496
+ Matej Stuchlik
497
+ Mathew Jennings
498
+ Mathieu Bridon
499
+ Mathieu Kniewallner
500
+ Matt Bacchi
501
+ Matt Good
502
+ Matt Maker
503
+ Matt Robenolt
504
+ Matt Wozniski
505
+ matthew
506
+ Matthew Einhorn
507
+ Matthew Feickert
508
+ Matthew Gilliard
509
+ Matthew Hughes
510
+ Matthew Iversen
511
+ Matthew Treinish
512
+ Matthew Trumbell
513
+ Matthew Willson
514
+ Matthias Bussonnier
515
+ mattip
516
+ Maurits van Rees
517
+ Max W Chase
518
+ Maxim Kurnikov
519
+ Maxime Rouyrre
520
+ mayeut
521
+ mbaluna
522
+ Md Sujauddin Sekh
523
+ mdebi
524
+ memoselyk
525
+ meowmeowcat
526
+ Michael
527
+ Michael Aquilina
528
+ Michael E. Karpeles
529
+ Michael Klich
530
+ Michael Mintz
531
+ Michael Williamson
532
+ michaelpacer
533
+ Michał Górny
534
+ Mickaël Schoentgen
535
+ Miguel Araujo Perez
536
+ Mihir Singh
537
+ Mike
538
+ Mike Hendricks
539
+ Min RK
540
+ MinRK
541
+ Miro Hrončok
542
+ Monica Baluna
543
+ montefra
544
+ Monty Taylor
545
+ morotti
546
+ mrKazzila
547
+ Muha Ajjan
548
+ Nadav Wexler
549
+ Nahuel Ambrosini
550
+ Nate Coraor
551
+ Nate Prewitt
552
+ Nathan Houghton
553
+ Nathaniel J. Smith
554
+ Nehal J Wani
555
+ Neil Botelho
556
+ Nguyễn Gia Phong
557
+ Nicholas Serra
558
+ Nick Coghlan
559
+ Nick Stenning
560
+ Nick Timkovich
561
+ Nicolas Bock
562
+ Nicole Harris
563
+ Nikhil Benesch
564
+ Nikhil Ladha
565
+ Nikita Chepanov
566
+ Nikolay Korolev
567
+ Nipunn Koorapati
568
+ Nitesh Sharma
569
+ Niyas Sait
570
+ Noah
571
+ Noah Gorny
572
+ Nowell Strite
573
+ NtaleGrey
574
+ nucccc
575
+ nvdv
576
+ OBITORASU
577
+ Ofek Lev
578
+ ofrinevo
579
+ Oleg Burnaev
580
+ Oliver Freund
581
+ Oliver Jeeves
582
+ Oliver Mannion
583
+ Oliver Tonnhofer
584
+ Olivier Girardot
585
+ Olivier Grisel
586
+ Ollie Rutherfurd
587
+ OMOTO Kenji
588
+ Omry Yadan
589
+ onlinejudge95
590
+ Oren Held
591
+ Oscar Benjamin
592
+ Oz N Tiram
593
+ Pachwenko
594
+ Patrick Dubroy
595
+ Patrick Jenkins
596
+ Patrick Lawson
597
+ patricktokeeffe
598
+ Patrik Kopkan
599
+ Paul Ganssle
600
+ Paul Kehrer
601
+ Paul Moore
602
+ Paul Nasrat
603
+ Paul Oswald
604
+ Paul van der Linden
605
+ Paulus Schoutsen
606
+ Pavel Safronov
607
+ Pavithra Eswaramoorthy
608
+ Pawel Jasinski
609
+ Paweł Szramowski
610
+ Pekka Klärck
611
+ Peter Gessler
612
+ Peter Lisák
613
+ Peter Shen
614
+ Peter Waller
615
+ Petr Viktorin
616
+ petr-tik
617
+ Phaneendra Chiruvella
618
+ Phil Elson
619
+ Phil Freo
620
+ Phil Pennock
621
+ Phil Whelan
622
+ Philip Jägenstedt
623
+ Philip Molloy
624
+ Philippe Ombredanne
625
+ Pi Delport
626
+ Pierre-Yves Rofes
627
+ Pieter Degroote
628
+ pip
629
+ Prabakaran Kumaresshan
630
+ Prabhjyotsing Surjit Singh Sodhi
631
+ Prabhu Marappan
632
+ Pradyun Gedam
633
+ Prashant Sharma
634
+ Pratik Mallya
635
+ pre-commit-ci[bot]
636
+ Preet Thakkar
637
+ Preston Holmes
638
+ Przemek Wrzos
639
+ Pulkit Goyal
640
+ q0w
641
+ Qiangning Hong
642
+ Qiming Xu
643
+ Quentin Lee
644
+ Quentin Pradet
645
+ R. David Murray
646
+ Rafael Caricio
647
+ Ralf Schmitt
648
+ Ran Benita
649
+ Randy Döring
650
+ Razzi Abuissa
651
+ rdb
652
+ Reece Dunham
653
+ Remi Rampin
654
+ Rene Dudfield
655
+ Riccardo Magliocchetti
656
+ Riccardo Schirone
657
+ Richard Jones
658
+ Richard Si
659
+ Ricky Ng-Adam
660
+ Rishi
661
+ rmorotti
662
+ RobberPhex
663
+ Robert Collins
664
+ Robert McGibbon
665
+ Robert Pollak
666
+ Robert T. McGibbon
667
+ robin elisha robinson
668
+ Roey Berman
669
+ Rohan Jain
670
+ Roman Bogorodskiy
671
+ Roman Donchenko
672
+ Romuald Brunet
673
+ ronaudinho
674
+ Ronny Pfannschmidt
675
+ Rory McCann
676
+ Ross Brattain
677
+ Roy Wellington Ⅳ
678
+ Ruairidh MacLeod
679
+ Russell Keith-Magee
680
+ Ryan Shepherd
681
+ Ryan Wooden
682
+ ryneeverett
683
+ S. Guliaev
684
+ Sachi King
685
+ Salvatore Rinchiera
686
+ sandeepkiran-js
687
+ Sander Van Balen
688
+ Savio Jomton
689
+ schlamar
690
+ Scott Kitterman
691
+ Sean
692
+ seanj
693
+ Sebastian Jordan
694
+ Sebastian Schaetz
695
+ Segev Finer
696
+ SeongSoo Cho
697
+ Sergey Vasilyev
698
+ Seth Michael Larson
699
+ Seth Woodworth
700
+ Shahar Epstein
701
+ Shantanu
702
+ shenxianpeng
703
+ shireenrao
704
+ Shivansh-007
705
+ Shixian Sheng
706
+ Shlomi Fish
707
+ Shovan Maity
708
+ Simeon Visser
709
+ Simon Cross
710
+ Simon Pichugin
711
+ sinoroc
712
+ sinscary
713
+ snook92
714
+ socketubs
715
+ Sorin Sbarnea
716
+ Srinivas Nyayapati
717
+ Srishti Hegde
718
+ Stavros Korokithakis
719
+ Stefan Scherfke
720
+ Stefano Rivera
721
+ Stephan Erb
722
+ Stephen Rosen
723
+ stepshal
724
+ Steve (Gadget) Barnes
725
+ Steve Barnes
726
+ Steve Dower
727
+ Steve Kowalik
728
+ Steven Myint
729
+ Steven Silvester
730
+ stonebig
731
+ studioj
732
+ Stéphane Bidoul
733
+ Stéphane Bidoul (ACSONE)
734
+ Stéphane Klein
735
+ Sumana Harihareswara
736
+ Surbhi Sharma
737
+ Sviatoslav Sydorenko
738
+ Sviatoslav Sydorenko (Святослав Сидоренко)
739
+ Swat009
740
+ Sylvain
741
+ Takayuki SHIMIZUKAWA
742
+ Taneli Hukkinen
743
+ tbeswick
744
+ Thiago
745
+ Thijs Triemstra
746
+ Thomas Fenzl
747
+ Thomas Grainger
748
+ Thomas Guettler
749
+ Thomas Johansson
750
+ Thomas Kluyver
751
+ Thomas Smith
752
+ Thomas VINCENT
753
+ Tim D. Smith
754
+ Tim Gates
755
+ Tim Harder
756
+ Tim Heap
757
+ tim smith
758
+ tinruufu
759
+ Tobias Hermann
760
+ Tom Forbes
761
+ Tom Freudenheim
762
+ Tom V
763
+ Tomas Hrnciar
764
+ Tomas Orsava
765
+ Tomer Chachamu
766
+ Tommi Enenkel | AnB
767
+ Tomáš Hrnčiar
768
+ Tony Beswick
769
+ Tony Narlock
770
+ Tony Zhaocheng Tan
771
+ TonyBeswick
772
+ toonarmycaptain
773
+ Toshio Kuratomi
774
+ toxinu
775
+ Travis Swicegood
776
+ Tushar Sadhwani
777
+ Tzu-ping Chung
778
+ Valentin Haenel
779
+ Victor Stinner
780
+ victorvpaulo
781
+ Vikram - Google
782
+ Viktor Szépe
783
+ Ville Skyttä
784
+ Vinay Sajip
785
+ Vincent Philippon
786
+ Vinicyus Macedo
787
+ Vipul Kumar
788
+ Vitaly Babiy
789
+ Vladimir Fokow
790
+ Vladimir Rutsky
791
+ W. Trevor King
792
+ Wil Tan
793
+ Wilfred Hughes
794
+ William Edwards
795
+ William ML Leslie
796
+ William T Olson
797
+ William Woodruff
798
+ Wilson Mo
799
+ wim glenn
800
+ Winson Luk
801
+ Wolfgang Maier
802
+ Wu Zhenyu
803
+ XAMES3
804
+ Xavier Fernandez
805
+ Xianpeng Shen
806
+ xoviat
807
+ xtreak
808
+ YAMAMOTO Takashi
809
+ Yen Chi Hsuan
810
+ Yeray Diaz Diaz
811
+ Yoval P
812
+ Yu Jian
813
+ Yuan Jing Vincent Yan
814
+ Yusuke Hayashi
815
+ Zearin
816
+ Zhiping Deng
817
+ ziebam
818
+ Zvezdan Petkovic
819
+ Łukasz Langa
820
+ Роман Донченко
821
+ Семён Марьясин
python_embeded/Lib/site-packages/pip-25.1.1.dist-info/licenses/LICENSE.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2008-present The pip developers (see AUTHORS.txt file)
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
python_embeded/Lib/site-packages/pip/_internal/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+
3
+ from pip._internal.utils import _log
4
+
5
+ # init_logging() must be called before any call to logging.getLogger()
6
+ # which happens at import of most modules.
7
+ _log.init_logging()
8
+
9
+
10
+ def main(args: Optional[List[str]] = None) -> int:
11
+ """This is preserved for old console scripts that may still be referencing
12
+ it.
13
+
14
+ For additional details, see https://github.com/pypa/pip/issues/7498.
15
+ """
16
+ from pip._internal.utils.entrypoints import _wrapper
17
+
18
+ return _wrapper(args)
python_embeded/Lib/site-packages/pip/_internal/build_env.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build Environment used for isolation during sdist building"""
2
+
3
+ import logging
4
+ import os
5
+ import pathlib
6
+ import site
7
+ import sys
8
+ import textwrap
9
+ from collections import OrderedDict
10
+ from types import TracebackType
11
+ from typing import TYPE_CHECKING, Iterable, List, Optional, Set, Tuple, Type, Union
12
+
13
+ from pip._vendor.packaging.version import Version
14
+
15
+ from pip import __file__ as pip_location
16
+ from pip._internal.cli.spinners import open_spinner
17
+ from pip._internal.locations import get_platlib, get_purelib, get_scheme
18
+ from pip._internal.metadata import get_default_environment, get_environment
19
+ from pip._internal.utils.logging import VERBOSE
20
+ from pip._internal.utils.packaging import get_requirement
21
+ from pip._internal.utils.subprocess import call_subprocess
22
+ from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
23
+
24
+ if TYPE_CHECKING:
25
+ from pip._internal.index.package_finder import PackageFinder
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ def _dedup(a: str, b: str) -> Union[Tuple[str], Tuple[str, str]]:
31
+ return (a, b) if a != b else (a,)
32
+
33
+
34
+ class _Prefix:
35
+ def __init__(self, path: str) -> None:
36
+ self.path = path
37
+ self.setup = False
38
+ scheme = get_scheme("", prefix=path)
39
+ self.bin_dir = scheme.scripts
40
+ self.lib_dirs = _dedup(scheme.purelib, scheme.platlib)
41
+
42
+
43
+ def get_runnable_pip() -> str:
44
+ """Get a file to pass to a Python executable, to run the currently-running pip.
45
+
46
+ This is used to run a pip subprocess, for installing requirements into the build
47
+ environment.
48
+ """
49
+ source = pathlib.Path(pip_location).resolve().parent
50
+
51
+ if not source.is_dir():
52
+ # This would happen if someone is using pip from inside a zip file. In that
53
+ # case, we can use that directly.
54
+ return str(source)
55
+
56
+ return os.fsdecode(source / "__pip-runner__.py")
57
+
58
+
59
+ def _get_system_sitepackages() -> Set[str]:
60
+ """Get system site packages
61
+
62
+ Usually from site.getsitepackages,
63
+ but fallback on `get_purelib()/get_platlib()` if unavailable
64
+ (e.g. in a virtualenv created by virtualenv<20)
65
+
66
+ Returns normalized set of strings.
67
+ """
68
+ if hasattr(site, "getsitepackages"):
69
+ system_sites = site.getsitepackages()
70
+ else:
71
+ # virtualenv < 20 overwrites site.py without getsitepackages
72
+ # fallback on get_purelib/get_platlib.
73
+ # this is known to miss things, but shouldn't in the cases
74
+ # where getsitepackages() has been removed (inside a virtualenv)
75
+ system_sites = [get_purelib(), get_platlib()]
76
+ return {os.path.normcase(path) for path in system_sites}
77
+
78
+
79
+ class BuildEnvironment:
80
+ """Creates and manages an isolated environment to install build deps"""
81
+
82
+ def __init__(self) -> None:
83
+ temp_dir = TempDirectory(kind=tempdir_kinds.BUILD_ENV, globally_managed=True)
84
+
85
+ self._prefixes = OrderedDict(
86
+ (name, _Prefix(os.path.join(temp_dir.path, name)))
87
+ for name in ("normal", "overlay")
88
+ )
89
+
90
+ self._bin_dirs: List[str] = []
91
+ self._lib_dirs: List[str] = []
92
+ for prefix in reversed(list(self._prefixes.values())):
93
+ self._bin_dirs.append(prefix.bin_dir)
94
+ self._lib_dirs.extend(prefix.lib_dirs)
95
+
96
+ # Customize site to:
97
+ # - ensure .pth files are honored
98
+ # - prevent access to system site packages
99
+ system_sites = _get_system_sitepackages()
100
+
101
+ self._site_dir = os.path.join(temp_dir.path, "site")
102
+ if not os.path.exists(self._site_dir):
103
+ os.mkdir(self._site_dir)
104
+ with open(
105
+ os.path.join(self._site_dir, "sitecustomize.py"), "w", encoding="utf-8"
106
+ ) as fp:
107
+ fp.write(
108
+ textwrap.dedent(
109
+ """
110
+ import os, site, sys
111
+
112
+ # First, drop system-sites related paths.
113
+ original_sys_path = sys.path[:]
114
+ known_paths = set()
115
+ for path in {system_sites!r}:
116
+ site.addsitedir(path, known_paths=known_paths)
117
+ system_paths = set(
118
+ os.path.normcase(path)
119
+ for path in sys.path[len(original_sys_path):]
120
+ )
121
+ original_sys_path = [
122
+ path for path in original_sys_path
123
+ if os.path.normcase(path) not in system_paths
124
+ ]
125
+ sys.path = original_sys_path
126
+
127
+ # Second, add lib directories.
128
+ # ensuring .pth file are processed.
129
+ for path in {lib_dirs!r}:
130
+ assert not path in sys.path
131
+ site.addsitedir(path)
132
+ """
133
+ ).format(system_sites=system_sites, lib_dirs=self._lib_dirs)
134
+ )
135
+
136
+ def __enter__(self) -> None:
137
+ self._save_env = {
138
+ name: os.environ.get(name, None)
139
+ for name in ("PATH", "PYTHONNOUSERSITE", "PYTHONPATH")
140
+ }
141
+
142
+ path = self._bin_dirs[:]
143
+ old_path = self._save_env["PATH"]
144
+ if old_path:
145
+ path.extend(old_path.split(os.pathsep))
146
+
147
+ pythonpath = [self._site_dir]
148
+
149
+ os.environ.update(
150
+ {
151
+ "PATH": os.pathsep.join(path),
152
+ "PYTHONNOUSERSITE": "1",
153
+ "PYTHONPATH": os.pathsep.join(pythonpath),
154
+ }
155
+ )
156
+
157
+ def __exit__(
158
+ self,
159
+ exc_type: Optional[Type[BaseException]],
160
+ exc_val: Optional[BaseException],
161
+ exc_tb: Optional[TracebackType],
162
+ ) -> None:
163
+ for varname, old_value in self._save_env.items():
164
+ if old_value is None:
165
+ os.environ.pop(varname, None)
166
+ else:
167
+ os.environ[varname] = old_value
168
+
169
+ def check_requirements(
170
+ self, reqs: Iterable[str]
171
+ ) -> Tuple[Set[Tuple[str, str]], Set[str]]:
172
+ """Return 2 sets:
173
+ - conflicting requirements: set of (installed, wanted) reqs tuples
174
+ - missing requirements: set of reqs
175
+ """
176
+ missing = set()
177
+ conflicting = set()
178
+ if reqs:
179
+ env = (
180
+ get_environment(self._lib_dirs)
181
+ if hasattr(self, "_lib_dirs")
182
+ else get_default_environment()
183
+ )
184
+ for req_str in reqs:
185
+ req = get_requirement(req_str)
186
+ # We're explicitly evaluating with an empty extra value, since build
187
+ # environments are not provided any mechanism to select specific extras.
188
+ if req.marker is not None and not req.marker.evaluate({"extra": ""}):
189
+ continue
190
+ dist = env.get_distribution(req.name)
191
+ if not dist:
192
+ missing.add(req_str)
193
+ continue
194
+ if isinstance(dist.version, Version):
195
+ installed_req_str = f"{req.name}=={dist.version}"
196
+ else:
197
+ installed_req_str = f"{req.name}==={dist.version}"
198
+ if not req.specifier.contains(dist.version, prereleases=True):
199
+ conflicting.add((installed_req_str, req_str))
200
+ # FIXME: Consider direct URL?
201
+ return conflicting, missing
202
+
203
+ def install_requirements(
204
+ self,
205
+ finder: "PackageFinder",
206
+ requirements: Iterable[str],
207
+ prefix_as_string: str,
208
+ *,
209
+ kind: str,
210
+ ) -> None:
211
+ prefix = self._prefixes[prefix_as_string]
212
+ assert not prefix.setup
213
+ prefix.setup = True
214
+ if not requirements:
215
+ return
216
+ self._install_requirements(
217
+ get_runnable_pip(),
218
+ finder,
219
+ requirements,
220
+ prefix,
221
+ kind=kind,
222
+ )
223
+
224
+ @staticmethod
225
+ def _install_requirements(
226
+ pip_runnable: str,
227
+ finder: "PackageFinder",
228
+ requirements: Iterable[str],
229
+ prefix: _Prefix,
230
+ *,
231
+ kind: str,
232
+ ) -> None:
233
+ args: List[str] = [
234
+ sys.executable,
235
+ pip_runnable,
236
+ "install",
237
+ "--ignore-installed",
238
+ "--no-user",
239
+ "--prefix",
240
+ prefix.path,
241
+ "--no-warn-script-location",
242
+ "--disable-pip-version-check",
243
+ # As the build environment is ephemeral, it's wasteful to
244
+ # pre-compile everything, especially as not every Python
245
+ # module will be used/compiled in most cases.
246
+ "--no-compile",
247
+ # The prefix specified two lines above, thus
248
+ # target from config file or env var should be ignored
249
+ "--target",
250
+ "",
251
+ ]
252
+ if logger.getEffectiveLevel() <= logging.DEBUG:
253
+ args.append("-vv")
254
+ elif logger.getEffectiveLevel() <= VERBOSE:
255
+ args.append("-v")
256
+ for format_control in ("no_binary", "only_binary"):
257
+ formats = getattr(finder.format_control, format_control)
258
+ args.extend(
259
+ (
260
+ "--" + format_control.replace("_", "-"),
261
+ ",".join(sorted(formats or {":none:"})),
262
+ )
263
+ )
264
+
265
+ index_urls = finder.index_urls
266
+ if index_urls:
267
+ args.extend(["-i", index_urls[0]])
268
+ for extra_index in index_urls[1:]:
269
+ args.extend(["--extra-index-url", extra_index])
270
+ else:
271
+ args.append("--no-index")
272
+ for link in finder.find_links:
273
+ args.extend(["--find-links", link])
274
+
275
+ if finder.proxy:
276
+ args.extend(["--proxy", finder.proxy])
277
+ for host in finder.trusted_hosts:
278
+ args.extend(["--trusted-host", host])
279
+ if finder.custom_cert:
280
+ args.extend(["--cert", finder.custom_cert])
281
+ if finder.client_cert:
282
+ args.extend(["--client-cert", finder.client_cert])
283
+ if finder.allow_all_prereleases:
284
+ args.append("--pre")
285
+ if finder.prefer_binary:
286
+ args.append("--prefer-binary")
287
+ args.append("--")
288
+ args.extend(requirements)
289
+ with open_spinner(f"Installing {kind}") as spinner:
290
+ call_subprocess(
291
+ args,
292
+ command_desc=f"pip subprocess to install {kind}",
293
+ spinner=spinner,
294
+ )
295
+
296
+
297
+ class NoOpBuildEnvironment(BuildEnvironment):
298
+ """A no-op drop-in replacement for BuildEnvironment"""
299
+
300
+ def __init__(self) -> None:
301
+ pass
302
+
303
+ def __enter__(self) -> None:
304
+ pass
305
+
306
+ def __exit__(
307
+ self,
308
+ exc_type: Optional[Type[BaseException]],
309
+ exc_val: Optional[BaseException],
310
+ exc_tb: Optional[TracebackType],
311
+ ) -> None:
312
+ pass
313
+
314
+ def cleanup(self) -> None:
315
+ pass
316
+
317
+ def install_requirements(
318
+ self,
319
+ finder: "PackageFinder",
320
+ requirements: Iterable[str],
321
+ prefix_as_string: str,
322
+ *,
323
+ kind: str,
324
+ ) -> None:
325
+ raise NotImplementedError()
python_embeded/Lib/site-packages/pip/_internal/cache.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cache Management"""
2
+
3
+ import hashlib
4
+ import json
5
+ import logging
6
+ import os
7
+ from pathlib import Path
8
+ from typing import Any, Dict, List, Optional
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.direct_url import DirectUrl
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
+ ORIGIN_JSON_NAME = "origin.json"
23
+
24
+
25
+ def _hash_dict(d: Dict[str, str]) -> str:
26
+ """Return a stable sha224 of a dictionary."""
27
+ s = json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
28
+ return hashlib.sha224(s.encode("ascii")).hexdigest()
29
+
30
+
31
+ class Cache:
32
+ """An abstract class - provides cache directories for data from links
33
+
34
+ :param cache_dir: The root of the cache.
35
+ """
36
+
37
+ def __init__(self, cache_dir: str) -> None:
38
+ super().__init__()
39
+ assert not cache_dir or os.path.isabs(cache_dir)
40
+ self.cache_dir = cache_dir or None
41
+
42
+ def _get_cache_path_parts(self, link: Link) -> List[str]:
43
+ """Get parts of part that must be os.path.joined with cache_dir"""
44
+
45
+ # We want to generate an url to use as our cache key, we don't want to
46
+ # just reuse the URL because it might have other items in the fragment
47
+ # and we don't care about those.
48
+ key_parts = {"url": link.url_without_fragment}
49
+ if link.hash_name is not None and link.hash is not None:
50
+ key_parts[link.hash_name] = link.hash
51
+ if link.subdirectory_fragment:
52
+ key_parts["subdirectory"] = link.subdirectory_fragment
53
+
54
+ # Include interpreter name, major and minor version in cache key
55
+ # to cope with ill-behaved sdists that build a different wheel
56
+ # depending on the python version their setup.py is being run on,
57
+ # and don't encode the difference in compatibility tags.
58
+ # https://github.com/pypa/pip/issues/7296
59
+ key_parts["interpreter_name"] = interpreter_name()
60
+ key_parts["interpreter_version"] = interpreter_version()
61
+
62
+ # Encode our key url with sha224, we'll use this because it has similar
63
+ # security properties to sha256, but with a shorter total output (and
64
+ # thus less secure). However the differences don't make a lot of
65
+ # difference for our use case here.
66
+ hashed = _hash_dict(key_parts)
67
+
68
+ # We want to nest the directories some to prevent having a ton of top
69
+ # level directories where we might run out of sub directories on some
70
+ # FS.
71
+ parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
72
+
73
+ return parts
74
+
75
+ def _get_candidates(self, link: Link, canonical_package_name: str) -> List[Any]:
76
+ can_not_cache = not self.cache_dir or not canonical_package_name or not link
77
+ if can_not_cache:
78
+ return []
79
+
80
+ path = self.get_path_for_link(link)
81
+ if os.path.isdir(path):
82
+ return [(candidate, path) for candidate in os.listdir(path)]
83
+ return []
84
+
85
+ def get_path_for_link(self, link: Link) -> str:
86
+ """Return a directory to store cached items in for link."""
87
+ raise NotImplementedError()
88
+
89
+ def get(
90
+ self,
91
+ link: Link,
92
+ package_name: Optional[str],
93
+ supported_tags: List[Tag],
94
+ ) -> Link:
95
+ """Returns a link to a cached item if it exists, otherwise returns the
96
+ passed link.
97
+ """
98
+ raise NotImplementedError()
99
+
100
+
101
+ class SimpleWheelCache(Cache):
102
+ """A cache of wheels for future installs."""
103
+
104
+ def __init__(self, cache_dir: str) -> None:
105
+ super().__init__(cache_dir)
106
+
107
+ def get_path_for_link(self, link: Link) -> str:
108
+ """Return a directory to store cached wheels for link
109
+
110
+ Because there are M wheels for any one sdist, we provide a directory
111
+ to cache them in, and then consult that directory when looking up
112
+ cache hits.
113
+
114
+ We only insert things into the cache if they have plausible version
115
+ numbers, so that we don't contaminate the cache with things that were
116
+ not unique. E.g. ./package might have dozens of installs done for it
117
+ and build a version of 0.0...and if we built and cached a wheel, we'd
118
+ end up using the same wheel even if the source has been edited.
119
+
120
+ :param link: The link of the sdist for which this will cache wheels.
121
+ """
122
+ parts = self._get_cache_path_parts(link)
123
+ assert self.cache_dir
124
+ # Store wheels within the root cache_dir
125
+ return os.path.join(self.cache_dir, "wheels", *parts)
126
+
127
+ def get(
128
+ self,
129
+ link: Link,
130
+ package_name: Optional[str],
131
+ supported_tags: List[Tag],
132
+ ) -> Link:
133
+ candidates = []
134
+
135
+ if not package_name:
136
+ return link
137
+
138
+ canonical_package_name = canonicalize_name(package_name)
139
+ for wheel_name, wheel_dir in self._get_candidates(link, canonical_package_name):
140
+ try:
141
+ wheel = Wheel(wheel_name)
142
+ except InvalidWheelFilename:
143
+ continue
144
+ if canonicalize_name(wheel.name) != canonical_package_name:
145
+ logger.debug(
146
+ "Ignoring cached wheel %s for %s as it "
147
+ "does not match the expected distribution name %s.",
148
+ wheel_name,
149
+ link,
150
+ package_name,
151
+ )
152
+ continue
153
+ if not wheel.supported(supported_tags):
154
+ # Built for a different python/arch/etc
155
+ continue
156
+ candidates.append(
157
+ (
158
+ wheel.support_index_min(supported_tags),
159
+ wheel_name,
160
+ wheel_dir,
161
+ )
162
+ )
163
+
164
+ if not candidates:
165
+ return link
166
+
167
+ _, wheel_name, wheel_dir = min(candidates)
168
+ return Link(path_to_url(os.path.join(wheel_dir, wheel_name)))
169
+
170
+
171
+ class EphemWheelCache(SimpleWheelCache):
172
+ """A SimpleWheelCache that creates it's own temporary cache directory"""
173
+
174
+ def __init__(self) -> None:
175
+ self._temp_dir = TempDirectory(
176
+ kind=tempdir_kinds.EPHEM_WHEEL_CACHE,
177
+ globally_managed=True,
178
+ )
179
+
180
+ super().__init__(self._temp_dir.path)
181
+
182
+
183
+ class CacheEntry:
184
+ def __init__(
185
+ self,
186
+ link: Link,
187
+ persistent: bool,
188
+ ):
189
+ self.link = link
190
+ self.persistent = persistent
191
+ self.origin: Optional[DirectUrl] = None
192
+ origin_direct_url_path = Path(self.link.file_path).parent / ORIGIN_JSON_NAME
193
+ if origin_direct_url_path.exists():
194
+ try:
195
+ self.origin = DirectUrl.from_json(
196
+ origin_direct_url_path.read_text(encoding="utf-8")
197
+ )
198
+ except Exception as e:
199
+ logger.warning(
200
+ "Ignoring invalid cache entry origin file %s for %s (%s)",
201
+ origin_direct_url_path,
202
+ link.filename,
203
+ e,
204
+ )
205
+
206
+
207
+ class WheelCache(Cache):
208
+ """Wraps EphemWheelCache and SimpleWheelCache into a single Cache
209
+
210
+ This Cache allows for gracefully degradation, using the ephem wheel cache
211
+ when a certain link is not found in the simple wheel cache first.
212
+ """
213
+
214
+ def __init__(self, cache_dir: str) -> None:
215
+ super().__init__(cache_dir)
216
+ self._wheel_cache = SimpleWheelCache(cache_dir)
217
+ self._ephem_cache = EphemWheelCache()
218
+
219
+ def get_path_for_link(self, link: Link) -> str:
220
+ return self._wheel_cache.get_path_for_link(link)
221
+
222
+ def get_ephem_path_for_link(self, link: Link) -> str:
223
+ return self._ephem_cache.get_path_for_link(link)
224
+
225
+ def get(
226
+ self,
227
+ link: Link,
228
+ package_name: Optional[str],
229
+ supported_tags: List[Tag],
230
+ ) -> Link:
231
+ cache_entry = self.get_cache_entry(link, package_name, supported_tags)
232
+ if cache_entry is None:
233
+ return link
234
+ return cache_entry.link
235
+
236
+ def get_cache_entry(
237
+ self,
238
+ link: Link,
239
+ package_name: Optional[str],
240
+ supported_tags: List[Tag],
241
+ ) -> Optional[CacheEntry]:
242
+ """Returns a CacheEntry with a link to a cached item if it exists or
243
+ None. The cache entry indicates if the item was found in the persistent
244
+ or ephemeral cache.
245
+ """
246
+ retval = self._wheel_cache.get(
247
+ link=link,
248
+ package_name=package_name,
249
+ supported_tags=supported_tags,
250
+ )
251
+ if retval is not link:
252
+ return CacheEntry(retval, persistent=True)
253
+
254
+ retval = self._ephem_cache.get(
255
+ link=link,
256
+ package_name=package_name,
257
+ supported_tags=supported_tags,
258
+ )
259
+ if retval is not link:
260
+ return CacheEntry(retval, persistent=False)
261
+
262
+ return None
263
+
264
+ @staticmethod
265
+ def record_download_origin(cache_dir: str, download_info: DirectUrl) -> None:
266
+ origin_path = Path(cache_dir) / ORIGIN_JSON_NAME
267
+ if origin_path.exists():
268
+ try:
269
+ origin = DirectUrl.from_json(origin_path.read_text(encoding="utf-8"))
270
+ except Exception as e:
271
+ logger.warning(
272
+ "Could not read origin file %s in cache entry (%s). "
273
+ "Will attempt to overwrite it.",
274
+ origin_path,
275
+ e,
276
+ )
277
+ else:
278
+ # TODO: use DirectUrl.equivalent when
279
+ # https://github.com/pypa/pip/pull/10564 is merged.
280
+ if origin.url != download_info.url:
281
+ logger.warning(
282
+ "Origin URL %s in cache entry %s does not match download URL "
283
+ "%s. This is likely a pip bug or a cache corruption issue. "
284
+ "Will overwrite it with the new value.",
285
+ origin.url,
286
+ cache_dir,
287
+ download_info.url,
288
+ )
289
+ origin_path.write_text(download_info.to_json(), encoding="utf-8")
python_embeded/Lib/site-packages/pip/_internal/cli/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """Subpackage containing all of pip's command line interface related code"""
2
+
3
+ # This file intentionally does not import submodules
python_embeded/Lib/site-packages/pip/_internal/cli/autocompletion.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Logic that powers autocompletion installed by ``pip completion``."""
2
+
3
+ import optparse
4
+ import os
5
+ import sys
6
+ from itertools import chain
7
+ from typing import Any, Iterable, List, Optional
8
+
9
+ from pip._internal.cli.main_parser import create_main_parser
10
+ from pip._internal.commands import commands_dict, create_command
11
+ from pip._internal.metadata import get_default_environment
12
+
13
+
14
+ def autocomplete() -> None:
15
+ """Entry Point for completion of main and subcommand options."""
16
+ # Don't complete if user hasn't sourced bash_completion file.
17
+ if "PIP_AUTO_COMPLETE" not in os.environ:
18
+ return
19
+ # Don't complete if autocompletion environment variables
20
+ # are not present
21
+ if not os.environ.get("COMP_WORDS") or not os.environ.get("COMP_CWORD"):
22
+ return
23
+ cwords = os.environ["COMP_WORDS"].split()[1:]
24
+ cword = int(os.environ["COMP_CWORD"])
25
+ try:
26
+ current = cwords[cword - 1]
27
+ except IndexError:
28
+ current = ""
29
+
30
+ parser = create_main_parser()
31
+ subcommands = list(commands_dict)
32
+ options = []
33
+
34
+ # subcommand
35
+ subcommand_name: Optional[str] = None
36
+ for word in cwords:
37
+ if word in subcommands:
38
+ subcommand_name = word
39
+ break
40
+ # subcommand options
41
+ if subcommand_name is not None:
42
+ # special case: 'help' subcommand has no options
43
+ if subcommand_name == "help":
44
+ sys.exit(1)
45
+ # special case: list locally installed dists for show and uninstall
46
+ should_list_installed = not current.startswith("-") and subcommand_name in [
47
+ "show",
48
+ "uninstall",
49
+ ]
50
+ if should_list_installed:
51
+ env = get_default_environment()
52
+ lc = current.lower()
53
+ installed = [
54
+ dist.canonical_name
55
+ for dist in env.iter_installed_distributions(local_only=True)
56
+ if dist.canonical_name.startswith(lc)
57
+ and dist.canonical_name not in cwords[1:]
58
+ ]
59
+ # if there are no dists installed, fall back to option completion
60
+ if installed:
61
+ for dist in installed:
62
+ print(dist)
63
+ sys.exit(1)
64
+
65
+ should_list_installables = (
66
+ not current.startswith("-") and subcommand_name == "install"
67
+ )
68
+ if should_list_installables:
69
+ for path in auto_complete_paths(current, "path"):
70
+ print(path)
71
+ sys.exit(1)
72
+
73
+ subcommand = create_command(subcommand_name)
74
+
75
+ for opt in subcommand.parser.option_list_all:
76
+ if opt.help != optparse.SUPPRESS_HELP:
77
+ options += [
78
+ (opt_str, opt.nargs) for opt_str in opt._long_opts + opt._short_opts
79
+ ]
80
+
81
+ # filter out previously specified options from available options
82
+ prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]]
83
+ options = [(x, v) for (x, v) in options if x not in prev_opts]
84
+ # filter options by current input
85
+ options = [(k, v) for k, v in options if k.startswith(current)]
86
+ # get completion type given cwords and available subcommand options
87
+ completion_type = get_path_completion_type(
88
+ cwords,
89
+ cword,
90
+ subcommand.parser.option_list_all,
91
+ )
92
+ # get completion files and directories if ``completion_type`` is
93
+ # ``<file>``, ``<dir>`` or ``<path>``
94
+ if completion_type:
95
+ paths = auto_complete_paths(current, completion_type)
96
+ options = [(path, 0) for path in paths]
97
+ for option in options:
98
+ opt_label = option[0]
99
+ # append '=' to options which require args
100
+ if option[1] and option[0][:2] == "--":
101
+ opt_label += "="
102
+ print(opt_label)
103
+ else:
104
+ # show main parser options only when necessary
105
+
106
+ opts = [i.option_list for i in parser.option_groups]
107
+ opts.append(parser.option_list)
108
+ flattened_opts = chain.from_iterable(opts)
109
+ if current.startswith("-"):
110
+ for opt in flattened_opts:
111
+ if opt.help != optparse.SUPPRESS_HELP:
112
+ subcommands += opt._long_opts + opt._short_opts
113
+ else:
114
+ # get completion type given cwords and all available options
115
+ completion_type = get_path_completion_type(cwords, cword, flattened_opts)
116
+ if completion_type:
117
+ subcommands = list(auto_complete_paths(current, completion_type))
118
+
119
+ print(" ".join([x for x in subcommands if x.startswith(current)]))
120
+ sys.exit(1)
121
+
122
+
123
+ def get_path_completion_type(
124
+ cwords: List[str], cword: int, opts: Iterable[Any]
125
+ ) -> Optional[str]:
126
+ """Get the type of path completion (``file``, ``dir``, ``path`` or None)
127
+
128
+ :param cwords: same as the environmental variable ``COMP_WORDS``
129
+ :param cword: same as the environmental variable ``COMP_CWORD``
130
+ :param opts: The available options to check
131
+ :return: path completion type (``file``, ``dir``, ``path`` or None)
132
+ """
133
+ if cword < 2 or not cwords[cword - 2].startswith("-"):
134
+ return None
135
+ for opt in opts:
136
+ if opt.help == optparse.SUPPRESS_HELP:
137
+ continue
138
+ for o in str(opt).split("/"):
139
+ if cwords[cword - 2].split("=")[0] == o:
140
+ if not opt.metavar or any(
141
+ x in ("path", "file", "dir") for x in opt.metavar.split("/")
142
+ ):
143
+ return opt.metavar
144
+ return None
145
+
146
+
147
+ def auto_complete_paths(current: str, completion_type: str) -> Iterable[str]:
148
+ """If ``completion_type`` is ``file`` or ``path``, list all regular files
149
+ and directories starting with ``current``; otherwise only list directories
150
+ starting with ``current``.
151
+
152
+ :param current: The word to be completed
153
+ :param completion_type: path completion type(``file``, ``path`` or ``dir``)
154
+ :return: A generator of regular files and/or directories
155
+ """
156
+ directory, filename = os.path.split(current)
157
+ current_path = os.path.abspath(directory)
158
+ # Don't complete paths if they can't be accessed
159
+ if not os.access(current_path, os.R_OK):
160
+ return
161
+ filename = os.path.normcase(filename)
162
+ # list all files that start with ``filename``
163
+ file_list = (
164
+ x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)
165
+ )
166
+ for f in file_list:
167
+ opt = os.path.join(current_path, f)
168
+ comp_file = os.path.normcase(os.path.join(directory, f))
169
+ # complete regular files when there is not ``<dir>`` after option
170
+ # complete directories when there is ``<file>``, ``<path>`` or
171
+ # ``<dir>``after option
172
+ if completion_type != "dir" and os.path.isfile(opt):
173
+ yield comp_file
174
+ elif os.path.isdir(opt):
175
+ yield os.path.join(comp_file, "")
python_embeded/Lib/site-packages/pip/_internal/cli/base_command.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 List, Optional, Tuple
11
+
12
+ from pip._vendor.rich import reconfigure
13
+ from pip._vendor.rich import traceback as rich_traceback
14
+
15
+ from pip._internal.cli import cmdoptions
16
+ from pip._internal.cli.command_context import CommandContextMixIn
17
+ from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
18
+ from pip._internal.cli.status_codes import (
19
+ ERROR,
20
+ PREVIOUS_BUILD_DIR_ERROR,
21
+ UNKNOWN_ERROR,
22
+ VIRTUALENV_NOT_FOUND,
23
+ )
24
+ from pip._internal.exceptions import (
25
+ BadCommand,
26
+ CommandError,
27
+ DiagnosticPipError,
28
+ InstallationError,
29
+ NetworkConnectionError,
30
+ PreviousBuildDirError,
31
+ )
32
+ from pip._internal.utils.filesystem import check_path_owner
33
+ from pip._internal.utils.logging import BrokenStdoutLoggingError, setup_logging
34
+ from pip._internal.utils.misc import get_prog, normalize_path
35
+ from pip._internal.utils.temp_dir import TempDirectoryTypeRegistry as TempDirRegistry
36
+ from pip._internal.utils.temp_dir import global_tempdir_manager, tempdir_registry
37
+ from pip._internal.utils.virtualenv import running_under_virtualenv
38
+
39
+ __all__ = ["Command"]
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+
44
+ class Command(CommandContextMixIn):
45
+ usage: str = ""
46
+ ignore_require_venv: bool = False
47
+
48
+ def __init__(self, name: str, summary: str, isolated: bool = False) -> None:
49
+ super().__init__()
50
+
51
+ self.name = name
52
+ self.summary = summary
53
+ self.parser = ConfigOptionParser(
54
+ usage=self.usage,
55
+ prog=f"{get_prog()} {name}",
56
+ formatter=UpdatingDefaultsHelpFormatter(),
57
+ add_help_option=False,
58
+ name=name,
59
+ description=self.__doc__,
60
+ isolated=isolated,
61
+ )
62
+
63
+ self.tempdir_registry: Optional[TempDirRegistry] = None
64
+
65
+ # Commands should add options to this option group
66
+ optgroup_name = f"{self.name.capitalize()} Options"
67
+ self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)
68
+
69
+ # Add the general options
70
+ gen_opts = cmdoptions.make_option_group(
71
+ cmdoptions.general_group,
72
+ self.parser,
73
+ )
74
+ self.parser.add_option_group(gen_opts)
75
+
76
+ self.add_options()
77
+
78
+ def add_options(self) -> None:
79
+ pass
80
+
81
+ def handle_pip_version_check(self, options: Values) -> None:
82
+ """
83
+ This is a no-op so that commands by default do not do the pip version
84
+ check.
85
+ """
86
+ # Make sure we do the pip version check if the index_group options
87
+ # are present.
88
+ assert not hasattr(options, "no_index")
89
+
90
+ def run(self, options: Values, args: List[str]) -> int:
91
+ raise NotImplementedError
92
+
93
+ def _run_wrapper(self, level_number: int, options: Values, args: List[str]) -> int:
94
+ def _inner_run() -> int:
95
+ try:
96
+ return self.run(options, args)
97
+ finally:
98
+ self.handle_pip_version_check(options)
99
+
100
+ if options.debug_mode:
101
+ rich_traceback.install(show_locals=True)
102
+ return _inner_run()
103
+
104
+ try:
105
+ status = _inner_run()
106
+ assert isinstance(status, int)
107
+ return status
108
+ except DiagnosticPipError as exc:
109
+ logger.error("%s", exc, extra={"rich": True})
110
+ logger.debug("Exception information:", exc_info=True)
111
+
112
+ return ERROR
113
+ except PreviousBuildDirError as exc:
114
+ logger.critical(str(exc))
115
+ logger.debug("Exception information:", exc_info=True)
116
+
117
+ return PREVIOUS_BUILD_DIR_ERROR
118
+ except (
119
+ InstallationError,
120
+ BadCommand,
121
+ NetworkConnectionError,
122
+ ) as exc:
123
+ logger.critical(str(exc))
124
+ logger.debug("Exception information:", exc_info=True)
125
+
126
+ return ERROR
127
+ except CommandError as exc:
128
+ logger.critical("%s", exc)
129
+ logger.debug("Exception information:", exc_info=True)
130
+
131
+ return ERROR
132
+ except BrokenStdoutLoggingError:
133
+ # Bypass our logger and write any remaining messages to
134
+ # stderr because stdout no longer works.
135
+ print("ERROR: Pipe to stdout was broken", file=sys.stderr)
136
+ if level_number <= logging.DEBUG:
137
+ traceback.print_exc(file=sys.stderr)
138
+
139
+ return ERROR
140
+ except KeyboardInterrupt:
141
+ logger.critical("Operation cancelled by user")
142
+ logger.debug("Exception information:", exc_info=True)
143
+
144
+ return ERROR
145
+ except BaseException:
146
+ logger.critical("Exception:", exc_info=True)
147
+
148
+ return UNKNOWN_ERROR
149
+
150
+ def parse_args(self, args: List[str]) -> Tuple[Values, List[str]]:
151
+ # factored out for testability
152
+ return self.parser.parse_args(args)
153
+
154
+ def main(self, args: List[str]) -> int:
155
+ try:
156
+ with self.main_context():
157
+ return self._main(args)
158
+ finally:
159
+ logging.shutdown()
160
+
161
+ def _main(self, args: List[str]) -> int:
162
+ # We must initialize this before the tempdir manager, otherwise the
163
+ # configuration would not be accessible by the time we clean up the
164
+ # tempdir manager.
165
+ self.tempdir_registry = self.enter_context(tempdir_registry())
166
+ # Intentionally set as early as possible so globally-managed temporary
167
+ # directories are available to the rest of the code.
168
+ self.enter_context(global_tempdir_manager())
169
+
170
+ options, args = self.parse_args(args)
171
+
172
+ # Set verbosity so that it can be used elsewhere.
173
+ self.verbosity = options.verbose - options.quiet
174
+ if options.debug_mode:
175
+ self.verbosity = 2
176
+
177
+ reconfigure(no_color=options.no_color)
178
+ level_number = setup_logging(
179
+ verbosity=self.verbosity,
180
+ no_color=options.no_color,
181
+ user_log_file=options.log,
182
+ )
183
+
184
+ always_enabled_features = set(options.features_enabled) & set(
185
+ cmdoptions.ALWAYS_ENABLED_FEATURES
186
+ )
187
+ if always_enabled_features:
188
+ logger.warning(
189
+ "The following features are always enabled: %s. ",
190
+ ", ".join(sorted(always_enabled_features)),
191
+ )
192
+
193
+ # Make sure that the --python argument isn't specified after the
194
+ # subcommand. We can tell, because if --python was specified,
195
+ # we should only reach this point if we're running in the created
196
+ # subprocess, which has the _PIP_RUNNING_IN_SUBPROCESS environment
197
+ # variable set.
198
+ if options.python and "_PIP_RUNNING_IN_SUBPROCESS" not in os.environ:
199
+ logger.critical(
200
+ "The --python option must be placed before the pip subcommand name"
201
+ )
202
+ sys.exit(ERROR)
203
+
204
+ # TODO: Try to get these passing down from the command?
205
+ # without resorting to os.environ to hold these.
206
+ # This also affects isolated builds and it should.
207
+
208
+ if options.no_input:
209
+ os.environ["PIP_NO_INPUT"] = "1"
210
+
211
+ if options.exists_action:
212
+ os.environ["PIP_EXISTS_ACTION"] = " ".join(options.exists_action)
213
+
214
+ if options.require_venv and not self.ignore_require_venv:
215
+ # If a venv is required check if it can really be found
216
+ if not running_under_virtualenv():
217
+ logger.critical("Could not find an activated virtualenv (required).")
218
+ sys.exit(VIRTUALENV_NOT_FOUND)
219
+
220
+ if options.cache_dir:
221
+ options.cache_dir = normalize_path(options.cache_dir)
222
+ if not check_path_owner(options.cache_dir):
223
+ logger.warning(
224
+ "The directory '%s' or its parent directory is not owned "
225
+ "or is not writable by the current user. The cache "
226
+ "has been disabled. Check the permissions and owner of "
227
+ "that directory. If executing pip with sudo, you should "
228
+ "use sudo's -H flag.",
229
+ options.cache_dir,
230
+ )
231
+ options.cache_dir = None
232
+
233
+ return self._run_wrapper(level_number, options, args)
python_embeded/Lib/site-packages/pip/_internal/cli/cmdoptions.py ADDED
@@ -0,0 +1,1133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ shared options and groups
3
+
4
+ The principle here is to define options once, but *not* instantiate them
5
+ globally. One reason being that options with action='append' can carry state
6
+ between parses. pip parses general options twice internally, and shouldn't
7
+ pass on state. To be consistent, all options will follow this design.
8
+ """
9
+
10
+ # The following comment should be removed at some point in the future.
11
+ # mypy: strict-optional=False
12
+
13
+ import importlib.util
14
+ import logging
15
+ import os
16
+ import pathlib
17
+ import textwrap
18
+ from functools import partial
19
+ from optparse import SUPPRESS_HELP, Option, OptionGroup, OptionParser, Values
20
+ from textwrap import dedent
21
+ from typing import Any, Callable, Dict, Optional, Tuple
22
+
23
+ from pip._vendor.packaging.utils import canonicalize_name
24
+
25
+ from pip._internal.cli.parser import ConfigOptionParser
26
+ from pip._internal.exceptions import CommandError
27
+ from pip._internal.locations import USER_CACHE_DIR, get_src_prefix
28
+ from pip._internal.models.format_control import FormatControl
29
+ from pip._internal.models.index import PyPI
30
+ from pip._internal.models.target_python import TargetPython
31
+ from pip._internal.utils.hashes import STRONG_HASHES
32
+ from pip._internal.utils.misc import strtobool
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ def raise_option_error(parser: OptionParser, option: Option, msg: str) -> None:
38
+ """
39
+ Raise an option parsing error using parser.error().
40
+
41
+ Args:
42
+ parser: an OptionParser instance.
43
+ option: an Option instance.
44
+ msg: the error text.
45
+ """
46
+ msg = f"{option} error: {msg}"
47
+ msg = textwrap.fill(" ".join(msg.split()))
48
+ parser.error(msg)
49
+
50
+
51
+ def make_option_group(group: Dict[str, Any], parser: ConfigOptionParser) -> OptionGroup:
52
+ """
53
+ Return an OptionGroup object
54
+ group -- assumed to be dict with 'name' and 'options' keys
55
+ parser -- an optparse Parser
56
+ """
57
+ option_group = OptionGroup(parser, group["name"])
58
+ for option in group["options"]:
59
+ option_group.add_option(option())
60
+ return option_group
61
+
62
+
63
+ def check_dist_restriction(options: Values, check_target: bool = False) -> None:
64
+ """Function for determining if custom platform options are allowed.
65
+
66
+ :param options: The OptionParser options.
67
+ :param check_target: Whether or not to check if --target is being used.
68
+ """
69
+ dist_restriction_set = any(
70
+ [
71
+ options.python_version,
72
+ options.platforms,
73
+ options.abis,
74
+ options.implementation,
75
+ ]
76
+ )
77
+
78
+ binary_only = FormatControl(set(), {":all:"})
79
+ sdist_dependencies_allowed = (
80
+ options.format_control != binary_only and not options.ignore_dependencies
81
+ )
82
+
83
+ # Installations or downloads using dist restrictions must not combine
84
+ # source distributions and dist-specific wheels, as they are not
85
+ # guaranteed to be locally compatible.
86
+ if dist_restriction_set and sdist_dependencies_allowed:
87
+ raise CommandError(
88
+ "When restricting platform and interpreter constraints using "
89
+ "--python-version, --platform, --abi, or --implementation, "
90
+ "either --no-deps must be set, or --only-binary=:all: must be "
91
+ "set and --no-binary must not be set (or must be set to "
92
+ ":none:)."
93
+ )
94
+
95
+ if check_target:
96
+ if not options.dry_run and dist_restriction_set and not options.target_dir:
97
+ raise CommandError(
98
+ "Can not use any platform or abi specific options unless "
99
+ "installing via '--target' or using '--dry-run'"
100
+ )
101
+
102
+
103
+ def _path_option_check(option: Option, opt: str, value: str) -> str:
104
+ return os.path.expanduser(value)
105
+
106
+
107
+ def _package_name_option_check(option: Option, opt: str, value: str) -> str:
108
+ return canonicalize_name(value)
109
+
110
+
111
+ class PipOption(Option):
112
+ TYPES = Option.TYPES + ("path", "package_name")
113
+ TYPE_CHECKER = Option.TYPE_CHECKER.copy()
114
+ TYPE_CHECKER["package_name"] = _package_name_option_check
115
+ TYPE_CHECKER["path"] = _path_option_check
116
+
117
+
118
+ ###########
119
+ # options #
120
+ ###########
121
+
122
+ help_: Callable[..., Option] = partial(
123
+ Option,
124
+ "-h",
125
+ "--help",
126
+ dest="help",
127
+ action="help",
128
+ help="Show help.",
129
+ )
130
+
131
+ debug_mode: Callable[..., Option] = partial(
132
+ Option,
133
+ "--debug",
134
+ dest="debug_mode",
135
+ action="store_true",
136
+ default=False,
137
+ help=(
138
+ "Let unhandled exceptions propagate outside the main subroutine, "
139
+ "instead of logging them to stderr."
140
+ ),
141
+ )
142
+
143
+ isolated_mode: Callable[..., Option] = partial(
144
+ Option,
145
+ "--isolated",
146
+ dest="isolated_mode",
147
+ action="store_true",
148
+ default=False,
149
+ help=(
150
+ "Run pip in an isolated mode, ignoring environment variables and user "
151
+ "configuration."
152
+ ),
153
+ )
154
+
155
+ require_virtualenv: Callable[..., Option] = partial(
156
+ Option,
157
+ "--require-virtualenv",
158
+ "--require-venv",
159
+ dest="require_venv",
160
+ action="store_true",
161
+ default=False,
162
+ help=(
163
+ "Allow pip to only run in a virtual environment; "
164
+ "exit with an error otherwise."
165
+ ),
166
+ )
167
+
168
+ override_externally_managed: Callable[..., Option] = partial(
169
+ Option,
170
+ "--break-system-packages",
171
+ dest="override_externally_managed",
172
+ action="store_true",
173
+ help="Allow pip to modify an EXTERNALLY-MANAGED Python installation",
174
+ )
175
+
176
+ python: Callable[..., Option] = partial(
177
+ Option,
178
+ "--python",
179
+ dest="python",
180
+ help="Run pip with the specified Python interpreter.",
181
+ )
182
+
183
+ verbose: Callable[..., Option] = partial(
184
+ Option,
185
+ "-v",
186
+ "--verbose",
187
+ dest="verbose",
188
+ action="count",
189
+ default=0,
190
+ help="Give more output. Option is additive, and can be used up to 3 times.",
191
+ )
192
+
193
+ no_color: Callable[..., Option] = partial(
194
+ Option,
195
+ "--no-color",
196
+ dest="no_color",
197
+ action="store_true",
198
+ default=False,
199
+ help="Suppress colored output.",
200
+ )
201
+
202
+ version: Callable[..., Option] = partial(
203
+ Option,
204
+ "-V",
205
+ "--version",
206
+ dest="version",
207
+ action="store_true",
208
+ help="Show version and exit.",
209
+ )
210
+
211
+ quiet: Callable[..., Option] = partial(
212
+ Option,
213
+ "-q",
214
+ "--quiet",
215
+ dest="quiet",
216
+ action="count",
217
+ default=0,
218
+ help=(
219
+ "Give less output. Option is additive, and can be used up to 3"
220
+ " times (corresponding to WARNING, ERROR, and CRITICAL logging"
221
+ " levels)."
222
+ ),
223
+ )
224
+
225
+ progress_bar: Callable[..., Option] = partial(
226
+ Option,
227
+ "--progress-bar",
228
+ dest="progress_bar",
229
+ type="choice",
230
+ choices=["on", "off", "raw"],
231
+ default="on",
232
+ help="Specify whether the progress bar should be used [on, off, raw] (default: on)",
233
+ )
234
+
235
+ log: Callable[..., Option] = partial(
236
+ PipOption,
237
+ "--log",
238
+ "--log-file",
239
+ "--local-log",
240
+ dest="log",
241
+ metavar="path",
242
+ type="path",
243
+ help="Path to a verbose appending log.",
244
+ )
245
+
246
+ no_input: Callable[..., Option] = partial(
247
+ Option,
248
+ # Don't ask for input
249
+ "--no-input",
250
+ dest="no_input",
251
+ action="store_true",
252
+ default=False,
253
+ help="Disable prompting for input.",
254
+ )
255
+
256
+ keyring_provider: Callable[..., Option] = partial(
257
+ Option,
258
+ "--keyring-provider",
259
+ dest="keyring_provider",
260
+ choices=["auto", "disabled", "import", "subprocess"],
261
+ default="auto",
262
+ help=(
263
+ "Enable the credential lookup via the keyring library if user input is allowed."
264
+ " Specify which mechanism to use [auto, disabled, import, subprocess]."
265
+ " (default: %default)"
266
+ ),
267
+ )
268
+
269
+ proxy: Callable[..., Option] = partial(
270
+ Option,
271
+ "--proxy",
272
+ dest="proxy",
273
+ type="str",
274
+ default="",
275
+ help="Specify a proxy in the form scheme://[user:passwd@]proxy.server:port.",
276
+ )
277
+
278
+ retries: Callable[..., Option] = partial(
279
+ Option,
280
+ "--retries",
281
+ dest="retries",
282
+ type="int",
283
+ default=5,
284
+ help="Maximum attempts to establish a new HTTP connection. (default: %default)",
285
+ )
286
+
287
+ resume_retries: Callable[..., Option] = partial(
288
+ Option,
289
+ "--resume-retries",
290
+ dest="resume_retries",
291
+ type="int",
292
+ default=0,
293
+ help="Maximum attempts to resume or restart an incomplete download. "
294
+ "(default: %default)",
295
+ )
296
+
297
+ timeout: Callable[..., Option] = partial(
298
+ Option,
299
+ "--timeout",
300
+ "--default-timeout",
301
+ metavar="sec",
302
+ dest="timeout",
303
+ type="float",
304
+ default=15,
305
+ help="Set the socket timeout (default %default seconds).",
306
+ )
307
+
308
+
309
+ def exists_action() -> Option:
310
+ return Option(
311
+ # Option when path already exist
312
+ "--exists-action",
313
+ dest="exists_action",
314
+ type="choice",
315
+ choices=["s", "i", "w", "b", "a"],
316
+ default=[],
317
+ action="append",
318
+ metavar="action",
319
+ help="Default action when a path already exists: "
320
+ "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.",
321
+ )
322
+
323
+
324
+ cert: Callable[..., Option] = partial(
325
+ PipOption,
326
+ "--cert",
327
+ dest="cert",
328
+ type="path",
329
+ metavar="path",
330
+ help=(
331
+ "Path to PEM-encoded CA certificate bundle. "
332
+ "If provided, overrides the default. "
333
+ "See 'SSL Certificate Verification' in pip documentation "
334
+ "for more information."
335
+ ),
336
+ )
337
+
338
+ client_cert: Callable[..., Option] = partial(
339
+ PipOption,
340
+ "--client-cert",
341
+ dest="client_cert",
342
+ type="path",
343
+ default=None,
344
+ metavar="path",
345
+ help="Path to SSL client certificate, a single file containing the "
346
+ "private key and the certificate in PEM format.",
347
+ )
348
+
349
+ index_url: Callable[..., Option] = partial(
350
+ Option,
351
+ "-i",
352
+ "--index-url",
353
+ "--pypi-url",
354
+ dest="index_url",
355
+ metavar="URL",
356
+ default=PyPI.simple_url,
357
+ help="Base URL of the Python Package Index (default %default). "
358
+ "This should point to a repository compliant with PEP 503 "
359
+ "(the simple repository API) or a local directory laid out "
360
+ "in the same format.",
361
+ )
362
+
363
+
364
+ def extra_index_url() -> Option:
365
+ return Option(
366
+ "--extra-index-url",
367
+ dest="extra_index_urls",
368
+ metavar="URL",
369
+ action="append",
370
+ default=[],
371
+ help="Extra URLs of package indexes to use in addition to "
372
+ "--index-url. Should follow the same rules as "
373
+ "--index-url.",
374
+ )
375
+
376
+
377
+ no_index: Callable[..., Option] = partial(
378
+ Option,
379
+ "--no-index",
380
+ dest="no_index",
381
+ action="store_true",
382
+ default=False,
383
+ help="Ignore package index (only looking at --find-links URLs instead).",
384
+ )
385
+
386
+
387
+ def find_links() -> Option:
388
+ return Option(
389
+ "-f",
390
+ "--find-links",
391
+ dest="find_links",
392
+ action="append",
393
+ default=[],
394
+ metavar="url",
395
+ help="If a URL or path to an html file, then parse for links to "
396
+ "archives such as sdist (.tar.gz) or wheel (.whl) files. "
397
+ "If a local path or file:// URL that's a directory, "
398
+ "then look for archives in the directory listing. "
399
+ "Links to VCS project URLs are not supported.",
400
+ )
401
+
402
+
403
+ def trusted_host() -> Option:
404
+ return Option(
405
+ "--trusted-host",
406
+ dest="trusted_hosts",
407
+ action="append",
408
+ metavar="HOSTNAME",
409
+ default=[],
410
+ help="Mark this host or host:port pair as trusted, even though it "
411
+ "does not have valid or any HTTPS.",
412
+ )
413
+
414
+
415
+ def constraints() -> Option:
416
+ return Option(
417
+ "-c",
418
+ "--constraint",
419
+ dest="constraints",
420
+ action="append",
421
+ default=[],
422
+ metavar="file",
423
+ help="Constrain versions using the given constraints file. "
424
+ "This option can be used multiple times.",
425
+ )
426
+
427
+
428
+ def requirements() -> Option:
429
+ return Option(
430
+ "-r",
431
+ "--requirement",
432
+ dest="requirements",
433
+ action="append",
434
+ default=[],
435
+ metavar="file",
436
+ help="Install from the given requirements file. "
437
+ "This option can be used multiple times.",
438
+ )
439
+
440
+
441
+ def editable() -> Option:
442
+ return Option(
443
+ "-e",
444
+ "--editable",
445
+ dest="editables",
446
+ action="append",
447
+ default=[],
448
+ metavar="path/url",
449
+ help=(
450
+ "Install a project in editable mode (i.e. setuptools "
451
+ '"develop mode") from a local project path or a VCS url.'
452
+ ),
453
+ )
454
+
455
+
456
+ def _handle_src(option: Option, opt_str: str, value: str, parser: OptionParser) -> None:
457
+ value = os.path.abspath(value)
458
+ setattr(parser.values, option.dest, value)
459
+
460
+
461
+ src: Callable[..., Option] = partial(
462
+ PipOption,
463
+ "--src",
464
+ "--source",
465
+ "--source-dir",
466
+ "--source-directory",
467
+ dest="src_dir",
468
+ type="path",
469
+ metavar="dir",
470
+ default=get_src_prefix(),
471
+ action="callback",
472
+ callback=_handle_src,
473
+ help="Directory to check out editable projects into. "
474
+ 'The default in a virtualenv is "<venv path>/src". '
475
+ 'The default for global installs is "<current dir>/src".',
476
+ )
477
+
478
+
479
+ def _get_format_control(values: Values, option: Option) -> Any:
480
+ """Get a format_control object."""
481
+ return getattr(values, option.dest)
482
+
483
+
484
+ def _handle_no_binary(
485
+ option: Option, opt_str: str, value: str, parser: OptionParser
486
+ ) -> None:
487
+ existing = _get_format_control(parser.values, option)
488
+ FormatControl.handle_mutual_excludes(
489
+ value,
490
+ existing.no_binary,
491
+ existing.only_binary,
492
+ )
493
+
494
+
495
+ def _handle_only_binary(
496
+ option: Option, opt_str: str, value: str, parser: OptionParser
497
+ ) -> None:
498
+ existing = _get_format_control(parser.values, option)
499
+ FormatControl.handle_mutual_excludes(
500
+ value,
501
+ existing.only_binary,
502
+ existing.no_binary,
503
+ )
504
+
505
+
506
+ def no_binary() -> Option:
507
+ format_control = FormatControl(set(), set())
508
+ return Option(
509
+ "--no-binary",
510
+ dest="format_control",
511
+ action="callback",
512
+ callback=_handle_no_binary,
513
+ type="str",
514
+ default=format_control,
515
+ help="Do not use binary packages. Can be supplied multiple times, and "
516
+ 'each time adds to the existing value. Accepts either ":all:" to '
517
+ 'disable all binary packages, ":none:" to empty the set (notice '
518
+ "the colons), or one or more package names with commas between "
519
+ "them (no colons). Note that some packages are tricky to compile "
520
+ "and may fail to install when this option is used on them.",
521
+ )
522
+
523
+
524
+ def only_binary() -> Option:
525
+ format_control = FormatControl(set(), set())
526
+ return Option(
527
+ "--only-binary",
528
+ dest="format_control",
529
+ action="callback",
530
+ callback=_handle_only_binary,
531
+ type="str",
532
+ default=format_control,
533
+ help="Do not use source packages. Can be supplied multiple times, and "
534
+ 'each time adds to the existing value. Accepts either ":all:" to '
535
+ 'disable all source packages, ":none:" to empty the set, or one '
536
+ "or more package names with commas between them. Packages "
537
+ "without binary distributions will fail to install when this "
538
+ "option is used on them.",
539
+ )
540
+
541
+
542
+ platforms: Callable[..., Option] = partial(
543
+ Option,
544
+ "--platform",
545
+ dest="platforms",
546
+ metavar="platform",
547
+ action="append",
548
+ default=None,
549
+ help=(
550
+ "Only use wheels compatible with <platform>. Defaults to the "
551
+ "platform of the running system. Use this option multiple times to "
552
+ "specify multiple platforms supported by the target interpreter."
553
+ ),
554
+ )
555
+
556
+
557
+ # This was made a separate function for unit-testing purposes.
558
+ def _convert_python_version(value: str) -> Tuple[Tuple[int, ...], Optional[str]]:
559
+ """
560
+ Convert a version string like "3", "37", or "3.7.3" into a tuple of ints.
561
+
562
+ :return: A 2-tuple (version_info, error_msg), where `error_msg` is
563
+ non-None if and only if there was a parsing error.
564
+ """
565
+ if not value:
566
+ # The empty string is the same as not providing a value.
567
+ return (None, None)
568
+
569
+ parts = value.split(".")
570
+ if len(parts) > 3:
571
+ return ((), "at most three version parts are allowed")
572
+
573
+ if len(parts) == 1:
574
+ # Then we are in the case of "3" or "37".
575
+ value = parts[0]
576
+ if len(value) > 1:
577
+ parts = [value[0], value[1:]]
578
+
579
+ try:
580
+ version_info = tuple(int(part) for part in parts)
581
+ except ValueError:
582
+ return ((), "each version part must be an integer")
583
+
584
+ return (version_info, None)
585
+
586
+
587
+ def _handle_python_version(
588
+ option: Option, opt_str: str, value: str, parser: OptionParser
589
+ ) -> None:
590
+ """
591
+ Handle a provided --python-version value.
592
+ """
593
+ version_info, error_msg = _convert_python_version(value)
594
+ if error_msg is not None:
595
+ msg = f"invalid --python-version value: {value!r}: {error_msg}"
596
+ raise_option_error(parser, option=option, msg=msg)
597
+
598
+ parser.values.python_version = version_info
599
+
600
+
601
+ python_version: Callable[..., Option] = partial(
602
+ Option,
603
+ "--python-version",
604
+ dest="python_version",
605
+ metavar="python_version",
606
+ action="callback",
607
+ callback=_handle_python_version,
608
+ type="str",
609
+ default=None,
610
+ help=dedent(
611
+ """\
612
+ The Python interpreter version to use for wheel and "Requires-Python"
613
+ compatibility checks. Defaults to a version derived from the running
614
+ interpreter. The version can be specified using up to three dot-separated
615
+ integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor
616
+ version can also be given as a string without dots (e.g. "37" for 3.7.0).
617
+ """
618
+ ),
619
+ )
620
+
621
+
622
+ implementation: Callable[..., Option] = partial(
623
+ Option,
624
+ "--implementation",
625
+ dest="implementation",
626
+ metavar="implementation",
627
+ default=None,
628
+ help=(
629
+ "Only use wheels compatible with Python "
630
+ "implementation <implementation>, e.g. 'pp', 'jy', 'cp', "
631
+ " or 'ip'. If not specified, then the current "
632
+ "interpreter implementation is used. Use 'py' to force "
633
+ "implementation-agnostic wheels."
634
+ ),
635
+ )
636
+
637
+
638
+ abis: Callable[..., Option] = partial(
639
+ Option,
640
+ "--abi",
641
+ dest="abis",
642
+ metavar="abi",
643
+ action="append",
644
+ default=None,
645
+ help=(
646
+ "Only use wheels compatible with Python abi <abi>, e.g. 'pypy_41'. "
647
+ "If not specified, then the current interpreter abi tag is used. "
648
+ "Use this option multiple times to specify multiple abis supported "
649
+ "by the target interpreter. Generally you will need to specify "
650
+ "--implementation, --platform, and --python-version when using this "
651
+ "option."
652
+ ),
653
+ )
654
+
655
+
656
+ def add_target_python_options(cmd_opts: OptionGroup) -> None:
657
+ cmd_opts.add_option(platforms())
658
+ cmd_opts.add_option(python_version())
659
+ cmd_opts.add_option(implementation())
660
+ cmd_opts.add_option(abis())
661
+
662
+
663
+ def make_target_python(options: Values) -> TargetPython:
664
+ target_python = TargetPython(
665
+ platforms=options.platforms,
666
+ py_version_info=options.python_version,
667
+ abis=options.abis,
668
+ implementation=options.implementation,
669
+ )
670
+
671
+ return target_python
672
+
673
+
674
+ def prefer_binary() -> Option:
675
+ return Option(
676
+ "--prefer-binary",
677
+ dest="prefer_binary",
678
+ action="store_true",
679
+ default=False,
680
+ help=(
681
+ "Prefer binary packages over source packages, even if the "
682
+ "source packages are newer."
683
+ ),
684
+ )
685
+
686
+
687
+ cache_dir: Callable[..., Option] = partial(
688
+ PipOption,
689
+ "--cache-dir",
690
+ dest="cache_dir",
691
+ default=USER_CACHE_DIR,
692
+ metavar="dir",
693
+ type="path",
694
+ help="Store the cache data in <dir>.",
695
+ )
696
+
697
+
698
+ def _handle_no_cache_dir(
699
+ option: Option, opt: str, value: str, parser: OptionParser
700
+ ) -> None:
701
+ """
702
+ Process a value provided for the --no-cache-dir option.
703
+
704
+ This is an optparse.Option callback for the --no-cache-dir option.
705
+ """
706
+ # The value argument will be None if --no-cache-dir is passed via the
707
+ # command-line, since the option doesn't accept arguments. However,
708
+ # the value can be non-None if the option is triggered e.g. by an
709
+ # environment variable, like PIP_NO_CACHE_DIR=true.
710
+ if value is not None:
711
+ # Then parse the string value to get argument error-checking.
712
+ try:
713
+ strtobool(value)
714
+ except ValueError as exc:
715
+ raise_option_error(parser, option=option, msg=str(exc))
716
+
717
+ # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool()
718
+ # converted to 0 (like "false" or "no") caused cache_dir to be disabled
719
+ # rather than enabled (logic would say the latter). Thus, we disable
720
+ # the cache directory not just on values that parse to True, but (for
721
+ # backwards compatibility reasons) also on values that parse to False.
722
+ # In other words, always set it to False if the option is provided in
723
+ # some (valid) form.
724
+ parser.values.cache_dir = False
725
+
726
+
727
+ no_cache: Callable[..., Option] = partial(
728
+ Option,
729
+ "--no-cache-dir",
730
+ dest="cache_dir",
731
+ action="callback",
732
+ callback=_handle_no_cache_dir,
733
+ help="Disable the cache.",
734
+ )
735
+
736
+ no_deps: Callable[..., Option] = partial(
737
+ Option,
738
+ "--no-deps",
739
+ "--no-dependencies",
740
+ dest="ignore_dependencies",
741
+ action="store_true",
742
+ default=False,
743
+ help="Don't install package dependencies.",
744
+ )
745
+
746
+
747
+ def _handle_dependency_group(
748
+ option: Option, opt: str, value: str, parser: OptionParser
749
+ ) -> None:
750
+ """
751
+ Process a value provided for the --group option.
752
+
753
+ Splits on the rightmost ":", and validates that the path (if present) ends
754
+ in `pyproject.toml`. Defaults the path to `pyproject.toml` when one is not given.
755
+
756
+ `:` cannot appear in dependency group names, so this is a safe and simple parse.
757
+
758
+ This is an optparse.Option callback for the dependency_groups option.
759
+ """
760
+ path, sep, groupname = value.rpartition(":")
761
+ if not sep:
762
+ path = "pyproject.toml"
763
+ else:
764
+ # check for 'pyproject.toml' filenames using pathlib
765
+ if pathlib.PurePath(path).name != "pyproject.toml":
766
+ msg = "group paths use 'pyproject.toml' filenames"
767
+ raise_option_error(parser, option=option, msg=msg)
768
+
769
+ parser.values.dependency_groups.append((path, groupname))
770
+
771
+
772
+ dependency_groups: Callable[..., Option] = partial(
773
+ Option,
774
+ "--group",
775
+ dest="dependency_groups",
776
+ default=[],
777
+ type=str,
778
+ action="callback",
779
+ callback=_handle_dependency_group,
780
+ metavar="[path:]group",
781
+ help='Install a named dependency-group from a "pyproject.toml" file. '
782
+ 'If a path is given, the name of the file must be "pyproject.toml". '
783
+ 'Defaults to using "pyproject.toml" in the current directory.',
784
+ )
785
+
786
+ ignore_requires_python: Callable[..., Option] = partial(
787
+ Option,
788
+ "--ignore-requires-python",
789
+ dest="ignore_requires_python",
790
+ action="store_true",
791
+ help="Ignore the Requires-Python information.",
792
+ )
793
+
794
+ no_build_isolation: Callable[..., Option] = partial(
795
+ Option,
796
+ "--no-build-isolation",
797
+ dest="build_isolation",
798
+ action="store_false",
799
+ default=True,
800
+ help="Disable isolation when building a modern source distribution. "
801
+ "Build dependencies specified by PEP 518 must be already installed "
802
+ "if this option is used.",
803
+ )
804
+
805
+ check_build_deps: Callable[..., Option] = partial(
806
+ Option,
807
+ "--check-build-dependencies",
808
+ dest="check_build_deps",
809
+ action="store_true",
810
+ default=False,
811
+ help="Check the build dependencies when PEP517 is used.",
812
+ )
813
+
814
+
815
+ def _handle_no_use_pep517(
816
+ option: Option, opt: str, value: str, parser: OptionParser
817
+ ) -> None:
818
+ """
819
+ Process a value provided for the --no-use-pep517 option.
820
+
821
+ This is an optparse.Option callback for the no_use_pep517 option.
822
+ """
823
+ # Since --no-use-pep517 doesn't accept arguments, the value argument
824
+ # will be None if --no-use-pep517 is passed via the command-line.
825
+ # However, the value can be non-None if the option is triggered e.g.
826
+ # by an environment variable, for example "PIP_NO_USE_PEP517=true".
827
+ if value is not None:
828
+ msg = """A value was passed for --no-use-pep517,
829
+ probably using either the PIP_NO_USE_PEP517 environment variable
830
+ or the "no-use-pep517" config file option. Use an appropriate value
831
+ of the PIP_USE_PEP517 environment variable or the "use-pep517"
832
+ config file option instead.
833
+ """
834
+ raise_option_error(parser, option=option, msg=msg)
835
+
836
+ # If user doesn't wish to use pep517, we check if setuptools is installed
837
+ # and raise error if it is not.
838
+ packages = ("setuptools",)
839
+ if not all(importlib.util.find_spec(package) for package in packages):
840
+ msg = (
841
+ f"It is not possible to use --no-use-pep517 "
842
+ f"without {' and '.join(packages)} installed."
843
+ )
844
+ raise_option_error(parser, option=option, msg=msg)
845
+
846
+ # Otherwise, --no-use-pep517 was passed via the command-line.
847
+ parser.values.use_pep517 = False
848
+
849
+
850
+ use_pep517: Any = partial(
851
+ Option,
852
+ "--use-pep517",
853
+ dest="use_pep517",
854
+ action="store_true",
855
+ default=None,
856
+ help="Use PEP 517 for building source distributions "
857
+ "(use --no-use-pep517 to force legacy behaviour).",
858
+ )
859
+
860
+ no_use_pep517: Any = partial(
861
+ Option,
862
+ "--no-use-pep517",
863
+ dest="use_pep517",
864
+ action="callback",
865
+ callback=_handle_no_use_pep517,
866
+ default=None,
867
+ help=SUPPRESS_HELP,
868
+ )
869
+
870
+
871
+ def _handle_config_settings(
872
+ option: Option, opt_str: str, value: str, parser: OptionParser
873
+ ) -> None:
874
+ key, sep, val = value.partition("=")
875
+ if sep != "=":
876
+ parser.error(f"Arguments to {opt_str} must be of the form KEY=VAL")
877
+ dest = getattr(parser.values, option.dest)
878
+ if dest is None:
879
+ dest = {}
880
+ setattr(parser.values, option.dest, dest)
881
+ if key in dest:
882
+ if isinstance(dest[key], list):
883
+ dest[key].append(val)
884
+ else:
885
+ dest[key] = [dest[key], val]
886
+ else:
887
+ dest[key] = val
888
+
889
+
890
+ config_settings: Callable[..., Option] = partial(
891
+ Option,
892
+ "-C",
893
+ "--config-settings",
894
+ dest="config_settings",
895
+ type=str,
896
+ action="callback",
897
+ callback=_handle_config_settings,
898
+ metavar="settings",
899
+ help="Configuration settings to be passed to the PEP 517 build backend. "
900
+ "Settings take the form KEY=VALUE. Use multiple --config-settings options "
901
+ "to pass multiple keys to the backend.",
902
+ )
903
+
904
+ build_options: Callable[..., Option] = partial(
905
+ Option,
906
+ "--build-option",
907
+ dest="build_options",
908
+ metavar="options",
909
+ action="append",
910
+ help="Extra arguments to be supplied to 'setup.py bdist_wheel'.",
911
+ )
912
+
913
+ global_options: Callable[..., Option] = partial(
914
+ Option,
915
+ "--global-option",
916
+ dest="global_options",
917
+ action="append",
918
+ metavar="options",
919
+ help="Extra global options to be supplied to the setup.py "
920
+ "call before the install or bdist_wheel command.",
921
+ )
922
+
923
+ no_clean: Callable[..., Option] = partial(
924
+ Option,
925
+ "--no-clean",
926
+ action="store_true",
927
+ default=False,
928
+ help="Don't clean up build directories.",
929
+ )
930
+
931
+ pre: Callable[..., Option] = partial(
932
+ Option,
933
+ "--pre",
934
+ action="store_true",
935
+ default=False,
936
+ help="Include pre-release and development versions. By default, "
937
+ "pip only finds stable versions.",
938
+ )
939
+
940
+ json: Callable[..., Option] = partial(
941
+ Option,
942
+ "--json",
943
+ action="store_true",
944
+ default=False,
945
+ help="Output data in a machine-readable JSON format.",
946
+ )
947
+
948
+ disable_pip_version_check: Callable[..., Option] = partial(
949
+ Option,
950
+ "--disable-pip-version-check",
951
+ dest="disable_pip_version_check",
952
+ action="store_true",
953
+ default=False,
954
+ help="Don't periodically check PyPI to determine whether a new version "
955
+ "of pip is available for download. Implied with --no-index.",
956
+ )
957
+
958
+ root_user_action: Callable[..., Option] = partial(
959
+ Option,
960
+ "--root-user-action",
961
+ dest="root_user_action",
962
+ default="warn",
963
+ choices=["warn", "ignore"],
964
+ help="Action if pip is run as a root user [warn, ignore] (default: warn)",
965
+ )
966
+
967
+
968
+ def _handle_merge_hash(
969
+ option: Option, opt_str: str, value: str, parser: OptionParser
970
+ ) -> None:
971
+ """Given a value spelled "algo:digest", append the digest to a list
972
+ pointed to in a dict by the algo name."""
973
+ if not parser.values.hashes:
974
+ parser.values.hashes = {}
975
+ try:
976
+ algo, digest = value.split(":", 1)
977
+ except ValueError:
978
+ parser.error(
979
+ f"Arguments to {opt_str} must be a hash name "
980
+ "followed by a value, like --hash=sha256:"
981
+ "abcde..."
982
+ )
983
+ if algo not in STRONG_HASHES:
984
+ parser.error(
985
+ "Allowed hash algorithms for {} are {}.".format(
986
+ opt_str, ", ".join(STRONG_HASHES)
987
+ )
988
+ )
989
+ parser.values.hashes.setdefault(algo, []).append(digest)
990
+
991
+
992
+ hash: Callable[..., Option] = partial(
993
+ Option,
994
+ "--hash",
995
+ # Hash values eventually end up in InstallRequirement.hashes due to
996
+ # __dict__ copying in process_line().
997
+ dest="hashes",
998
+ action="callback",
999
+ callback=_handle_merge_hash,
1000
+ type="string",
1001
+ help="Verify that the package's archive matches this "
1002
+ "hash before installing. Example: --hash=sha256:abcdef...",
1003
+ )
1004
+
1005
+
1006
+ require_hashes: Callable[..., Option] = partial(
1007
+ Option,
1008
+ "--require-hashes",
1009
+ dest="require_hashes",
1010
+ action="store_true",
1011
+ default=False,
1012
+ help="Require a hash to check each requirement against, for "
1013
+ "repeatable installs. This option is implied when any package in a "
1014
+ "requirements file has a --hash option.",
1015
+ )
1016
+
1017
+
1018
+ list_path: Callable[..., Option] = partial(
1019
+ PipOption,
1020
+ "--path",
1021
+ dest="path",
1022
+ type="path",
1023
+ action="append",
1024
+ help="Restrict to the specified installation path for listing "
1025
+ "packages (can be used multiple times).",
1026
+ )
1027
+
1028
+
1029
+ def check_list_path_option(options: Values) -> None:
1030
+ if options.path and (options.user or options.local):
1031
+ raise CommandError("Cannot combine '--path' with '--user' or '--local'")
1032
+
1033
+
1034
+ list_exclude: Callable[..., Option] = partial(
1035
+ PipOption,
1036
+ "--exclude",
1037
+ dest="excludes",
1038
+ action="append",
1039
+ metavar="package",
1040
+ type="package_name",
1041
+ help="Exclude specified package from the output",
1042
+ )
1043
+
1044
+
1045
+ no_python_version_warning: Callable[..., Option] = partial(
1046
+ Option,
1047
+ "--no-python-version-warning",
1048
+ dest="no_python_version_warning",
1049
+ action="store_true",
1050
+ default=False,
1051
+ help=SUPPRESS_HELP, # No-op, a hold-over from the Python 2->3 transition.
1052
+ )
1053
+
1054
+
1055
+ # Features that are now always on. A warning is printed if they are used.
1056
+ ALWAYS_ENABLED_FEATURES = [
1057
+ "truststore", # always on since 24.2
1058
+ "no-binary-enable-wheel-cache", # always on since 23.1
1059
+ ]
1060
+
1061
+ use_new_feature: Callable[..., Option] = partial(
1062
+ Option,
1063
+ "--use-feature",
1064
+ dest="features_enabled",
1065
+ metavar="feature",
1066
+ action="append",
1067
+ default=[],
1068
+ choices=[
1069
+ "fast-deps",
1070
+ ]
1071
+ + ALWAYS_ENABLED_FEATURES,
1072
+ help="Enable new functionality, that may be backward incompatible.",
1073
+ )
1074
+
1075
+ use_deprecated_feature: Callable[..., Option] = partial(
1076
+ Option,
1077
+ "--use-deprecated",
1078
+ dest="deprecated_features_enabled",
1079
+ metavar="feature",
1080
+ action="append",
1081
+ default=[],
1082
+ choices=[
1083
+ "legacy-resolver",
1084
+ "legacy-certs",
1085
+ ],
1086
+ help=("Enable deprecated functionality, that will be removed in the future."),
1087
+ )
1088
+
1089
+ ##########
1090
+ # groups #
1091
+ ##########
1092
+
1093
+ general_group: Dict[str, Any] = {
1094
+ "name": "General Options",
1095
+ "options": [
1096
+ help_,
1097
+ debug_mode,
1098
+ isolated_mode,
1099
+ require_virtualenv,
1100
+ python,
1101
+ verbose,
1102
+ version,
1103
+ quiet,
1104
+ log,
1105
+ no_input,
1106
+ keyring_provider,
1107
+ proxy,
1108
+ retries,
1109
+ timeout,
1110
+ exists_action,
1111
+ trusted_host,
1112
+ cert,
1113
+ client_cert,
1114
+ cache_dir,
1115
+ no_cache,
1116
+ disable_pip_version_check,
1117
+ no_color,
1118
+ no_python_version_warning,
1119
+ use_new_feature,
1120
+ use_deprecated_feature,
1121
+ resume_retries,
1122
+ ],
1123
+ }
1124
+
1125
+ index_group: Dict[str, Any] = {
1126
+ "name": "Package Index Options",
1127
+ "options": [
1128
+ index_url,
1129
+ extra_index_url,
1130
+ no_index,
1131
+ find_links,
1132
+ ],
1133
+ }
python_embeded/Lib/site-packages/pip/_internal/cli/command_context.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import ExitStack, contextmanager
2
+ from typing import ContextManager, Generator, TypeVar
3
+
4
+ _T = TypeVar("_T", covariant=True)
5
+
6
+
7
+ class CommandContextMixIn:
8
+ def __init__(self) -> None:
9
+ super().__init__()
10
+ self._in_main_context = False
11
+ self._main_context = ExitStack()
12
+
13
+ @contextmanager
14
+ def main_context(self) -> Generator[None, None, None]:
15
+ assert not self._in_main_context
16
+
17
+ self._in_main_context = True
18
+ try:
19
+ with self._main_context:
20
+ yield
21
+ finally:
22
+ self._in_main_context = False
23
+
24
+ def enter_context(self, context_provider: ContextManager[_T]) -> _T:
25
+ assert self._in_main_context
26
+
27
+ return self._main_context.enter_context(context_provider)
python_embeded/Lib/site-packages/pip/_internal/cli/index_command.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Contains command classes which may interact with an index / the network.
3
+
4
+ Unlike its sister module, req_command, this module still uses lazy imports
5
+ so commands which don't always hit the network (e.g. list w/o --outdated or
6
+ --uptodate) don't need waste time importing PipSession and friends.
7
+ """
8
+
9
+ import logging
10
+ import os
11
+ import sys
12
+ from functools import lru_cache
13
+ from optparse import Values
14
+ from typing import TYPE_CHECKING, List, Optional
15
+
16
+ from pip._vendor import certifi
17
+
18
+ from pip._internal.cli.base_command import Command
19
+ from pip._internal.cli.command_context import CommandContextMixIn
20
+
21
+ if TYPE_CHECKING:
22
+ from ssl import SSLContext
23
+
24
+ from pip._internal.network.session import PipSession
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ @lru_cache
30
+ def _create_truststore_ssl_context() -> Optional["SSLContext"]:
31
+ if sys.version_info < (3, 10):
32
+ logger.debug("Disabling truststore because Python version isn't 3.10+")
33
+ return None
34
+
35
+ try:
36
+ import ssl
37
+ except ImportError:
38
+ logger.warning("Disabling truststore since ssl support is missing")
39
+ return None
40
+
41
+ try:
42
+ from pip._vendor import truststore
43
+ except ImportError:
44
+ logger.warning("Disabling truststore because platform isn't supported")
45
+ return None
46
+
47
+ ctx = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
48
+ ctx.load_verify_locations(certifi.where())
49
+ return ctx
50
+
51
+
52
+ class SessionCommandMixin(CommandContextMixIn):
53
+ """
54
+ A class mixin for command classes needing _build_session().
55
+ """
56
+
57
+ def __init__(self) -> None:
58
+ super().__init__()
59
+ self._session: Optional[PipSession] = None
60
+
61
+ @classmethod
62
+ def _get_index_urls(cls, options: Values) -> Optional[List[str]]:
63
+ """Return a list of index urls from user-provided options."""
64
+ index_urls = []
65
+ if not getattr(options, "no_index", False):
66
+ url = getattr(options, "index_url", None)
67
+ if url:
68
+ index_urls.append(url)
69
+ urls = getattr(options, "extra_index_urls", None)
70
+ if urls:
71
+ index_urls.extend(urls)
72
+ # Return None rather than an empty list
73
+ return index_urls or None
74
+
75
+ def get_default_session(self, options: Values) -> "PipSession":
76
+ """Get a default-managed session."""
77
+ if self._session is None:
78
+ self._session = self.enter_context(self._build_session(options))
79
+ # there's no type annotation on requests.Session, so it's
80
+ # automatically ContextManager[Any] and self._session becomes Any,
81
+ # then https://github.com/python/mypy/issues/7696 kicks in
82
+ assert self._session is not None
83
+ return self._session
84
+
85
+ def _build_session(
86
+ self,
87
+ options: Values,
88
+ retries: Optional[int] = None,
89
+ timeout: Optional[int] = None,
90
+ ) -> "PipSession":
91
+ from pip._internal.network.session import PipSession
92
+
93
+ cache_dir = options.cache_dir
94
+ assert not cache_dir or os.path.isabs(cache_dir)
95
+
96
+ if "legacy-certs" not in options.deprecated_features_enabled:
97
+ ssl_context = _create_truststore_ssl_context()
98
+ else:
99
+ ssl_context = None
100
+
101
+ session = PipSession(
102
+ cache=os.path.join(cache_dir, "http-v2") if cache_dir else None,
103
+ retries=retries if retries is not None else options.retries,
104
+ trusted_hosts=options.trusted_hosts,
105
+ index_urls=self._get_index_urls(options),
106
+ ssl_context=ssl_context,
107
+ )
108
+
109
+ # Handle custom ca-bundles from the user
110
+ if options.cert:
111
+ session.verify = options.cert
112
+
113
+ # Handle SSL client certificate
114
+ if options.client_cert:
115
+ session.cert = options.client_cert
116
+
117
+ # Handle timeouts
118
+ if options.timeout or timeout:
119
+ session.timeout = timeout if timeout is not None else options.timeout
120
+
121
+ # Handle configured proxies
122
+ if options.proxy:
123
+ session.proxies = {
124
+ "http": options.proxy,
125
+ "https": options.proxy,
126
+ }
127
+ session.trust_env = False
128
+ session.pip_proxy = options.proxy
129
+
130
+ # Determine if we can prompt the user for authentication or not
131
+ session.auth.prompting = not options.no_input
132
+ session.auth.keyring_provider = options.keyring_provider
133
+
134
+ return session
135
+
136
+
137
+ def _pip_self_version_check(session: "PipSession", options: Values) -> None:
138
+ from pip._internal.self_outdated_check import pip_self_version_check as check
139
+
140
+ check(session, options)
141
+
142
+
143
+ class IndexGroupCommand(Command, SessionCommandMixin):
144
+ """
145
+ Abstract base class for commands with the index_group options.
146
+
147
+ This also corresponds to the commands that permit the pip version check.
148
+ """
149
+
150
+ def handle_pip_version_check(self, options: Values) -> None:
151
+ """
152
+ Do the pip version check if not disabled.
153
+
154
+ This overrides the default behavior of not doing the check.
155
+ """
156
+ # Make sure the index_group options are present.
157
+ assert hasattr(options, "no_index")
158
+
159
+ if options.disable_pip_version_check or options.no_index:
160
+ return
161
+
162
+ try:
163
+ # Otherwise, check if we're using the latest version of pip available.
164
+ session = self._build_session(
165
+ options,
166
+ retries=0,
167
+ timeout=min(5, options.timeout),
168
+ )
169
+ with session:
170
+ _pip_self_version_check(session, options)
171
+ except Exception:
172
+ logger.warning("There was an error checking the latest version of pip.")
173
+ logger.debug("See below for error", exc_info=True)
python_embeded/Lib/site-packages/pip/_internal/cli/main.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Primary application entrypoint."""
2
+
3
+ import locale
4
+ import logging
5
+ import os
6
+ import sys
7
+ import warnings
8
+ from typing import List, Optional
9
+
10
+ from pip._internal.cli.autocompletion import autocomplete
11
+ from pip._internal.cli.main_parser import parse_command
12
+ from pip._internal.commands import create_command
13
+ from pip._internal.exceptions import PipError
14
+ from pip._internal.utils import deprecation
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ # Do not import and use main() directly! Using it directly is actively
20
+ # discouraged by pip's maintainers. The name, location and behavior of
21
+ # this function is subject to change, so calling it directly is not
22
+ # portable across different pip versions.
23
+
24
+ # In addition, running pip in-process is unsupported and unsafe. This is
25
+ # elaborated in detail at
26
+ # https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program.
27
+ # That document also provides suggestions that should work for nearly
28
+ # all users that are considering importing and using main() directly.
29
+
30
+ # However, we know that certain users will still want to invoke pip
31
+ # in-process. If you understand and accept the implications of using pip
32
+ # in an unsupported manner, the best approach is to use runpy to avoid
33
+ # depending on the exact location of this entry point.
34
+
35
+ # The following example shows how to use runpy to invoke pip in that
36
+ # case:
37
+ #
38
+ # sys.argv = ["pip", your, args, here]
39
+ # runpy.run_module("pip", run_name="__main__")
40
+ #
41
+ # Note that this will exit the process after running, unlike a direct
42
+ # call to main. As it is not safe to do any processing after calling
43
+ # main, this should not be an issue in practice.
44
+
45
+
46
+ def main(args: Optional[List[str]] = None) -> int:
47
+ if args is None:
48
+ args = sys.argv[1:]
49
+
50
+ # Suppress the pkg_resources deprecation warning
51
+ # Note - we use a module of .*pkg_resources to cover
52
+ # the normal case (pip._vendor.pkg_resources) and the
53
+ # devendored case (a bare pkg_resources)
54
+ warnings.filterwarnings(
55
+ action="ignore", category=DeprecationWarning, module=".*pkg_resources"
56
+ )
57
+
58
+ # Configure our deprecation warnings to be sent through loggers
59
+ deprecation.install_warning_logger()
60
+
61
+ autocomplete()
62
+
63
+ try:
64
+ cmd_name, cmd_args = parse_command(args)
65
+ except PipError as exc:
66
+ sys.stderr.write(f"ERROR: {exc}")
67
+ sys.stderr.write(os.linesep)
68
+ sys.exit(1)
69
+
70
+ # Needed for locale.getpreferredencoding(False) to work
71
+ # in pip._internal.utils.encoding.auto_decode
72
+ try:
73
+ locale.setlocale(locale.LC_ALL, "")
74
+ except locale.Error as e:
75
+ # setlocale can apparently crash if locale are uninitialized
76
+ logger.debug("Ignoring error %s when setting locale", e)
77
+ command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
78
+
79
+ return command.main(cmd_args)
python_embeded/Lib/site-packages/pip/_internal/cli/main_parser.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A single place for constructing and exposing the main parser"""
2
+
3
+ import os
4
+ import subprocess
5
+ import sys
6
+ from typing import List, Optional, Tuple
7
+
8
+ from pip._internal.build_env import get_runnable_pip
9
+ from pip._internal.cli import cmdoptions
10
+ from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
11
+ from pip._internal.commands import commands_dict, get_similar_commands
12
+ from pip._internal.exceptions import CommandError
13
+ from pip._internal.utils.misc import get_pip_version, get_prog
14
+
15
+ __all__ = ["create_main_parser", "parse_command"]
16
+
17
+
18
+ def create_main_parser() -> ConfigOptionParser:
19
+ """Creates and returns the main parser for pip's CLI"""
20
+
21
+ parser = ConfigOptionParser(
22
+ usage="\n%prog <command> [options]",
23
+ add_help_option=False,
24
+ formatter=UpdatingDefaultsHelpFormatter(),
25
+ name="global",
26
+ prog=get_prog(),
27
+ )
28
+ parser.disable_interspersed_args()
29
+
30
+ parser.version = get_pip_version()
31
+
32
+ # add the general options
33
+ gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)
34
+ parser.add_option_group(gen_opts)
35
+
36
+ # so the help formatter knows
37
+ parser.main = True # type: ignore
38
+
39
+ # create command listing for description
40
+ description = [""] + [
41
+ f"{name:27} {command_info.summary}"
42
+ for name, command_info in commands_dict.items()
43
+ ]
44
+ parser.description = "\n".join(description)
45
+
46
+ return parser
47
+
48
+
49
+ def identify_python_interpreter(python: str) -> Optional[str]:
50
+ # If the named file exists, use it.
51
+ # If it's a directory, assume it's a virtual environment and
52
+ # look for the environment's Python executable.
53
+ if os.path.exists(python):
54
+ if os.path.isdir(python):
55
+ # bin/python for Unix, Scripts/python.exe for Windows
56
+ # Try both in case of odd cases like cygwin.
57
+ for exe in ("bin/python", "Scripts/python.exe"):
58
+ py = os.path.join(python, exe)
59
+ if os.path.exists(py):
60
+ return py
61
+ else:
62
+ return python
63
+
64
+ # Could not find the interpreter specified
65
+ return None
66
+
67
+
68
+ def parse_command(args: List[str]) -> Tuple[str, List[str]]:
69
+ parser = create_main_parser()
70
+
71
+ # Note: parser calls disable_interspersed_args(), so the result of this
72
+ # call is to split the initial args into the general options before the
73
+ # subcommand and everything else.
74
+ # For example:
75
+ # args: ['--timeout=5', 'install', '--user', 'INITools']
76
+ # general_options: ['--timeout==5']
77
+ # args_else: ['install', '--user', 'INITools']
78
+ general_options, args_else = parser.parse_args(args)
79
+
80
+ # --python
81
+ if general_options.python and "_PIP_RUNNING_IN_SUBPROCESS" not in os.environ:
82
+ # Re-invoke pip using the specified Python interpreter
83
+ interpreter = identify_python_interpreter(general_options.python)
84
+ if interpreter is None:
85
+ raise CommandError(
86
+ f"Could not locate Python interpreter {general_options.python}"
87
+ )
88
+
89
+ pip_cmd = [
90
+ interpreter,
91
+ get_runnable_pip(),
92
+ ]
93
+ pip_cmd.extend(args)
94
+
95
+ # Set a flag so the child doesn't re-invoke itself, causing
96
+ # an infinite loop.
97
+ os.environ["_PIP_RUNNING_IN_SUBPROCESS"] = "1"
98
+ returncode = 0
99
+ try:
100
+ proc = subprocess.run(pip_cmd)
101
+ returncode = proc.returncode
102
+ except (subprocess.SubprocessError, OSError) as exc:
103
+ raise CommandError(f"Failed to run pip under {interpreter}: {exc}")
104
+ sys.exit(returncode)
105
+
106
+ # --version
107
+ if general_options.version:
108
+ sys.stdout.write(parser.version)
109
+ sys.stdout.write(os.linesep)
110
+ sys.exit()
111
+
112
+ # pip || pip help -> print_help()
113
+ if not args_else or (args_else[0] == "help" and len(args_else) == 1):
114
+ parser.print_help()
115
+ sys.exit()
116
+
117
+ # the subcommand name
118
+ cmd_name = args_else[0]
119
+
120
+ if cmd_name not in commands_dict:
121
+ guess = get_similar_commands(cmd_name)
122
+
123
+ msg = [f'unknown command "{cmd_name}"']
124
+ if guess:
125
+ msg.append(f'maybe you meant "{guess}"')
126
+
127
+ raise CommandError(" - ".join(msg))
128
+
129
+ # all the args without the subcommand
130
+ cmd_args = args[:]
131
+ cmd_args.remove(cmd_name)
132
+
133
+ return cmd_name, cmd_args
python_embeded/Lib/site-packages/pip/_internal/cli/parser.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base option parser setup"""
2
+
3
+ import logging
4
+ import optparse
5
+ import shutil
6
+ import sys
7
+ import textwrap
8
+ from contextlib import suppress
9
+ from typing import Any, Dict, Generator, List, NoReturn, Optional, 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: Optional[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: Optional[str]) -> str:
89
+ # leave full control over epilog to us
90
+ if epilog:
91
+ return epilog
92
+ else:
93
+ return ""
94
+
95
+ def indent_lines(self, text: str, indent: str) -> str:
96
+ new_lines = [indent + line for line in text.split("\n")]
97
+ return "\n".join(new_lines)
98
+
99
+
100
+ class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):
101
+ """Custom help formatter for use in ConfigOptionParser.
102
+
103
+ This is updates the defaults before expanding them, allowing
104
+ them to show up correctly in the help listing.
105
+
106
+ Also redact auth from url type options
107
+ """
108
+
109
+ def expand_default(self, option: optparse.Option) -> str:
110
+ default_values = None
111
+ if self.parser is not None:
112
+ assert isinstance(self.parser, ConfigOptionParser)
113
+ self.parser._update_defaults(self.parser.defaults)
114
+ assert option.dest is not None
115
+ default_values = self.parser.defaults.get(option.dest)
116
+ help_text = super().expand_default(option)
117
+
118
+ if default_values and option.metavar == "URL":
119
+ if isinstance(default_values, str):
120
+ default_values = [default_values]
121
+
122
+ # If its not a list, we should abort and just return the help text
123
+ if not isinstance(default_values, list):
124
+ default_values = []
125
+
126
+ for val in default_values:
127
+ help_text = help_text.replace(val, redact_auth_from_url(val))
128
+
129
+ return help_text
130
+
131
+
132
+ class CustomOptionParser(optparse.OptionParser):
133
+ def insert_option_group(
134
+ self, idx: int, *args: Any, **kwargs: Any
135
+ ) -> optparse.OptionGroup:
136
+ """Insert an OptionGroup at a given position."""
137
+ group = self.add_option_group(*args, **kwargs)
138
+
139
+ self.option_groups.pop()
140
+ self.option_groups.insert(idx, group)
141
+
142
+ return group
143
+
144
+ @property
145
+ def option_list_all(self) -> List[optparse.Option]:
146
+ """Get a list of all options, including those in option groups."""
147
+ res = self.option_list[:]
148
+ for i in self.option_groups:
149
+ res.extend(i.option_list)
150
+
151
+ return res
152
+
153
+
154
+ class ConfigOptionParser(CustomOptionParser):
155
+ """Custom option parser which updates its defaults by checking the
156
+ configuration files and environmental variables"""
157
+
158
+ def __init__(
159
+ self,
160
+ *args: Any,
161
+ name: str,
162
+ isolated: bool = False,
163
+ **kwargs: Any,
164
+ ) -> None:
165
+ self.name = name
166
+ self.config = Configuration(isolated)
167
+
168
+ assert self.name
169
+ super().__init__(*args, **kwargs)
170
+
171
+ def check_default(self, option: optparse.Option, key: str, val: Any) -> Any:
172
+ try:
173
+ return option.check_value(key, val)
174
+ except optparse.OptionValueError as exc:
175
+ print(f"An error occurred during configuration: {exc}")
176
+ sys.exit(3)
177
+
178
+ def _get_ordered_configuration_items(
179
+ self,
180
+ ) -> Generator[Tuple[str, Any], None, None]:
181
+ # Configuration gives keys in an unordered manner. Order them.
182
+ override_order = ["global", self.name, ":env:"]
183
+
184
+ # Pool the options into different groups
185
+ section_items: Dict[str, List[Tuple[str, Any]]] = {
186
+ name: [] for name in override_order
187
+ }
188
+ for section_key, val in self.config.items():
189
+ # ignore empty values
190
+ if not val:
191
+ logger.debug(
192
+ "Ignoring configuration key '%s' as it's value is empty.",
193
+ section_key,
194
+ )
195
+ continue
196
+
197
+ section, key = section_key.split(".", 1)
198
+ if section in override_order:
199
+ section_items[section].append((key, val))
200
+
201
+ # Yield each group in their override order
202
+ for section in override_order:
203
+ for key, val in section_items[section]:
204
+ yield key, val
205
+
206
+ def _update_defaults(self, defaults: Dict[str, Any]) -> Dict[str, Any]:
207
+ """Updates the given defaults with values from the config files and
208
+ the environ. Does a little special handling for certain types of
209
+ options (lists)."""
210
+
211
+ # Accumulate complex default state.
212
+ self.values = optparse.Values(self.defaults)
213
+ late_eval = set()
214
+ # Then set the options with those values
215
+ for key, val in self._get_ordered_configuration_items():
216
+ # '--' because configuration supports only long names
217
+ option = self.get_option("--" + key)
218
+
219
+ # Ignore options not present in this parser. E.g. non-globals put
220
+ # in [global] by users that want them to apply to all applicable
221
+ # commands.
222
+ if option is None:
223
+ continue
224
+
225
+ assert option.dest is not None
226
+
227
+ if option.action in ("store_true", "store_false"):
228
+ try:
229
+ val = strtobool(val)
230
+ except ValueError:
231
+ self.error(
232
+ f"{val} is not a valid value for {key} option, "
233
+ "please specify a boolean value like yes/no, "
234
+ "true/false or 1/0 instead."
235
+ )
236
+ elif option.action == "count":
237
+ with suppress(ValueError):
238
+ val = strtobool(val)
239
+ with suppress(ValueError):
240
+ val = int(val)
241
+ if not isinstance(val, int) or val < 0:
242
+ self.error(
243
+ f"{val} is not a valid value for {key} option, "
244
+ "please instead specify either a non-negative integer "
245
+ "or a boolean value like yes/no or false/true "
246
+ "which is equivalent to 1/0."
247
+ )
248
+ elif option.action == "append":
249
+ val = val.split()
250
+ val = [self.check_default(option, key, v) for v in val]
251
+ elif option.action == "callback":
252
+ assert option.callback is not None
253
+ late_eval.add(option.dest)
254
+ opt_str = option.get_opt_string()
255
+ val = option.convert_value(opt_str, val)
256
+ # From take_action
257
+ args = option.callback_args or ()
258
+ kwargs = option.callback_kwargs or {}
259
+ option.callback(option, opt_str, val, self, *args, **kwargs)
260
+ else:
261
+ val = self.check_default(option, key, val)
262
+
263
+ defaults[option.dest] = val
264
+
265
+ for key in late_eval:
266
+ defaults[key] = getattr(self.values, key)
267
+ self.values = None
268
+ return defaults
269
+
270
+ def get_default_values(self) -> optparse.Values:
271
+ """Overriding to make updating the defaults after instantiation of
272
+ the option parser possible, _update_defaults() does the dirty work."""
273
+ if not self.process_default_values:
274
+ # Old, pre-Optik 1.5 behaviour.
275
+ return optparse.Values(self.defaults)
276
+
277
+ # Load the configuration, or error out in case of an error
278
+ try:
279
+ self.config.load()
280
+ except ConfigurationError as err:
281
+ self.exit(UNKNOWN_ERROR, str(err))
282
+
283
+ defaults = self._update_defaults(self.defaults.copy()) # ours
284
+ for option in self._get_all_options():
285
+ assert option.dest is not None
286
+ default = defaults.get(option.dest)
287
+ if isinstance(default, str):
288
+ opt_str = option.get_opt_string()
289
+ defaults[option.dest] = option.check_value(opt_str, default)
290
+ return optparse.Values(defaults)
291
+
292
+ def error(self, msg: str) -> NoReturn:
293
+ self.print_usage(sys.stderr)
294
+ self.exit(UNKNOWN_ERROR, f"{msg}\n")
python_embeded/Lib/site-packages/pip/_internal/cli/progress_bars.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import sys
3
+ from typing import Callable, Generator, Iterable, Iterator, Optional, Tuple, TypeVar
4
+
5
+ from pip._vendor.rich.progress import (
6
+ BarColumn,
7
+ DownloadColumn,
8
+ FileSizeColumn,
9
+ MofNCompleteColumn,
10
+ Progress,
11
+ ProgressColumn,
12
+ SpinnerColumn,
13
+ TextColumn,
14
+ TimeElapsedColumn,
15
+ TimeRemainingColumn,
16
+ TransferSpeedColumn,
17
+ )
18
+
19
+ from pip._internal.cli.spinners import RateLimiter
20
+ from pip._internal.req.req_install import InstallRequirement
21
+ from pip._internal.utils.logging import get_console, get_indentation
22
+
23
+ T = TypeVar("T")
24
+ ProgressRenderer = Callable[[Iterable[T]], Iterator[T]]
25
+
26
+
27
+ def _rich_download_progress_bar(
28
+ iterable: Iterable[bytes],
29
+ *,
30
+ bar_type: str,
31
+ size: Optional[int],
32
+ initial_progress: Optional[int] = None,
33
+ ) -> Generator[bytes, None, None]:
34
+ assert bar_type == "on", "This should only be used in the default mode."
35
+
36
+ if not size:
37
+ total = float("inf")
38
+ columns: Tuple[ProgressColumn, ...] = (
39
+ TextColumn("[progress.description]{task.description}"),
40
+ SpinnerColumn("line", speed=1.5),
41
+ FileSizeColumn(),
42
+ TransferSpeedColumn(),
43
+ TimeElapsedColumn(),
44
+ )
45
+ else:
46
+ total = size
47
+ columns = (
48
+ TextColumn("[progress.description]{task.description}"),
49
+ BarColumn(),
50
+ DownloadColumn(),
51
+ TransferSpeedColumn(),
52
+ TextColumn("eta"),
53
+ TimeRemainingColumn(),
54
+ )
55
+
56
+ progress = Progress(*columns, refresh_per_second=5)
57
+ task_id = progress.add_task(" " * (get_indentation() + 2), total=total)
58
+ if initial_progress is not None:
59
+ progress.update(task_id, advance=initial_progress)
60
+ with progress:
61
+ for chunk in iterable:
62
+ yield chunk
63
+ progress.update(task_id, advance=len(chunk))
64
+
65
+
66
+ def _rich_install_progress_bar(
67
+ iterable: Iterable[InstallRequirement], *, total: int
68
+ ) -> Iterator[InstallRequirement]:
69
+ columns = (
70
+ TextColumn("{task.fields[indent]}"),
71
+ BarColumn(),
72
+ MofNCompleteColumn(),
73
+ TextColumn("{task.description}"),
74
+ )
75
+ console = get_console()
76
+
77
+ bar = Progress(*columns, refresh_per_second=6, console=console, transient=True)
78
+ # Hiding the progress bar at initialization forces a refresh cycle to occur
79
+ # until the bar appears, avoiding very short flashes.
80
+ task = bar.add_task("", total=total, indent=" " * get_indentation(), visible=False)
81
+ with bar:
82
+ for req in iterable:
83
+ bar.update(task, description=rf"\[{req.name}]", visible=True)
84
+ yield req
85
+ bar.advance(task)
86
+
87
+
88
+ def _raw_progress_bar(
89
+ iterable: Iterable[bytes],
90
+ *,
91
+ size: Optional[int],
92
+ initial_progress: Optional[int] = None,
93
+ ) -> Generator[bytes, None, None]:
94
+ def write_progress(current: int, total: int) -> None:
95
+ sys.stdout.write(f"Progress {current} of {total}\n")
96
+ sys.stdout.flush()
97
+
98
+ current = initial_progress or 0
99
+ total = size or 0
100
+ rate_limiter = RateLimiter(0.25)
101
+
102
+ write_progress(current, total)
103
+ for chunk in iterable:
104
+ current += len(chunk)
105
+ if rate_limiter.ready() or current == total:
106
+ write_progress(current, total)
107
+ rate_limiter.reset()
108
+ yield chunk
109
+
110
+
111
+ def get_download_progress_renderer(
112
+ *, bar_type: str, size: Optional[int] = None, initial_progress: Optional[int] = None
113
+ ) -> ProgressRenderer[bytes]:
114
+ """Get an object that can be used to render the download progress.
115
+
116
+ Returns a callable, that takes an iterable to "wrap".
117
+ """
118
+ if bar_type == "on":
119
+ return functools.partial(
120
+ _rich_download_progress_bar,
121
+ bar_type=bar_type,
122
+ size=size,
123
+ initial_progress=initial_progress,
124
+ )
125
+ elif bar_type == "raw":
126
+ return functools.partial(
127
+ _raw_progress_bar,
128
+ size=size,
129
+ initial_progress=initial_progress,
130
+ )
131
+ else:
132
+ return iter # no-op, when passed an iterator
133
+
134
+
135
+ def get_install_progress_renderer(
136
+ *, bar_type: str, total: int
137
+ ) -> ProgressRenderer[InstallRequirement]:
138
+ """Get an object that can be used to render the install progress.
139
+ Returns a callable, that takes an iterable to "wrap".
140
+ """
141
+ if bar_type == "on":
142
+ return functools.partial(_rich_install_progress_bar, total=total)
143
+ else:
144
+ return iter
python_embeded/Lib/site-packages/pip/_internal/cli/req_command.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contains the RequirementCommand base class.
2
+
3
+ This class is in a separate module so the commands that do not always
4
+ need PackageFinder capability don't unnecessarily import the
5
+ PackageFinder machinery and all its vendored dependencies, etc.
6
+ """
7
+
8
+ import logging
9
+ from functools import partial
10
+ from optparse import Values
11
+ from typing import Any, List, Optional, Tuple
12
+
13
+ from pip._internal.cache import WheelCache
14
+ from pip._internal.cli import cmdoptions
15
+ from pip._internal.cli.index_command import IndexGroupCommand
16
+ from pip._internal.cli.index_command import SessionCommandMixin as SessionCommandMixin
17
+ from pip._internal.exceptions import CommandError, PreviousBuildDirError
18
+ from pip._internal.index.collector import LinkCollector
19
+ from pip._internal.index.package_finder import PackageFinder
20
+ from pip._internal.models.selection_prefs import SelectionPreferences
21
+ from pip._internal.models.target_python import TargetPython
22
+ from pip._internal.network.session import PipSession
23
+ from pip._internal.operations.build.build_tracker import BuildTracker
24
+ from pip._internal.operations.prepare import RequirementPreparer
25
+ from pip._internal.req.constructors import (
26
+ install_req_from_editable,
27
+ install_req_from_line,
28
+ install_req_from_parsed_requirement,
29
+ install_req_from_req_string,
30
+ )
31
+ from pip._internal.req.req_dependency_group import parse_dependency_groups
32
+ from pip._internal.req.req_file import parse_requirements
33
+ from pip._internal.req.req_install import InstallRequirement
34
+ from pip._internal.resolution.base import BaseResolver
35
+ from pip._internal.utils.temp_dir import (
36
+ TempDirectory,
37
+ TempDirectoryTypeRegistry,
38
+ tempdir_kinds,
39
+ )
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+
44
+ KEEPABLE_TEMPDIR_TYPES = [
45
+ tempdir_kinds.BUILD_ENV,
46
+ tempdir_kinds.EPHEM_WHEEL_CACHE,
47
+ tempdir_kinds.REQ_BUILD,
48
+ ]
49
+
50
+
51
+ def with_cleanup(func: Any) -> Any:
52
+ """Decorator for common logic related to managing temporary
53
+ directories.
54
+ """
55
+
56
+ def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None:
57
+ for t in KEEPABLE_TEMPDIR_TYPES:
58
+ registry.set_delete(t, False)
59
+
60
+ def wrapper(
61
+ self: RequirementCommand, options: Values, args: List[Any]
62
+ ) -> Optional[int]:
63
+ assert self.tempdir_registry is not None
64
+ if options.no_clean:
65
+ configure_tempdir_registry(self.tempdir_registry)
66
+
67
+ try:
68
+ return func(self, options, args)
69
+ except PreviousBuildDirError:
70
+ # This kind of conflict can occur when the user passes an explicit
71
+ # build directory with a pre-existing folder. In that case we do
72
+ # not want to accidentally remove it.
73
+ configure_tempdir_registry(self.tempdir_registry)
74
+ raise
75
+
76
+ return wrapper
77
+
78
+
79
+ class RequirementCommand(IndexGroupCommand):
80
+ def __init__(self, *args: Any, **kw: Any) -> None:
81
+ super().__init__(*args, **kw)
82
+
83
+ self.cmd_opts.add_option(cmdoptions.dependency_groups())
84
+ self.cmd_opts.add_option(cmdoptions.no_clean())
85
+
86
+ @staticmethod
87
+ def determine_resolver_variant(options: Values) -> str:
88
+ """Determines which resolver should be used, based on the given options."""
89
+ if "legacy-resolver" in options.deprecated_features_enabled:
90
+ return "legacy"
91
+
92
+ return "resolvelib"
93
+
94
+ @classmethod
95
+ def make_requirement_preparer(
96
+ cls,
97
+ temp_build_dir: TempDirectory,
98
+ options: Values,
99
+ build_tracker: BuildTracker,
100
+ session: PipSession,
101
+ finder: PackageFinder,
102
+ use_user_site: bool,
103
+ download_dir: Optional[str] = None,
104
+ verbosity: int = 0,
105
+ ) -> RequirementPreparer:
106
+ """
107
+ Create a RequirementPreparer instance for the given parameters.
108
+ """
109
+ temp_build_dir_path = temp_build_dir.path
110
+ assert temp_build_dir_path is not None
111
+ legacy_resolver = False
112
+
113
+ resolver_variant = cls.determine_resolver_variant(options)
114
+ if resolver_variant == "resolvelib":
115
+ lazy_wheel = "fast-deps" in options.features_enabled
116
+ if lazy_wheel:
117
+ logger.warning(
118
+ "pip is using lazily downloaded wheels using HTTP "
119
+ "range requests to obtain dependency information. "
120
+ "This experimental feature is enabled through "
121
+ "--use-feature=fast-deps and it is not ready for "
122
+ "production."
123
+ )
124
+ else:
125
+ legacy_resolver = True
126
+ lazy_wheel = False
127
+ if "fast-deps" in options.features_enabled:
128
+ logger.warning(
129
+ "fast-deps has no effect when used with the legacy resolver."
130
+ )
131
+
132
+ return RequirementPreparer(
133
+ build_dir=temp_build_dir_path,
134
+ src_dir=options.src_dir,
135
+ download_dir=download_dir,
136
+ build_isolation=options.build_isolation,
137
+ check_build_deps=options.check_build_deps,
138
+ build_tracker=build_tracker,
139
+ session=session,
140
+ progress_bar=options.progress_bar,
141
+ finder=finder,
142
+ require_hashes=options.require_hashes,
143
+ use_user_site=use_user_site,
144
+ lazy_wheel=lazy_wheel,
145
+ verbosity=verbosity,
146
+ legacy_resolver=legacy_resolver,
147
+ resume_retries=options.resume_retries,
148
+ )
149
+
150
+ @classmethod
151
+ def make_resolver(
152
+ cls,
153
+ preparer: RequirementPreparer,
154
+ finder: PackageFinder,
155
+ options: Values,
156
+ wheel_cache: Optional[WheelCache] = None,
157
+ use_user_site: bool = False,
158
+ ignore_installed: bool = True,
159
+ ignore_requires_python: bool = False,
160
+ force_reinstall: bool = False,
161
+ upgrade_strategy: str = "to-satisfy-only",
162
+ use_pep517: Optional[bool] = None,
163
+ py_version_info: Optional[Tuple[int, ...]] = None,
164
+ ) -> BaseResolver:
165
+ """
166
+ Create a Resolver instance for the given parameters.
167
+ """
168
+ make_install_req = partial(
169
+ install_req_from_req_string,
170
+ isolated=options.isolated_mode,
171
+ use_pep517=use_pep517,
172
+ )
173
+ resolver_variant = cls.determine_resolver_variant(options)
174
+ # The long import name and duplicated invocation is needed to convince
175
+ # Mypy into correctly typechecking. Otherwise it would complain the
176
+ # "Resolver" class being redefined.
177
+ if resolver_variant == "resolvelib":
178
+ import pip._internal.resolution.resolvelib.resolver
179
+
180
+ return pip._internal.resolution.resolvelib.resolver.Resolver(
181
+ preparer=preparer,
182
+ finder=finder,
183
+ wheel_cache=wheel_cache,
184
+ make_install_req=make_install_req,
185
+ use_user_site=use_user_site,
186
+ ignore_dependencies=options.ignore_dependencies,
187
+ ignore_installed=ignore_installed,
188
+ ignore_requires_python=ignore_requires_python,
189
+ force_reinstall=force_reinstall,
190
+ upgrade_strategy=upgrade_strategy,
191
+ py_version_info=py_version_info,
192
+ )
193
+ import pip._internal.resolution.legacy.resolver
194
+
195
+ return pip._internal.resolution.legacy.resolver.Resolver(
196
+ preparer=preparer,
197
+ finder=finder,
198
+ wheel_cache=wheel_cache,
199
+ make_install_req=make_install_req,
200
+ use_user_site=use_user_site,
201
+ ignore_dependencies=options.ignore_dependencies,
202
+ ignore_installed=ignore_installed,
203
+ ignore_requires_python=ignore_requires_python,
204
+ force_reinstall=force_reinstall,
205
+ upgrade_strategy=upgrade_strategy,
206
+ py_version_info=py_version_info,
207
+ )
208
+
209
+ def get_requirements(
210
+ self,
211
+ args: List[str],
212
+ options: Values,
213
+ finder: PackageFinder,
214
+ session: PipSession,
215
+ ) -> List[InstallRequirement]:
216
+ """
217
+ Parse command-line arguments into the corresponding requirements.
218
+ """
219
+ requirements: List[InstallRequirement] = []
220
+ for filename in options.constraints:
221
+ for parsed_req in parse_requirements(
222
+ filename,
223
+ constraint=True,
224
+ finder=finder,
225
+ options=options,
226
+ session=session,
227
+ ):
228
+ req_to_add = install_req_from_parsed_requirement(
229
+ parsed_req,
230
+ isolated=options.isolated_mode,
231
+ user_supplied=False,
232
+ )
233
+ requirements.append(req_to_add)
234
+
235
+ for req in args:
236
+ req_to_add = install_req_from_line(
237
+ req,
238
+ comes_from=None,
239
+ isolated=options.isolated_mode,
240
+ use_pep517=options.use_pep517,
241
+ user_supplied=True,
242
+ config_settings=getattr(options, "config_settings", None),
243
+ )
244
+ requirements.append(req_to_add)
245
+
246
+ if options.dependency_groups:
247
+ for req in parse_dependency_groups(options.dependency_groups):
248
+ req_to_add = install_req_from_req_string(
249
+ req,
250
+ isolated=options.isolated_mode,
251
+ use_pep517=options.use_pep517,
252
+ user_supplied=True,
253
+ )
254
+ requirements.append(req_to_add)
255
+
256
+ for req in options.editables:
257
+ req_to_add = install_req_from_editable(
258
+ req,
259
+ user_supplied=True,
260
+ isolated=options.isolated_mode,
261
+ use_pep517=options.use_pep517,
262
+ config_settings=getattr(options, "config_settings", None),
263
+ )
264
+ requirements.append(req_to_add)
265
+
266
+ # NOTE: options.require_hashes may be set if --require-hashes is True
267
+ for filename in options.requirements:
268
+ for parsed_req in parse_requirements(
269
+ filename, finder=finder, options=options, session=session
270
+ ):
271
+ req_to_add = install_req_from_parsed_requirement(
272
+ parsed_req,
273
+ isolated=options.isolated_mode,
274
+ use_pep517=options.use_pep517,
275
+ user_supplied=True,
276
+ config_settings=(
277
+ parsed_req.options.get("config_settings")
278
+ if parsed_req.options
279
+ else None
280
+ ),
281
+ )
282
+ requirements.append(req_to_add)
283
+
284
+ # If any requirement has hash options, enable hash checking.
285
+ if any(req.has_hash_options for req in requirements):
286
+ options.require_hashes = True
287
+
288
+ if not (
289
+ args
290
+ or options.editables
291
+ or options.requirements
292
+ or options.dependency_groups
293
+ ):
294
+ opts = {"name": self.name}
295
+ if options.find_links:
296
+ raise CommandError(
297
+ "You must give at least one requirement to {name} "
298
+ '(maybe you meant "pip {name} {links}"?)'.format(
299
+ **dict(opts, links=" ".join(options.find_links))
300
+ )
301
+ )
302
+ else:
303
+ raise CommandError(
304
+ "You must give at least one requirement to {name} "
305
+ '(see "pip help {name}")'.format(**opts)
306
+ )
307
+
308
+ return requirements
309
+
310
+ @staticmethod
311
+ def trace_basic_info(finder: PackageFinder) -> None:
312
+ """
313
+ Trace basic information about the provided objects.
314
+ """
315
+ # Display where finder is looking for packages
316
+ search_scope = finder.search_scope
317
+ locations = search_scope.get_formatted_locations()
318
+ if locations:
319
+ logger.info(locations)
320
+
321
+ def _build_package_finder(
322
+ self,
323
+ options: Values,
324
+ session: PipSession,
325
+ target_python: Optional[TargetPython] = None,
326
+ ignore_requires_python: Optional[bool] = None,
327
+ ) -> PackageFinder:
328
+ """
329
+ Create a package finder appropriate to this requirement command.
330
+
331
+ :param ignore_requires_python: Whether to ignore incompatible
332
+ "Requires-Python" values in links. Defaults to False.
333
+ """
334
+ link_collector = LinkCollector.create(session, options=options)
335
+ selection_prefs = SelectionPreferences(
336
+ allow_yanked=True,
337
+ format_control=options.format_control,
338
+ allow_all_prereleases=options.pre,
339
+ prefer_binary=options.prefer_binary,
340
+ ignore_requires_python=ignore_requires_python,
341
+ )
342
+
343
+ return PackageFinder.create(
344
+ link_collector=link_collector,
345
+ selection_prefs=selection_prefs,
346
+ target_python=target_python,
347
+ )
python_embeded/Lib/site-packages/pip/_internal/cli/spinners.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import itertools
3
+ import logging
4
+ import sys
5
+ import time
6
+ from typing import IO, Generator, Optional
7
+
8
+ from pip._internal.utils.compat import WINDOWS
9
+ from pip._internal.utils.logging import get_indentation
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class SpinnerInterface:
15
+ def spin(self) -> None:
16
+ raise NotImplementedError()
17
+
18
+ def finish(self, final_status: str) -> None:
19
+ raise NotImplementedError()
20
+
21
+
22
+ class InteractiveSpinner(SpinnerInterface):
23
+ def __init__(
24
+ self,
25
+ message: str,
26
+ file: Optional[IO[str]] = None,
27
+ spin_chars: str = "-\\|/",
28
+ # Empirically, 8 updates/second looks nice
29
+ min_update_interval_seconds: float = 0.125,
30
+ ):
31
+ self._message = message
32
+ if file is None:
33
+ file = sys.stdout
34
+ self._file = file
35
+ self._rate_limiter = RateLimiter(min_update_interval_seconds)
36
+ self._finished = False
37
+
38
+ self._spin_cycle = itertools.cycle(spin_chars)
39
+
40
+ self._file.write(" " * get_indentation() + self._message + " ... ")
41
+ self._width = 0
42
+
43
+ def _write(self, status: str) -> None:
44
+ assert not self._finished
45
+ # Erase what we wrote before by backspacing to the beginning, writing
46
+ # spaces to overwrite the old text, and then backspacing again
47
+ backup = "\b" * self._width
48
+ self._file.write(backup + " " * self._width + backup)
49
+ # Now we have a blank slate to add our status
50
+ self._file.write(status)
51
+ self._width = len(status)
52
+ self._file.flush()
53
+ self._rate_limiter.reset()
54
+
55
+ def spin(self) -> None:
56
+ if self._finished:
57
+ return
58
+ if not self._rate_limiter.ready():
59
+ return
60
+ self._write(next(self._spin_cycle))
61
+
62
+ def finish(self, final_status: str) -> None:
63
+ if self._finished:
64
+ return
65
+ self._write(final_status)
66
+ self._file.write("\n")
67
+ self._file.flush()
68
+ self._finished = True
69
+
70
+
71
+ # Used for dumb terminals, non-interactive installs (no tty), etc.
72
+ # We still print updates occasionally (once every 60 seconds by default) to
73
+ # act as a keep-alive for systems like Travis-CI that take lack-of-output as
74
+ # an indication that a task has frozen.
75
+ class NonInteractiveSpinner(SpinnerInterface):
76
+ def __init__(self, message: str, min_update_interval_seconds: float = 60.0) -> None:
77
+ self._message = message
78
+ self._finished = False
79
+ self._rate_limiter = RateLimiter(min_update_interval_seconds)
80
+ self._update("started")
81
+
82
+ def _update(self, status: str) -> None:
83
+ assert not self._finished
84
+ self._rate_limiter.reset()
85
+ logger.info("%s: %s", self._message, status)
86
+
87
+ def spin(self) -> None:
88
+ if self._finished:
89
+ return
90
+ if not self._rate_limiter.ready():
91
+ return
92
+ self._update("still running...")
93
+
94
+ def finish(self, final_status: str) -> None:
95
+ if self._finished:
96
+ return
97
+ self._update(f"finished with status '{final_status}'")
98
+ self._finished = True
99
+
100
+
101
+ class RateLimiter:
102
+ def __init__(self, min_update_interval_seconds: float) -> None:
103
+ self._min_update_interval_seconds = min_update_interval_seconds
104
+ self._last_update: float = 0
105
+
106
+ def ready(self) -> bool:
107
+ now = time.time()
108
+ delta = now - self._last_update
109
+ return delta >= self._min_update_interval_seconds
110
+
111
+ def reset(self) -> None:
112
+ self._last_update = time.time()
113
+
114
+
115
+ @contextlib.contextmanager
116
+ def open_spinner(message: str) -> Generator[SpinnerInterface, None, None]:
117
+ # Interactive spinner goes directly to sys.stdout rather than being routed
118
+ # through the logging system, but it acts like it has level INFO,
119
+ # i.e. it's only displayed if we're at level INFO or better.
120
+ # Non-interactive spinner goes through the logging system, so it is always
121
+ # in sync with logging configuration.
122
+ if sys.stdout.isatty() and logger.getEffectiveLevel() <= logging.INFO:
123
+ spinner: SpinnerInterface = InteractiveSpinner(message)
124
+ else:
125
+ spinner = NonInteractiveSpinner(message)
126
+ try:
127
+ with hidden_cursor(sys.stdout):
128
+ yield spinner
129
+ except KeyboardInterrupt:
130
+ spinner.finish("canceled")
131
+ raise
132
+ except Exception:
133
+ spinner.finish("error")
134
+ raise
135
+ else:
136
+ spinner.finish("done")
137
+
138
+
139
+ HIDE_CURSOR = "\x1b[?25l"
140
+ SHOW_CURSOR = "\x1b[?25h"
141
+
142
+
143
+ @contextlib.contextmanager
144
+ def hidden_cursor(file: IO[str]) -> Generator[None, None, None]:
145
+ # The Windows terminal does not support the hide/show cursor ANSI codes,
146
+ # even via colorama. So don't even try.
147
+ if WINDOWS:
148
+ yield
149
+ # We don't want to clutter the output with control characters if we're
150
+ # writing to a file, or if the user is running with --quiet.
151
+ # See https://github.com/pypa/pip/issues/3418
152
+ elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO:
153
+ yield
154
+ else:
155
+ file.write(HIDE_CURSOR)
156
+ try:
157
+ yield
158
+ finally:
159
+ file.write(SHOW_CURSOR)
python_embeded/Lib/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
python_embeded/Lib/site-packages/pip/_internal/commands/__init__.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Package containing all pip commands
3
+ """
4
+
5
+ import importlib
6
+ from collections import namedtuple
7
+ from typing import Any, Dict, Optional
8
+
9
+ from pip._internal.cli.base_command import Command
10
+
11
+ CommandInfo = namedtuple("CommandInfo", "module_path, class_name, summary")
12
+
13
+ # This dictionary does a bunch of heavy lifting for help output:
14
+ # - Enables avoiding additional (costly) imports for presenting `--help`.
15
+ # - The ordering matters for help display.
16
+ #
17
+ # Even though the module path starts with the same "pip._internal.commands"
18
+ # prefix, the full path makes testing easier (specifically when modifying
19
+ # `commands_dict` in test setup / teardown).
20
+ commands_dict: Dict[str, CommandInfo] = {
21
+ "install": CommandInfo(
22
+ "pip._internal.commands.install",
23
+ "InstallCommand",
24
+ "Install packages.",
25
+ ),
26
+ "lock": CommandInfo(
27
+ "pip._internal.commands.lock",
28
+ "LockCommand",
29
+ "Generate a lock file.",
30
+ ),
31
+ "download": CommandInfo(
32
+ "pip._internal.commands.download",
33
+ "DownloadCommand",
34
+ "Download packages.",
35
+ ),
36
+ "uninstall": CommandInfo(
37
+ "pip._internal.commands.uninstall",
38
+ "UninstallCommand",
39
+ "Uninstall packages.",
40
+ ),
41
+ "freeze": CommandInfo(
42
+ "pip._internal.commands.freeze",
43
+ "FreezeCommand",
44
+ "Output installed packages in requirements format.",
45
+ ),
46
+ "inspect": CommandInfo(
47
+ "pip._internal.commands.inspect",
48
+ "InspectCommand",
49
+ "Inspect the python environment.",
50
+ ),
51
+ "list": CommandInfo(
52
+ "pip._internal.commands.list",
53
+ "ListCommand",
54
+ "List installed packages.",
55
+ ),
56
+ "show": CommandInfo(
57
+ "pip._internal.commands.show",
58
+ "ShowCommand",
59
+ "Show information about installed packages.",
60
+ ),
61
+ "check": CommandInfo(
62
+ "pip._internal.commands.check",
63
+ "CheckCommand",
64
+ "Verify installed packages have compatible dependencies.",
65
+ ),
66
+ "config": CommandInfo(
67
+ "pip._internal.commands.configuration",
68
+ "ConfigurationCommand",
69
+ "Manage local and global configuration.",
70
+ ),
71
+ "search": CommandInfo(
72
+ "pip._internal.commands.search",
73
+ "SearchCommand",
74
+ "Search PyPI for packages.",
75
+ ),
76
+ "cache": CommandInfo(
77
+ "pip._internal.commands.cache",
78
+ "CacheCommand",
79
+ "Inspect and manage pip's wheel cache.",
80
+ ),
81
+ "index": CommandInfo(
82
+ "pip._internal.commands.index",
83
+ "IndexCommand",
84
+ "Inspect information available from package indexes.",
85
+ ),
86
+ "wheel": CommandInfo(
87
+ "pip._internal.commands.wheel",
88
+ "WheelCommand",
89
+ "Build wheels from your requirements.",
90
+ ),
91
+ "hash": CommandInfo(
92
+ "pip._internal.commands.hash",
93
+ "HashCommand",
94
+ "Compute hashes of package archives.",
95
+ ),
96
+ "completion": CommandInfo(
97
+ "pip._internal.commands.completion",
98
+ "CompletionCommand",
99
+ "A helper command used for command completion.",
100
+ ),
101
+ "debug": CommandInfo(
102
+ "pip._internal.commands.debug",
103
+ "DebugCommand",
104
+ "Show information useful for debugging.",
105
+ ),
106
+ "help": CommandInfo(
107
+ "pip._internal.commands.help",
108
+ "HelpCommand",
109
+ "Show help for commands.",
110
+ ),
111
+ }
112
+
113
+
114
+ def create_command(name: str, **kwargs: Any) -> Command:
115
+ """
116
+ Create an instance of the Command class with the given name.
117
+ """
118
+ module_path, class_name, summary = commands_dict[name]
119
+ module = importlib.import_module(module_path)
120
+ command_class = getattr(module, class_name)
121
+ command = command_class(name=name, summary=summary, **kwargs)
122
+
123
+ return command
124
+
125
+
126
+ def get_similar_commands(name: str) -> Optional[str]:
127
+ """Command name auto-correct."""
128
+ from difflib import get_close_matches
129
+
130
+ name = name.lower()
131
+
132
+ close_commands = get_close_matches(name, commands_dict.keys())
133
+
134
+ if close_commands:
135
+ return close_commands[0]
136
+ else:
137
+ return None
python_embeded/Lib/site-packages/pip/_internal/commands/cache.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import textwrap
3
+ from optparse import Values
4
+ from typing import Any, List
5
+
6
+ from pip._internal.cli.base_command import Command
7
+ from pip._internal.cli.status_codes import ERROR, SUCCESS
8
+ from pip._internal.exceptions import CommandError, PipError
9
+ from pip._internal.utils import filesystem
10
+ from pip._internal.utils.logging import getLogger
11
+ from pip._internal.utils.misc import format_size
12
+
13
+ logger = getLogger(__name__)
14
+
15
+
16
+ class CacheCommand(Command):
17
+ """
18
+ Inspect and manage pip's wheel cache.
19
+
20
+ Subcommands:
21
+
22
+ - dir: Show the cache directory.
23
+ - info: Show information about the cache.
24
+ - list: List filenames of packages stored in the cache.
25
+ - remove: Remove one or more package from the cache.
26
+ - purge: Remove all items from the cache.
27
+
28
+ ``<pattern>`` can be a glob expression or a package name.
29
+ """
30
+
31
+ ignore_require_venv = True
32
+ usage = """
33
+ %prog dir
34
+ %prog info
35
+ %prog list [<pattern>] [--format=[human, abspath]]
36
+ %prog remove <pattern>
37
+ %prog purge
38
+ """
39
+
40
+ def add_options(self) -> None:
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[str]) -> 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 function since cache is disabled.")
63
+ return ERROR
64
+
65
+ # Determine action
66
+ if not args or args[0] not in handlers:
67
+ logger.error(
68
+ "Need an action (%s) to perform.",
69
+ ", ".join(sorted(handlers)),
70
+ )
71
+ return ERROR
72
+
73
+ action = args[0]
74
+
75
+ # Error handling happens here, not in the action-handlers.
76
+ try:
77
+ handlers[action](options, args[1:])
78
+ except PipError as e:
79
+ logger.error(e.args[0])
80
+ return ERROR
81
+
82
+ return SUCCESS
83
+
84
+ def get_cache_dir(self, options: Values, args: List[Any]) -> None:
85
+ if args:
86
+ raise CommandError("Too many arguments")
87
+
88
+ logger.info(options.cache_dir)
89
+
90
+ def get_cache_info(self, options: Values, args: List[Any]) -> None:
91
+ if args:
92
+ raise CommandError("Too many arguments")
93
+
94
+ num_http_files = len(self._find_http_files(options))
95
+ num_packages = len(self._find_wheels(options, "*"))
96
+
97
+ http_cache_location = self._cache_dir(options, "http-v2")
98
+ old_http_cache_location = self._cache_dir(options, "http")
99
+ wheels_cache_location = self._cache_dir(options, "wheels")
100
+ http_cache_size = filesystem.format_size(
101
+ filesystem.directory_size(http_cache_location)
102
+ + filesystem.directory_size(old_http_cache_location)
103
+ )
104
+ wheels_cache_size = filesystem.format_directory_size(wheels_cache_location)
105
+
106
+ message = (
107
+ textwrap.dedent(
108
+ """
109
+ Package index page cache location (pip v23.3+): {http_cache_location}
110
+ Package index page cache location (older pips): {old_http_cache_location}
111
+ Package index page cache size: {http_cache_size}
112
+ Number of HTTP files: {num_http_files}
113
+ Locally built wheels location: {wheels_cache_location}
114
+ Locally built wheels size: {wheels_cache_size}
115
+ Number of locally built wheels: {package_count}
116
+ """ # noqa: E501
117
+ )
118
+ .format(
119
+ http_cache_location=http_cache_location,
120
+ old_http_cache_location=old_http_cache_location,
121
+ http_cache_size=http_cache_size,
122
+ num_http_files=num_http_files,
123
+ wheels_cache_location=wheels_cache_location,
124
+ package_count=num_packages,
125
+ wheels_cache_size=wheels_cache_size,
126
+ )
127
+ .strip()
128
+ )
129
+
130
+ logger.info(message)
131
+
132
+ def list_cache_items(self, options: Values, args: List[Any]) -> None:
133
+ if len(args) > 1:
134
+ raise CommandError("Too many arguments")
135
+
136
+ if args:
137
+ pattern = args[0]
138
+ else:
139
+ pattern = "*"
140
+
141
+ files = self._find_wheels(options, pattern)
142
+ if options.list_format == "human":
143
+ self.format_for_human(files)
144
+ else:
145
+ self.format_for_abspath(files)
146
+
147
+ def format_for_human(self, files: List[str]) -> None:
148
+ if not files:
149
+ logger.info("No locally built wheels cached.")
150
+ return
151
+
152
+ results = []
153
+ for filename in files:
154
+ wheel = os.path.basename(filename)
155
+ size = filesystem.format_file_size(filename)
156
+ results.append(f" - {wheel} ({size})")
157
+ logger.info("Cache contents:\n")
158
+ logger.info("\n".join(sorted(results)))
159
+
160
+ def format_for_abspath(self, files: List[str]) -> None:
161
+ if files:
162
+ logger.info("\n".join(sorted(files)))
163
+
164
+ def remove_cache_items(self, options: Values, args: List[Any]) -> None:
165
+ if len(args) > 1:
166
+ raise CommandError("Too many arguments")
167
+
168
+ if not args:
169
+ raise CommandError("Please provide a pattern")
170
+
171
+ files = self._find_wheels(options, args[0])
172
+
173
+ no_matching_msg = "No matching packages"
174
+ if args[0] == "*":
175
+ # Only fetch http files if no specific pattern given
176
+ files += self._find_http_files(options)
177
+ else:
178
+ # Add the pattern to the log message
179
+ no_matching_msg += f' for pattern "{args[0]}"'
180
+
181
+ if not files:
182
+ logger.warning(no_matching_msg)
183
+
184
+ bytes_removed = 0
185
+ for filename in files:
186
+ bytes_removed += os.stat(filename).st_size
187
+ os.unlink(filename)
188
+ logger.verbose("Removed %s", filename)
189
+ logger.info("Files removed: %s (%s)", len(files), format_size(bytes_removed))
190
+
191
+ def purge_cache(self, options: Values, args: List[Any]) -> None:
192
+ if args:
193
+ raise CommandError("Too many arguments")
194
+
195
+ return self.remove_cache_items(options, ["*"])
196
+
197
+ def _cache_dir(self, options: Values, subdir: str) -> str:
198
+ return os.path.join(options.cache_dir, subdir)
199
+
200
+ def _find_http_files(self, options: Values) -> List[str]:
201
+ old_http_dir = self._cache_dir(options, "http")
202
+ new_http_dir = self._cache_dir(options, "http-v2")
203
+ return filesystem.find_files(old_http_dir, "*") + filesystem.find_files(
204
+ new_http_dir, "*"
205
+ )
206
+
207
+ def _find_wheels(self, options: Values, pattern: str) -> List[str]:
208
+ wheel_dir = self._cache_dir(options, "wheels")
209
+
210
+ # The wheel filename format, as specified in PEP 427, is:
211
+ # {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl
212
+ #
213
+ # Additionally, non-alphanumeric values in the distribution are
214
+ # normalized to underscores (_), meaning hyphens can never occur
215
+ # before `-{version}`.
216
+ #
217
+ # Given that information:
218
+ # - If the pattern we're given contains a hyphen (-), the user is
219
+ # providing at least the version. Thus, we can just append `*.whl`
220
+ # to match the rest of it.
221
+ # - If the pattern we're given doesn't contain a hyphen (-), the
222
+ # user is only providing the name. Thus, we append `-*.whl` to
223
+ # match the hyphen before the version, followed by anything else.
224
+ #
225
+ # PEP 427: https://www.python.org/dev/peps/pep-0427/
226
+ pattern = pattern + ("*.whl" if "-" in pattern else "-*.whl")
227
+
228
+ return filesystem.find_files(wheel_dir, pattern)
python_embeded/Lib/site-packages/pip/_internal/commands/check.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from optparse import Values
3
+ from typing import List
4
+
5
+ from pip._internal.cli.base_command import Command
6
+ from pip._internal.cli.status_codes import ERROR, SUCCESS
7
+ from pip._internal.metadata import get_default_environment
8
+ from pip._internal.operations.check import (
9
+ check_package_set,
10
+ check_unsupported,
11
+ create_package_set_from_installed,
12
+ )
13
+ from pip._internal.utils.compatibility_tags import get_supported
14
+ from pip._internal.utils.misc import write_output
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class CheckCommand(Command):
20
+ """Verify installed packages have compatible dependencies."""
21
+
22
+ ignore_require_venv = True
23
+ usage = """
24
+ %prog [options]"""
25
+
26
+ def run(self, options: Values, args: List[str]) -> int:
27
+ package_set, parsing_probs = create_package_set_from_installed()
28
+ missing, conflicting = check_package_set(package_set)
29
+ unsupported = list(
30
+ check_unsupported(
31
+ get_default_environment().iter_installed_distributions(),
32
+ get_supported(),
33
+ )
34
+ )
35
+
36
+ for project_name in missing:
37
+ version = package_set[project_name].version
38
+ for dependency in missing[project_name]:
39
+ write_output(
40
+ "%s %s requires %s, which is not installed.",
41
+ project_name,
42
+ version,
43
+ dependency[0],
44
+ )
45
+
46
+ for project_name in conflicting:
47
+ version = package_set[project_name].version
48
+ for dep_name, dep_version, req in conflicting[project_name]:
49
+ write_output(
50
+ "%s %s has requirement %s, but you have %s %s.",
51
+ project_name,
52
+ version,
53
+ req,
54
+ dep_name,
55
+ dep_version,
56
+ )
57
+ for package in unsupported:
58
+ write_output(
59
+ "%s %s is not supported on this platform",
60
+ package.raw_name,
61
+ package.version,
62
+ )
63
+ if missing or conflicting or parsing_probs or unsupported:
64
+ return ERROR
65
+ else:
66
+ write_output("No broken requirements found.")
67
+ return SUCCESS
python_embeded/Lib/site-packages/pip/_internal/commands/completion.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import textwrap
3
+ from optparse import Values
4
+ from typing import List
5
+
6
+ from pip._internal.cli.base_command import Command
7
+ from pip._internal.cli.status_codes import SUCCESS
8
+ from pip._internal.utils.misc import get_prog
9
+
10
+ BASE_COMPLETION = """
11
+ # pip {shell} completion start{script}# pip {shell} completion end
12
+ """
13
+
14
+ COMPLETION_SCRIPTS = {
15
+ "bash": """
16
+ _pip_completion()
17
+ {{
18
+ COMPREPLY=( $( COMP_WORDS="${{COMP_WORDS[*]}}" \\
19
+ COMP_CWORD=$COMP_CWORD \\
20
+ PIP_AUTO_COMPLETE=1 $1 2>/dev/null ) )
21
+ }}
22
+ complete -o default -F _pip_completion {prog}
23
+ """,
24
+ "zsh": """
25
+ #compdef -P pip[0-9.]#
26
+ __pip() {{
27
+ compadd $( COMP_WORDS="$words[*]" \\
28
+ COMP_CWORD=$((CURRENT-1)) \\
29
+ PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null )
30
+ }}
31
+ if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
32
+ # autoload from fpath, call function directly
33
+ __pip "$@"
34
+ else
35
+ # eval/source/. command, register function for later
36
+ compdef __pip -P 'pip[0-9.]#'
37
+ fi
38
+ """,
39
+ "fish": """
40
+ function __fish_complete_pip
41
+ set -lx COMP_WORDS \\
42
+ (commandline --current-process --tokenize --cut-at-cursor) \\
43
+ (commandline --current-token --cut-at-cursor)
44
+ set -lx COMP_CWORD (math (count $COMP_WORDS) - 1)
45
+ set -lx PIP_AUTO_COMPLETE 1
46
+ set -l completions
47
+ if string match -q '2.*' $version
48
+ set completions (eval $COMP_WORDS[1])
49
+ else
50
+ set completions ($COMP_WORDS[1])
51
+ end
52
+ string split \\ -- $completions
53
+ end
54
+ complete -fa "(__fish_complete_pip)" -c {prog}
55
+ """,
56
+ "powershell": """
57
+ if ((Test-Path Function:\\TabExpansion) -and -not `
58
+ (Test-Path Function:\\_pip_completeBackup)) {{
59
+ Rename-Item Function:\\TabExpansion _pip_completeBackup
60
+ }}
61
+ function TabExpansion($line, $lastWord) {{
62
+ $lastBlock = [regex]::Split($line, '[|;]')[-1].TrimStart()
63
+ if ($lastBlock.StartsWith("{prog} ")) {{
64
+ $Env:COMP_WORDS=$lastBlock
65
+ $Env:COMP_CWORD=$lastBlock.Split().Length - 1
66
+ $Env:PIP_AUTO_COMPLETE=1
67
+ (& {prog}).Split()
68
+ Remove-Item Env:COMP_WORDS
69
+ Remove-Item Env:COMP_CWORD
70
+ Remove-Item Env:PIP_AUTO_COMPLETE
71
+ }}
72
+ elseif (Test-Path Function:\\_pip_completeBackup) {{
73
+ # Fall back on existing tab expansion
74
+ _pip_completeBackup $line $lastWord
75
+ }}
76
+ }}
77
+ """,
78
+ }
79
+
80
+
81
+ class CompletionCommand(Command):
82
+ """A helper command to be used for command completion."""
83
+
84
+ ignore_require_venv = True
85
+
86
+ def add_options(self) -> None:
87
+ self.cmd_opts.add_option(
88
+ "--bash",
89
+ "-b",
90
+ action="store_const",
91
+ const="bash",
92
+ dest="shell",
93
+ help="Emit completion code for bash",
94
+ )
95
+ self.cmd_opts.add_option(
96
+ "--zsh",
97
+ "-z",
98
+ action="store_const",
99
+ const="zsh",
100
+ dest="shell",
101
+ help="Emit completion code for zsh",
102
+ )
103
+ self.cmd_opts.add_option(
104
+ "--fish",
105
+ "-f",
106
+ action="store_const",
107
+ const="fish",
108
+ dest="shell",
109
+ help="Emit completion code for fish",
110
+ )
111
+ self.cmd_opts.add_option(
112
+ "--powershell",
113
+ "-p",
114
+ action="store_const",
115
+ const="powershell",
116
+ dest="shell",
117
+ help="Emit completion code for powershell",
118
+ )
119
+
120
+ self.parser.insert_option_group(0, self.cmd_opts)
121
+
122
+ def run(self, options: Values, args: List[str]) -> int:
123
+ """Prints the completion code of the given shell"""
124
+ shells = COMPLETION_SCRIPTS.keys()
125
+ shell_options = ["--" + shell for shell in sorted(shells)]
126
+ if options.shell in shells:
127
+ script = textwrap.dedent(
128
+ COMPLETION_SCRIPTS.get(options.shell, "").format(prog=get_prog())
129
+ )
130
+ print(BASE_COMPLETION.format(script=script, shell=options.shell))
131
+ return SUCCESS
132
+ else:
133
+ sys.stderr.write(
134
+ "ERROR: You must pass {}\n".format(" or ".join(shell_options))
135
+ )
136
+ return SUCCESS
python_embeded/Lib/site-packages/pip/_internal/commands/configuration.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import subprocess
4
+ from optparse import Values
5
+ from typing import Any, List, Optional
6
+
7
+ from pip._internal.cli.base_command import Command
8
+ from pip._internal.cli.status_codes import ERROR, SUCCESS
9
+ from pip._internal.configuration import (
10
+ Configuration,
11
+ Kind,
12
+ get_configuration_files,
13
+ kinds,
14
+ )
15
+ from pip._internal.exceptions import PipError
16
+ from pip._internal.utils.logging import indent_log
17
+ from pip._internal.utils.misc import get_prog, write_output
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ class ConfigurationCommand(Command):
23
+ """
24
+ Manage local and global configuration.
25
+
26
+ Subcommands:
27
+
28
+ - list: List the active configuration (or from the file specified)
29
+ - edit: Edit the configuration file in an editor
30
+ - get: Get the value associated with command.option
31
+ - set: Set the command.option=value
32
+ - unset: Unset the value associated with command.option
33
+ - debug: List the configuration files and values defined under them
34
+
35
+ Configuration keys should be dot separated command and option name,
36
+ with the special prefix "global" affecting any command. For example,
37
+ "pip config set global.index-url https://example.org/" would configure
38
+ the index url for all commands, but "pip config set download.timeout 10"
39
+ would configure a 10 second timeout only for "pip download" commands.
40
+
41
+ If none of --user, --global and --site are passed, a virtual
42
+ environment configuration file is used if one is active and the file
43
+ exists. Otherwise, all modifications happen to the user file by
44
+ default.
45
+ """
46
+
47
+ ignore_require_venv = True
48
+ usage = """
49
+ %prog [<file-option>] list
50
+ %prog [<file-option>] [--editor <editor-path>] edit
51
+
52
+ %prog [<file-option>] get command.option
53
+ %prog [<file-option>] set command.option value
54
+ %prog [<file-option>] unset command.option
55
+ %prog [<file-option>] debug
56
+ """
57
+
58
+ def add_options(self) -> None:
59
+ self.cmd_opts.add_option(
60
+ "--editor",
61
+ dest="editor",
62
+ action="store",
63
+ default=None,
64
+ help=(
65
+ "Editor to use to edit the file. Uses VISUAL or EDITOR "
66
+ "environment variables if not provided."
67
+ ),
68
+ )
69
+
70
+ self.cmd_opts.add_option(
71
+ "--global",
72
+ dest="global_file",
73
+ action="store_true",
74
+ default=False,
75
+ help="Use the system-wide configuration file only",
76
+ )
77
+
78
+ self.cmd_opts.add_option(
79
+ "--user",
80
+ dest="user_file",
81
+ action="store_true",
82
+ default=False,
83
+ help="Use the user configuration file only",
84
+ )
85
+
86
+ self.cmd_opts.add_option(
87
+ "--site",
88
+ dest="site_file",
89
+ action="store_true",
90
+ default=False,
91
+ help="Use the current environment configuration file only",
92
+ )
93
+
94
+ self.parser.insert_option_group(0, self.cmd_opts)
95
+
96
+ def run(self, options: Values, args: List[str]) -> int:
97
+ handlers = {
98
+ "list": self.list_values,
99
+ "edit": self.open_in_editor,
100
+ "get": self.get_name,
101
+ "set": self.set_name_value,
102
+ "unset": self.unset_name,
103
+ "debug": self.list_config_values,
104
+ }
105
+
106
+ # Determine action
107
+ if not args or args[0] not in handlers:
108
+ logger.error(
109
+ "Need an action (%s) to perform.",
110
+ ", ".join(sorted(handlers)),
111
+ )
112
+ return ERROR
113
+
114
+ action = args[0]
115
+
116
+ # Determine which configuration files are to be loaded
117
+ # Depends on whether the command is modifying.
118
+ try:
119
+ load_only = self._determine_file(
120
+ options, need_value=(action in ["get", "set", "unset", "edit"])
121
+ )
122
+ except PipError as e:
123
+ logger.error(e.args[0])
124
+ return ERROR
125
+
126
+ # Load a new configuration
127
+ self.configuration = Configuration(
128
+ isolated=options.isolated_mode, load_only=load_only
129
+ )
130
+ self.configuration.load()
131
+
132
+ # Error handling happens here, not in the action-handlers.
133
+ try:
134
+ handlers[action](options, args[1:])
135
+ except PipError as e:
136
+ logger.error(e.args[0])
137
+ return ERROR
138
+
139
+ return SUCCESS
140
+
141
+ def _determine_file(self, options: Values, need_value: bool) -> Optional[Kind]:
142
+ file_options = [
143
+ key
144
+ for key, value in (
145
+ (kinds.USER, options.user_file),
146
+ (kinds.GLOBAL, options.global_file),
147
+ (kinds.SITE, options.site_file),
148
+ )
149
+ if value
150
+ ]
151
+
152
+ if not file_options:
153
+ if not need_value:
154
+ return None
155
+ # Default to user, unless there's a site file.
156
+ elif any(
157
+ os.path.exists(site_config_file)
158
+ for site_config_file in get_configuration_files()[kinds.SITE]
159
+ ):
160
+ return kinds.SITE
161
+ else:
162
+ return kinds.USER
163
+ elif len(file_options) == 1:
164
+ return file_options[0]
165
+
166
+ raise PipError(
167
+ "Need exactly one file to operate upon "
168
+ "(--user, --site, --global) to perform."
169
+ )
170
+
171
+ def list_values(self, options: Values, args: List[str]) -> None:
172
+ self._get_n_args(args, "list", n=0)
173
+
174
+ for key, value in sorted(self.configuration.items()):
175
+ write_output("%s=%r", key, value)
176
+
177
+ def get_name(self, options: Values, args: List[str]) -> None:
178
+ key = self._get_n_args(args, "get [name]", n=1)
179
+ value = self.configuration.get_value(key)
180
+
181
+ write_output("%s", value)
182
+
183
+ def set_name_value(self, options: Values, args: List[str]) -> None:
184
+ key, value = self._get_n_args(args, "set [name] [value]", n=2)
185
+ self.configuration.set_value(key, value)
186
+
187
+ self._save_configuration()
188
+
189
+ def unset_name(self, options: Values, args: List[str]) -> None:
190
+ key = self._get_n_args(args, "unset [name]", n=1)
191
+ self.configuration.unset_value(key)
192
+
193
+ self._save_configuration()
194
+
195
+ def list_config_values(self, options: Values, args: List[str]) -> None:
196
+ """List config key-value pairs across different config files"""
197
+ self._get_n_args(args, "debug", n=0)
198
+
199
+ self.print_env_var_values()
200
+ # Iterate over config files and print if they exist, and the
201
+ # key-value pairs present in them if they do
202
+ for variant, files in sorted(self.configuration.iter_config_files()):
203
+ write_output("%s:", variant)
204
+ for fname in files:
205
+ with indent_log():
206
+ file_exists = os.path.exists(fname)
207
+ write_output("%s, exists: %r", fname, file_exists)
208
+ if file_exists:
209
+ self.print_config_file_values(variant)
210
+
211
+ def print_config_file_values(self, variant: Kind) -> None:
212
+ """Get key-value pairs from the file of a variant"""
213
+ for name, value in self.configuration.get_values_in_config(variant).items():
214
+ with indent_log():
215
+ write_output("%s: %s", name, value)
216
+
217
+ def print_env_var_values(self) -> None:
218
+ """Get key-values pairs present as environment variables"""
219
+ write_output("%s:", "env_var")
220
+ with indent_log():
221
+ for key, value in sorted(self.configuration.get_environ_vars()):
222
+ env_var = f"PIP_{key.upper()}"
223
+ write_output("%s=%r", env_var, value)
224
+
225
+ def open_in_editor(self, options: Values, args: List[str]) -> None:
226
+ editor = self._determine_editor(options)
227
+
228
+ fname = self.configuration.get_file_to_edit()
229
+ if fname is None:
230
+ raise PipError("Could not determine appropriate file.")
231
+ elif '"' in fname:
232
+ # This shouldn't happen, unless we see a username like that.
233
+ # If that happens, we'd appreciate a pull request fixing this.
234
+ raise PipError(
235
+ f'Can not open an editor for a file name containing "\n{fname}'
236
+ )
237
+
238
+ try:
239
+ subprocess.check_call(f'{editor} "{fname}"', shell=True)
240
+ except FileNotFoundError as e:
241
+ if not e.filename:
242
+ e.filename = editor
243
+ raise
244
+ except subprocess.CalledProcessError as e:
245
+ raise PipError(f"Editor Subprocess exited with exit code {e.returncode}")
246
+
247
+ def _get_n_args(self, args: List[str], example: str, n: int) -> Any:
248
+ """Helper to make sure the command got the right number of arguments"""
249
+ if len(args) != n:
250
+ msg = (
251
+ f"Got unexpected number of arguments, expected {n}. "
252
+ f'(example: "{get_prog()} config {example}")'
253
+ )
254
+ raise PipError(msg)
255
+
256
+ if n == 1:
257
+ return args[0]
258
+ else:
259
+ return args
260
+
261
+ def _save_configuration(self) -> None:
262
+ # We successfully ran a modifying command. Need to save the
263
+ # configuration.
264
+ try:
265
+ self.configuration.save()
266
+ except Exception:
267
+ logger.exception(
268
+ "Unable to save configuration. Please report this as a bug."
269
+ )
270
+ raise PipError("Internal Error.")
271
+
272
+ def _determine_editor(self, options: Values) -> str:
273
+ if options.editor is not None:
274
+ return options.editor
275
+ elif "VISUAL" in os.environ:
276
+ return os.environ["VISUAL"]
277
+ elif "EDITOR" in os.environ:
278
+ return os.environ["EDITOR"]
279
+ else:
280
+ raise PipError("Could not determine editor to use.")
python_embeded/Lib/site-packages/pip/_internal/commands/debug.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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._internal.cli import cmdoptions
14
+ from pip._internal.cli.base_command import Command
15
+ from pip._internal.cli.cmdoptions import make_target_python
16
+ from pip._internal.cli.status_codes import SUCCESS
17
+ from pip._internal.configuration import Configuration
18
+ from pip._internal.metadata import get_environment
19
+ from pip._internal.utils.compat import open_text_resource
20
+ from pip._internal.utils.logging import indent_log
21
+ from pip._internal.utils.misc import get_pip_version
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ def show_value(name: str, value: Any) -> None:
27
+ logger.info("%s: %s", name, value)
28
+
29
+
30
+ def show_sys_implementation() -> None:
31
+ logger.info("sys.implementation:")
32
+ implementation_name = sys.implementation.name
33
+ with indent_log():
34
+ show_value("name", implementation_name)
35
+
36
+
37
+ def create_vendor_txt_map() -> Dict[str, str]:
38
+ with open_text_resource("pip._vendor", "vendor.txt") as f:
39
+ # Purge non version specifying lines.
40
+ # Also, remove any space prefix or suffixes (including comments).
41
+ lines = [
42
+ line.strip().split(" ", 1)[0] for line in f.readlines() if "==" in line
43
+ ]
44
+
45
+ # Transform into "module" -> version dict.
46
+ return dict(line.split("==", 1) for line in lines)
47
+
48
+
49
+ def get_module_from_module_name(module_name: str) -> Optional[ModuleType]:
50
+ # Module name can be uppercase in vendor.txt for some reason...
51
+ module_name = module_name.lower().replace("-", "_")
52
+ # PATCH: setuptools is actually only pkg_resources.
53
+ if module_name == "setuptools":
54
+ module_name = "pkg_resources"
55
+
56
+ try:
57
+ __import__(f"pip._vendor.{module_name}", globals(), locals(), level=0)
58
+ return getattr(pip._vendor, module_name)
59
+ except ImportError:
60
+ # We allow 'truststore' to fail to import due
61
+ # to being unavailable on Python 3.9 and earlier.
62
+ if module_name == "truststore" and sys.version_info < (3, 10):
63
+ return None
64
+ raise
65
+
66
+
67
+ def get_vendor_version_from_module(module_name: str) -> Optional[str]:
68
+ module = get_module_from_module_name(module_name)
69
+ version = getattr(module, "__version__", None)
70
+
71
+ if module and not version:
72
+ # Try to find version in debundled module info.
73
+ assert module.__file__ is not None
74
+ env = get_environment([os.path.dirname(module.__file__)])
75
+ dist = env.get_distribution(module_name)
76
+ if dist:
77
+ version = str(dist.version)
78
+
79
+ return version
80
+
81
+
82
+ def show_actual_vendor_versions(vendor_txt_versions: Dict[str, str]) -> None:
83
+ """Log the actual version and print extra info if there is
84
+ a conflict or if the actual version could not be imported.
85
+ """
86
+ for module_name, expected_version in vendor_txt_versions.items():
87
+ extra_message = ""
88
+ actual_version = get_vendor_version_from_module(module_name)
89
+ if not actual_version:
90
+ extra_message = (
91
+ " (Unable to locate actual module version, using"
92
+ " vendor.txt specified version)"
93
+ )
94
+ actual_version = expected_version
95
+ elif parse_version(actual_version) != parse_version(expected_version):
96
+ extra_message = (
97
+ " (CONFLICT: vendor.txt suggests version should"
98
+ f" be {expected_version})"
99
+ )
100
+ logger.info("%s==%s%s", module_name, actual_version, extra_message)
101
+
102
+
103
+ def show_vendor_versions() -> None:
104
+ logger.info("vendored library versions:")
105
+
106
+ vendor_txt_versions = create_vendor_txt_map()
107
+ with indent_log():
108
+ show_actual_vendor_versions(vendor_txt_versions)
109
+
110
+
111
+ def show_tags(options: Values) -> None:
112
+ tag_limit = 10
113
+
114
+ target_python = make_target_python(options)
115
+ tags = target_python.get_sorted_tags()
116
+
117
+ # Display the target options that were explicitly provided.
118
+ formatted_target = target_python.format_given()
119
+ suffix = ""
120
+ if formatted_target:
121
+ suffix = f" (target: {formatted_target})"
122
+
123
+ msg = f"Compatible tags: {len(tags)}{suffix}"
124
+ logger.info(msg)
125
+
126
+ if options.verbose < 1 and len(tags) > tag_limit:
127
+ tags_limited = True
128
+ tags = tags[:tag_limit]
129
+ else:
130
+ tags_limited = False
131
+
132
+ with indent_log():
133
+ for tag in tags:
134
+ logger.info(str(tag))
135
+
136
+ if tags_limited:
137
+ msg = f"...\n[First {tag_limit} tags shown. Pass --verbose to show all.]"
138
+ logger.info(msg)
139
+
140
+
141
+ def ca_bundle_info(config: Configuration) -> str:
142
+ levels = {key.split(".", 1)[0] for key, _ in config.items()}
143
+ if not levels:
144
+ return "Not specified"
145
+
146
+ levels_that_override_global = ["install", "wheel", "download"]
147
+ global_overriding_level = [
148
+ level for level in levels if level in levels_that_override_global
149
+ ]
150
+ if not global_overriding_level:
151
+ return "global"
152
+
153
+ if "global" in levels:
154
+ levels.remove("global")
155
+ return ", ".join(levels)
156
+
157
+
158
+ class DebugCommand(Command):
159
+ """
160
+ Display debug information.
161
+ """
162
+
163
+ usage = """
164
+ %prog <options>"""
165
+ ignore_require_venv = True
166
+
167
+ def add_options(self) -> None:
168
+ cmdoptions.add_target_python_options(self.cmd_opts)
169
+ self.parser.insert_option_group(0, self.cmd_opts)
170
+ self.parser.config.load()
171
+
172
+ def run(self, options: Values, args: List[str]) -> int:
173
+ logger.warning(
174
+ "This command is only meant for debugging. "
175
+ "Do not use this with automation for parsing and getting these "
176
+ "details, since the output and options of this command may "
177
+ "change without notice."
178
+ )
179
+ show_value("pip version", get_pip_version())
180
+ show_value("sys.version", sys.version)
181
+ show_value("sys.executable", sys.executable)
182
+ show_value("sys.getdefaultencoding", sys.getdefaultencoding())
183
+ show_value("sys.getfilesystemencoding", sys.getfilesystemencoding())
184
+ show_value(
185
+ "locale.getpreferredencoding",
186
+ locale.getpreferredencoding(),
187
+ )
188
+ show_value("sys.platform", sys.platform)
189
+ show_sys_implementation()
190
+
191
+ show_value("'cert' config value", ca_bundle_info(self.parser.config))
192
+ show_value("REQUESTS_CA_BUNDLE", os.environ.get("REQUESTS_CA_BUNDLE"))
193
+ show_value("CURL_CA_BUNDLE", os.environ.get("CURL_CA_BUNDLE"))
194
+ show_value("pip._vendor.certifi.where()", where())
195
+ show_value("pip._vendor.DEBUNDLED", pip._vendor.DEBUNDLED)
196
+
197
+ show_vendor_versions()
198
+
199
+ show_tags(options)
200
+
201
+ return SUCCESS
python_embeded/Lib/site-packages/pip/_internal/commands/download.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ from optparse import Values
4
+ from typing import List
5
+
6
+ from pip._internal.cli import cmdoptions
7
+ from pip._internal.cli.cmdoptions import make_target_python
8
+ from pip._internal.cli.req_command import RequirementCommand, with_cleanup
9
+ from pip._internal.cli.status_codes import SUCCESS
10
+ from pip._internal.operations.build.build_tracker import get_build_tracker
11
+ from pip._internal.req.req_install import check_legacy_setup_py_options
12
+ from pip._internal.utils.misc import ensure_dir, normalize_path, write_output
13
+ from pip._internal.utils.temp_dir import TempDirectory
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class DownloadCommand(RequirementCommand):
19
+ """
20
+ Download packages from:
21
+
22
+ - PyPI (and other indexes) using requirement specifiers.
23
+ - VCS project urls.
24
+ - Local project directories.
25
+ - Local or remote source archives.
26
+
27
+ pip also supports downloading from "requirements files", which provide
28
+ an easy way to specify a whole environment to be downloaded.
29
+ """
30
+
31
+ usage = """
32
+ %prog [options] <requirement specifier> [package-index-options] ...
33
+ %prog [options] -r <requirements file> [package-index-options] ...
34
+ %prog [options] <vcs project url> ...
35
+ %prog [options] <local project path> ...
36
+ %prog [options] <archive url/path> ..."""
37
+
38
+ def add_options(self) -> None:
39
+ self.cmd_opts.add_option(cmdoptions.constraints())
40
+ self.cmd_opts.add_option(cmdoptions.requirements())
41
+ self.cmd_opts.add_option(cmdoptions.no_deps())
42
+ self.cmd_opts.add_option(cmdoptions.global_options())
43
+ self.cmd_opts.add_option(cmdoptions.no_binary())
44
+ self.cmd_opts.add_option(cmdoptions.only_binary())
45
+ self.cmd_opts.add_option(cmdoptions.prefer_binary())
46
+ self.cmd_opts.add_option(cmdoptions.src())
47
+ self.cmd_opts.add_option(cmdoptions.pre())
48
+ self.cmd_opts.add_option(cmdoptions.require_hashes())
49
+ self.cmd_opts.add_option(cmdoptions.progress_bar())
50
+ self.cmd_opts.add_option(cmdoptions.no_build_isolation())
51
+ self.cmd_opts.add_option(cmdoptions.use_pep517())
52
+ self.cmd_opts.add_option(cmdoptions.no_use_pep517())
53
+ self.cmd_opts.add_option(cmdoptions.check_build_deps())
54
+ self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
55
+
56
+ self.cmd_opts.add_option(
57
+ "-d",
58
+ "--dest",
59
+ "--destination-dir",
60
+ "--destination-directory",
61
+ dest="download_dir",
62
+ metavar="dir",
63
+ default=os.curdir,
64
+ help="Download packages into <dir>.",
65
+ )
66
+
67
+ cmdoptions.add_target_python_options(self.cmd_opts)
68
+
69
+ index_opts = cmdoptions.make_option_group(
70
+ cmdoptions.index_group,
71
+ self.parser,
72
+ )
73
+
74
+ self.parser.insert_option_group(0, index_opts)
75
+ self.parser.insert_option_group(0, self.cmd_opts)
76
+
77
+ @with_cleanup
78
+ def run(self, options: Values, args: List[str]) -> int:
79
+ options.ignore_installed = True
80
+ # editable doesn't really make sense for `pip download`, but the bowels
81
+ # of the RequirementSet code require that property.
82
+ options.editables = []
83
+
84
+ cmdoptions.check_dist_restriction(options)
85
+
86
+ options.download_dir = normalize_path(options.download_dir)
87
+ ensure_dir(options.download_dir)
88
+
89
+ session = self.get_default_session(options)
90
+
91
+ target_python = make_target_python(options)
92
+ finder = self._build_package_finder(
93
+ options=options,
94
+ session=session,
95
+ target_python=target_python,
96
+ ignore_requires_python=options.ignore_requires_python,
97
+ )
98
+
99
+ build_tracker = self.enter_context(get_build_tracker())
100
+
101
+ directory = TempDirectory(
102
+ delete=not options.no_clean,
103
+ kind="download",
104
+ globally_managed=True,
105
+ )
106
+
107
+ reqs = self.get_requirements(args, options, finder, session)
108
+ check_legacy_setup_py_options(options, reqs)
109
+
110
+ preparer = self.make_requirement_preparer(
111
+ temp_build_dir=directory,
112
+ options=options,
113
+ build_tracker=build_tracker,
114
+ session=session,
115
+ finder=finder,
116
+ download_dir=options.download_dir,
117
+ use_user_site=False,
118
+ verbosity=self.verbosity,
119
+ )
120
+
121
+ resolver = self.make_resolver(
122
+ preparer=preparer,
123
+ finder=finder,
124
+ options=options,
125
+ ignore_requires_python=options.ignore_requires_python,
126
+ use_pep517=options.use_pep517,
127
+ py_version_info=options.python_version,
128
+ )
129
+
130
+ self.trace_basic_info(finder)
131
+
132
+ requirement_set = resolver.resolve(reqs, check_supported_wheels=True)
133
+
134
+ downloaded: List[str] = []
135
+ for req in requirement_set.requirements.values():
136
+ if req.satisfied_by is None:
137
+ assert req.name is not None
138
+ preparer.save_linked_requirement(req)
139
+ downloaded.append(req.name)
140
+
141
+ preparer.prepare_linked_requirements_more(requirement_set.requirements.values())
142
+
143
+ if downloaded:
144
+ write_output("Successfully downloaded %s", " ".join(downloaded))
145
+
146
+ return SUCCESS
python_embeded/Lib/site-packages/pip/_internal/commands/freeze.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from optparse import Values
3
+ from typing import AbstractSet, 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
+
12
+ def _should_suppress_build_backends() -> bool:
13
+ return sys.version_info < (3, 12)
14
+
15
+
16
+ def _dev_pkgs() -> AbstractSet[str]:
17
+ pkgs = {"pip"}
18
+
19
+ if _should_suppress_build_backends():
20
+ pkgs |= {"setuptools", "distribute", "wheel"}
21
+
22
+ return pkgs
23
+
24
+
25
+ class FreezeCommand(Command):
26
+ """
27
+ Output installed packages in requirements format.
28
+
29
+ packages are listed in a case-insensitive sorted order.
30
+ """
31
+
32
+ ignore_require_venv = True
33
+ usage = """
34
+ %prog [options]"""
35
+
36
+ def add_options(self) -> None:
37
+ self.cmd_opts.add_option(
38
+ "-r",
39
+ "--requirement",
40
+ dest="requirements",
41
+ action="append",
42
+ default=[],
43
+ metavar="file",
44
+ help=(
45
+ "Use the order in the given requirements file and its "
46
+ "comments when generating output. This option can be "
47
+ "used multiple times."
48
+ ),
49
+ )
50
+ self.cmd_opts.add_option(
51
+ "-l",
52
+ "--local",
53
+ dest="local",
54
+ action="store_true",
55
+ default=False,
56
+ help=(
57
+ "If in a virtualenv that has global access, do not output "
58
+ "globally-installed packages."
59
+ ),
60
+ )
61
+ self.cmd_opts.add_option(
62
+ "--user",
63
+ dest="user",
64
+ action="store_true",
65
+ default=False,
66
+ help="Only output packages installed in user-site.",
67
+ )
68
+ self.cmd_opts.add_option(cmdoptions.list_path())
69
+ self.cmd_opts.add_option(
70
+ "--all",
71
+ dest="freeze_all",
72
+ action="store_true",
73
+ help=(
74
+ "Do not skip these packages in the output:"
75
+ " {}".format(", ".join(_dev_pkgs()))
76
+ ),
77
+ )
78
+ self.cmd_opts.add_option(
79
+ "--exclude-editable",
80
+ dest="exclude_editable",
81
+ action="store_true",
82
+ help="Exclude editable package from output.",
83
+ )
84
+ self.cmd_opts.add_option(cmdoptions.list_exclude())
85
+
86
+ self.parser.insert_option_group(0, self.cmd_opts)
87
+
88
+ def run(self, options: Values, args: List[str]) -> int:
89
+ skip = set(stdlib_pkgs)
90
+ if not options.freeze_all:
91
+ skip.update(_dev_pkgs())
92
+
93
+ if options.excludes:
94
+ skip.update(options.excludes)
95
+
96
+ cmdoptions.check_list_path_option(options)
97
+
98
+ for line in freeze(
99
+ requirement=options.requirements,
100
+ local_only=options.local,
101
+ user_only=options.user,
102
+ paths=options.path,
103
+ isolated=options.isolated_mode,
104
+ skip=skip,
105
+ exclude_editable=options.exclude_editable,
106
+ ):
107
+ sys.stdout.write(line + "\n")
108
+ return SUCCESS
python_embeded/Lib/site-packages/pip/_internal/commands/hash.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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",
29
+ "--algorithm",
30
+ dest="algorithm",
31
+ choices=STRONG_HASHES,
32
+ action="store",
33
+ default=FAVORITE_HASH,
34
+ help="The hash algorithm to use: one of {}".format(
35
+ ", ".join(STRONG_HASHES)
36
+ ),
37
+ )
38
+ self.parser.insert_option_group(0, self.cmd_opts)
39
+
40
+ def run(self, options: Values, args: List[str]) -> int:
41
+ if not args:
42
+ self.parser.print_usage(sys.stderr)
43
+ return ERROR
44
+
45
+ algorithm = options.algorithm
46
+ for path in args:
47
+ write_output(
48
+ "%s:\n--hash=%s:%s", path, algorithm, _hash_of_file(path, algorithm)
49
+ )
50
+ return SUCCESS
51
+
52
+
53
+ def _hash_of_file(path: str, algorithm: str) -> str:
54
+ """Return the hash digest of a file."""
55
+ with open(path, "rb") as archive:
56
+ hash = hashlib.new(algorithm)
57
+ for chunk in read_chunks(archive):
58
+ hash.update(chunk)
59
+ return hash.hexdigest()
python_embeded/Lib/site-packages/pip/_internal/commands/help.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from optparse import Values
2
+ from typing import List
3
+
4
+ from pip._internal.cli.base_command import Command
5
+ from pip._internal.cli.status_codes import SUCCESS
6
+ from pip._internal.exceptions import CommandError
7
+
8
+
9
+ class HelpCommand(Command):
10
+ """Show help for commands"""
11
+
12
+ usage = """
13
+ %prog <command>"""
14
+ ignore_require_venv = True
15
+
16
+ def run(self, options: Values, args: List[str]) -> int:
17
+ from pip._internal.commands import (
18
+ commands_dict,
19
+ create_command,
20
+ get_similar_commands,
21
+ )
22
+
23
+ try:
24
+ # 'pip help' with no args is handled by pip.__init__.parseopt()
25
+ cmd_name = args[0] # the command we need help for
26
+ except IndexError:
27
+ return SUCCESS
28
+
29
+ if cmd_name not in commands_dict:
30
+ guess = get_similar_commands(cmd_name)
31
+
32
+ msg = [f'unknown command "{cmd_name}"']
33
+ if guess:
34
+ msg.append(f'maybe you meant "{guess}"')
35
+
36
+ raise CommandError(" - ".join(msg))
37
+
38
+ command = create_command(cmd_name)
39
+ command.parser.print_help()
40
+
41
+ return SUCCESS
python_embeded/Lib/site-packages/pip/_internal/commands/index.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ from optparse import Values
4
+ from typing import Any, Iterable, List, Optional
5
+
6
+ from pip._vendor.packaging.version import Version
7
+
8
+ from pip._internal.cli import cmdoptions
9
+ from pip._internal.cli.req_command import IndexGroupCommand
10
+ from pip._internal.cli.status_codes import ERROR, SUCCESS
11
+ from pip._internal.commands.search import (
12
+ get_installed_distribution,
13
+ print_dist_installation_info,
14
+ )
15
+ from pip._internal.exceptions import CommandError, DistributionNotFound, PipError
16
+ from pip._internal.index.collector import LinkCollector
17
+ from pip._internal.index.package_finder import PackageFinder
18
+ from pip._internal.models.selection_prefs import SelectionPreferences
19
+ from pip._internal.models.target_python import TargetPython
20
+ from pip._internal.network.session import PipSession
21
+ from pip._internal.utils.misc import write_output
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ class IndexCommand(IndexGroupCommand):
27
+ """
28
+ Inspect information available from package indexes.
29
+ """
30
+
31
+ ignore_require_venv = True
32
+ usage = """
33
+ %prog versions <package>
34
+ """
35
+
36
+ def add_options(self) -> None:
37
+ cmdoptions.add_target_python_options(self.cmd_opts)
38
+
39
+ self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
40
+ self.cmd_opts.add_option(cmdoptions.pre())
41
+ self.cmd_opts.add_option(cmdoptions.json())
42
+ self.cmd_opts.add_option(cmdoptions.no_binary())
43
+ self.cmd_opts.add_option(cmdoptions.only_binary())
44
+
45
+ index_opts = cmdoptions.make_option_group(
46
+ cmdoptions.index_group,
47
+ self.parser,
48
+ )
49
+
50
+ self.parser.insert_option_group(0, index_opts)
51
+ self.parser.insert_option_group(0, self.cmd_opts)
52
+
53
+ def run(self, options: Values, args: List[str]) -> int:
54
+ handlers = {
55
+ "versions": self.get_available_package_versions,
56
+ }
57
+
58
+ # Determine action
59
+ if not args or args[0] not in handlers:
60
+ logger.error(
61
+ "Need an action (%s) to perform.",
62
+ ", ".join(sorted(handlers)),
63
+ )
64
+ return ERROR
65
+
66
+ action = args[0]
67
+
68
+ # Error handling happens here, not in the action-handlers.
69
+ try:
70
+ handlers[action](options, args[1:])
71
+ except PipError as e:
72
+ logger.error(e.args[0])
73
+ return ERROR
74
+
75
+ return SUCCESS
76
+
77
+ def _build_package_finder(
78
+ self,
79
+ options: Values,
80
+ session: PipSession,
81
+ target_python: Optional[TargetPython] = None,
82
+ ignore_requires_python: Optional[bool] = None,
83
+ ) -> PackageFinder:
84
+ """
85
+ Create a package finder appropriate to the index command.
86
+ """
87
+ link_collector = LinkCollector.create(session, options=options)
88
+
89
+ # Pass allow_yanked=False to ignore yanked versions.
90
+ selection_prefs = SelectionPreferences(
91
+ allow_yanked=False,
92
+ allow_all_prereleases=options.pre,
93
+ ignore_requires_python=ignore_requires_python,
94
+ )
95
+
96
+ return PackageFinder.create(
97
+ link_collector=link_collector,
98
+ selection_prefs=selection_prefs,
99
+ target_python=target_python,
100
+ )
101
+
102
+ def get_available_package_versions(self, options: Values, args: List[Any]) -> None:
103
+ if len(args) != 1:
104
+ raise CommandError("You need to specify exactly one argument")
105
+
106
+ target_python = cmdoptions.make_target_python(options)
107
+ query = args[0]
108
+
109
+ with self._build_session(options) as session:
110
+ finder = self._build_package_finder(
111
+ options=options,
112
+ session=session,
113
+ target_python=target_python,
114
+ ignore_requires_python=options.ignore_requires_python,
115
+ )
116
+
117
+ versions: Iterable[Version] = (
118
+ candidate.version for candidate in finder.find_all_candidates(query)
119
+ )
120
+
121
+ if not options.pre:
122
+ # Remove prereleases
123
+ versions = (
124
+ version for version in versions if not version.is_prerelease
125
+ )
126
+ versions = set(versions)
127
+
128
+ if not versions:
129
+ raise DistributionNotFound(
130
+ f"No matching distribution found for {query}"
131
+ )
132
+
133
+ formatted_versions = [str(ver) for ver in sorted(versions, reverse=True)]
134
+ latest = formatted_versions[0]
135
+
136
+ dist = get_installed_distribution(query)
137
+
138
+ if options.json:
139
+ structured_output = {
140
+ "name": query,
141
+ "versions": formatted_versions,
142
+ "latest": latest,
143
+ }
144
+
145
+ if dist is not None:
146
+ structured_output["installed_version"] = str(dist.version)
147
+
148
+ write_output(json.dumps(structured_output))
149
+
150
+ else:
151
+ write_output(f"{query} ({latest})")
152
+ write_output("Available versions: {}".format(", ".join(formatted_versions)))
153
+ print_dist_installation_info(latest, dist)
python_embeded/Lib/site-packages/pip/_internal/commands/inspect.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from optparse import Values
3
+ from typing import Any, Dict, List
4
+
5
+ from pip._vendor.packaging.markers import default_environment
6
+ from pip._vendor.rich import print_json
7
+
8
+ from pip import __version__
9
+ from pip._internal.cli import cmdoptions
10
+ from pip._internal.cli.base_command import Command
11
+ from pip._internal.cli.status_codes import SUCCESS
12
+ from pip._internal.metadata import BaseDistribution, get_environment
13
+ from pip._internal.utils.compat import stdlib_pkgs
14
+ from pip._internal.utils.urls import path_to_url
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class InspectCommand(Command):
20
+ """
21
+ Inspect the content of a Python environment and produce a report in JSON format.
22
+ """
23
+
24
+ ignore_require_venv = True
25
+ usage = """
26
+ %prog [options]"""
27
+
28
+ def add_options(self) -> None:
29
+ self.cmd_opts.add_option(
30
+ "--local",
31
+ action="store_true",
32
+ default=False,
33
+ help=(
34
+ "If in a virtualenv that has global access, do not list "
35
+ "globally-installed packages."
36
+ ),
37
+ )
38
+ self.cmd_opts.add_option(
39
+ "--user",
40
+ dest="user",
41
+ action="store_true",
42
+ default=False,
43
+ help="Only output packages installed in user-site.",
44
+ )
45
+ self.cmd_opts.add_option(cmdoptions.list_path())
46
+ self.parser.insert_option_group(0, self.cmd_opts)
47
+
48
+ def run(self, options: Values, args: List[str]) -> int:
49
+ cmdoptions.check_list_path_option(options)
50
+ dists = get_environment(options.path).iter_installed_distributions(
51
+ local_only=options.local,
52
+ user_only=options.user,
53
+ skip=set(stdlib_pkgs),
54
+ )
55
+ output = {
56
+ "version": "1",
57
+ "pip_version": __version__,
58
+ "installed": [self._dist_to_dict(dist) for dist in dists],
59
+ "environment": default_environment(),
60
+ # TODO tags? scheme?
61
+ }
62
+ print_json(data=output)
63
+ return SUCCESS
64
+
65
+ def _dist_to_dict(self, dist: BaseDistribution) -> Dict[str, Any]:
66
+ res: Dict[str, Any] = {
67
+ "metadata": dist.metadata_dict,
68
+ "metadata_location": dist.info_location,
69
+ }
70
+ # direct_url. Note that we don't have download_info (as in the installation
71
+ # report) since it is not recorded in installed metadata.
72
+ direct_url = dist.direct_url
73
+ if direct_url is not None:
74
+ res["direct_url"] = direct_url.to_dict()
75
+ else:
76
+ # Emulate direct_url for legacy editable installs.
77
+ editable_project_location = dist.editable_project_location
78
+ if editable_project_location is not None:
79
+ res["direct_url"] = {
80
+ "url": path_to_url(editable_project_location),
81
+ "dir_info": {
82
+ "editable": True,
83
+ },
84
+ }
85
+ # installer
86
+ installer = dist.installer
87
+ if dist.installer:
88
+ res["installer"] = installer
89
+ # requested
90
+ if dist.installed_with_dist_info:
91
+ res["requested"] = dist.requested
92
+ return res
python_embeded/Lib/site-packages/pip/_internal/commands/install.py ADDED
@@ -0,0 +1,793 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import errno
2
+ import json
3
+ import operator
4
+ import os
5
+ import shutil
6
+ import site
7
+ from optparse import SUPPRESS_HELP, Values
8
+ from typing import List, Optional
9
+
10
+ from pip._vendor.packaging.utils import canonicalize_name
11
+ from pip._vendor.requests.exceptions import InvalidProxyURL
12
+ from pip._vendor.rich import print_json
13
+
14
+ # Eagerly import self_outdated_check to avoid crashes. Otherwise,
15
+ # this module would be imported *after* pip was replaced, resulting
16
+ # in crashes if the new self_outdated_check module was incompatible
17
+ # with the rest of pip that's already imported, or allowing a
18
+ # wheel to execute arbitrary code on install by replacing
19
+ # self_outdated_check.
20
+ import pip._internal.self_outdated_check # noqa: F401
21
+ from pip._internal.cache import WheelCache
22
+ from pip._internal.cli import cmdoptions
23
+ from pip._internal.cli.cmdoptions import make_target_python
24
+ from pip._internal.cli.req_command import (
25
+ RequirementCommand,
26
+ with_cleanup,
27
+ )
28
+ from pip._internal.cli.status_codes import ERROR, SUCCESS
29
+ from pip._internal.exceptions import CommandError, InstallationError
30
+ from pip._internal.locations import get_scheme
31
+ from pip._internal.metadata import get_environment
32
+ from pip._internal.models.installation_report import InstallationReport
33
+ from pip._internal.operations.build.build_tracker import get_build_tracker
34
+ from pip._internal.operations.check import ConflictDetails, check_install_conflicts
35
+ from pip._internal.req import install_given_reqs
36
+ from pip._internal.req.req_install import (
37
+ InstallRequirement,
38
+ check_legacy_setup_py_options,
39
+ )
40
+ from pip._internal.utils.compat import WINDOWS
41
+ from pip._internal.utils.filesystem import test_writable_dir
42
+ from pip._internal.utils.logging import getLogger
43
+ from pip._internal.utils.misc import (
44
+ check_externally_managed,
45
+ ensure_dir,
46
+ get_pip_version,
47
+ protect_pip_from_modification_on_windows,
48
+ warn_if_run_as_root,
49
+ write_output,
50
+ )
51
+ from pip._internal.utils.temp_dir import TempDirectory
52
+ from pip._internal.utils.virtualenv import (
53
+ running_under_virtualenv,
54
+ virtualenv_no_global,
55
+ )
56
+ from pip._internal.wheel_builder import build, should_build_for_install_command
57
+
58
+ logger = getLogger(__name__)
59
+
60
+
61
+ class InstallCommand(RequirementCommand):
62
+ """
63
+ Install packages from:
64
+
65
+ - PyPI (and other indexes) using requirement specifiers.
66
+ - VCS project urls.
67
+ - Local project directories.
68
+ - Local or remote source archives.
69
+
70
+ pip also supports installing from "requirements files", which provide
71
+ an easy way to specify a whole environment to be installed.
72
+ """
73
+
74
+ usage = """
75
+ %prog [options] <requirement specifier> [package-index-options] ...
76
+ %prog [options] -r <requirements file> [package-index-options] ...
77
+ %prog [options] [-e] <vcs project url> ...
78
+ %prog [options] [-e] <local project path> ...
79
+ %prog [options] <archive url/path> ..."""
80
+
81
+ def add_options(self) -> None:
82
+ self.cmd_opts.add_option(cmdoptions.requirements())
83
+ self.cmd_opts.add_option(cmdoptions.constraints())
84
+ self.cmd_opts.add_option(cmdoptions.no_deps())
85
+ self.cmd_opts.add_option(cmdoptions.pre())
86
+
87
+ self.cmd_opts.add_option(cmdoptions.editable())
88
+ self.cmd_opts.add_option(
89
+ "--dry-run",
90
+ action="store_true",
91
+ dest="dry_run",
92
+ default=False,
93
+ help=(
94
+ "Don't actually install anything, just print what would be. "
95
+ "Can be used in combination with --ignore-installed "
96
+ "to 'resolve' the requirements."
97
+ ),
98
+ )
99
+ self.cmd_opts.add_option(
100
+ "-t",
101
+ "--target",
102
+ dest="target_dir",
103
+ metavar="dir",
104
+ default=None,
105
+ help=(
106
+ "Install packages into <dir>. "
107
+ "By default this will not replace existing files/folders in "
108
+ "<dir>. Use --upgrade to replace existing packages in <dir> "
109
+ "with new versions."
110
+ ),
111
+ )
112
+ cmdoptions.add_target_python_options(self.cmd_opts)
113
+
114
+ self.cmd_opts.add_option(
115
+ "--user",
116
+ dest="use_user_site",
117
+ action="store_true",
118
+ help=(
119
+ "Install to the Python user install directory for your "
120
+ "platform. Typically ~/.local/, or %APPDATA%\\Python on "
121
+ "Windows. (See the Python documentation for site.USER_BASE "
122
+ "for full details.)"
123
+ ),
124
+ )
125
+ self.cmd_opts.add_option(
126
+ "--no-user",
127
+ dest="use_user_site",
128
+ action="store_false",
129
+ help=SUPPRESS_HELP,
130
+ )
131
+ self.cmd_opts.add_option(
132
+ "--root",
133
+ dest="root_path",
134
+ metavar="dir",
135
+ default=None,
136
+ help="Install everything relative to this alternate root directory.",
137
+ )
138
+ self.cmd_opts.add_option(
139
+ "--prefix",
140
+ dest="prefix_path",
141
+ metavar="dir",
142
+ default=None,
143
+ help=(
144
+ "Installation prefix where lib, bin and other top-level "
145
+ "folders are placed. Note that the resulting installation may "
146
+ "contain scripts and other resources which reference the "
147
+ "Python interpreter of pip, and not that of ``--prefix``. "
148
+ "See also the ``--python`` option if the intention is to "
149
+ "install packages into another (possibly pip-free) "
150
+ "environment."
151
+ ),
152
+ )
153
+
154
+ self.cmd_opts.add_option(cmdoptions.src())
155
+
156
+ self.cmd_opts.add_option(
157
+ "-U",
158
+ "--upgrade",
159
+ dest="upgrade",
160
+ action="store_true",
161
+ help=(
162
+ "Upgrade all specified packages to the newest available "
163
+ "version. The handling of dependencies depends on the "
164
+ "upgrade-strategy used."
165
+ ),
166
+ )
167
+
168
+ self.cmd_opts.add_option(
169
+ "--upgrade-strategy",
170
+ dest="upgrade_strategy",
171
+ default="only-if-needed",
172
+ choices=["only-if-needed", "eager"],
173
+ help=(
174
+ "Determines how dependency upgrading should be handled "
175
+ "[default: %default]. "
176
+ '"eager" - dependencies are upgraded regardless of '
177
+ "whether the currently installed version satisfies the "
178
+ "requirements of the upgraded package(s). "
179
+ '"only-if-needed" - are upgraded only when they do not '
180
+ "satisfy the requirements of the upgraded package(s)."
181
+ ),
182
+ )
183
+
184
+ self.cmd_opts.add_option(
185
+ "--force-reinstall",
186
+ dest="force_reinstall",
187
+ action="store_true",
188
+ help="Reinstall all packages even if they are already up-to-date.",
189
+ )
190
+
191
+ self.cmd_opts.add_option(
192
+ "-I",
193
+ "--ignore-installed",
194
+ dest="ignore_installed",
195
+ action="store_true",
196
+ help=(
197
+ "Ignore the installed packages, overwriting them. "
198
+ "This can break your system if the existing package "
199
+ "is of a different version or was installed "
200
+ "with a different package manager!"
201
+ ),
202
+ )
203
+
204
+ self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
205
+ self.cmd_opts.add_option(cmdoptions.no_build_isolation())
206
+ self.cmd_opts.add_option(cmdoptions.use_pep517())
207
+ self.cmd_opts.add_option(cmdoptions.no_use_pep517())
208
+ self.cmd_opts.add_option(cmdoptions.check_build_deps())
209
+ self.cmd_opts.add_option(cmdoptions.override_externally_managed())
210
+
211
+ self.cmd_opts.add_option(cmdoptions.config_settings())
212
+ self.cmd_opts.add_option(cmdoptions.global_options())
213
+
214
+ self.cmd_opts.add_option(
215
+ "--compile",
216
+ action="store_true",
217
+ dest="compile",
218
+ default=True,
219
+ help="Compile Python source files to bytecode",
220
+ )
221
+
222
+ self.cmd_opts.add_option(
223
+ "--no-compile",
224
+ action="store_false",
225
+ dest="compile",
226
+ help="Do not compile Python source files to bytecode",
227
+ )
228
+
229
+ self.cmd_opts.add_option(
230
+ "--no-warn-script-location",
231
+ action="store_false",
232
+ dest="warn_script_location",
233
+ default=True,
234
+ help="Do not warn when installing scripts outside PATH",
235
+ )
236
+ self.cmd_opts.add_option(
237
+ "--no-warn-conflicts",
238
+ action="store_false",
239
+ dest="warn_about_conflicts",
240
+ default=True,
241
+ help="Do not warn about broken dependencies",
242
+ )
243
+ self.cmd_opts.add_option(cmdoptions.no_binary())
244
+ self.cmd_opts.add_option(cmdoptions.only_binary())
245
+ self.cmd_opts.add_option(cmdoptions.prefer_binary())
246
+ self.cmd_opts.add_option(cmdoptions.require_hashes())
247
+ self.cmd_opts.add_option(cmdoptions.progress_bar())
248
+ self.cmd_opts.add_option(cmdoptions.root_user_action())
249
+
250
+ index_opts = cmdoptions.make_option_group(
251
+ cmdoptions.index_group,
252
+ self.parser,
253
+ )
254
+
255
+ self.parser.insert_option_group(0, index_opts)
256
+ self.parser.insert_option_group(0, self.cmd_opts)
257
+
258
+ self.cmd_opts.add_option(
259
+ "--report",
260
+ dest="json_report_file",
261
+ metavar="file",
262
+ default=None,
263
+ help=(
264
+ "Generate a JSON file describing what pip did to install "
265
+ "the provided requirements. "
266
+ "Can be used in combination with --dry-run and --ignore-installed "
267
+ "to 'resolve' the requirements. "
268
+ "When - is used as file name it writes to stdout. "
269
+ "When writing to stdout, please combine with the --quiet option "
270
+ "to avoid mixing pip logging output with JSON output."
271
+ ),
272
+ )
273
+
274
+ @with_cleanup
275
+ def run(self, options: Values, args: List[str]) -> int:
276
+ if options.use_user_site and options.target_dir is not None:
277
+ raise CommandError("Can not combine '--user' and '--target'")
278
+
279
+ # Check whether the environment we're installing into is externally
280
+ # managed, as specified in PEP 668. Specifying --root, --target, or
281
+ # --prefix disables the check, since there's no reliable way to locate
282
+ # the EXTERNALLY-MANAGED file for those cases. An exception is also
283
+ # made specifically for "--dry-run --report" for convenience.
284
+ installing_into_current_environment = (
285
+ not (options.dry_run and options.json_report_file)
286
+ and options.root_path is None
287
+ and options.target_dir is None
288
+ and options.prefix_path is None
289
+ )
290
+ if (
291
+ installing_into_current_environment
292
+ and not options.override_externally_managed
293
+ ):
294
+ check_externally_managed()
295
+
296
+ upgrade_strategy = "to-satisfy-only"
297
+ if options.upgrade:
298
+ upgrade_strategy = options.upgrade_strategy
299
+
300
+ cmdoptions.check_dist_restriction(options, check_target=True)
301
+
302
+ logger.verbose("Using %s", get_pip_version())
303
+ options.use_user_site = decide_user_install(
304
+ options.use_user_site,
305
+ prefix_path=options.prefix_path,
306
+ target_dir=options.target_dir,
307
+ root_path=options.root_path,
308
+ isolated_mode=options.isolated_mode,
309
+ )
310
+
311
+ target_temp_dir: Optional[TempDirectory] = None
312
+ target_temp_dir_path: Optional[str] = None
313
+ if options.target_dir:
314
+ options.ignore_installed = True
315
+ options.target_dir = os.path.abspath(options.target_dir)
316
+ if (
317
+ # fmt: off
318
+ os.path.exists(options.target_dir) and
319
+ not os.path.isdir(options.target_dir)
320
+ # fmt: on
321
+ ):
322
+ raise CommandError(
323
+ "Target path exists but is not a directory, will not continue."
324
+ )
325
+
326
+ # Create a target directory for using with the target option
327
+ target_temp_dir = TempDirectory(kind="target")
328
+ target_temp_dir_path = target_temp_dir.path
329
+ self.enter_context(target_temp_dir)
330
+
331
+ global_options = options.global_options or []
332
+
333
+ session = self.get_default_session(options)
334
+
335
+ target_python = make_target_python(options)
336
+ finder = self._build_package_finder(
337
+ options=options,
338
+ session=session,
339
+ target_python=target_python,
340
+ ignore_requires_python=options.ignore_requires_python,
341
+ )
342
+ build_tracker = self.enter_context(get_build_tracker())
343
+
344
+ directory = TempDirectory(
345
+ delete=not options.no_clean,
346
+ kind="install",
347
+ globally_managed=True,
348
+ )
349
+
350
+ try:
351
+ reqs = self.get_requirements(args, options, finder, session)
352
+ check_legacy_setup_py_options(options, reqs)
353
+
354
+ wheel_cache = WheelCache(options.cache_dir)
355
+
356
+ # Only when installing is it permitted to use PEP 660.
357
+ # In other circumstances (pip wheel, pip download) we generate
358
+ # regular (i.e. non editable) metadata and wheels.
359
+ for req in reqs:
360
+ req.permit_editable_wheels = True
361
+
362
+ preparer = self.make_requirement_preparer(
363
+ temp_build_dir=directory,
364
+ options=options,
365
+ build_tracker=build_tracker,
366
+ session=session,
367
+ finder=finder,
368
+ use_user_site=options.use_user_site,
369
+ verbosity=self.verbosity,
370
+ )
371
+ resolver = self.make_resolver(
372
+ preparer=preparer,
373
+ finder=finder,
374
+ options=options,
375
+ wheel_cache=wheel_cache,
376
+ use_user_site=options.use_user_site,
377
+ ignore_installed=options.ignore_installed,
378
+ ignore_requires_python=options.ignore_requires_python,
379
+ force_reinstall=options.force_reinstall,
380
+ upgrade_strategy=upgrade_strategy,
381
+ use_pep517=options.use_pep517,
382
+ py_version_info=options.python_version,
383
+ )
384
+
385
+ self.trace_basic_info(finder)
386
+
387
+ requirement_set = resolver.resolve(
388
+ reqs, check_supported_wheels=not options.target_dir
389
+ )
390
+
391
+ if options.json_report_file:
392
+ report = InstallationReport(requirement_set.requirements_to_install)
393
+ if options.json_report_file == "-":
394
+ print_json(data=report.to_dict())
395
+ else:
396
+ with open(options.json_report_file, "w", encoding="utf-8") as f:
397
+ json.dump(report.to_dict(), f, indent=2, ensure_ascii=False)
398
+
399
+ if options.dry_run:
400
+ would_install_items = sorted(
401
+ (r.metadata["name"], r.metadata["version"])
402
+ for r in requirement_set.requirements_to_install
403
+ )
404
+ if would_install_items:
405
+ write_output(
406
+ "Would install %s",
407
+ " ".join("-".join(item) for item in would_install_items),
408
+ )
409
+ return SUCCESS
410
+
411
+ try:
412
+ pip_req = requirement_set.get_requirement("pip")
413
+ except KeyError:
414
+ modifying_pip = False
415
+ else:
416
+ # If we're not replacing an already installed pip,
417
+ # we're not modifying it.
418
+ modifying_pip = pip_req.satisfied_by is None
419
+ protect_pip_from_modification_on_windows(modifying_pip=modifying_pip)
420
+
421
+ reqs_to_build = [
422
+ r
423
+ for r in requirement_set.requirements_to_install
424
+ if should_build_for_install_command(r)
425
+ ]
426
+
427
+ _, build_failures = build(
428
+ reqs_to_build,
429
+ wheel_cache=wheel_cache,
430
+ verify=True,
431
+ build_options=[],
432
+ global_options=global_options,
433
+ )
434
+
435
+ if build_failures:
436
+ raise InstallationError(
437
+ "Failed to build installable wheels for some "
438
+ "pyproject.toml based projects ({})".format(
439
+ ", ".join(r.name for r in build_failures) # type: ignore
440
+ )
441
+ )
442
+
443
+ to_install = resolver.get_installation_order(requirement_set)
444
+
445
+ # Check for conflicts in the package set we're installing.
446
+ conflicts: Optional[ConflictDetails] = None
447
+ should_warn_about_conflicts = (
448
+ not options.ignore_dependencies and options.warn_about_conflicts
449
+ )
450
+ if should_warn_about_conflicts:
451
+ conflicts = self._determine_conflicts(to_install)
452
+
453
+ # Don't warn about script install locations if
454
+ # --target or --prefix has been specified
455
+ warn_script_location = options.warn_script_location
456
+ if options.target_dir or options.prefix_path:
457
+ warn_script_location = False
458
+
459
+ installed = install_given_reqs(
460
+ to_install,
461
+ global_options,
462
+ root=options.root_path,
463
+ home=target_temp_dir_path,
464
+ prefix=options.prefix_path,
465
+ warn_script_location=warn_script_location,
466
+ use_user_site=options.use_user_site,
467
+ pycompile=options.compile,
468
+ progress_bar=options.progress_bar,
469
+ )
470
+
471
+ lib_locations = get_lib_location_guesses(
472
+ user=options.use_user_site,
473
+ home=target_temp_dir_path,
474
+ root=options.root_path,
475
+ prefix=options.prefix_path,
476
+ isolated=options.isolated_mode,
477
+ )
478
+ env = get_environment(lib_locations)
479
+
480
+ # Display a summary of installed packages, with extra care to
481
+ # display a package name as it was requested by the user.
482
+ installed.sort(key=operator.attrgetter("name"))
483
+ summary = []
484
+ installed_versions = {}
485
+ for distribution in env.iter_all_distributions():
486
+ installed_versions[distribution.canonical_name] = distribution.version
487
+ for package in installed:
488
+ display_name = package.name
489
+ version = installed_versions.get(canonicalize_name(display_name), None)
490
+ if version:
491
+ text = f"{display_name}-{version}"
492
+ else:
493
+ text = display_name
494
+ summary.append(text)
495
+
496
+ if conflicts is not None:
497
+ self._warn_about_conflicts(
498
+ conflicts,
499
+ resolver_variant=self.determine_resolver_variant(options),
500
+ )
501
+
502
+ installed_desc = " ".join(summary)
503
+ if installed_desc:
504
+ write_output(
505
+ "Successfully installed %s",
506
+ installed_desc,
507
+ )
508
+ except OSError as error:
509
+ show_traceback = self.verbosity >= 1
510
+
511
+ message = create_os_error_message(
512
+ error,
513
+ show_traceback,
514
+ options.use_user_site,
515
+ )
516
+ logger.error(message, exc_info=show_traceback)
517
+
518
+ return ERROR
519
+
520
+ if options.target_dir:
521
+ assert target_temp_dir
522
+ self._handle_target_dir(
523
+ options.target_dir, target_temp_dir, options.upgrade
524
+ )
525
+ if options.root_user_action == "warn":
526
+ warn_if_run_as_root()
527
+ return SUCCESS
528
+
529
+ def _handle_target_dir(
530
+ self, target_dir: str, target_temp_dir: TempDirectory, upgrade: bool
531
+ ) -> None:
532
+ ensure_dir(target_dir)
533
+
534
+ # Checking both purelib and platlib directories for installed
535
+ # packages to be moved to target directory
536
+ lib_dir_list = []
537
+
538
+ # Checking both purelib and platlib directories for installed
539
+ # packages to be moved to target directory
540
+ scheme = get_scheme("", home=target_temp_dir.path)
541
+ purelib_dir = scheme.purelib
542
+ platlib_dir = scheme.platlib
543
+ data_dir = scheme.data
544
+
545
+ if os.path.exists(purelib_dir):
546
+ lib_dir_list.append(purelib_dir)
547
+ if os.path.exists(platlib_dir) and platlib_dir != purelib_dir:
548
+ lib_dir_list.append(platlib_dir)
549
+ if os.path.exists(data_dir):
550
+ lib_dir_list.append(data_dir)
551
+
552
+ for lib_dir in lib_dir_list:
553
+ for item in os.listdir(lib_dir):
554
+ if lib_dir == data_dir:
555
+ ddir = os.path.join(data_dir, item)
556
+ if any(s.startswith(ddir) for s in lib_dir_list[:-1]):
557
+ continue
558
+ target_item_dir = os.path.join(target_dir, item)
559
+ if os.path.exists(target_item_dir):
560
+ if not upgrade:
561
+ logger.warning(
562
+ "Target directory %s already exists. Specify "
563
+ "--upgrade to force replacement.",
564
+ target_item_dir,
565
+ )
566
+ continue
567
+ if os.path.islink(target_item_dir):
568
+ logger.warning(
569
+ "Target directory %s already exists and is "
570
+ "a link. pip will not automatically replace "
571
+ "links, please remove if replacement is "
572
+ "desired.",
573
+ target_item_dir,
574
+ )
575
+ continue
576
+ if os.path.isdir(target_item_dir):
577
+ shutil.rmtree(target_item_dir)
578
+ else:
579
+ os.remove(target_item_dir)
580
+
581
+ shutil.move(os.path.join(lib_dir, item), target_item_dir)
582
+
583
+ def _determine_conflicts(
584
+ self, to_install: List[InstallRequirement]
585
+ ) -> Optional[ConflictDetails]:
586
+ try:
587
+ return check_install_conflicts(to_install)
588
+ except Exception:
589
+ logger.exception(
590
+ "Error while checking for conflicts. Please file an issue on "
591
+ "pip's issue tracker: https://github.com/pypa/pip/issues/new"
592
+ )
593
+ return None
594
+
595
+ def _warn_about_conflicts(
596
+ self, conflict_details: ConflictDetails, resolver_variant: str
597
+ ) -> None:
598
+ package_set, (missing, conflicting) = conflict_details
599
+ if not missing and not conflicting:
600
+ return
601
+
602
+ parts: List[str] = []
603
+ if resolver_variant == "legacy":
604
+ parts.append(
605
+ "pip's legacy dependency resolver does not consider dependency "
606
+ "conflicts when selecting packages. This behaviour is the "
607
+ "source of the following dependency conflicts."
608
+ )
609
+ else:
610
+ assert resolver_variant == "resolvelib"
611
+ parts.append(
612
+ "pip's dependency resolver does not currently take into account "
613
+ "all the packages that are installed. This behaviour is the "
614
+ "source of the following dependency conflicts."
615
+ )
616
+
617
+ # NOTE: There is some duplication here, with commands/check.py
618
+ for project_name in missing:
619
+ version = package_set[project_name][0]
620
+ for dependency in missing[project_name]:
621
+ message = (
622
+ f"{project_name} {version} requires {dependency[1]}, "
623
+ "which is not installed."
624
+ )
625
+ parts.append(message)
626
+
627
+ for project_name in conflicting:
628
+ version = package_set[project_name][0]
629
+ for dep_name, dep_version, req in conflicting[project_name]:
630
+ message = (
631
+ "{name} {version} requires {requirement}, but {you} have "
632
+ "{dep_name} {dep_version} which is incompatible."
633
+ ).format(
634
+ name=project_name,
635
+ version=version,
636
+ requirement=req,
637
+ dep_name=dep_name,
638
+ dep_version=dep_version,
639
+ you=("you" if resolver_variant == "resolvelib" else "you'll"),
640
+ )
641
+ parts.append(message)
642
+
643
+ logger.critical("\n".join(parts))
644
+
645
+
646
+ def get_lib_location_guesses(
647
+ user: bool = False,
648
+ home: Optional[str] = None,
649
+ root: Optional[str] = None,
650
+ isolated: bool = False,
651
+ prefix: Optional[str] = None,
652
+ ) -> List[str]:
653
+ scheme = get_scheme(
654
+ "",
655
+ user=user,
656
+ home=home,
657
+ root=root,
658
+ isolated=isolated,
659
+ prefix=prefix,
660
+ )
661
+ return [scheme.purelib, scheme.platlib]
662
+
663
+
664
+ def site_packages_writable(root: Optional[str], isolated: bool) -> bool:
665
+ return all(
666
+ test_writable_dir(d)
667
+ for d in set(get_lib_location_guesses(root=root, isolated=isolated))
668
+ )
669
+
670
+
671
+ def decide_user_install(
672
+ use_user_site: Optional[bool],
673
+ prefix_path: Optional[str] = None,
674
+ target_dir: Optional[str] = None,
675
+ root_path: Optional[str] = None,
676
+ isolated_mode: bool = False,
677
+ ) -> bool:
678
+ """Determine whether to do a user install based on the input options.
679
+
680
+ If use_user_site is False, no additional checks are done.
681
+ If use_user_site is True, it is checked for compatibility with other
682
+ options.
683
+ If use_user_site is None, the default behaviour depends on the environment,
684
+ which is provided by the other arguments.
685
+ """
686
+ # In some cases (config from tox), use_user_site can be set to an integer
687
+ # rather than a bool, which 'use_user_site is False' wouldn't catch.
688
+ if (use_user_site is not None) and (not use_user_site):
689
+ logger.debug("Non-user install by explicit request")
690
+ return False
691
+
692
+ if use_user_site:
693
+ if prefix_path:
694
+ raise CommandError(
695
+ "Can not combine '--user' and '--prefix' as they imply "
696
+ "different installation locations"
697
+ )
698
+ if virtualenv_no_global():
699
+ raise InstallationError(
700
+ "Can not perform a '--user' install. User site-packages "
701
+ "are not visible in this virtualenv."
702
+ )
703
+ logger.debug("User install by explicit request")
704
+ return True
705
+
706
+ # If we are here, user installs have not been explicitly requested/avoided
707
+ assert use_user_site is None
708
+
709
+ # user install incompatible with --prefix/--target
710
+ if prefix_path or target_dir:
711
+ logger.debug("Non-user install due to --prefix or --target option")
712
+ return False
713
+
714
+ # If user installs are not enabled, choose a non-user install
715
+ if not site.ENABLE_USER_SITE:
716
+ logger.debug("Non-user install because user site-packages disabled")
717
+ return False
718
+
719
+ # If we have permission for a non-user install, do that,
720
+ # otherwise do a user install.
721
+ if site_packages_writable(root=root_path, isolated=isolated_mode):
722
+ logger.debug("Non-user install because site-packages writeable")
723
+ return False
724
+
725
+ logger.info(
726
+ "Defaulting to user installation because normal site-packages "
727
+ "is not writeable"
728
+ )
729
+ return True
730
+
731
+
732
+ def create_os_error_message(
733
+ error: OSError, show_traceback: bool, using_user_site: bool
734
+ ) -> str:
735
+ """Format an error message for an OSError
736
+
737
+ It may occur anytime during the execution of the install command.
738
+ """
739
+ parts = []
740
+
741
+ # Mention the error if we are not going to show a traceback
742
+ parts.append("Could not install packages due to an OSError")
743
+ if not show_traceback:
744
+ parts.append(": ")
745
+ parts.append(str(error))
746
+ else:
747
+ parts.append(".")
748
+
749
+ # Spilt the error indication from a helper message (if any)
750
+ parts[-1] += "\n"
751
+
752
+ # Suggest useful actions to the user:
753
+ # (1) using user site-packages or (2) verifying the permissions
754
+ if error.errno == errno.EACCES:
755
+ user_option_part = "Consider using the `--user` option"
756
+ permissions_part = "Check the permissions"
757
+
758
+ if not running_under_virtualenv() and not using_user_site:
759
+ parts.extend(
760
+ [
761
+ user_option_part,
762
+ " or ",
763
+ permissions_part.lower(),
764
+ ]
765
+ )
766
+ else:
767
+ parts.append(permissions_part)
768
+ parts.append(".\n")
769
+
770
+ # Suggest to check "pip config debug" in case of invalid proxy
771
+ if type(error) is InvalidProxyURL:
772
+ parts.append(
773
+ 'Consider checking your local proxy configuration with "pip config debug"'
774
+ )
775
+ parts.append(".\n")
776
+
777
+ # Suggest the user to enable Long Paths if path length is
778
+ # more than 260
779
+ if (
780
+ WINDOWS
781
+ and error.errno == errno.ENOENT
782
+ and error.filename
783
+ and len(error.filename) > 260
784
+ ):
785
+ parts.append(
786
+ "HINT: This error might have occurred since "
787
+ "this system does not have Windows Long Path "
788
+ "support enabled. You can find information on "
789
+ "how to enable this at "
790
+ "https://pip.pypa.io/warnings/enable-long-paths\n"
791
+ )
792
+
793
+ return "".join(parts).strip() + "\n"
python_embeded/Lib/site-packages/pip/_internal/commands/list.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ from email.parser import Parser
4
+ from optparse import Values
5
+ from typing import TYPE_CHECKING, Generator, List, Optional, Sequence, Tuple, cast
6
+
7
+ from pip._vendor.packaging.utils import canonicalize_name
8
+ from pip._vendor.packaging.version import Version
9
+
10
+ from pip._internal.cli import cmdoptions
11
+ from pip._internal.cli.index_command import IndexGroupCommand
12
+ from pip._internal.cli.status_codes import SUCCESS
13
+ from pip._internal.exceptions import CommandError
14
+ from pip._internal.metadata import BaseDistribution, get_environment
15
+ from pip._internal.models.selection_prefs import SelectionPreferences
16
+ from pip._internal.utils.compat import stdlib_pkgs
17
+ from pip._internal.utils.misc import tabulate, write_output
18
+
19
+ if TYPE_CHECKING:
20
+ from pip._internal.index.package_finder import PackageFinder
21
+ from pip._internal.network.session import PipSession
22
+
23
+ class _DistWithLatestInfo(BaseDistribution):
24
+ """Give the distribution object a couple of extra fields.
25
+
26
+ These will be populated during ``get_outdated()``. This is dirty but
27
+ makes the rest of the code much cleaner.
28
+ """
29
+
30
+ latest_version: Version
31
+ latest_filetype: str
32
+
33
+ _ProcessedDists = Sequence[_DistWithLatestInfo]
34
+
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+
39
+ class ListCommand(IndexGroupCommand):
40
+ """
41
+ List installed packages, including editables.
42
+
43
+ Packages are listed in a case-insensitive sorted order.
44
+ """
45
+
46
+ ignore_require_venv = True
47
+ usage = """
48
+ %prog [options]"""
49
+
50
+ def add_options(self) -> None:
51
+ self.cmd_opts.add_option(
52
+ "-o",
53
+ "--outdated",
54
+ action="store_true",
55
+ default=False,
56
+ help="List outdated packages",
57
+ )
58
+ self.cmd_opts.add_option(
59
+ "-u",
60
+ "--uptodate",
61
+ action="store_true",
62
+ default=False,
63
+ help="List uptodate packages",
64
+ )
65
+ self.cmd_opts.add_option(
66
+ "-e",
67
+ "--editable",
68
+ action="store_true",
69
+ default=False,
70
+ help="List editable projects.",
71
+ )
72
+ self.cmd_opts.add_option(
73
+ "-l",
74
+ "--local",
75
+ action="store_true",
76
+ default=False,
77
+ help=(
78
+ "If in a virtualenv that has global access, do not list "
79
+ "globally-installed packages."
80
+ ),
81
+ )
82
+ self.cmd_opts.add_option(
83
+ "--user",
84
+ dest="user",
85
+ action="store_true",
86
+ default=False,
87
+ help="Only output packages installed in user-site.",
88
+ )
89
+ self.cmd_opts.add_option(cmdoptions.list_path())
90
+ self.cmd_opts.add_option(
91
+ "--pre",
92
+ action="store_true",
93
+ default=False,
94
+ help=(
95
+ "Include pre-release and development versions. By default, "
96
+ "pip only finds stable versions."
97
+ ),
98
+ )
99
+
100
+ self.cmd_opts.add_option(
101
+ "--format",
102
+ action="store",
103
+ dest="list_format",
104
+ default="columns",
105
+ choices=("columns", "freeze", "json"),
106
+ help=(
107
+ "Select the output format among: columns (default), freeze, or json. "
108
+ "The 'freeze' format cannot be used with the --outdated option."
109
+ ),
110
+ )
111
+
112
+ self.cmd_opts.add_option(
113
+ "--not-required",
114
+ action="store_true",
115
+ dest="not_required",
116
+ help="List packages that are not dependencies of installed packages.",
117
+ )
118
+
119
+ self.cmd_opts.add_option(
120
+ "--exclude-editable",
121
+ action="store_false",
122
+ dest="include_editable",
123
+ help="Exclude editable package from output.",
124
+ )
125
+ self.cmd_opts.add_option(
126
+ "--include-editable",
127
+ action="store_true",
128
+ dest="include_editable",
129
+ help="Include editable package in output.",
130
+ default=True,
131
+ )
132
+ self.cmd_opts.add_option(cmdoptions.list_exclude())
133
+ index_opts = cmdoptions.make_option_group(cmdoptions.index_group, self.parser)
134
+
135
+ self.parser.insert_option_group(0, index_opts)
136
+ self.parser.insert_option_group(0, self.cmd_opts)
137
+
138
+ def handle_pip_version_check(self, options: Values) -> None:
139
+ if options.outdated or options.uptodate:
140
+ super().handle_pip_version_check(options)
141
+
142
+ def _build_package_finder(
143
+ self, options: Values, session: "PipSession"
144
+ ) -> "PackageFinder":
145
+ """
146
+ Create a package finder appropriate to this list command.
147
+ """
148
+ # Lazy import the heavy index modules as most list invocations won't need 'em.
149
+ from pip._internal.index.collector import LinkCollector
150
+ from pip._internal.index.package_finder import PackageFinder
151
+
152
+ link_collector = LinkCollector.create(session, options=options)
153
+
154
+ # Pass allow_yanked=False to ignore yanked versions.
155
+ selection_prefs = SelectionPreferences(
156
+ allow_yanked=False,
157
+ allow_all_prereleases=options.pre,
158
+ )
159
+
160
+ return PackageFinder.create(
161
+ link_collector=link_collector,
162
+ selection_prefs=selection_prefs,
163
+ )
164
+
165
+ def run(self, options: Values, args: List[str]) -> int:
166
+ if options.outdated and options.uptodate:
167
+ raise CommandError("Options --outdated and --uptodate cannot be combined.")
168
+
169
+ if options.outdated and options.list_format == "freeze":
170
+ raise CommandError(
171
+ "List format 'freeze' cannot be used with the --outdated option."
172
+ )
173
+
174
+ cmdoptions.check_list_path_option(options)
175
+
176
+ skip = set(stdlib_pkgs)
177
+ if options.excludes:
178
+ skip.update(canonicalize_name(n) for n in options.excludes)
179
+
180
+ packages: _ProcessedDists = [
181
+ cast("_DistWithLatestInfo", d)
182
+ for d in get_environment(options.path).iter_installed_distributions(
183
+ local_only=options.local,
184
+ user_only=options.user,
185
+ editables_only=options.editable,
186
+ include_editables=options.include_editable,
187
+ skip=skip,
188
+ )
189
+ ]
190
+
191
+ # get_not_required must be called firstly in order to find and
192
+ # filter out all dependencies correctly. Otherwise a package
193
+ # can't be identified as requirement because some parent packages
194
+ # could be filtered out before.
195
+ if options.not_required:
196
+ packages = self.get_not_required(packages, options)
197
+
198
+ if options.outdated:
199
+ packages = self.get_outdated(packages, options)
200
+ elif options.uptodate:
201
+ packages = self.get_uptodate(packages, options)
202
+
203
+ self.output_package_listing(packages, options)
204
+ return SUCCESS
205
+
206
+ def get_outdated(
207
+ self, packages: "_ProcessedDists", options: Values
208
+ ) -> "_ProcessedDists":
209
+ return [
210
+ dist
211
+ for dist in self.iter_packages_latest_infos(packages, options)
212
+ if dist.latest_version > dist.version
213
+ ]
214
+
215
+ def get_uptodate(
216
+ self, packages: "_ProcessedDists", options: Values
217
+ ) -> "_ProcessedDists":
218
+ return [
219
+ dist
220
+ for dist in self.iter_packages_latest_infos(packages, options)
221
+ if dist.latest_version == dist.version
222
+ ]
223
+
224
+ def get_not_required(
225
+ self, packages: "_ProcessedDists", options: Values
226
+ ) -> "_ProcessedDists":
227
+ dep_keys = {
228
+ canonicalize_name(dep.name)
229
+ for dist in packages
230
+ for dep in (dist.iter_dependencies() or ())
231
+ }
232
+
233
+ # Create a set to remove duplicate packages, and cast it to a list
234
+ # to keep the return type consistent with get_outdated and
235
+ # get_uptodate
236
+ return list({pkg for pkg in packages if pkg.canonical_name not in dep_keys})
237
+
238
+ def iter_packages_latest_infos(
239
+ self, packages: "_ProcessedDists", options: Values
240
+ ) -> Generator["_DistWithLatestInfo", None, None]:
241
+ with self._build_session(options) as session:
242
+ finder = self._build_package_finder(options, session)
243
+
244
+ def latest_info(
245
+ dist: "_DistWithLatestInfo",
246
+ ) -> Optional["_DistWithLatestInfo"]:
247
+ all_candidates = finder.find_all_candidates(dist.canonical_name)
248
+ if not options.pre:
249
+ # Remove prereleases
250
+ all_candidates = [
251
+ candidate
252
+ for candidate in all_candidates
253
+ if not candidate.version.is_prerelease
254
+ ]
255
+
256
+ evaluator = finder.make_candidate_evaluator(
257
+ project_name=dist.canonical_name,
258
+ )
259
+ best_candidate = evaluator.sort_best_candidate(all_candidates)
260
+ if best_candidate is None:
261
+ return None
262
+
263
+ remote_version = best_candidate.version
264
+ if best_candidate.link.is_wheel:
265
+ typ = "wheel"
266
+ else:
267
+ typ = "sdist"
268
+ dist.latest_version = remote_version
269
+ dist.latest_filetype = typ
270
+ return dist
271
+
272
+ for dist in map(latest_info, packages):
273
+ if dist is not None:
274
+ yield dist
275
+
276
+ def output_package_listing(
277
+ self, packages: "_ProcessedDists", options: Values
278
+ ) -> None:
279
+ packages = sorted(
280
+ packages,
281
+ key=lambda dist: dist.canonical_name,
282
+ )
283
+ if options.list_format == "columns" and packages:
284
+ data, header = format_for_columns(packages, options)
285
+ self.output_package_listing_columns(data, header)
286
+ elif options.list_format == "freeze":
287
+ for dist in packages:
288
+ if options.verbose >= 1:
289
+ write_output(
290
+ "%s==%s (%s)", dist.raw_name, dist.version, dist.location
291
+ )
292
+ else:
293
+ write_output("%s==%s", dist.raw_name, dist.version)
294
+ elif options.list_format == "json":
295
+ write_output(format_for_json(packages, options))
296
+
297
+ def output_package_listing_columns(
298
+ self, data: List[List[str]], header: List[str]
299
+ ) -> None:
300
+ # insert the header first: we need to know the size of column names
301
+ if len(data) > 0:
302
+ data.insert(0, header)
303
+
304
+ pkg_strings, sizes = tabulate(data)
305
+
306
+ # Create and add a separator.
307
+ if len(data) > 0:
308
+ pkg_strings.insert(1, " ".join("-" * x for x in sizes))
309
+
310
+ for val in pkg_strings:
311
+ write_output(val)
312
+
313
+
314
+ def format_for_columns(
315
+ pkgs: "_ProcessedDists", options: Values
316
+ ) -> Tuple[List[List[str]], List[str]]:
317
+ """
318
+ Convert the package data into something usable
319
+ by output_package_listing_columns.
320
+ """
321
+ header = ["Package", "Version"]
322
+
323
+ running_outdated = options.outdated
324
+ if running_outdated:
325
+ header.extend(["Latest", "Type"])
326
+
327
+ def wheel_build_tag(dist: BaseDistribution) -> Optional[str]:
328
+ try:
329
+ wheel_file = dist.read_text("WHEEL")
330
+ except FileNotFoundError:
331
+ return None
332
+ return Parser().parsestr(wheel_file).get("Build")
333
+
334
+ build_tags = [wheel_build_tag(p) for p in pkgs]
335
+ has_build_tags = any(build_tags)
336
+ if has_build_tags:
337
+ header.append("Build")
338
+
339
+ if options.verbose >= 1:
340
+ header.append("Location")
341
+ if options.verbose >= 1:
342
+ header.append("Installer")
343
+
344
+ has_editables = any(x.editable for x in pkgs)
345
+ if has_editables:
346
+ header.append("Editable project location")
347
+
348
+ data = []
349
+ for i, proj in enumerate(pkgs):
350
+ # if we're working on the 'outdated' list, separate out the
351
+ # latest_version and type
352
+ row = [proj.raw_name, proj.raw_version]
353
+
354
+ if running_outdated:
355
+ row.append(str(proj.latest_version))
356
+ row.append(proj.latest_filetype)
357
+
358
+ if has_build_tags:
359
+ row.append(build_tags[i] or "")
360
+
361
+ if has_editables:
362
+ row.append(proj.editable_project_location or "")
363
+
364
+ if options.verbose >= 1:
365
+ row.append(proj.location or "")
366
+ if options.verbose >= 1:
367
+ row.append(proj.installer)
368
+
369
+ data.append(row)
370
+
371
+ return data, header
372
+
373
+
374
+ def format_for_json(packages: "_ProcessedDists", options: Values) -> str:
375
+ data = []
376
+ for dist in packages:
377
+ info = {
378
+ "name": dist.raw_name,
379
+ "version": str(dist.version),
380
+ }
381
+ if options.verbose >= 1:
382
+ info["location"] = dist.location or ""
383
+ info["installer"] = dist.installer
384
+ if options.outdated:
385
+ info["latest_version"] = str(dist.latest_version)
386
+ info["latest_filetype"] = dist.latest_filetype
387
+ editable_project_location = dist.editable_project_location
388
+ if editable_project_location:
389
+ info["editable_project_location"] = editable_project_location
390
+ data.append(info)
391
+ return json.dumps(data)
python_embeded/Lib/site-packages/pip/_internal/commands/lock.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from optparse import Values
3
+ from pathlib import Path
4
+ from typing import List
5
+
6
+ from pip._internal.cache import WheelCache
7
+ from pip._internal.cli import cmdoptions
8
+ from pip._internal.cli.req_command import (
9
+ RequirementCommand,
10
+ with_cleanup,
11
+ )
12
+ from pip._internal.cli.status_codes import SUCCESS
13
+ from pip._internal.models.pylock import Pylock, is_valid_pylock_file_name
14
+ from pip._internal.operations.build.build_tracker import get_build_tracker
15
+ from pip._internal.req.req_install import (
16
+ check_legacy_setup_py_options,
17
+ )
18
+ from pip._internal.utils.logging import getLogger
19
+ from pip._internal.utils.misc import (
20
+ get_pip_version,
21
+ )
22
+ from pip._internal.utils.temp_dir import TempDirectory
23
+
24
+ logger = getLogger(__name__)
25
+
26
+
27
+ class LockCommand(RequirementCommand):
28
+ """
29
+ EXPERIMENTAL - Lock packages and their dependencies from:
30
+
31
+ - PyPI (and other indexes) using requirement specifiers.
32
+ - VCS project urls.
33
+ - Local project directories.
34
+ - Local or remote source archives.
35
+
36
+ pip also supports locking from "requirements files", which provide an easy
37
+ way to specify a whole environment to be installed.
38
+
39
+ The generated lock file is only guaranteed to be valid for the current
40
+ python version and platform.
41
+ """
42
+
43
+ usage = """
44
+ %prog [options] [-e] <local project path> ...
45
+ %prog [options] <requirement specifier> [package-index-options] ...
46
+ %prog [options] -r <requirements file> [package-index-options] ...
47
+ %prog [options] <archive url/path> ..."""
48
+
49
+ def add_options(self) -> None:
50
+ self.cmd_opts.add_option(
51
+ cmdoptions.PipOption(
52
+ "--output",
53
+ "-o",
54
+ dest="output_file",
55
+ metavar="path",
56
+ type="path",
57
+ default="pylock.toml",
58
+ help="Lock file name (default=pylock.toml). Use - for stdout.",
59
+ )
60
+ )
61
+ self.cmd_opts.add_option(cmdoptions.requirements())
62
+ self.cmd_opts.add_option(cmdoptions.constraints())
63
+ self.cmd_opts.add_option(cmdoptions.no_deps())
64
+ self.cmd_opts.add_option(cmdoptions.pre())
65
+
66
+ self.cmd_opts.add_option(cmdoptions.editable())
67
+
68
+ self.cmd_opts.add_option(cmdoptions.src())
69
+
70
+ self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
71
+ self.cmd_opts.add_option(cmdoptions.no_build_isolation())
72
+ self.cmd_opts.add_option(cmdoptions.use_pep517())
73
+ self.cmd_opts.add_option(cmdoptions.no_use_pep517())
74
+ self.cmd_opts.add_option(cmdoptions.check_build_deps())
75
+
76
+ self.cmd_opts.add_option(cmdoptions.config_settings())
77
+
78
+ self.cmd_opts.add_option(cmdoptions.no_binary())
79
+ self.cmd_opts.add_option(cmdoptions.only_binary())
80
+ self.cmd_opts.add_option(cmdoptions.prefer_binary())
81
+ self.cmd_opts.add_option(cmdoptions.require_hashes())
82
+ self.cmd_opts.add_option(cmdoptions.progress_bar())
83
+
84
+ index_opts = cmdoptions.make_option_group(
85
+ cmdoptions.index_group,
86
+ self.parser,
87
+ )
88
+
89
+ self.parser.insert_option_group(0, index_opts)
90
+ self.parser.insert_option_group(0, self.cmd_opts)
91
+
92
+ @with_cleanup
93
+ def run(self, options: Values, args: List[str]) -> int:
94
+ logger.verbose("Using %s", get_pip_version())
95
+
96
+ logger.warning(
97
+ "pip lock is currently an experimental command. "
98
+ "It may be removed/changed in a future release "
99
+ "without prior warning."
100
+ )
101
+
102
+ session = self.get_default_session(options)
103
+
104
+ finder = self._build_package_finder(
105
+ options=options,
106
+ session=session,
107
+ ignore_requires_python=options.ignore_requires_python,
108
+ )
109
+ build_tracker = self.enter_context(get_build_tracker())
110
+
111
+ directory = TempDirectory(
112
+ delete=not options.no_clean,
113
+ kind="install",
114
+ globally_managed=True,
115
+ )
116
+
117
+ reqs = self.get_requirements(args, options, finder, session)
118
+ check_legacy_setup_py_options(options, reqs)
119
+
120
+ wheel_cache = WheelCache(options.cache_dir)
121
+
122
+ # Only when installing is it permitted to use PEP 660.
123
+ # In other circumstances (pip wheel, pip download) we generate
124
+ # regular (i.e. non editable) metadata and wheels.
125
+ for req in reqs:
126
+ req.permit_editable_wheels = True
127
+
128
+ preparer = self.make_requirement_preparer(
129
+ temp_build_dir=directory,
130
+ options=options,
131
+ build_tracker=build_tracker,
132
+ session=session,
133
+ finder=finder,
134
+ use_user_site=False,
135
+ verbosity=self.verbosity,
136
+ )
137
+ resolver = self.make_resolver(
138
+ preparer=preparer,
139
+ finder=finder,
140
+ options=options,
141
+ wheel_cache=wheel_cache,
142
+ use_user_site=False,
143
+ ignore_installed=True,
144
+ ignore_requires_python=options.ignore_requires_python,
145
+ upgrade_strategy="to-satisfy-only",
146
+ use_pep517=options.use_pep517,
147
+ )
148
+
149
+ self.trace_basic_info(finder)
150
+
151
+ requirement_set = resolver.resolve(reqs, check_supported_wheels=True)
152
+
153
+ if options.output_file == "-":
154
+ base_dir = Path.cwd()
155
+ else:
156
+ output_file_path = Path(options.output_file)
157
+ if not is_valid_pylock_file_name(output_file_path):
158
+ logger.warning(
159
+ "%s is not a valid lock file name.",
160
+ output_file_path,
161
+ )
162
+ base_dir = output_file_path.parent
163
+ pylock_toml = Pylock.from_install_requirements(
164
+ requirement_set.requirements.values(), base_dir=base_dir
165
+ ).as_toml()
166
+ if options.output_file == "-":
167
+ sys.stdout.write(pylock_toml)
168
+ else:
169
+ output_file_path.write_text(pylock_toml, encoding="utf-8")
170
+
171
+ return SUCCESS
python_embeded/Lib/site-packages/pip/_internal/commands/search.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import shutil
3
+ import sys
4
+ import textwrap
5
+ import xmlrpc.client
6
+ from collections import OrderedDict
7
+ from optparse import Values
8
+ from typing import Dict, List, Optional, TypedDict
9
+
10
+ from pip._vendor.packaging.version import parse as parse_version
11
+
12
+ from pip._internal.cli.base_command import Command
13
+ from pip._internal.cli.req_command import SessionCommandMixin
14
+ from pip._internal.cli.status_codes import NO_MATCHES_FOUND, SUCCESS
15
+ from pip._internal.exceptions import CommandError
16
+ from pip._internal.metadata import get_default_environment
17
+ from pip._internal.metadata.base import BaseDistribution
18
+ from pip._internal.models.index import PyPI
19
+ from pip._internal.network.xmlrpc import PipXmlrpcTransport
20
+ from pip._internal.utils.logging import indent_log
21
+ from pip._internal.utils.misc import write_output
22
+
23
+
24
+ class TransformedHit(TypedDict):
25
+ name: str
26
+ summary: str
27
+ versions: List[str]
28
+
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ class SearchCommand(Command, SessionCommandMixin):
34
+ """Search for PyPI packages whose name or summary contains <query>."""
35
+
36
+ usage = """
37
+ %prog [options] <query>"""
38
+ ignore_require_venv = True
39
+
40
+ def add_options(self) -> None:
41
+ self.cmd_opts.add_option(
42
+ "-i",
43
+ "--index",
44
+ dest="index",
45
+ metavar="URL",
46
+ default=PyPI.pypi_url,
47
+ help="Base URL of Python Package Index (default %default)",
48
+ )
49
+
50
+ self.parser.insert_option_group(0, self.cmd_opts)
51
+
52
+ def run(self, options: Values, args: List[str]) -> int:
53
+ if not args:
54
+ raise CommandError("Missing required argument (search query).")
55
+ query = args
56
+ pypi_hits = self.search(query, options)
57
+ hits = transform_hits(pypi_hits)
58
+
59
+ terminal_width = None
60
+ if sys.stdout.isatty():
61
+ terminal_width = shutil.get_terminal_size()[0]
62
+
63
+ print_results(hits, terminal_width=terminal_width)
64
+ if pypi_hits:
65
+ return SUCCESS
66
+ return NO_MATCHES_FOUND
67
+
68
+ def search(self, query: List[str], options: Values) -> List[Dict[str, str]]:
69
+ index_url = options.index
70
+
71
+ session = self.get_default_session(options)
72
+
73
+ transport = PipXmlrpcTransport(index_url, session)
74
+ pypi = xmlrpc.client.ServerProxy(index_url, transport)
75
+ try:
76
+ hits = pypi.search({"name": query, "summary": query}, "or")
77
+ except xmlrpc.client.Fault as fault:
78
+ message = (
79
+ f"XMLRPC request failed [code: {fault.faultCode}]\n{fault.faultString}"
80
+ )
81
+ raise CommandError(message)
82
+ assert isinstance(hits, list)
83
+ return hits
84
+
85
+
86
+ def transform_hits(hits: List[Dict[str, str]]) -> List["TransformedHit"]:
87
+ """
88
+ The list from pypi is really a list of versions. We want a list of
89
+ packages with the list of versions stored inline. This converts the
90
+ list from pypi into one we can use.
91
+ """
92
+ packages: Dict[str, TransformedHit] = OrderedDict()
93
+ for hit in hits:
94
+ name = hit["name"]
95
+ summary = hit["summary"]
96
+ version = hit["version"]
97
+
98
+ if name not in packages.keys():
99
+ packages[name] = {
100
+ "name": name,
101
+ "summary": summary,
102
+ "versions": [version],
103
+ }
104
+ else:
105
+ packages[name]["versions"].append(version)
106
+
107
+ # if this is the highest version, replace summary and score
108
+ if version == highest_version(packages[name]["versions"]):
109
+ packages[name]["summary"] = summary
110
+
111
+ return list(packages.values())
112
+
113
+
114
+ def print_dist_installation_info(latest: str, dist: Optional[BaseDistribution]) -> None:
115
+ if dist is not None:
116
+ with indent_log():
117
+ if dist.version == latest:
118
+ write_output("INSTALLED: %s (latest)", dist.version)
119
+ else:
120
+ write_output("INSTALLED: %s", dist.version)
121
+ if parse_version(latest).pre:
122
+ write_output(
123
+ "LATEST: %s (pre-release; install"
124
+ " with `pip install --pre`)",
125
+ latest,
126
+ )
127
+ else:
128
+ write_output("LATEST: %s", latest)
129
+
130
+
131
+ def get_installed_distribution(name: str) -> Optional[BaseDistribution]:
132
+ env = get_default_environment()
133
+ return env.get_distribution(name)
134
+
135
+
136
+ def print_results(
137
+ hits: List["TransformedHit"],
138
+ name_column_width: Optional[int] = None,
139
+ terminal_width: Optional[int] = None,
140
+ ) -> None:
141
+ if not hits:
142
+ return
143
+ if name_column_width is None:
144
+ name_column_width = (
145
+ max(
146
+ [
147
+ len(hit["name"]) + len(highest_version(hit.get("versions", ["-"])))
148
+ for hit in hits
149
+ ]
150
+ )
151
+ + 4
152
+ )
153
+
154
+ for hit in hits:
155
+ name = hit["name"]
156
+ summary = hit["summary"] or ""
157
+ latest = highest_version(hit.get("versions", ["-"]))
158
+ if terminal_width is not None:
159
+ target_width = terminal_width - name_column_width - 5
160
+ if target_width > 10:
161
+ # wrap and indent summary to fit terminal
162
+ summary_lines = textwrap.wrap(summary, target_width)
163
+ summary = ("\n" + " " * (name_column_width + 3)).join(summary_lines)
164
+
165
+ name_latest = f"{name} ({latest})"
166
+ line = f"{name_latest:{name_column_width}} - {summary}"
167
+ try:
168
+ write_output(line)
169
+ dist = get_installed_distribution(name)
170
+ print_dist_installation_info(latest, dist)
171
+ except UnicodeEncodeError:
172
+ pass
173
+
174
+
175
+ def highest_version(versions: List[str]) -> str:
176
+ return max(versions, key=parse_version)
python_embeded/Lib/site-packages/pip/_internal/commands/show.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import string
3
+ from optparse import Values
4
+ from typing import Generator, Iterable, Iterator, List, NamedTuple, Optional
5
+
6
+ from pip._vendor.packaging.requirements import InvalidRequirement
7
+ from pip._vendor.packaging.utils import canonicalize_name
8
+
9
+ from pip._internal.cli.base_command import Command
10
+ from pip._internal.cli.status_codes import ERROR, SUCCESS
11
+ from pip._internal.metadata import BaseDistribution, get_default_environment
12
+ from pip._internal.utils.misc import write_output
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def normalize_project_url_label(label: str) -> str:
18
+ # This logic is from PEP 753 (Well-known Project URLs in Metadata).
19
+ chars_to_remove = string.punctuation + string.whitespace
20
+ removal_map = str.maketrans("", "", chars_to_remove)
21
+ return label.translate(removal_map).lower()
22
+
23
+
24
+ class ShowCommand(Command):
25
+ """
26
+ Show information about one or more installed packages.
27
+
28
+ The output is in RFC-compliant mail header format.
29
+ """
30
+
31
+ usage = """
32
+ %prog [options] <package> ..."""
33
+ ignore_require_venv = True
34
+
35
+ def add_options(self) -> None:
36
+ self.cmd_opts.add_option(
37
+ "-f",
38
+ "--files",
39
+ dest="files",
40
+ action="store_true",
41
+ default=False,
42
+ help="Show the full list of installed files for each package.",
43
+ )
44
+
45
+ self.parser.insert_option_group(0, self.cmd_opts)
46
+
47
+ def run(self, options: Values, args: List[str]) -> int:
48
+ if not args:
49
+ logger.warning("ERROR: Please provide a package name or names.")
50
+ return ERROR
51
+ query = args
52
+
53
+ results = search_packages_info(query)
54
+ if not print_results(
55
+ results, list_files=options.files, verbose=options.verbose
56
+ ):
57
+ return ERROR
58
+ return SUCCESS
59
+
60
+
61
+ class _PackageInfo(NamedTuple):
62
+ name: str
63
+ version: str
64
+ location: str
65
+ editable_project_location: Optional[str]
66
+ requires: List[str]
67
+ required_by: List[str]
68
+ installer: str
69
+ metadata_version: str
70
+ classifiers: List[str]
71
+ summary: str
72
+ homepage: str
73
+ project_urls: List[str]
74
+ author: str
75
+ author_email: str
76
+ license: str
77
+ license_expression: str
78
+ entry_points: List[str]
79
+ files: Optional[List[str]]
80
+
81
+
82
+ def search_packages_info(query: List[str]) -> Generator[_PackageInfo, None, None]:
83
+ """
84
+ Gather details from installed distributions. Print distribution name,
85
+ version, location, and installed files. Installed files requires a
86
+ pip generated 'installed-files.txt' in the distributions '.egg-info'
87
+ directory.
88
+ """
89
+ env = get_default_environment()
90
+
91
+ installed = {dist.canonical_name: dist for dist in env.iter_all_distributions()}
92
+ query_names = [canonicalize_name(name) for name in query]
93
+ missing = sorted(
94
+ [name for name, pkg in zip(query, query_names) if pkg not in installed]
95
+ )
96
+ if missing:
97
+ logger.warning("Package(s) not found: %s", ", ".join(missing))
98
+
99
+ def _get_requiring_packages(current_dist: BaseDistribution) -> Iterator[str]:
100
+ return (
101
+ dist.metadata["Name"] or "UNKNOWN"
102
+ for dist in installed.values()
103
+ if current_dist.canonical_name
104
+ in {canonicalize_name(d.name) for d in dist.iter_dependencies()}
105
+ )
106
+
107
+ for query_name in query_names:
108
+ try:
109
+ dist = installed[query_name]
110
+ except KeyError:
111
+ continue
112
+
113
+ try:
114
+ requires = sorted(
115
+ # Avoid duplicates in requirements (e.g. due to environment markers).
116
+ {req.name for req in dist.iter_dependencies()},
117
+ key=str.lower,
118
+ )
119
+ except InvalidRequirement:
120
+ requires = sorted(dist.iter_raw_dependencies(), key=str.lower)
121
+
122
+ try:
123
+ required_by = sorted(_get_requiring_packages(dist), key=str.lower)
124
+ except InvalidRequirement:
125
+ required_by = ["#N/A"]
126
+
127
+ try:
128
+ entry_points_text = dist.read_text("entry_points.txt")
129
+ entry_points = entry_points_text.splitlines(keepends=False)
130
+ except FileNotFoundError:
131
+ entry_points = []
132
+
133
+ files_iter = dist.iter_declared_entries()
134
+ if files_iter is None:
135
+ files: Optional[List[str]] = None
136
+ else:
137
+ files = sorted(files_iter)
138
+
139
+ metadata = dist.metadata
140
+
141
+ project_urls = metadata.get_all("Project-URL", [])
142
+ homepage = metadata.get("Home-page", "")
143
+ if not homepage:
144
+ # It's common that there is a "homepage" Project-URL, but Home-page
145
+ # remains unset (especially as PEP 621 doesn't surface the field).
146
+ for url in project_urls:
147
+ url_label, url = url.split(",", maxsplit=1)
148
+ normalized_label = normalize_project_url_label(url_label)
149
+ if normalized_label == "homepage":
150
+ homepage = url.strip()
151
+ break
152
+
153
+ yield _PackageInfo(
154
+ name=dist.raw_name,
155
+ version=dist.raw_version,
156
+ location=dist.location or "",
157
+ editable_project_location=dist.editable_project_location,
158
+ requires=requires,
159
+ required_by=required_by,
160
+ installer=dist.installer,
161
+ metadata_version=dist.metadata_version or "",
162
+ classifiers=metadata.get_all("Classifier", []),
163
+ summary=metadata.get("Summary", ""),
164
+ homepage=homepage,
165
+ project_urls=project_urls,
166
+ author=metadata.get("Author", ""),
167
+ author_email=metadata.get("Author-email", ""),
168
+ license=metadata.get("License", ""),
169
+ license_expression=metadata.get("License-Expression", ""),
170
+ entry_points=entry_points,
171
+ files=files,
172
+ )
173
+
174
+
175
+ def print_results(
176
+ distributions: Iterable[_PackageInfo],
177
+ list_files: bool,
178
+ verbose: bool,
179
+ ) -> bool:
180
+ """
181
+ Print the information from installed distributions found.
182
+ """
183
+ results_printed = False
184
+ for i, dist in enumerate(distributions):
185
+ results_printed = True
186
+ if i > 0:
187
+ write_output("---")
188
+
189
+ metadata_version_tuple = tuple(map(int, dist.metadata_version.split(".")))
190
+
191
+ write_output("Name: %s", dist.name)
192
+ write_output("Version: %s", dist.version)
193
+ write_output("Summary: %s", dist.summary)
194
+ write_output("Home-page: %s", dist.homepage)
195
+ write_output("Author: %s", dist.author)
196
+ write_output("Author-email: %s", dist.author_email)
197
+ if metadata_version_tuple >= (2, 4) and dist.license_expression:
198
+ write_output("License-Expression: %s", dist.license_expression)
199
+ else:
200
+ write_output("License: %s", dist.license)
201
+ write_output("Location: %s", dist.location)
202
+ if dist.editable_project_location is not None:
203
+ write_output(
204
+ "Editable project location: %s", dist.editable_project_location
205
+ )
206
+ write_output("Requires: %s", ", ".join(dist.requires))
207
+ write_output("Required-by: %s", ", ".join(dist.required_by))
208
+
209
+ if verbose:
210
+ write_output("Metadata-Version: %s", dist.metadata_version)
211
+ write_output("Installer: %s", dist.installer)
212
+ write_output("Classifiers:")
213
+ for classifier in dist.classifiers:
214
+ write_output(" %s", classifier)
215
+ write_output("Entry-points:")
216
+ for entry in dist.entry_points:
217
+ write_output(" %s", entry.strip())
218
+ write_output("Project-URLs:")
219
+ for project_url in dist.project_urls:
220
+ write_output(" %s", project_url)
221
+ if list_files:
222
+ write_output("Files:")
223
+ if dist.files is None:
224
+ write_output("Cannot locate RECORD or installed-files.txt")
225
+ else:
226
+ for line in dist.files:
227
+ write_output(" %s", line.strip())
228
+ return results_printed
python_embeded/Lib/site-packages/pip/_internal/commands/uninstall.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from optparse import Values
3
+ from typing import List
4
+
5
+ from pip._vendor.packaging.utils import canonicalize_name
6
+
7
+ from pip._internal.cli import cmdoptions
8
+ from pip._internal.cli.base_command import Command
9
+ from pip._internal.cli.index_command import SessionCommandMixin
10
+ from pip._internal.cli.status_codes import SUCCESS
11
+ from pip._internal.exceptions import InstallationError
12
+ from pip._internal.req import parse_requirements
13
+ from pip._internal.req.constructors import (
14
+ install_req_from_line,
15
+ install_req_from_parsed_requirement,
16
+ )
17
+ from pip._internal.utils.misc import (
18
+ check_externally_managed,
19
+ protect_pip_from_modification_on_windows,
20
+ warn_if_run_as_root,
21
+ )
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ class UninstallCommand(Command, SessionCommandMixin):
27
+ """
28
+ Uninstall packages.
29
+
30
+ pip is able to uninstall most installed packages. Known exceptions are:
31
+
32
+ - Pure distutils packages installed with ``python setup.py install``, which
33
+ leave behind no metadata to determine what files were installed.
34
+ - Script wrappers installed by ``python setup.py develop``.
35
+ """
36
+
37
+ usage = """
38
+ %prog [options] <package> ...
39
+ %prog [options] -r <requirements file> ..."""
40
+
41
+ def add_options(self) -> None:
42
+ self.cmd_opts.add_option(
43
+ "-r",
44
+ "--requirement",
45
+ dest="requirements",
46
+ action="append",
47
+ default=[],
48
+ metavar="file",
49
+ help=(
50
+ "Uninstall all the packages listed in the given requirements "
51
+ "file. This option can be used multiple times."
52
+ ),
53
+ )
54
+ self.cmd_opts.add_option(
55
+ "-y",
56
+ "--yes",
57
+ dest="yes",
58
+ action="store_true",
59
+ help="Don't ask for confirmation of uninstall deletions.",
60
+ )
61
+ self.cmd_opts.add_option(cmdoptions.root_user_action())
62
+ self.cmd_opts.add_option(cmdoptions.override_externally_managed())
63
+ self.parser.insert_option_group(0, self.cmd_opts)
64
+
65
+ def run(self, options: Values, args: List[str]) -> int:
66
+ session = self.get_default_session(options)
67
+
68
+ reqs_to_uninstall = {}
69
+ for name in args:
70
+ req = install_req_from_line(
71
+ name,
72
+ isolated=options.isolated_mode,
73
+ )
74
+ if req.name:
75
+ reqs_to_uninstall[canonicalize_name(req.name)] = req
76
+ else:
77
+ logger.warning(
78
+ "Invalid requirement: %r ignored -"
79
+ " the uninstall command expects named"
80
+ " requirements.",
81
+ name,
82
+ )
83
+ for filename in options.requirements:
84
+ for parsed_req in parse_requirements(
85
+ filename, options=options, session=session
86
+ ):
87
+ req = install_req_from_parsed_requirement(
88
+ parsed_req, isolated=options.isolated_mode
89
+ )
90
+ if req.name:
91
+ reqs_to_uninstall[canonicalize_name(req.name)] = req
92
+ if not reqs_to_uninstall:
93
+ raise InstallationError(
94
+ f"You must give at least one requirement to {self.name} (see "
95
+ f'"pip help {self.name}")'
96
+ )
97
+
98
+ if not options.override_externally_managed:
99
+ check_externally_managed()
100
+
101
+ protect_pip_from_modification_on_windows(
102
+ modifying_pip="pip" in reqs_to_uninstall
103
+ )
104
+
105
+ for req in reqs_to_uninstall.values():
106
+ uninstall_pathset = req.uninstall(
107
+ auto_confirm=options.yes,
108
+ verbose=self.verbosity > 0,
109
+ )
110
+ if uninstall_pathset:
111
+ uninstall_pathset.commit()
112
+ if options.root_user_action == "warn":
113
+ warn_if_run_as_root()
114
+ return SUCCESS
python_embeded/Lib/site-packages/pip/_internal/commands/wheel.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import shutil
4
+ from optparse import Values
5
+ from typing import List
6
+
7
+ from pip._internal.cache import WheelCache
8
+ from pip._internal.cli import cmdoptions
9
+ from pip._internal.cli.req_command import RequirementCommand, with_cleanup
10
+ from pip._internal.cli.status_codes import SUCCESS
11
+ from pip._internal.exceptions import CommandError
12
+ from pip._internal.operations.build.build_tracker import get_build_tracker
13
+ from pip._internal.req.req_install import (
14
+ InstallRequirement,
15
+ check_legacy_setup_py_options,
16
+ )
17
+ from pip._internal.utils.misc import ensure_dir, normalize_path
18
+ from pip._internal.utils.temp_dir import TempDirectory
19
+ from pip._internal.wheel_builder import build
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ class WheelCommand(RequirementCommand):
25
+ """
26
+ Build Wheel archives for your requirements and dependencies.
27
+
28
+ Wheel is a built-package format, and offers the advantage of not
29
+ recompiling your software during every install. For more details, see the
30
+ wheel docs: https://wheel.readthedocs.io/en/latest/
31
+
32
+ 'pip wheel' uses the build system interface as described here:
33
+ https://pip.pypa.io/en/stable/reference/build-system/
34
+
35
+ """
36
+
37
+ usage = """
38
+ %prog [options] <requirement specifier> ...
39
+ %prog [options] -r <requirements file> ...
40
+ %prog [options] [-e] <vcs project url> ...
41
+ %prog [options] [-e] <local project path> ...
42
+ %prog [options] <archive url/path> ..."""
43
+
44
+ def add_options(self) -> None:
45
+ self.cmd_opts.add_option(
46
+ "-w",
47
+ "--wheel-dir",
48
+ dest="wheel_dir",
49
+ metavar="dir",
50
+ default=os.curdir,
51
+ help=(
52
+ "Build wheels into <dir>, where the default is the "
53
+ "current working directory."
54
+ ),
55
+ )
56
+ self.cmd_opts.add_option(cmdoptions.no_binary())
57
+ self.cmd_opts.add_option(cmdoptions.only_binary())
58
+ self.cmd_opts.add_option(cmdoptions.prefer_binary())
59
+ self.cmd_opts.add_option(cmdoptions.no_build_isolation())
60
+ self.cmd_opts.add_option(cmdoptions.use_pep517())
61
+ self.cmd_opts.add_option(cmdoptions.no_use_pep517())
62
+ self.cmd_opts.add_option(cmdoptions.check_build_deps())
63
+ self.cmd_opts.add_option(cmdoptions.constraints())
64
+ self.cmd_opts.add_option(cmdoptions.editable())
65
+ self.cmd_opts.add_option(cmdoptions.requirements())
66
+ self.cmd_opts.add_option(cmdoptions.src())
67
+ self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
68
+ self.cmd_opts.add_option(cmdoptions.no_deps())
69
+ self.cmd_opts.add_option(cmdoptions.progress_bar())
70
+
71
+ self.cmd_opts.add_option(
72
+ "--no-verify",
73
+ dest="no_verify",
74
+ action="store_true",
75
+ default=False,
76
+ help="Don't verify if built wheel is valid.",
77
+ )
78
+
79
+ self.cmd_opts.add_option(cmdoptions.config_settings())
80
+ self.cmd_opts.add_option(cmdoptions.build_options())
81
+ self.cmd_opts.add_option(cmdoptions.global_options())
82
+
83
+ self.cmd_opts.add_option(
84
+ "--pre",
85
+ action="store_true",
86
+ default=False,
87
+ help=(
88
+ "Include pre-release and development versions. By default, "
89
+ "pip only finds stable versions."
90
+ ),
91
+ )
92
+
93
+ self.cmd_opts.add_option(cmdoptions.require_hashes())
94
+
95
+ index_opts = cmdoptions.make_option_group(
96
+ cmdoptions.index_group,
97
+ self.parser,
98
+ )
99
+
100
+ self.parser.insert_option_group(0, index_opts)
101
+ self.parser.insert_option_group(0, self.cmd_opts)
102
+
103
+ @with_cleanup
104
+ def run(self, options: Values, args: List[str]) -> int:
105
+ session = self.get_default_session(options)
106
+
107
+ finder = self._build_package_finder(options, session)
108
+
109
+ options.wheel_dir = normalize_path(options.wheel_dir)
110
+ ensure_dir(options.wheel_dir)
111
+
112
+ build_tracker = self.enter_context(get_build_tracker())
113
+
114
+ directory = TempDirectory(
115
+ delete=not options.no_clean,
116
+ kind="wheel",
117
+ globally_managed=True,
118
+ )
119
+
120
+ reqs = self.get_requirements(args, options, finder, session)
121
+ check_legacy_setup_py_options(options, reqs)
122
+
123
+ wheel_cache = WheelCache(options.cache_dir)
124
+
125
+ preparer = self.make_requirement_preparer(
126
+ temp_build_dir=directory,
127
+ options=options,
128
+ build_tracker=build_tracker,
129
+ session=session,
130
+ finder=finder,
131
+ download_dir=options.wheel_dir,
132
+ use_user_site=False,
133
+ verbosity=self.verbosity,
134
+ )
135
+
136
+ resolver = self.make_resolver(
137
+ preparer=preparer,
138
+ finder=finder,
139
+ options=options,
140
+ wheel_cache=wheel_cache,
141
+ ignore_requires_python=options.ignore_requires_python,
142
+ use_pep517=options.use_pep517,
143
+ )
144
+
145
+ self.trace_basic_info(finder)
146
+
147
+ requirement_set = resolver.resolve(reqs, check_supported_wheels=True)
148
+
149
+ reqs_to_build: List[InstallRequirement] = []
150
+ for req in requirement_set.requirements.values():
151
+ if req.is_wheel:
152
+ preparer.save_linked_requirement(req)
153
+ else:
154
+ reqs_to_build.append(req)
155
+
156
+ preparer.prepare_linked_requirements_more(requirement_set.requirements.values())
157
+
158
+ # build wheels
159
+ build_successes, build_failures = build(
160
+ reqs_to_build,
161
+ wheel_cache=wheel_cache,
162
+ verify=(not options.no_verify),
163
+ build_options=options.build_options or [],
164
+ global_options=options.global_options or [],
165
+ )
166
+ for req in build_successes:
167
+ assert req.link and req.link.is_wheel
168
+ assert req.local_file_path
169
+ # copy from cache to target directory
170
+ try:
171
+ shutil.copy(req.local_file_path, options.wheel_dir)
172
+ except OSError as e:
173
+ logger.warning(
174
+ "Building wheel for %s failed: %s",
175
+ req.name,
176
+ e,
177
+ )
178
+ build_failures.append(req)
179
+ if len(build_failures) != 0:
180
+ raise CommandError("Failed to build one or more wheels")
181
+
182
+ return SUCCESS
python_embeded/Lib/site-packages/pip/_internal/configuration.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration management setup
2
+
3
+ Some terminology:
4
+ - name
5
+ As written in config files.
6
+ - value
7
+ Value associated with a name
8
+ - key
9
+ Name combined with it's section (section.name)
10
+ - variant
11
+ A single word describing where the configuration key-value pair came from
12
+ """
13
+
14
+ import configparser
15
+ import locale
16
+ import os
17
+ import sys
18
+ from typing import Any, Dict, Iterable, List, NewType, Optional, Tuple
19
+
20
+ from pip._internal.exceptions import (
21
+ ConfigurationError,
22
+ ConfigurationFileCouldNotBeLoaded,
23
+ )
24
+ from pip._internal.utils import appdirs
25
+ from pip._internal.utils.compat import WINDOWS
26
+ from pip._internal.utils.logging import getLogger
27
+ from pip._internal.utils.misc import ensure_dir, enum
28
+
29
+ RawConfigParser = configparser.RawConfigParser # Shorthand
30
+ Kind = NewType("Kind", str)
31
+
32
+ CONFIG_BASENAME = "pip.ini" if WINDOWS else "pip.conf"
33
+ ENV_NAMES_IGNORED = "version", "help"
34
+
35
+ # The kinds of configurations there are.
36
+ kinds = enum(
37
+ USER="user", # User Specific
38
+ GLOBAL="global", # System Wide
39
+ SITE="site", # [Virtual] Environment Specific
40
+ ENV="env", # from PIP_CONFIG_FILE
41
+ ENV_VAR="env-var", # from Environment Variables
42
+ )
43
+ OVERRIDE_ORDER = kinds.GLOBAL, kinds.USER, kinds.SITE, kinds.ENV, kinds.ENV_VAR
44
+ VALID_LOAD_ONLY = kinds.USER, kinds.GLOBAL, kinds.SITE
45
+
46
+ logger = getLogger(__name__)
47
+
48
+
49
+ # NOTE: Maybe use the optionx attribute to normalize keynames.
50
+ def _normalize_name(name: str) -> str:
51
+ """Make a name consistent regardless of source (environment or file)"""
52
+ name = name.lower().replace("_", "-")
53
+ if name.startswith("--"):
54
+ name = name[2:] # only prefer long opts
55
+ return name
56
+
57
+
58
+ def _disassemble_key(name: str) -> List[str]:
59
+ if "." not in name:
60
+ error_message = (
61
+ "Key does not contain dot separated section and key. "
62
+ f"Perhaps you wanted to use 'global.{name}' instead?"
63
+ )
64
+ raise ConfigurationError(error_message)
65
+ return name.split(".", 1)
66
+
67
+
68
+ def get_configuration_files() -> Dict[Kind, List[str]]:
69
+ global_config_files = [
70
+ os.path.join(path, CONFIG_BASENAME) for path in appdirs.site_config_dirs("pip")
71
+ ]
72
+
73
+ site_config_file = os.path.join(sys.prefix, CONFIG_BASENAME)
74
+ legacy_config_file = os.path.join(
75
+ os.path.expanduser("~"),
76
+ "pip" if WINDOWS else ".pip",
77
+ CONFIG_BASENAME,
78
+ )
79
+ new_config_file = os.path.join(appdirs.user_config_dir("pip"), CONFIG_BASENAME)
80
+ return {
81
+ kinds.GLOBAL: global_config_files,
82
+ kinds.SITE: [site_config_file],
83
+ kinds.USER: [legacy_config_file, new_config_file],
84
+ }
85
+
86
+
87
+ class Configuration:
88
+ """Handles management of configuration.
89
+
90
+ Provides an interface to accessing and managing configuration files.
91
+
92
+ This class converts provides an API that takes "section.key-name" style
93
+ keys and stores the value associated with it as "key-name" under the
94
+ section "section".
95
+
96
+ This allows for a clean interface wherein the both the section and the
97
+ key-name are preserved in an easy to manage form in the configuration files
98
+ and the data stored is also nice.
99
+ """
100
+
101
+ def __init__(self, isolated: bool, load_only: Optional[Kind] = None) -> None:
102
+ super().__init__()
103
+
104
+ if load_only is not None and load_only not in VALID_LOAD_ONLY:
105
+ raise ConfigurationError(
106
+ "Got invalid value for load_only - should be one of {}".format(
107
+ ", ".join(map(repr, VALID_LOAD_ONLY))
108
+ )
109
+ )
110
+ self.isolated = isolated
111
+ self.load_only = load_only
112
+
113
+ # Because we keep track of where we got the data from
114
+ self._parsers: Dict[Kind, List[Tuple[str, RawConfigParser]]] = {
115
+ variant: [] for variant in OVERRIDE_ORDER
116
+ }
117
+ self._config: Dict[Kind, Dict[str, Any]] = {
118
+ variant: {} for variant in OVERRIDE_ORDER
119
+ }
120
+ self._modified_parsers: List[Tuple[str, RawConfigParser]] = []
121
+
122
+ def load(self) -> None:
123
+ """Loads configuration from configuration files and environment"""
124
+ self._load_config_files()
125
+ if not self.isolated:
126
+ self._load_environment_vars()
127
+
128
+ def get_file_to_edit(self) -> Optional[str]:
129
+ """Returns the file with highest priority in configuration"""
130
+ assert self.load_only is not None, "Need to be specified a file to be editing"
131
+
132
+ try:
133
+ return self._get_parser_to_modify()[0]
134
+ except IndexError:
135
+ return None
136
+
137
+ def items(self) -> Iterable[Tuple[str, Any]]:
138
+ """Returns key-value pairs like dict.items() representing the loaded
139
+ configuration
140
+ """
141
+ return self._dictionary.items()
142
+
143
+ def get_value(self, key: str) -> Any:
144
+ """Get a value from the configuration."""
145
+ orig_key = key
146
+ key = _normalize_name(key)
147
+ try:
148
+ return self._dictionary[key]
149
+ except KeyError:
150
+ # disassembling triggers a more useful error message than simply
151
+ # "No such key" in the case that the key isn't in the form command.option
152
+ _disassemble_key(key)
153
+ raise ConfigurationError(f"No such key - {orig_key}")
154
+
155
+ def set_value(self, key: str, value: Any) -> None:
156
+ """Modify a value in the configuration."""
157
+ key = _normalize_name(key)
158
+ self._ensure_have_load_only()
159
+
160
+ assert self.load_only
161
+ fname, parser = self._get_parser_to_modify()
162
+
163
+ if parser is not None:
164
+ section, name = _disassemble_key(key)
165
+
166
+ # Modify the parser and the configuration
167
+ if not parser.has_section(section):
168
+ parser.add_section(section)
169
+ parser.set(section, name, value)
170
+
171
+ self._config[self.load_only][key] = value
172
+ self._mark_as_modified(fname, parser)
173
+
174
+ def unset_value(self, key: str) -> None:
175
+ """Unset a value in the configuration."""
176
+ orig_key = key
177
+ key = _normalize_name(key)
178
+ self._ensure_have_load_only()
179
+
180
+ assert self.load_only
181
+ if key not in self._config[self.load_only]:
182
+ raise ConfigurationError(f"No such key - {orig_key}")
183
+
184
+ fname, parser = self._get_parser_to_modify()
185
+
186
+ if parser is not None:
187
+ section, name = _disassemble_key(key)
188
+ if not (
189
+ parser.has_section(section) and parser.remove_option(section, name)
190
+ ):
191
+ # The option was not removed.
192
+ raise ConfigurationError(
193
+ "Fatal Internal error [id=1]. Please report as a bug."
194
+ )
195
+
196
+ # The section may be empty after the option was removed.
197
+ if not parser.items(section):
198
+ parser.remove_section(section)
199
+ self._mark_as_modified(fname, parser)
200
+
201
+ del self._config[self.load_only][key]
202
+
203
+ def save(self) -> None:
204
+ """Save the current in-memory state."""
205
+ self._ensure_have_load_only()
206
+
207
+ for fname, parser in self._modified_parsers:
208
+ logger.info("Writing to %s", fname)
209
+
210
+ # Ensure directory exists.
211
+ ensure_dir(os.path.dirname(fname))
212
+
213
+ # Ensure directory's permission(need to be writeable)
214
+ try:
215
+ with open(fname, "w") as f:
216
+ parser.write(f)
217
+ except OSError as error:
218
+ raise ConfigurationError(
219
+ f"An error occurred while writing to the configuration file "
220
+ f"{fname}: {error}"
221
+ )
222
+
223
+ #
224
+ # Private routines
225
+ #
226
+
227
+ def _ensure_have_load_only(self) -> None:
228
+ if self.load_only is None:
229
+ raise ConfigurationError("Needed a specific file to be modifying.")
230
+ logger.debug("Will be working with %s variant only", self.load_only)
231
+
232
+ @property
233
+ def _dictionary(self) -> Dict[str, Any]:
234
+ """A dictionary representing the loaded configuration."""
235
+ # NOTE: Dictionaries are not populated if not loaded. So, conditionals
236
+ # are not needed here.
237
+ retval = {}
238
+
239
+ for variant in OVERRIDE_ORDER:
240
+ retval.update(self._config[variant])
241
+
242
+ return retval
243
+
244
+ def _load_config_files(self) -> None:
245
+ """Loads configuration from configuration files"""
246
+ config_files = dict(self.iter_config_files())
247
+ if config_files[kinds.ENV][0:1] == [os.devnull]:
248
+ logger.debug(
249
+ "Skipping loading configuration files due to "
250
+ "environment's PIP_CONFIG_FILE being os.devnull"
251
+ )
252
+ return
253
+
254
+ for variant, files in config_files.items():
255
+ for fname in files:
256
+ # If there's specific variant set in `load_only`, load only
257
+ # that variant, not the others.
258
+ if self.load_only is not None and variant != self.load_only:
259
+ logger.debug("Skipping file '%s' (variant: %s)", fname, variant)
260
+ continue
261
+
262
+ parser = self._load_file(variant, fname)
263
+
264
+ # Keeping track of the parsers used
265
+ self._parsers[variant].append((fname, parser))
266
+
267
+ def _load_file(self, variant: Kind, fname: str) -> RawConfigParser:
268
+ logger.verbose("For variant '%s', will try loading '%s'", variant, fname)
269
+ parser = self._construct_parser(fname)
270
+
271
+ for section in parser.sections():
272
+ items = parser.items(section)
273
+ self._config[variant].update(self._normalized_keys(section, items))
274
+
275
+ return parser
276
+
277
+ def _construct_parser(self, fname: str) -> RawConfigParser:
278
+ parser = configparser.RawConfigParser()
279
+ # If there is no such file, don't bother reading it but create the
280
+ # parser anyway, to hold the data.
281
+ # Doing this is useful when modifying and saving files, where we don't
282
+ # need to construct a parser.
283
+ if os.path.exists(fname):
284
+ locale_encoding = locale.getpreferredencoding(False)
285
+ try:
286
+ parser.read(fname, encoding=locale_encoding)
287
+ except UnicodeDecodeError:
288
+ # See https://github.com/pypa/pip/issues/4963
289
+ raise ConfigurationFileCouldNotBeLoaded(
290
+ reason=f"contains invalid {locale_encoding} characters",
291
+ fname=fname,
292
+ )
293
+ except configparser.Error as error:
294
+ # See https://github.com/pypa/pip/issues/4893
295
+ raise ConfigurationFileCouldNotBeLoaded(error=error)
296
+ return parser
297
+
298
+ def _load_environment_vars(self) -> None:
299
+ """Loads configuration from environment variables"""
300
+ self._config[kinds.ENV_VAR].update(
301
+ self._normalized_keys(":env:", self.get_environ_vars())
302
+ )
303
+
304
+ def _normalized_keys(
305
+ self, section: str, items: Iterable[Tuple[str, Any]]
306
+ ) -> Dict[str, Any]:
307
+ """Normalizes items to construct a dictionary with normalized keys.
308
+
309
+ This routine is where the names become keys and are made the same
310
+ regardless of source - configuration files or environment.
311
+ """
312
+ normalized = {}
313
+ for name, val in items:
314
+ key = section + "." + _normalize_name(name)
315
+ normalized[key] = val
316
+ return normalized
317
+
318
+ def get_environ_vars(self) -> Iterable[Tuple[str, str]]:
319
+ """Returns a generator with all environmental vars with prefix PIP_"""
320
+ for key, val in os.environ.items():
321
+ if key.startswith("PIP_"):
322
+ name = key[4:].lower()
323
+ if name not in ENV_NAMES_IGNORED:
324
+ yield name, val
325
+
326
+ # XXX: This is patched in the tests.
327
+ def iter_config_files(self) -> Iterable[Tuple[Kind, List[str]]]:
328
+ """Yields variant and configuration files associated with it.
329
+
330
+ This should be treated like items of a dictionary. The order
331
+ here doesn't affect what gets overridden. That is controlled
332
+ by OVERRIDE_ORDER. However this does control the order they are
333
+ displayed to the user. It's probably most ergonomic to display
334
+ things in the same order as OVERRIDE_ORDER
335
+ """
336
+ # SMELL: Move the conditions out of this function
337
+
338
+ env_config_file = os.environ.get("PIP_CONFIG_FILE", None)
339
+ config_files = get_configuration_files()
340
+
341
+ yield kinds.GLOBAL, config_files[kinds.GLOBAL]
342
+
343
+ # per-user config is not loaded when env_config_file exists
344
+ should_load_user_config = not self.isolated and not (
345
+ env_config_file and os.path.exists(env_config_file)
346
+ )
347
+ if should_load_user_config:
348
+ # The legacy config file is overridden by the new config file
349
+ yield kinds.USER, config_files[kinds.USER]
350
+
351
+ # virtualenv config
352
+ yield kinds.SITE, config_files[kinds.SITE]
353
+
354
+ if env_config_file is not None:
355
+ yield kinds.ENV, [env_config_file]
356
+ else:
357
+ yield kinds.ENV, []
358
+
359
+ def get_values_in_config(self, variant: Kind) -> Dict[str, Any]:
360
+ """Get values present in a config file"""
361
+ return self._config[variant]
362
+
363
+ def _get_parser_to_modify(self) -> Tuple[str, RawConfigParser]:
364
+ # Determine which parser to modify
365
+ assert self.load_only
366
+ parsers = self._parsers[self.load_only]
367
+ if not parsers:
368
+ # This should not happen if everything works correctly.
369
+ raise ConfigurationError(
370
+ "Fatal Internal error [id=2]. Please report as a bug."
371
+ )
372
+
373
+ # Use the highest priority parser.
374
+ return parsers[-1]
375
+
376
+ # XXX: This is patched in the tests.
377
+ def _mark_as_modified(self, fname: str, parser: RawConfigParser) -> None:
378
+ file_parser_tuple = (fname, parser)
379
+ if file_parser_tuple not in self._modified_parsers:
380
+ self._modified_parsers.append(file_parser_tuple)
381
+
382
+ def __repr__(self) -> str:
383
+ return f"{self.__class__.__name__}({self._dictionary!r})"
python_embeded/Lib/site-packages/pip/_internal/distributions/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pip._internal.distributions.base import AbstractDistribution
2
+ from pip._internal.distributions.sdist import SourceDistribution
3
+ from pip._internal.distributions.wheel import WheelDistribution
4
+ from pip._internal.req.req_install import InstallRequirement
5
+
6
+
7
+ def make_distribution_for_install_requirement(
8
+ install_req: InstallRequirement,
9
+ ) -> AbstractDistribution:
10
+ """Returns a Distribution for the given InstallRequirement"""
11
+ # Editable requirements will always be source distributions. They use the
12
+ # legacy logic until we create a modern standard for them.
13
+ if install_req.editable:
14
+ return SourceDistribution(install_req)
15
+
16
+ # If it's a wheel, it's a WheelDistribution
17
+ if install_req.is_wheel:
18
+ return WheelDistribution(install_req)
19
+
20
+ # Otherwise, a SourceDistribution
21
+ return SourceDistribution(install_req)
python_embeded/Lib/site-packages/pip/_internal/distributions/base.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ from typing import TYPE_CHECKING, Optional
3
+
4
+ from pip._internal.metadata.base import BaseDistribution
5
+ from pip._internal.req import InstallRequirement
6
+
7
+ if TYPE_CHECKING:
8
+ from pip._internal.index.package_finder import PackageFinder
9
+
10
+
11
+ class AbstractDistribution(metaclass=abc.ABCMeta):
12
+ """A base class for handling installable artifacts.
13
+
14
+ The requirements for anything installable are as follows:
15
+
16
+ - we must be able to determine the requirement name
17
+ (or we can't correctly handle the non-upgrade case).
18
+
19
+ - for packages with setup requirements, we must also be able
20
+ to determine their requirements without installing additional
21
+ packages (for the same reason as run-time dependencies)
22
+
23
+ - we must be able to create a Distribution object exposing the
24
+ above metadata.
25
+
26
+ - if we need to do work in the build tracker, we must be able to generate a unique
27
+ string to identify the requirement in the build tracker.
28
+ """
29
+
30
+ def __init__(self, req: InstallRequirement) -> None:
31
+ super().__init__()
32
+ self.req = req
33
+
34
+ @abc.abstractproperty
35
+ def build_tracker_id(self) -> Optional[str]:
36
+ """A string that uniquely identifies this requirement to the build tracker.
37
+
38
+ If None, then this dist has no work to do in the build tracker, and
39
+ ``.prepare_distribution_metadata()`` will not be called."""
40
+ raise NotImplementedError()
41
+
42
+ @abc.abstractmethod
43
+ def get_metadata_distribution(self) -> BaseDistribution:
44
+ raise NotImplementedError()
45
+
46
+ @abc.abstractmethod
47
+ def prepare_distribution_metadata(
48
+ self,
49
+ finder: "PackageFinder",
50
+ build_isolation: bool,
51
+ check_build_deps: bool,
52
+ ) -> None:
53
+ raise NotImplementedError()
python_embeded/Lib/site-packages/pip/_internal/distributions/installed.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ from pip._internal.distributions.base import AbstractDistribution
4
+ from pip._internal.index.package_finder import PackageFinder
5
+ from pip._internal.metadata import BaseDistribution
6
+
7
+
8
+ class InstalledDistribution(AbstractDistribution):
9
+ """Represents an installed package.
10
+
11
+ This does not need any preparation as the required information has already
12
+ been computed.
13
+ """
14
+
15
+ @property
16
+ def build_tracker_id(self) -> Optional[str]:
17
+ return None
18
+
19
+ def get_metadata_distribution(self) -> BaseDistribution:
20
+ assert self.req.satisfied_by is not None, "not actually installed"
21
+ return self.req.satisfied_by
22
+
23
+ def prepare_distribution_metadata(
24
+ self,
25
+ finder: PackageFinder,
26
+ build_isolation: bool,
27
+ check_build_deps: bool,
28
+ ) -> None:
29
+ pass
python_embeded/Lib/site-packages/pip/_internal/distributions/sdist.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import TYPE_CHECKING, Iterable, Optional, Set, Tuple
3
+
4
+ from pip._internal.build_env import BuildEnvironment
5
+ from pip._internal.distributions.base import AbstractDistribution
6
+ from pip._internal.exceptions import InstallationError
7
+ from pip._internal.metadata import BaseDistribution
8
+ from pip._internal.utils.subprocess import runner_with_spinner_message
9
+
10
+ if TYPE_CHECKING:
11
+ from pip._internal.index.package_finder import PackageFinder
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class SourceDistribution(AbstractDistribution):
17
+ """Represents a source distribution.
18
+
19
+ The preparation step for these needs metadata for the packages to be
20
+ generated, either using PEP 517 or using the legacy `setup.py egg_info`.
21
+ """
22
+
23
+ @property
24
+ def build_tracker_id(self) -> Optional[str]:
25
+ """Identify this requirement uniquely by its link."""
26
+ assert self.req.link
27
+ return self.req.link.url_without_fragment
28
+
29
+ def get_metadata_distribution(self) -> BaseDistribution:
30
+ return self.req.get_dist()
31
+
32
+ def prepare_distribution_metadata(
33
+ self,
34
+ finder: "PackageFinder",
35
+ build_isolation: bool,
36
+ check_build_deps: bool,
37
+ ) -> None:
38
+ # Load pyproject.toml, to determine whether PEP 517 is to be used
39
+ self.req.load_pyproject_toml()
40
+
41
+ # Set up the build isolation, if this requirement should be isolated
42
+ should_isolate = self.req.use_pep517 and build_isolation
43
+ if should_isolate:
44
+ # Setup an isolated environment and install the build backend static
45
+ # requirements in it.
46
+ self._prepare_build_backend(finder)
47
+ # Check that if the requirement is editable, it either supports PEP 660 or
48
+ # has a setup.py or a setup.cfg. This cannot be done earlier because we need
49
+ # to setup the build backend to verify it supports build_editable, nor can
50
+ # it be done later, because we want to avoid installing build requirements
51
+ # needlessly. Doing it here also works around setuptools generating
52
+ # UNKNOWN.egg-info when running get_requires_for_build_wheel on a directory
53
+ # without setup.py nor setup.cfg.
54
+ self.req.isolated_editable_sanity_check()
55
+ # Install the dynamic build requirements.
56
+ self._install_build_reqs(finder)
57
+ # Check if the current environment provides build dependencies
58
+ should_check_deps = self.req.use_pep517 and check_build_deps
59
+ if should_check_deps:
60
+ pyproject_requires = self.req.pyproject_requires
61
+ assert pyproject_requires is not None
62
+ conflicting, missing = self.req.build_env.check_requirements(
63
+ pyproject_requires
64
+ )
65
+ if conflicting:
66
+ self._raise_conflicts("the backend dependencies", conflicting)
67
+ if missing:
68
+ self._raise_missing_reqs(missing)
69
+ self.req.prepare_metadata()
70
+
71
+ def _prepare_build_backend(self, finder: "PackageFinder") -> None:
72
+ # Isolate in a BuildEnvironment and install the build-time
73
+ # requirements.
74
+ pyproject_requires = self.req.pyproject_requires
75
+ assert pyproject_requires is not None
76
+
77
+ self.req.build_env = BuildEnvironment()
78
+ self.req.build_env.install_requirements(
79
+ finder, pyproject_requires, "overlay", kind="build dependencies"
80
+ )
81
+ conflicting, missing = self.req.build_env.check_requirements(
82
+ self.req.requirements_to_check
83
+ )
84
+ if conflicting:
85
+ self._raise_conflicts("PEP 517/518 supported requirements", conflicting)
86
+ if missing:
87
+ logger.warning(
88
+ "Missing build requirements in pyproject.toml for %s.",
89
+ self.req,
90
+ )
91
+ logger.warning(
92
+ "The project does not specify a build backend, and "
93
+ "pip cannot fall back to setuptools without %s.",
94
+ " and ".join(map(repr, sorted(missing))),
95
+ )
96
+
97
+ def _get_build_requires_wheel(self) -> Iterable[str]:
98
+ with self.req.build_env:
99
+ runner = runner_with_spinner_message("Getting requirements to build wheel")
100
+ backend = self.req.pep517_backend
101
+ assert backend is not None
102
+ with backend.subprocess_runner(runner):
103
+ return backend.get_requires_for_build_wheel()
104
+
105
+ def _get_build_requires_editable(self) -> Iterable[str]:
106
+ with self.req.build_env:
107
+ runner = runner_with_spinner_message(
108
+ "Getting requirements to build editable"
109
+ )
110
+ backend = self.req.pep517_backend
111
+ assert backend is not None
112
+ with backend.subprocess_runner(runner):
113
+ return backend.get_requires_for_build_editable()
114
+
115
+ def _install_build_reqs(self, finder: "PackageFinder") -> None:
116
+ # Install any extra build dependencies that the backend requests.
117
+ # This must be done in a second pass, as the pyproject.toml
118
+ # dependencies must be installed before we can call the backend.
119
+ if (
120
+ self.req.editable
121
+ and self.req.permit_editable_wheels
122
+ and self.req.supports_pyproject_editable
123
+ ):
124
+ build_reqs = self._get_build_requires_editable()
125
+ else:
126
+ build_reqs = self._get_build_requires_wheel()
127
+ conflicting, missing = self.req.build_env.check_requirements(build_reqs)
128
+ if conflicting:
129
+ self._raise_conflicts("the backend dependencies", conflicting)
130
+ self.req.build_env.install_requirements(
131
+ finder, missing, "normal", kind="backend dependencies"
132
+ )
133
+
134
+ def _raise_conflicts(
135
+ self, conflicting_with: str, conflicting_reqs: Set[Tuple[str, str]]
136
+ ) -> None:
137
+ format_string = (
138
+ "Some build dependencies for {requirement} "
139
+ "conflict with {conflicting_with}: {description}."
140
+ )
141
+ error_message = format_string.format(
142
+ requirement=self.req,
143
+ conflicting_with=conflicting_with,
144
+ description=", ".join(
145
+ f"{installed} is incompatible with {wanted}"
146
+ for installed, wanted in sorted(conflicting_reqs)
147
+ ),
148
+ )
149
+ raise InstallationError(error_message)
150
+
151
+ def _raise_missing_reqs(self, missing: Set[str]) -> None:
152
+ format_string = (
153
+ "Some build dependencies for {requirement} are missing: {missing}."
154
+ )
155
+ error_message = format_string.format(
156
+ requirement=self.req, missing=", ".join(map(repr, sorted(missing)))
157
+ )
158
+ raise InstallationError(error_message)
python_embeded/Lib/site-packages/pip/_internal/distributions/wheel.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING, Optional
2
+
3
+ from pip._vendor.packaging.utils import canonicalize_name
4
+
5
+ from pip._internal.distributions.base import AbstractDistribution
6
+ from pip._internal.metadata import (
7
+ BaseDistribution,
8
+ FilesystemWheel,
9
+ get_wheel_distribution,
10
+ )
11
+
12
+ if TYPE_CHECKING:
13
+ from pip._internal.index.package_finder import PackageFinder
14
+
15
+
16
+ class WheelDistribution(AbstractDistribution):
17
+ """Represents a wheel distribution.
18
+
19
+ This does not need any preparation as wheels can be directly unpacked.
20
+ """
21
+
22
+ @property
23
+ def build_tracker_id(self) -> Optional[str]:
24
+ return None
25
+
26
+ def get_metadata_distribution(self) -> BaseDistribution:
27
+ """Loads the metadata from the wheel file into memory and returns a
28
+ Distribution that uses it, not relying on the wheel file or
29
+ requirement.
30
+ """
31
+ assert self.req.local_file_path, "Set as part of preparation during download"
32
+ assert self.req.name, "Wheels are never unnamed"
33
+ wheel = FilesystemWheel(self.req.local_file_path)
34
+ return get_wheel_distribution(wheel, canonicalize_name(self.req.name))
35
+
36
+ def prepare_distribution_metadata(
37
+ self,
38
+ finder: "PackageFinder",
39
+ build_isolation: bool,
40
+ check_build_deps: bool,
41
+ ) -> None:
42
+ pass
python_embeded/Lib/site-packages/pip/_internal/exceptions.py ADDED
@@ -0,0 +1,862 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exceptions used throughout package.
2
+
3
+ This module MUST NOT try to import from anything within `pip._internal` to
4
+ operate. This is expected to be importable from any/all files within the
5
+ subpackage and, thus, should not depend on them.
6
+ """
7
+
8
+ import configparser
9
+ import contextlib
10
+ import locale
11
+ import logging
12
+ import pathlib
13
+ import re
14
+ import sys
15
+ from itertools import chain, groupby, repeat
16
+ from typing import TYPE_CHECKING, Dict, Iterator, List, Literal, Optional, Union
17
+
18
+ from pip._vendor.packaging.requirements import InvalidRequirement
19
+ from pip._vendor.packaging.version import InvalidVersion
20
+ from pip._vendor.rich.console import Console, ConsoleOptions, RenderResult
21
+ from pip._vendor.rich.markup import escape
22
+ from pip._vendor.rich.text import Text
23
+
24
+ if TYPE_CHECKING:
25
+ from hashlib import _Hash
26
+
27
+ from pip._vendor.requests.models import Request, Response
28
+
29
+ from pip._internal.metadata import BaseDistribution
30
+ from pip._internal.models.link import Link
31
+ from pip._internal.req.req_install import InstallRequirement
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+
36
+ #
37
+ # Scaffolding
38
+ #
39
+ def _is_kebab_case(s: str) -> bool:
40
+ return re.match(r"^[a-z]+(-[a-z]+)*$", s) is not None
41
+
42
+
43
+ def _prefix_with_indent(
44
+ s: Union[Text, str],
45
+ console: Console,
46
+ *,
47
+ prefix: str,
48
+ indent: str,
49
+ ) -> Text:
50
+ if isinstance(s, Text):
51
+ text = s
52
+ else:
53
+ text = console.render_str(s)
54
+
55
+ return console.render_str(prefix, overflow="ignore") + console.render_str(
56
+ f"\n{indent}", overflow="ignore"
57
+ ).join(text.split(allow_blank=True))
58
+
59
+
60
+ class PipError(Exception):
61
+ """The base pip error."""
62
+
63
+
64
+ class DiagnosticPipError(PipError):
65
+ """An error, that presents diagnostic information to the user.
66
+
67
+ This contains a bunch of logic, to enable pretty presentation of our error
68
+ messages. Each error gets a unique reference. Each error can also include
69
+ additional context, a hint and/or a note -- which are presented with the
70
+ main error message in a consistent style.
71
+
72
+ This is adapted from the error output styling in `sphinx-theme-builder`.
73
+ """
74
+
75
+ reference: str
76
+
77
+ def __init__(
78
+ self,
79
+ *,
80
+ kind: 'Literal["error", "warning"]' = "error",
81
+ reference: Optional[str] = None,
82
+ message: Union[str, Text],
83
+ context: Optional[Union[str, Text]],
84
+ hint_stmt: Optional[Union[str, Text]],
85
+ note_stmt: Optional[Union[str, Text]] = None,
86
+ link: Optional[str] = None,
87
+ ) -> None:
88
+ # Ensure a proper reference is provided.
89
+ if reference is None:
90
+ assert hasattr(self, "reference"), "error reference not provided!"
91
+ reference = self.reference
92
+ assert _is_kebab_case(reference), "error reference must be kebab-case!"
93
+
94
+ self.kind = kind
95
+ self.reference = reference
96
+
97
+ self.message = message
98
+ self.context = context
99
+
100
+ self.note_stmt = note_stmt
101
+ self.hint_stmt = hint_stmt
102
+
103
+ self.link = link
104
+
105
+ super().__init__(f"<{self.__class__.__name__}: {self.reference}>")
106
+
107
+ def __repr__(self) -> str:
108
+ return (
109
+ f"<{self.__class__.__name__}("
110
+ f"reference={self.reference!r}, "
111
+ f"message={self.message!r}, "
112
+ f"context={self.context!r}, "
113
+ f"note_stmt={self.note_stmt!r}, "
114
+ f"hint_stmt={self.hint_stmt!r}"
115
+ ")>"
116
+ )
117
+
118
+ def __rich_console__(
119
+ self,
120
+ console: Console,
121
+ options: ConsoleOptions,
122
+ ) -> RenderResult:
123
+ colour = "red" if self.kind == "error" else "yellow"
124
+
125
+ yield f"[{colour} bold]{self.kind}[/]: [bold]{self.reference}[/]"
126
+ yield ""
127
+
128
+ if not options.ascii_only:
129
+ # Present the main message, with relevant context indented.
130
+ if self.context is not None:
131
+ yield _prefix_with_indent(
132
+ self.message,
133
+ console,
134
+ prefix=f"[{colour}]×[/] ",
135
+ indent=f"[{colour}]│[/] ",
136
+ )
137
+ yield _prefix_with_indent(
138
+ self.context,
139
+ console,
140
+ prefix=f"[{colour}]╰─>[/] ",
141
+ indent=f"[{colour}] [/] ",
142
+ )
143
+ else:
144
+ yield _prefix_with_indent(
145
+ self.message,
146
+ console,
147
+ prefix="[red]×[/] ",
148
+ indent=" ",
149
+ )
150
+ else:
151
+ yield self.message
152
+ if self.context is not None:
153
+ yield ""
154
+ yield self.context
155
+
156
+ if self.note_stmt is not None or self.hint_stmt is not None:
157
+ yield ""
158
+
159
+ if self.note_stmt is not None:
160
+ yield _prefix_with_indent(
161
+ self.note_stmt,
162
+ console,
163
+ prefix="[magenta bold]note[/]: ",
164
+ indent=" ",
165
+ )
166
+ if self.hint_stmt is not None:
167
+ yield _prefix_with_indent(
168
+ self.hint_stmt,
169
+ console,
170
+ prefix="[cyan bold]hint[/]: ",
171
+ indent=" ",
172
+ )
173
+
174
+ if self.link is not None:
175
+ yield ""
176
+ yield f"Link: {self.link}"
177
+
178
+
179
+ #
180
+ # Actual Errors
181
+ #
182
+ class ConfigurationError(PipError):
183
+ """General exception in configuration"""
184
+
185
+
186
+ class InstallationError(PipError):
187
+ """General exception during installation"""
188
+
189
+
190
+ class MissingPyProjectBuildRequires(DiagnosticPipError):
191
+ """Raised when pyproject.toml has `build-system`, but no `build-system.requires`."""
192
+
193
+ reference = "missing-pyproject-build-system-requires"
194
+
195
+ def __init__(self, *, package: str) -> None:
196
+ super().__init__(
197
+ message=f"Can not process {escape(package)}",
198
+ context=Text(
199
+ "This package has an invalid pyproject.toml file.\n"
200
+ "The [build-system] table is missing the mandatory `requires` key."
201
+ ),
202
+ note_stmt="This is an issue with the package mentioned above, not pip.",
203
+ hint_stmt=Text("See PEP 518 for the detailed specification."),
204
+ )
205
+
206
+
207
+ class InvalidPyProjectBuildRequires(DiagnosticPipError):
208
+ """Raised when pyproject.toml an invalid `build-system.requires`."""
209
+
210
+ reference = "invalid-pyproject-build-system-requires"
211
+
212
+ def __init__(self, *, package: str, reason: str) -> None:
213
+ super().__init__(
214
+ message=f"Can not process {escape(package)}",
215
+ context=Text(
216
+ "This package has an invalid `build-system.requires` key in "
217
+ f"pyproject.toml.\n{reason}"
218
+ ),
219
+ note_stmt="This is an issue with the package mentioned above, not pip.",
220
+ hint_stmt=Text("See PEP 518 for the detailed specification."),
221
+ )
222
+
223
+
224
+ class NoneMetadataError(PipError):
225
+ """Raised when accessing a Distribution's "METADATA" or "PKG-INFO".
226
+
227
+ This signifies an inconsistency, when the Distribution claims to have
228
+ the metadata file (if not, raise ``FileNotFoundError`` instead), but is
229
+ not actually able to produce its content. This may be due to permission
230
+ errors.
231
+ """
232
+
233
+ def __init__(
234
+ self,
235
+ dist: "BaseDistribution",
236
+ metadata_name: str,
237
+ ) -> None:
238
+ """
239
+ :param dist: A Distribution object.
240
+ :param metadata_name: The name of the metadata being accessed
241
+ (can be "METADATA" or "PKG-INFO").
242
+ """
243
+ self.dist = dist
244
+ self.metadata_name = metadata_name
245
+
246
+ def __str__(self) -> str:
247
+ # Use `dist` in the error message because its stringification
248
+ # includes more information, like the version and location.
249
+ return f"None {self.metadata_name} metadata found for distribution: {self.dist}"
250
+
251
+
252
+ class UserInstallationInvalid(InstallationError):
253
+ """A --user install is requested on an environment without user site."""
254
+
255
+ def __str__(self) -> str:
256
+ return "User base directory is not specified"
257
+
258
+
259
+ class InvalidSchemeCombination(InstallationError):
260
+ def __str__(self) -> str:
261
+ before = ", ".join(str(a) for a in self.args[:-1])
262
+ return f"Cannot set {before} and {self.args[-1]} together"
263
+
264
+
265
+ class DistributionNotFound(InstallationError):
266
+ """Raised when a distribution cannot be found to satisfy a requirement"""
267
+
268
+
269
+ class RequirementsFileParseError(InstallationError):
270
+ """Raised when a general error occurs parsing a requirements file line."""
271
+
272
+
273
+ class BestVersionAlreadyInstalled(PipError):
274
+ """Raised when the most up-to-date version of a package is already
275
+ installed."""
276
+
277
+
278
+ class BadCommand(PipError):
279
+ """Raised when virtualenv or a command is not found"""
280
+
281
+
282
+ class CommandError(PipError):
283
+ """Raised when there is an error in command-line arguments"""
284
+
285
+
286
+ class PreviousBuildDirError(PipError):
287
+ """Raised when there's a previous conflicting build directory"""
288
+
289
+
290
+ class NetworkConnectionError(PipError):
291
+ """HTTP connection error"""
292
+
293
+ def __init__(
294
+ self,
295
+ error_msg: str,
296
+ response: Optional["Response"] = None,
297
+ request: Optional["Request"] = None,
298
+ ) -> None:
299
+ """
300
+ Initialize NetworkConnectionError with `request` and `response`
301
+ objects.
302
+ """
303
+ self.response = response
304
+ self.request = request
305
+ self.error_msg = error_msg
306
+ if (
307
+ self.response is not None
308
+ and not self.request
309
+ and hasattr(response, "request")
310
+ ):
311
+ self.request = self.response.request
312
+ super().__init__(error_msg, response, request)
313
+
314
+ def __str__(self) -> str:
315
+ return str(self.error_msg)
316
+
317
+
318
+ class InvalidWheelFilename(InstallationError):
319
+ """Invalid wheel filename."""
320
+
321
+
322
+ class UnsupportedWheel(InstallationError):
323
+ """Unsupported wheel."""
324
+
325
+
326
+ class InvalidWheel(InstallationError):
327
+ """Invalid (e.g. corrupt) wheel."""
328
+
329
+ def __init__(self, location: str, name: str):
330
+ self.location = location
331
+ self.name = name
332
+
333
+ def __str__(self) -> str:
334
+ return f"Wheel '{self.name}' located at {self.location} is invalid."
335
+
336
+
337
+ class MetadataInconsistent(InstallationError):
338
+ """Built metadata contains inconsistent information.
339
+
340
+ This is raised when the metadata contains values (e.g. name and version)
341
+ that do not match the information previously obtained from sdist filename,
342
+ user-supplied ``#egg=`` value, or an install requirement name.
343
+ """
344
+
345
+ def __init__(
346
+ self, ireq: "InstallRequirement", field: str, f_val: str, m_val: str
347
+ ) -> None:
348
+ self.ireq = ireq
349
+ self.field = field
350
+ self.f_val = f_val
351
+ self.m_val = m_val
352
+
353
+ def __str__(self) -> str:
354
+ return (
355
+ f"Requested {self.ireq} has inconsistent {self.field}: "
356
+ f"expected {self.f_val!r}, but metadata has {self.m_val!r}"
357
+ )
358
+
359
+
360
+ class MetadataInvalid(InstallationError):
361
+ """Metadata is invalid."""
362
+
363
+ def __init__(self, ireq: "InstallRequirement", error: str) -> None:
364
+ self.ireq = ireq
365
+ self.error = error
366
+
367
+ def __str__(self) -> str:
368
+ return f"Requested {self.ireq} has invalid metadata: {self.error}"
369
+
370
+
371
+ class InstallationSubprocessError(DiagnosticPipError, InstallationError):
372
+ """A subprocess call failed."""
373
+
374
+ reference = "subprocess-exited-with-error"
375
+
376
+ def __init__(
377
+ self,
378
+ *,
379
+ command_description: str,
380
+ exit_code: int,
381
+ output_lines: Optional[List[str]],
382
+ ) -> None:
383
+ if output_lines is None:
384
+ output_prompt = Text("See above for output.")
385
+ else:
386
+ output_prompt = (
387
+ Text.from_markup(f"[red][{len(output_lines)} lines of output][/]\n")
388
+ + Text("".join(output_lines))
389
+ + Text.from_markup(R"[red]\[end of output][/]")
390
+ )
391
+
392
+ super().__init__(
393
+ message=(
394
+ f"[green]{escape(command_description)}[/] did not run successfully.\n"
395
+ f"exit code: {exit_code}"
396
+ ),
397
+ context=output_prompt,
398
+ hint_stmt=None,
399
+ note_stmt=(
400
+ "This error originates from a subprocess, and is likely not a "
401
+ "problem with pip."
402
+ ),
403
+ )
404
+
405
+ self.command_description = command_description
406
+ self.exit_code = exit_code
407
+
408
+ def __str__(self) -> str:
409
+ return f"{self.command_description} exited with {self.exit_code}"
410
+
411
+
412
+ class MetadataGenerationFailed(InstallationSubprocessError, InstallationError):
413
+ reference = "metadata-generation-failed"
414
+
415
+ def __init__(
416
+ self,
417
+ *,
418
+ package_details: str,
419
+ ) -> None:
420
+ super(InstallationSubprocessError, self).__init__(
421
+ message="Encountered error while generating package metadata.",
422
+ context=escape(package_details),
423
+ hint_stmt="See above for details.",
424
+ note_stmt="This is an issue with the package mentioned above, not pip.",
425
+ )
426
+
427
+ def __str__(self) -> str:
428
+ return "metadata generation failed"
429
+
430
+
431
+ class HashErrors(InstallationError):
432
+ """Multiple HashError instances rolled into one for reporting"""
433
+
434
+ def __init__(self) -> None:
435
+ self.errors: List[HashError] = []
436
+
437
+ def append(self, error: "HashError") -> None:
438
+ self.errors.append(error)
439
+
440
+ def __str__(self) -> str:
441
+ lines = []
442
+ self.errors.sort(key=lambda e: e.order)
443
+ for cls, errors_of_cls in groupby(self.errors, lambda e: e.__class__):
444
+ lines.append(cls.head)
445
+ lines.extend(e.body() for e in errors_of_cls)
446
+ if lines:
447
+ return "\n".join(lines)
448
+ return ""
449
+
450
+ def __bool__(self) -> bool:
451
+ return bool(self.errors)
452
+
453
+
454
+ class HashError(InstallationError):
455
+ """
456
+ A failure to verify a package against known-good hashes
457
+
458
+ :cvar order: An int sorting hash exception classes by difficulty of
459
+ recovery (lower being harder), so the user doesn't bother fretting
460
+ about unpinned packages when he has deeper issues, like VCS
461
+ dependencies, to deal with. Also keeps error reports in a
462
+ deterministic order.
463
+ :cvar head: A section heading for display above potentially many
464
+ exceptions of this kind
465
+ :ivar req: The InstallRequirement that triggered this error. This is
466
+ pasted on after the exception is instantiated, because it's not
467
+ typically available earlier.
468
+
469
+ """
470
+
471
+ req: Optional["InstallRequirement"] = None
472
+ head = ""
473
+ order: int = -1
474
+
475
+ def body(self) -> str:
476
+ """Return a summary of me for display under the heading.
477
+
478
+ This default implementation simply prints a description of the
479
+ triggering requirement.
480
+
481
+ :param req: The InstallRequirement that provoked this error, with
482
+ its link already populated by the resolver's _populate_link().
483
+
484
+ """
485
+ return f" {self._requirement_name()}"
486
+
487
+ def __str__(self) -> str:
488
+ return f"{self.head}\n{self.body()}"
489
+
490
+ def _requirement_name(self) -> str:
491
+ """Return a description of the requirement that triggered me.
492
+
493
+ This default implementation returns long description of the req, with
494
+ line numbers
495
+
496
+ """
497
+ return str(self.req) if self.req else "unknown package"
498
+
499
+
500
+ class VcsHashUnsupported(HashError):
501
+ """A hash was provided for a version-control-system-based requirement, but
502
+ we don't have a method for hashing those."""
503
+
504
+ order = 0
505
+ head = (
506
+ "Can't verify hashes for these requirements because we don't "
507
+ "have a way to hash version control repositories:"
508
+ )
509
+
510
+
511
+ class DirectoryUrlHashUnsupported(HashError):
512
+ """A hash was provided for a version-control-system-based requirement, but
513
+ we don't have a method for hashing those."""
514
+
515
+ order = 1
516
+ head = (
517
+ "Can't verify hashes for these file:// requirements because they "
518
+ "point to directories:"
519
+ )
520
+
521
+
522
+ class HashMissing(HashError):
523
+ """A hash was needed for a requirement but is absent."""
524
+
525
+ order = 2
526
+ head = (
527
+ "Hashes are required in --require-hashes mode, but they are "
528
+ "missing from some requirements. Here is a list of those "
529
+ "requirements along with the hashes their downloaded archives "
530
+ "actually had. Add lines like these to your requirements files to "
531
+ "prevent tampering. (If you did not enable --require-hashes "
532
+ "manually, note that it turns on automatically when any package "
533
+ "has a hash.)"
534
+ )
535
+
536
+ def __init__(self, gotten_hash: str) -> None:
537
+ """
538
+ :param gotten_hash: The hash of the (possibly malicious) archive we
539
+ just downloaded
540
+ """
541
+ self.gotten_hash = gotten_hash
542
+
543
+ def body(self) -> str:
544
+ # Dodge circular import.
545
+ from pip._internal.utils.hashes import FAVORITE_HASH
546
+
547
+ package = None
548
+ if self.req:
549
+ # In the case of URL-based requirements, display the original URL
550
+ # seen in the requirements file rather than the package name,
551
+ # so the output can be directly copied into the requirements file.
552
+ package = (
553
+ self.req.original_link
554
+ if self.req.is_direct
555
+ # In case someone feeds something downright stupid
556
+ # to InstallRequirement's constructor.
557
+ else getattr(self.req, "req", None)
558
+ )
559
+ return " {} --hash={}:{}".format(
560
+ package or "unknown package", FAVORITE_HASH, self.gotten_hash
561
+ )
562
+
563
+
564
+ class HashUnpinned(HashError):
565
+ """A requirement had a hash specified but was not pinned to a specific
566
+ version."""
567
+
568
+ order = 3
569
+ head = (
570
+ "In --require-hashes mode, all requirements must have their "
571
+ "versions pinned with ==. These do not:"
572
+ )
573
+
574
+
575
+ class HashMismatch(HashError):
576
+ """
577
+ Distribution file hash values don't match.
578
+
579
+ :ivar package_name: The name of the package that triggered the hash
580
+ mismatch. Feel free to write to this after the exception is raise to
581
+ improve its error message.
582
+
583
+ """
584
+
585
+ order = 4
586
+ head = (
587
+ "THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS "
588
+ "FILE. If you have updated the package versions, please update "
589
+ "the hashes. Otherwise, examine the package contents carefully; "
590
+ "someone may have tampered with them."
591
+ )
592
+
593
+ def __init__(self, allowed: Dict[str, List[str]], gots: Dict[str, "_Hash"]) -> None:
594
+ """
595
+ :param allowed: A dict of algorithm names pointing to lists of allowed
596
+ hex digests
597
+ :param gots: A dict of algorithm names pointing to hashes we
598
+ actually got from the files under suspicion
599
+ """
600
+ self.allowed = allowed
601
+ self.gots = gots
602
+
603
+ def body(self) -> str:
604
+ return f" {self._requirement_name()}:\n{self._hash_comparison()}"
605
+
606
+ def _hash_comparison(self) -> str:
607
+ """
608
+ Return a comparison of actual and expected hash values.
609
+
610
+ Example::
611
+
612
+ Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
613
+ or 123451234512345123451234512345123451234512345
614
+ Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef
615
+
616
+ """
617
+
618
+ def hash_then_or(hash_name: str) -> "chain[str]":
619
+ # For now, all the decent hashes have 6-char names, so we can get
620
+ # away with hard-coding space literals.
621
+ return chain([hash_name], repeat(" or"))
622
+
623
+ lines: List[str] = []
624
+ for hash_name, expecteds in self.allowed.items():
625
+ prefix = hash_then_or(hash_name)
626
+ lines.extend((f" Expected {next(prefix)} {e}") for e in expecteds)
627
+ lines.append(
628
+ f" Got {self.gots[hash_name].hexdigest()}\n"
629
+ )
630
+ return "\n".join(lines)
631
+
632
+
633
+ class UnsupportedPythonVersion(InstallationError):
634
+ """Unsupported python version according to Requires-Python package
635
+ metadata."""
636
+
637
+
638
+ class ConfigurationFileCouldNotBeLoaded(ConfigurationError):
639
+ """When there are errors while loading a configuration file"""
640
+
641
+ def __init__(
642
+ self,
643
+ reason: str = "could not be loaded",
644
+ fname: Optional[str] = None,
645
+ error: Optional[configparser.Error] = None,
646
+ ) -> None:
647
+ super().__init__(error)
648
+ self.reason = reason
649
+ self.fname = fname
650
+ self.error = error
651
+
652
+ def __str__(self) -> str:
653
+ if self.fname is not None:
654
+ message_part = f" in {self.fname}."
655
+ else:
656
+ assert self.error is not None
657
+ message_part = f".\n{self.error}\n"
658
+ return f"Configuration file {self.reason}{message_part}"
659
+
660
+
661
+ _DEFAULT_EXTERNALLY_MANAGED_ERROR = f"""\
662
+ The Python environment under {sys.prefix} is managed externally, and may not be
663
+ manipulated by the user. Please use specific tooling from the distributor of
664
+ the Python installation to interact with this environment instead.
665
+ """
666
+
667
+
668
+ class ExternallyManagedEnvironment(DiagnosticPipError):
669
+ """The current environment is externally managed.
670
+
671
+ This is raised when the current environment is externally managed, as
672
+ defined by `PEP 668`_. The ``EXTERNALLY-MANAGED`` configuration is checked
673
+ and displayed when the error is bubbled up to the user.
674
+
675
+ :param error: The error message read from ``EXTERNALLY-MANAGED``.
676
+ """
677
+
678
+ reference = "externally-managed-environment"
679
+
680
+ def __init__(self, error: Optional[str]) -> None:
681
+ if error is None:
682
+ context = Text(_DEFAULT_EXTERNALLY_MANAGED_ERROR)
683
+ else:
684
+ context = Text(error)
685
+ super().__init__(
686
+ message="This environment is externally managed",
687
+ context=context,
688
+ note_stmt=(
689
+ "If you believe this is a mistake, please contact your "
690
+ "Python installation or OS distribution provider. "
691
+ "You can override this, at the risk of breaking your Python "
692
+ "installation or OS, by passing --break-system-packages."
693
+ ),
694
+ hint_stmt=Text("See PEP 668 for the detailed specification."),
695
+ )
696
+
697
+ @staticmethod
698
+ def _iter_externally_managed_error_keys() -> Iterator[str]:
699
+ # LC_MESSAGES is in POSIX, but not the C standard. The most common
700
+ # platform that does not implement this category is Windows, where
701
+ # using other categories for console message localization is equally
702
+ # unreliable, so we fall back to the locale-less vendor message. This
703
+ # can always be re-evaluated when a vendor proposes a new alternative.
704
+ try:
705
+ category = locale.LC_MESSAGES
706
+ except AttributeError:
707
+ lang: Optional[str] = None
708
+ else:
709
+ lang, _ = locale.getlocale(category)
710
+ if lang is not None:
711
+ yield f"Error-{lang}"
712
+ for sep in ("-", "_"):
713
+ before, found, _ = lang.partition(sep)
714
+ if not found:
715
+ continue
716
+ yield f"Error-{before}"
717
+ yield "Error"
718
+
719
+ @classmethod
720
+ def from_config(
721
+ cls,
722
+ config: Union[pathlib.Path, str],
723
+ ) -> "ExternallyManagedEnvironment":
724
+ parser = configparser.ConfigParser(interpolation=None)
725
+ try:
726
+ parser.read(config, encoding="utf-8")
727
+ section = parser["externally-managed"]
728
+ for key in cls._iter_externally_managed_error_keys():
729
+ with contextlib.suppress(KeyError):
730
+ return cls(section[key])
731
+ except KeyError:
732
+ pass
733
+ except (OSError, UnicodeDecodeError, configparser.ParsingError):
734
+ from pip._internal.utils._log import VERBOSE
735
+
736
+ exc_info = logger.isEnabledFor(VERBOSE)
737
+ logger.warning("Failed to read %s", config, exc_info=exc_info)
738
+ return cls(None)
739
+
740
+
741
+ class UninstallMissingRecord(DiagnosticPipError):
742
+ reference = "uninstall-no-record-file"
743
+
744
+ def __init__(self, *, distribution: "BaseDistribution") -> None:
745
+ installer = distribution.installer
746
+ if not installer or installer == "pip":
747
+ dep = f"{distribution.raw_name}=={distribution.version}"
748
+ hint = Text.assemble(
749
+ "You might be able to recover from this via: ",
750
+ (f"pip install --force-reinstall --no-deps {dep}", "green"),
751
+ )
752
+ else:
753
+ hint = Text(
754
+ f"The package was installed by {installer}. "
755
+ "You should check if it can uninstall the package."
756
+ )
757
+
758
+ super().__init__(
759
+ message=Text(f"Cannot uninstall {distribution}"),
760
+ context=(
761
+ "The package's contents are unknown: "
762
+ f"no RECORD file was found for {distribution.raw_name}."
763
+ ),
764
+ hint_stmt=hint,
765
+ )
766
+
767
+
768
+ class LegacyDistutilsInstall(DiagnosticPipError):
769
+ reference = "uninstall-distutils-installed-package"
770
+
771
+ def __init__(self, *, distribution: "BaseDistribution") -> None:
772
+ super().__init__(
773
+ message=Text(f"Cannot uninstall {distribution}"),
774
+ context=(
775
+ "It is a distutils installed project and thus we cannot accurately "
776
+ "determine which files belong to it which would lead to only a partial "
777
+ "uninstall."
778
+ ),
779
+ hint_stmt=None,
780
+ )
781
+
782
+
783
+ class InvalidInstalledPackage(DiagnosticPipError):
784
+ reference = "invalid-installed-package"
785
+
786
+ def __init__(
787
+ self,
788
+ *,
789
+ dist: "BaseDistribution",
790
+ invalid_exc: Union[InvalidRequirement, InvalidVersion],
791
+ ) -> None:
792
+ installed_location = dist.installed_location
793
+
794
+ if isinstance(invalid_exc, InvalidRequirement):
795
+ invalid_type = "requirement"
796
+ else:
797
+ invalid_type = "version"
798
+
799
+ super().__init__(
800
+ message=Text(
801
+ f"Cannot process installed package {dist} "
802
+ + (f"in {installed_location!r} " if installed_location else "")
803
+ + f"because it has an invalid {invalid_type}:\n{invalid_exc.args[0]}"
804
+ ),
805
+ context=(
806
+ "Starting with pip 24.1, packages with invalid "
807
+ f"{invalid_type}s can not be processed."
808
+ ),
809
+ hint_stmt="To proceed this package must be uninstalled.",
810
+ )
811
+
812
+
813
+ class IncompleteDownloadError(DiagnosticPipError):
814
+ """Raised when the downloader receives fewer bytes than advertised
815
+ in the Content-Length header."""
816
+
817
+ reference = "incomplete-download"
818
+
819
+ def __init__(
820
+ self, link: "Link", received: int, expected: int, *, retries: int
821
+ ) -> None:
822
+ # Dodge circular import.
823
+ from pip._internal.utils.misc import format_size
824
+
825
+ download_status = f"{format_size(received)}/{format_size(expected)}"
826
+ if retries:
827
+ retry_status = f"after {retries} attempts "
828
+ hint = "Use --resume-retries to configure resume attempt limit."
829
+ else:
830
+ retry_status = ""
831
+ hint = "Consider using --resume-retries to enable download resumption."
832
+ message = Text(
833
+ f"Download failed {retry_status}because not enough bytes "
834
+ f"were received ({download_status})"
835
+ )
836
+
837
+ super().__init__(
838
+ message=message,
839
+ context=f"URL: {link.redacted_url}",
840
+ hint_stmt=hint,
841
+ note_stmt="This is an issue with network connectivity, not pip.",
842
+ )
843
+
844
+
845
+ class ResolutionTooDeepError(DiagnosticPipError):
846
+ """Raised when the dependency resolver exceeds the maximum recursion depth."""
847
+
848
+ reference = "resolution-too-deep"
849
+
850
+ def __init__(self) -> None:
851
+ super().__init__(
852
+ message="Dependency resolution exceeded maximum depth",
853
+ context=(
854
+ "Pip cannot resolve the current dependencies as the dependency graph "
855
+ "is too complex for pip to solve efficiently."
856
+ ),
857
+ hint_stmt=(
858
+ "Try adding lower bounds to constrain your dependencies, "
859
+ "for example: 'package>=2.0.0' instead of just 'package'. "
860
+ ),
861
+ link="https://pip.pypa.io/en/stable/topics/dependency-resolution/#handling-resolution-too-deep-errors",
862
+ )
python_embeded/Lib/site-packages/pip/_internal/index/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Index interaction code"""
python_embeded/Lib/site-packages/pip/_internal/index/collector.py ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The main purpose of this module is to expose LinkCollector.collect_sources().
3
+ """
4
+
5
+ import collections
6
+ import email.message
7
+ import functools
8
+ import itertools
9
+ import json
10
+ import logging
11
+ import os
12
+ import urllib.parse
13
+ import urllib.request
14
+ from dataclasses import dataclass
15
+ from html.parser import HTMLParser
16
+ from optparse import Values
17
+ from typing import (
18
+ Callable,
19
+ Dict,
20
+ Iterable,
21
+ List,
22
+ MutableMapping,
23
+ NamedTuple,
24
+ Optional,
25
+ Protocol,
26
+ Sequence,
27
+ Tuple,
28
+ Union,
29
+ )
30
+
31
+ from pip._vendor import requests
32
+ from pip._vendor.requests import Response
33
+ from pip._vendor.requests.exceptions import RetryError, SSLError
34
+
35
+ from pip._internal.exceptions import NetworkConnectionError
36
+ from pip._internal.models.link import Link
37
+ from pip._internal.models.search_scope import SearchScope
38
+ from pip._internal.network.session import PipSession
39
+ from pip._internal.network.utils import raise_for_status
40
+ from pip._internal.utils.filetypes import is_archive_file
41
+ from pip._internal.utils.misc import redact_auth_from_url
42
+ from pip._internal.vcs import vcs
43
+
44
+ from .sources import CandidatesFromPage, LinkSource, build_source
45
+
46
+ logger = logging.getLogger(__name__)
47
+
48
+ ResponseHeaders = MutableMapping[str, str]
49
+
50
+
51
+ def _match_vcs_scheme(url: str) -> Optional[str]:
52
+ """Look for VCS schemes in the URL.
53
+
54
+ Returns the matched VCS scheme, or None if there's no match.
55
+ """
56
+ for scheme in vcs.schemes:
57
+ if url.lower().startswith(scheme) and url[len(scheme)] in "+:":
58
+ return scheme
59
+ return None
60
+
61
+
62
+ class _NotAPIContent(Exception):
63
+ def __init__(self, content_type: str, request_desc: str) -> None:
64
+ super().__init__(content_type, request_desc)
65
+ self.content_type = content_type
66
+ self.request_desc = request_desc
67
+
68
+
69
+ def _ensure_api_header(response: Response) -> None:
70
+ """
71
+ Check the Content-Type header to ensure the response contains a Simple
72
+ API Response.
73
+
74
+ Raises `_NotAPIContent` if the content type is not a valid content-type.
75
+ """
76
+ content_type = response.headers.get("Content-Type", "Unknown")
77
+
78
+ content_type_l = content_type.lower()
79
+ if content_type_l.startswith(
80
+ (
81
+ "text/html",
82
+ "application/vnd.pypi.simple.v1+html",
83
+ "application/vnd.pypi.simple.v1+json",
84
+ )
85
+ ):
86
+ return
87
+
88
+ raise _NotAPIContent(content_type, response.request.method)
89
+
90
+
91
+ class _NotHTTP(Exception):
92
+ pass
93
+
94
+
95
+ def _ensure_api_response(url: str, session: PipSession) -> None:
96
+ """
97
+ Send a HEAD request to the URL, and ensure the response contains a simple
98
+ API Response.
99
+
100
+ Raises `_NotHTTP` if the URL is not available for a HEAD request, or
101
+ `_NotAPIContent` if the content type is not a valid content type.
102
+ """
103
+ scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url)
104
+ if scheme not in {"http", "https"}:
105
+ raise _NotHTTP()
106
+
107
+ resp = session.head(url, allow_redirects=True)
108
+ raise_for_status(resp)
109
+
110
+ _ensure_api_header(resp)
111
+
112
+
113
+ def _get_simple_response(url: str, session: PipSession) -> Response:
114
+ """Access an Simple API response with GET, and return the response.
115
+
116
+ This consists of three parts:
117
+
118
+ 1. If the URL looks suspiciously like an archive, send a HEAD first to
119
+ check the Content-Type is HTML or Simple API, to avoid downloading a
120
+ large file. Raise `_NotHTTP` if the content type cannot be determined, or
121
+ `_NotAPIContent` if it is not HTML or a Simple API.
122
+ 2. Actually perform the request. Raise HTTP exceptions on network failures.
123
+ 3. Check the Content-Type header to make sure we got a Simple API response,
124
+ and raise `_NotAPIContent` otherwise.
125
+ """
126
+ if is_archive_file(Link(url).filename):
127
+ _ensure_api_response(url, session=session)
128
+
129
+ logger.debug("Getting page %s", redact_auth_from_url(url))
130
+
131
+ resp = session.get(
132
+ url,
133
+ headers={
134
+ "Accept": ", ".join(
135
+ [
136
+ "application/vnd.pypi.simple.v1+json",
137
+ "application/vnd.pypi.simple.v1+html; q=0.1",
138
+ "text/html; q=0.01",
139
+ ]
140
+ ),
141
+ # We don't want to blindly returned cached data for
142
+ # /simple/, because authors generally expecting that
143
+ # twine upload && pip install will function, but if
144
+ # they've done a pip install in the last ~10 minutes
145
+ # it won't. Thus by setting this to zero we will not
146
+ # blindly use any cached data, however the benefit of
147
+ # using max-age=0 instead of no-cache, is that we will
148
+ # still support conditional requests, so we will still
149
+ # minimize traffic sent in cases where the page hasn't
150
+ # changed at all, we will just always incur the round
151
+ # trip for the conditional GET now instead of only
152
+ # once per 10 minutes.
153
+ # For more information, please see pypa/pip#5670.
154
+ "Cache-Control": "max-age=0",
155
+ },
156
+ )
157
+ raise_for_status(resp)
158
+
159
+ # The check for archives above only works if the url ends with
160
+ # something that looks like an archive. However that is not a
161
+ # requirement of an url. Unless we issue a HEAD request on every
162
+ # url we cannot know ahead of time for sure if something is a
163
+ # Simple API response or not. However we can check after we've
164
+ # downloaded it.
165
+ _ensure_api_header(resp)
166
+
167
+ logger.debug(
168
+ "Fetched page %s as %s",
169
+ redact_auth_from_url(url),
170
+ resp.headers.get("Content-Type", "Unknown"),
171
+ )
172
+
173
+ return resp
174
+
175
+
176
+ def _get_encoding_from_headers(headers: ResponseHeaders) -> Optional[str]:
177
+ """Determine if we have any encoding information in our headers."""
178
+ if headers and "Content-Type" in headers:
179
+ m = email.message.Message()
180
+ m["content-type"] = headers["Content-Type"]
181
+ charset = m.get_param("charset")
182
+ if charset:
183
+ return str(charset)
184
+ return None
185
+
186
+
187
+ class CacheablePageContent:
188
+ def __init__(self, page: "IndexContent") -> None:
189
+ assert page.cache_link_parsing
190
+ self.page = page
191
+
192
+ def __eq__(self, other: object) -> bool:
193
+ return isinstance(other, type(self)) and self.page.url == other.page.url
194
+
195
+ def __hash__(self) -> int:
196
+ return hash(self.page.url)
197
+
198
+
199
+ class ParseLinks(Protocol):
200
+ def __call__(self, page: "IndexContent") -> Iterable[Link]: ...
201
+
202
+
203
+ def with_cached_index_content(fn: ParseLinks) -> ParseLinks:
204
+ """
205
+ Given a function that parses an Iterable[Link] from an IndexContent, cache the
206
+ function's result (keyed by CacheablePageContent), unless the IndexContent
207
+ `page` has `page.cache_link_parsing == False`.
208
+ """
209
+
210
+ @functools.lru_cache(maxsize=None)
211
+ def wrapper(cacheable_page: CacheablePageContent) -> List[Link]:
212
+ return list(fn(cacheable_page.page))
213
+
214
+ @functools.wraps(fn)
215
+ def wrapper_wrapper(page: "IndexContent") -> List[Link]:
216
+ if page.cache_link_parsing:
217
+ return wrapper(CacheablePageContent(page))
218
+ return list(fn(page))
219
+
220
+ return wrapper_wrapper
221
+
222
+
223
+ @with_cached_index_content
224
+ def parse_links(page: "IndexContent") -> Iterable[Link]:
225
+ """
226
+ Parse a Simple API's Index Content, and yield its anchor elements as Link objects.
227
+ """
228
+
229
+ content_type_l = page.content_type.lower()
230
+ if content_type_l.startswith("application/vnd.pypi.simple.v1+json"):
231
+ data = json.loads(page.content)
232
+ for file in data.get("files", []):
233
+ link = Link.from_json(file, page.url)
234
+ if link is None:
235
+ continue
236
+ yield link
237
+ return
238
+
239
+ parser = HTMLLinkParser(page.url)
240
+ encoding = page.encoding or "utf-8"
241
+ parser.feed(page.content.decode(encoding))
242
+
243
+ url = page.url
244
+ base_url = parser.base_url or url
245
+ for anchor in parser.anchors:
246
+ link = Link.from_element(anchor, page_url=url, base_url=base_url)
247
+ if link is None:
248
+ continue
249
+ yield link
250
+
251
+
252
+ @dataclass(frozen=True)
253
+ class IndexContent:
254
+ """Represents one response (or page), along with its URL.
255
+
256
+ :param encoding: the encoding to decode the given content.
257
+ :param url: the URL from which the HTML was downloaded.
258
+ :param cache_link_parsing: whether links parsed from this page's url
259
+ should be cached. PyPI index urls should
260
+ have this set to False, for example.
261
+ """
262
+
263
+ content: bytes
264
+ content_type: str
265
+ encoding: Optional[str]
266
+ url: str
267
+ cache_link_parsing: bool = True
268
+
269
+ def __str__(self) -> str:
270
+ return redact_auth_from_url(self.url)
271
+
272
+
273
+ class HTMLLinkParser(HTMLParser):
274
+ """
275
+ HTMLParser that keeps the first base HREF and a list of all anchor
276
+ elements' attributes.
277
+ """
278
+
279
+ def __init__(self, url: str) -> None:
280
+ super().__init__(convert_charrefs=True)
281
+
282
+ self.url: str = url
283
+ self.base_url: Optional[str] = None
284
+ self.anchors: List[Dict[str, Optional[str]]] = []
285
+
286
+ def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None:
287
+ if tag == "base" and self.base_url is None:
288
+ href = self.get_href(attrs)
289
+ if href is not None:
290
+ self.base_url = href
291
+ elif tag == "a":
292
+ self.anchors.append(dict(attrs))
293
+
294
+ def get_href(self, attrs: List[Tuple[str, Optional[str]]]) -> Optional[str]:
295
+ for name, value in attrs:
296
+ if name == "href":
297
+ return value
298
+ return None
299
+
300
+
301
+ def _handle_get_simple_fail(
302
+ link: Link,
303
+ reason: Union[str, Exception],
304
+ meth: Optional[Callable[..., None]] = None,
305
+ ) -> None:
306
+ if meth is None:
307
+ meth = logger.debug
308
+ meth("Could not fetch URL %s: %s - skipping", link, reason)
309
+
310
+
311
+ def _make_index_content(
312
+ response: Response, cache_link_parsing: bool = True
313
+ ) -> IndexContent:
314
+ encoding = _get_encoding_from_headers(response.headers)
315
+ return IndexContent(
316
+ response.content,
317
+ response.headers["Content-Type"],
318
+ encoding=encoding,
319
+ url=response.url,
320
+ cache_link_parsing=cache_link_parsing,
321
+ )
322
+
323
+
324
+ def _get_index_content(link: Link, *, session: PipSession) -> Optional["IndexContent"]:
325
+ url = link.url.split("#", 1)[0]
326
+
327
+ # Check for VCS schemes that do not support lookup as web pages.
328
+ vcs_scheme = _match_vcs_scheme(url)
329
+ if vcs_scheme:
330
+ logger.warning(
331
+ "Cannot look at %s URL %s because it does not support lookup as web pages.",
332
+ vcs_scheme,
333
+ link,
334
+ )
335
+ return None
336
+
337
+ # Tack index.html onto file:// URLs that point to directories
338
+ scheme, _, path, _, _, _ = urllib.parse.urlparse(url)
339
+ if scheme == "file" and os.path.isdir(urllib.request.url2pathname(path)):
340
+ # add trailing slash if not present so urljoin doesn't trim
341
+ # final segment
342
+ if not url.endswith("/"):
343
+ url += "/"
344
+ # TODO: In the future, it would be nice if pip supported PEP 691
345
+ # style responses in the file:// URLs, however there's no
346
+ # standard file extension for application/vnd.pypi.simple.v1+json
347
+ # so we'll need to come up with something on our own.
348
+ url = urllib.parse.urljoin(url, "index.html")
349
+ logger.debug(" file: URL is directory, getting %s", url)
350
+
351
+ try:
352
+ resp = _get_simple_response(url, session=session)
353
+ except _NotHTTP:
354
+ logger.warning(
355
+ "Skipping page %s because it looks like an archive, and cannot "
356
+ "be checked by a HTTP HEAD request.",
357
+ link,
358
+ )
359
+ except _NotAPIContent as exc:
360
+ logger.warning(
361
+ "Skipping page %s because the %s request got Content-Type: %s. "
362
+ "The only supported Content-Types are application/vnd.pypi.simple.v1+json, "
363
+ "application/vnd.pypi.simple.v1+html, and text/html",
364
+ link,
365
+ exc.request_desc,
366
+ exc.content_type,
367
+ )
368
+ except NetworkConnectionError as exc:
369
+ _handle_get_simple_fail(link, exc)
370
+ except RetryError as exc:
371
+ _handle_get_simple_fail(link, exc)
372
+ except SSLError as exc:
373
+ reason = "There was a problem confirming the ssl certificate: "
374
+ reason += str(exc)
375
+ _handle_get_simple_fail(link, reason, meth=logger.info)
376
+ except requests.ConnectionError as exc:
377
+ _handle_get_simple_fail(link, f"connection error: {exc}")
378
+ except requests.Timeout:
379
+ _handle_get_simple_fail(link, "timed out")
380
+ else:
381
+ return _make_index_content(resp, cache_link_parsing=link.cache_link_parsing)
382
+ return None
383
+
384
+
385
+ class CollectedSources(NamedTuple):
386
+ find_links: Sequence[Optional[LinkSource]]
387
+ index_urls: Sequence[Optional[LinkSource]]
388
+
389
+
390
+ class LinkCollector:
391
+ """
392
+ Responsible for collecting Link objects from all configured locations,
393
+ making network requests as needed.
394
+
395
+ The class's main method is its collect_sources() method.
396
+ """
397
+
398
+ def __init__(
399
+ self,
400
+ session: PipSession,
401
+ search_scope: SearchScope,
402
+ ) -> None:
403
+ self.search_scope = search_scope
404
+ self.session = session
405
+
406
+ @classmethod
407
+ def create(
408
+ cls,
409
+ session: PipSession,
410
+ options: Values,
411
+ suppress_no_index: bool = False,
412
+ ) -> "LinkCollector":
413
+ """
414
+ :param session: The Session to use to make requests.
415
+ :param suppress_no_index: Whether to ignore the --no-index option
416
+ when constructing the SearchScope object.
417
+ """
418
+ index_urls = [options.index_url] + options.extra_index_urls
419
+ if options.no_index and not suppress_no_index:
420
+ logger.debug(
421
+ "Ignoring indexes: %s",
422
+ ",".join(redact_auth_from_url(url) for url in index_urls),
423
+ )
424
+ index_urls = []
425
+
426
+ # Make sure find_links is a list before passing to create().
427
+ find_links = options.find_links or []
428
+
429
+ search_scope = SearchScope.create(
430
+ find_links=find_links,
431
+ index_urls=index_urls,
432
+ no_index=options.no_index,
433
+ )
434
+ link_collector = LinkCollector(
435
+ session=session,
436
+ search_scope=search_scope,
437
+ )
438
+ return link_collector
439
+
440
+ @property
441
+ def find_links(self) -> List[str]:
442
+ return self.search_scope.find_links
443
+
444
+ def fetch_response(self, location: Link) -> Optional[IndexContent]:
445
+ """
446
+ Fetch an HTML page containing package links.
447
+ """
448
+ return _get_index_content(location, session=self.session)
449
+
450
+ def collect_sources(
451
+ self,
452
+ project_name: str,
453
+ candidates_from_page: CandidatesFromPage,
454
+ ) -> CollectedSources:
455
+ # The OrderedDict calls deduplicate sources by URL.
456
+ index_url_sources = collections.OrderedDict(
457
+ build_source(
458
+ loc,
459
+ candidates_from_page=candidates_from_page,
460
+ page_validator=self.session.is_secure_origin,
461
+ expand_dir=False,
462
+ cache_link_parsing=False,
463
+ project_name=project_name,
464
+ )
465
+ for loc in self.search_scope.get_index_urls_locations(project_name)
466
+ ).values()
467
+ find_links_sources = collections.OrderedDict(
468
+ build_source(
469
+ loc,
470
+ candidates_from_page=candidates_from_page,
471
+ page_validator=self.session.is_secure_origin,
472
+ expand_dir=True,
473
+ cache_link_parsing=True,
474
+ project_name=project_name,
475
+ )
476
+ for loc in self.find_links
477
+ ).values()
478
+
479
+ if logger.isEnabledFor(logging.DEBUG):
480
+ lines = [
481
+ f"* {s.link}"
482
+ for s in itertools.chain(find_links_sources, index_url_sources)
483
+ if s is not None and s.link is not None
484
+ ]
485
+ lines = [
486
+ f"{len(lines)} location(s) to search "
487
+ f"for versions of {project_name}:"
488
+ ] + lines
489
+ logger.debug("\n".join(lines))
490
+
491
+ return CollectedSources(
492
+ find_links=list(find_links_sources),
493
+ index_urls=list(index_url_sources),
494
+ )
python_embeded/Lib/site-packages/pip/_internal/index/package_finder.py ADDED
@@ -0,0 +1,1050 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Routines related to PyPI, indexes"""
2
+
3
+ import enum
4
+ import functools
5
+ import itertools
6
+ import logging
7
+ import re
8
+ from dataclasses import dataclass
9
+ from typing import (
10
+ TYPE_CHECKING,
11
+ Dict,
12
+ FrozenSet,
13
+ Iterable,
14
+ List,
15
+ Optional,
16
+ Set,
17
+ Tuple,
18
+ Union,
19
+ )
20
+
21
+ from pip._vendor.packaging import specifiers
22
+ from pip._vendor.packaging.tags import Tag
23
+ from pip._vendor.packaging.utils import canonicalize_name
24
+ from pip._vendor.packaging.version import InvalidVersion, _BaseVersion
25
+ from pip._vendor.packaging.version import parse as parse_version
26
+
27
+ from pip._internal.exceptions import (
28
+ BestVersionAlreadyInstalled,
29
+ DistributionNotFound,
30
+ InvalidWheelFilename,
31
+ UnsupportedWheel,
32
+ )
33
+ from pip._internal.index.collector import LinkCollector, parse_links
34
+ from pip._internal.models.candidate import InstallationCandidate
35
+ from pip._internal.models.format_control import FormatControl
36
+ from pip._internal.models.link import Link
37
+ from pip._internal.models.search_scope import SearchScope
38
+ from pip._internal.models.selection_prefs import SelectionPreferences
39
+ from pip._internal.models.target_python import TargetPython
40
+ from pip._internal.models.wheel import Wheel
41
+ from pip._internal.req import InstallRequirement
42
+ from pip._internal.utils._log import getLogger
43
+ from pip._internal.utils.filetypes import WHEEL_EXTENSION
44
+ from pip._internal.utils.hashes import Hashes
45
+ from pip._internal.utils.logging import indent_log
46
+ from pip._internal.utils.misc import build_netloc
47
+ from pip._internal.utils.packaging import check_requires_python
48
+ from pip._internal.utils.unpacking import SUPPORTED_EXTENSIONS
49
+
50
+ if TYPE_CHECKING:
51
+ from pip._vendor.typing_extensions import TypeGuard
52
+
53
+ __all__ = ["FormatControl", "BestCandidateResult", "PackageFinder"]
54
+
55
+
56
+ logger = getLogger(__name__)
57
+
58
+ BuildTag = Union[Tuple[()], Tuple[int, str]]
59
+ CandidateSortingKey = Tuple[int, int, int, _BaseVersion, Optional[int], BuildTag]
60
+
61
+
62
+ def _check_link_requires_python(
63
+ link: Link,
64
+ version_info: Tuple[int, int, int],
65
+ ignore_requires_python: bool = False,
66
+ ) -> bool:
67
+ """
68
+ Return whether the given Python version is compatible with a link's
69
+ "Requires-Python" value.
70
+
71
+ :param version_info: A 3-tuple of ints representing the Python
72
+ major-minor-micro version to check.
73
+ :param ignore_requires_python: Whether to ignore the "Requires-Python"
74
+ value if the given Python version isn't compatible.
75
+ """
76
+ try:
77
+ is_compatible = check_requires_python(
78
+ link.requires_python,
79
+ version_info=version_info,
80
+ )
81
+ except specifiers.InvalidSpecifier:
82
+ logger.debug(
83
+ "Ignoring invalid Requires-Python (%r) for link: %s",
84
+ link.requires_python,
85
+ link,
86
+ )
87
+ else:
88
+ if not is_compatible:
89
+ version = ".".join(map(str, version_info))
90
+ if not ignore_requires_python:
91
+ logger.verbose(
92
+ "Link requires a different Python (%s not in: %r): %s",
93
+ version,
94
+ link.requires_python,
95
+ link,
96
+ )
97
+ return False
98
+
99
+ logger.debug(
100
+ "Ignoring failed Requires-Python check (%s not in: %r) for link: %s",
101
+ version,
102
+ link.requires_python,
103
+ link,
104
+ )
105
+
106
+ return True
107
+
108
+
109
+ class LinkType(enum.Enum):
110
+ candidate = enum.auto()
111
+ different_project = enum.auto()
112
+ yanked = enum.auto()
113
+ format_unsupported = enum.auto()
114
+ format_invalid = enum.auto()
115
+ platform_mismatch = enum.auto()
116
+ requires_python_mismatch = enum.auto()
117
+
118
+
119
+ class LinkEvaluator:
120
+ """
121
+ Responsible for evaluating links for a particular project.
122
+ """
123
+
124
+ _py_version_re = re.compile(r"-py([123]\.?[0-9]?)$")
125
+
126
+ # Don't include an allow_yanked default value to make sure each call
127
+ # site considers whether yanked releases are allowed. This also causes
128
+ # that decision to be made explicit in the calling code, which helps
129
+ # people when reading the code.
130
+ def __init__(
131
+ self,
132
+ project_name: str,
133
+ canonical_name: str,
134
+ formats: FrozenSet[str],
135
+ target_python: TargetPython,
136
+ allow_yanked: bool,
137
+ ignore_requires_python: Optional[bool] = None,
138
+ ) -> None:
139
+ """
140
+ :param project_name: The user supplied package name.
141
+ :param canonical_name: The canonical package name.
142
+ :param formats: The formats allowed for this package. Should be a set
143
+ with 'binary' or 'source' or both in it.
144
+ :param target_python: The target Python interpreter to use when
145
+ evaluating link compatibility. This is used, for example, to
146
+ check wheel compatibility, as well as when checking the Python
147
+ version, e.g. the Python version embedded in a link filename
148
+ (or egg fragment) and against an HTML link's optional PEP 503
149
+ "data-requires-python" attribute.
150
+ :param allow_yanked: Whether files marked as yanked (in the sense
151
+ of PEP 592) are permitted to be candidates for install.
152
+ :param ignore_requires_python: Whether to ignore incompatible
153
+ PEP 503 "data-requires-python" values in HTML links. Defaults
154
+ to False.
155
+ """
156
+ if ignore_requires_python is None:
157
+ ignore_requires_python = False
158
+
159
+ self._allow_yanked = allow_yanked
160
+ self._canonical_name = canonical_name
161
+ self._ignore_requires_python = ignore_requires_python
162
+ self._formats = formats
163
+ self._target_python = target_python
164
+
165
+ self.project_name = project_name
166
+
167
+ def evaluate_link(self, link: Link) -> Tuple[LinkType, str]:
168
+ """
169
+ Determine whether a link is a candidate for installation.
170
+
171
+ :return: A tuple (result, detail), where *result* is an enum
172
+ representing whether the evaluation found a candidate, or the reason
173
+ why one is not found. If a candidate is found, *detail* will be the
174
+ candidate's version string; if one is not found, it contains the
175
+ reason the link fails to qualify.
176
+ """
177
+ version = None
178
+ if link.is_yanked and not self._allow_yanked:
179
+ reason = link.yanked_reason or "<none given>"
180
+ return (LinkType.yanked, f"yanked for reason: {reason}")
181
+
182
+ if link.egg_fragment:
183
+ egg_info = link.egg_fragment
184
+ ext = link.ext
185
+ else:
186
+ egg_info, ext = link.splitext()
187
+ if not ext:
188
+ return (LinkType.format_unsupported, "not a file")
189
+ if ext not in SUPPORTED_EXTENSIONS:
190
+ return (
191
+ LinkType.format_unsupported,
192
+ f"unsupported archive format: {ext}",
193
+ )
194
+ if "binary" not in self._formats and ext == WHEEL_EXTENSION:
195
+ reason = f"No binaries permitted for {self.project_name}"
196
+ return (LinkType.format_unsupported, reason)
197
+ if "macosx10" in link.path and ext == ".zip":
198
+ return (LinkType.format_unsupported, "macosx10 one")
199
+ if ext == WHEEL_EXTENSION:
200
+ try:
201
+ wheel = Wheel(link.filename)
202
+ except InvalidWheelFilename:
203
+ return (
204
+ LinkType.format_invalid,
205
+ "invalid wheel filename",
206
+ )
207
+ if canonicalize_name(wheel.name) != self._canonical_name:
208
+ reason = f"wrong project name (not {self.project_name})"
209
+ return (LinkType.different_project, reason)
210
+
211
+ supported_tags = self._target_python.get_unsorted_tags()
212
+ if not wheel.supported(supported_tags):
213
+ # Include the wheel's tags in the reason string to
214
+ # simplify troubleshooting compatibility issues.
215
+ file_tags = ", ".join(wheel.get_formatted_file_tags())
216
+ reason = (
217
+ f"none of the wheel's tags ({file_tags}) are compatible "
218
+ f"(run pip debug --verbose to show compatible tags)"
219
+ )
220
+ return (LinkType.platform_mismatch, reason)
221
+
222
+ version = wheel.version
223
+
224
+ # This should be up by the self.ok_binary check, but see issue 2700.
225
+ if "source" not in self._formats and ext != WHEEL_EXTENSION:
226
+ reason = f"No sources permitted for {self.project_name}"
227
+ return (LinkType.format_unsupported, reason)
228
+
229
+ if not version:
230
+ version = _extract_version_from_fragment(
231
+ egg_info,
232
+ self._canonical_name,
233
+ )
234
+ if not version:
235
+ reason = f"Missing project version for {self.project_name}"
236
+ return (LinkType.format_invalid, reason)
237
+
238
+ match = self._py_version_re.search(version)
239
+ if match:
240
+ version = version[: match.start()]
241
+ py_version = match.group(1)
242
+ if py_version != self._target_python.py_version:
243
+ return (
244
+ LinkType.platform_mismatch,
245
+ "Python version is incorrect",
246
+ )
247
+
248
+ supports_python = _check_link_requires_python(
249
+ link,
250
+ version_info=self._target_python.py_version_info,
251
+ ignore_requires_python=self._ignore_requires_python,
252
+ )
253
+ if not supports_python:
254
+ reason = f"{version} Requires-Python {link.requires_python}"
255
+ return (LinkType.requires_python_mismatch, reason)
256
+
257
+ logger.debug("Found link %s, version: %s", link, version)
258
+
259
+ return (LinkType.candidate, version)
260
+
261
+
262
+ def filter_unallowed_hashes(
263
+ candidates: List[InstallationCandidate],
264
+ hashes: Optional[Hashes],
265
+ project_name: str,
266
+ ) -> List[InstallationCandidate]:
267
+ """
268
+ Filter out candidates whose hashes aren't allowed, and return a new
269
+ list of candidates.
270
+
271
+ If at least one candidate has an allowed hash, then all candidates with
272
+ either an allowed hash or no hash specified are returned. Otherwise,
273
+ the given candidates are returned.
274
+
275
+ Including the candidates with no hash specified when there is a match
276
+ allows a warning to be logged if there is a more preferred candidate
277
+ with no hash specified. Returning all candidates in the case of no
278
+ matches lets pip report the hash of the candidate that would otherwise
279
+ have been installed (e.g. permitting the user to more easily update
280
+ their requirements file with the desired hash).
281
+ """
282
+ if not hashes:
283
+ logger.debug(
284
+ "Given no hashes to check %s links for project %r: "
285
+ "discarding no candidates",
286
+ len(candidates),
287
+ project_name,
288
+ )
289
+ # Make sure we're not returning back the given value.
290
+ return list(candidates)
291
+
292
+ matches_or_no_digest = []
293
+ # Collect the non-matches for logging purposes.
294
+ non_matches = []
295
+ match_count = 0
296
+ for candidate in candidates:
297
+ link = candidate.link
298
+ if not link.has_hash:
299
+ pass
300
+ elif link.is_hash_allowed(hashes=hashes):
301
+ match_count += 1
302
+ else:
303
+ non_matches.append(candidate)
304
+ continue
305
+
306
+ matches_or_no_digest.append(candidate)
307
+
308
+ if match_count:
309
+ filtered = matches_or_no_digest
310
+ else:
311
+ # Make sure we're not returning back the given value.
312
+ filtered = list(candidates)
313
+
314
+ if len(filtered) == len(candidates):
315
+ discard_message = "discarding no candidates"
316
+ else:
317
+ discard_message = "discarding {} non-matches:\n {}".format(
318
+ len(non_matches),
319
+ "\n ".join(str(candidate.link) for candidate in non_matches),
320
+ )
321
+
322
+ logger.debug(
323
+ "Checked %s links for project %r against %s hashes "
324
+ "(%s matches, %s no digest): %s",
325
+ len(candidates),
326
+ project_name,
327
+ hashes.digest_count,
328
+ match_count,
329
+ len(matches_or_no_digest) - match_count,
330
+ discard_message,
331
+ )
332
+
333
+ return filtered
334
+
335
+
336
+ @dataclass
337
+ class CandidatePreferences:
338
+ """
339
+ Encapsulates some of the preferences for filtering and sorting
340
+ InstallationCandidate objects.
341
+ """
342
+
343
+ prefer_binary: bool = False
344
+ allow_all_prereleases: bool = False
345
+
346
+
347
+ @dataclass(frozen=True)
348
+ class BestCandidateResult:
349
+ """A collection of candidates, returned by `PackageFinder.find_best_candidate`.
350
+
351
+ This class is only intended to be instantiated by CandidateEvaluator's
352
+ `compute_best_candidate()` method.
353
+
354
+ :param all_candidates: A sequence of all available candidates found.
355
+ :param applicable_candidates: The applicable candidates.
356
+ :param best_candidate: The most preferred candidate found, or None
357
+ if no applicable candidates were found.
358
+ """
359
+
360
+ all_candidates: List[InstallationCandidate]
361
+ applicable_candidates: List[InstallationCandidate]
362
+ best_candidate: Optional[InstallationCandidate]
363
+
364
+ def __post_init__(self) -> None:
365
+ assert set(self.applicable_candidates) <= set(self.all_candidates)
366
+
367
+ if self.best_candidate is None:
368
+ assert not self.applicable_candidates
369
+ else:
370
+ assert self.best_candidate in self.applicable_candidates
371
+
372
+
373
+ class CandidateEvaluator:
374
+ """
375
+ Responsible for filtering and sorting candidates for installation based
376
+ on what tags are valid.
377
+ """
378
+
379
+ @classmethod
380
+ def create(
381
+ cls,
382
+ project_name: str,
383
+ target_python: Optional[TargetPython] = None,
384
+ prefer_binary: bool = False,
385
+ allow_all_prereleases: bool = False,
386
+ specifier: Optional[specifiers.BaseSpecifier] = None,
387
+ hashes: Optional[Hashes] = None,
388
+ ) -> "CandidateEvaluator":
389
+ """Create a CandidateEvaluator object.
390
+
391
+ :param target_python: The target Python interpreter to use when
392
+ checking compatibility. If None (the default), a TargetPython
393
+ object will be constructed from the running Python.
394
+ :param specifier: An optional object implementing `filter`
395
+ (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable
396
+ versions.
397
+ :param hashes: An optional collection of allowed hashes.
398
+ """
399
+ if target_python is None:
400
+ target_python = TargetPython()
401
+ if specifier is None:
402
+ specifier = specifiers.SpecifierSet()
403
+
404
+ supported_tags = target_python.get_sorted_tags()
405
+
406
+ return cls(
407
+ project_name=project_name,
408
+ supported_tags=supported_tags,
409
+ specifier=specifier,
410
+ prefer_binary=prefer_binary,
411
+ allow_all_prereleases=allow_all_prereleases,
412
+ hashes=hashes,
413
+ )
414
+
415
+ def __init__(
416
+ self,
417
+ project_name: str,
418
+ supported_tags: List[Tag],
419
+ specifier: specifiers.BaseSpecifier,
420
+ prefer_binary: bool = False,
421
+ allow_all_prereleases: bool = False,
422
+ hashes: Optional[Hashes] = None,
423
+ ) -> None:
424
+ """
425
+ :param supported_tags: The PEP 425 tags supported by the target
426
+ Python in order of preference (most preferred first).
427
+ """
428
+ self._allow_all_prereleases = allow_all_prereleases
429
+ self._hashes = hashes
430
+ self._prefer_binary = prefer_binary
431
+ self._project_name = project_name
432
+ self._specifier = specifier
433
+ self._supported_tags = supported_tags
434
+ # Since the index of the tag in the _supported_tags list is used
435
+ # as a priority, precompute a map from tag to index/priority to be
436
+ # used in wheel.find_most_preferred_tag.
437
+ self._wheel_tag_preferences = {
438
+ tag: idx for idx, tag in enumerate(supported_tags)
439
+ }
440
+
441
+ def get_applicable_candidates(
442
+ self,
443
+ candidates: List[InstallationCandidate],
444
+ ) -> List[InstallationCandidate]:
445
+ """
446
+ Return the applicable candidates from a list of candidates.
447
+ """
448
+ # Using None infers from the specifier instead.
449
+ allow_prereleases = self._allow_all_prereleases or None
450
+ specifier = self._specifier
451
+
452
+ # We turn the version object into a str here because otherwise
453
+ # when we're debundled but setuptools isn't, Python will see
454
+ # packaging.version.Version and
455
+ # pkg_resources._vendor.packaging.version.Version as different
456
+ # types. This way we'll use a str as a common data interchange
457
+ # format. If we stop using the pkg_resources provided specifier
458
+ # and start using our own, we can drop the cast to str().
459
+ candidates_and_versions = [(c, str(c.version)) for c in candidates]
460
+ versions = set(
461
+ specifier.filter(
462
+ (v for _, v in candidates_and_versions),
463
+ prereleases=allow_prereleases,
464
+ )
465
+ )
466
+
467
+ applicable_candidates = [c for c, v in candidates_and_versions if v in versions]
468
+ filtered_applicable_candidates = filter_unallowed_hashes(
469
+ candidates=applicable_candidates,
470
+ hashes=self._hashes,
471
+ project_name=self._project_name,
472
+ )
473
+
474
+ return sorted(filtered_applicable_candidates, key=self._sort_key)
475
+
476
+ def _sort_key(self, candidate: InstallationCandidate) -> CandidateSortingKey:
477
+ """
478
+ Function to pass as the `key` argument to a call to sorted() to sort
479
+ InstallationCandidates by preference.
480
+
481
+ Returns a tuple such that tuples sorting as greater using Python's
482
+ default comparison operator are more preferred.
483
+
484
+ The preference is as follows:
485
+
486
+ First and foremost, candidates with allowed (matching) hashes are
487
+ always preferred over candidates without matching hashes. This is
488
+ because e.g. if the only candidate with an allowed hash is yanked,
489
+ we still want to use that candidate.
490
+
491
+ Second, excepting hash considerations, candidates that have been
492
+ yanked (in the sense of PEP 592) are always less preferred than
493
+ candidates that haven't been yanked. Then:
494
+
495
+ If not finding wheels, they are sorted by version only.
496
+ If finding wheels, then the sort order is by version, then:
497
+ 1. existing installs
498
+ 2. wheels ordered via Wheel.support_index_min(self._supported_tags)
499
+ 3. source archives
500
+ If prefer_binary was set, then all wheels are sorted above sources.
501
+
502
+ Note: it was considered to embed this logic into the Link
503
+ comparison operators, but then different sdist links
504
+ with the same version, would have to be considered equal
505
+ """
506
+ valid_tags = self._supported_tags
507
+ support_num = len(valid_tags)
508
+ build_tag: BuildTag = ()
509
+ binary_preference = 0
510
+ link = candidate.link
511
+ if link.is_wheel:
512
+ # can raise InvalidWheelFilename
513
+ wheel = Wheel(link.filename)
514
+ try:
515
+ pri = -(
516
+ wheel.find_most_preferred_tag(
517
+ valid_tags, self._wheel_tag_preferences
518
+ )
519
+ )
520
+ except ValueError:
521
+ raise UnsupportedWheel(
522
+ f"{wheel.filename} is not a supported wheel for this platform. It "
523
+ "can't be sorted."
524
+ )
525
+ if self._prefer_binary:
526
+ binary_preference = 1
527
+ build_tag = wheel.build_tag
528
+ else: # sdist
529
+ pri = -(support_num)
530
+ has_allowed_hash = int(link.is_hash_allowed(self._hashes))
531
+ yank_value = -1 * int(link.is_yanked) # -1 for yanked.
532
+ return (
533
+ has_allowed_hash,
534
+ yank_value,
535
+ binary_preference,
536
+ candidate.version,
537
+ pri,
538
+ build_tag,
539
+ )
540
+
541
+ def sort_best_candidate(
542
+ self,
543
+ candidates: List[InstallationCandidate],
544
+ ) -> Optional[InstallationCandidate]:
545
+ """
546
+ Return the best candidate per the instance's sort order, or None if
547
+ no candidate is acceptable.
548
+ """
549
+ if not candidates:
550
+ return None
551
+ best_candidate = max(candidates, key=self._sort_key)
552
+ return best_candidate
553
+
554
+ def compute_best_candidate(
555
+ self,
556
+ candidates: List[InstallationCandidate],
557
+ ) -> BestCandidateResult:
558
+ """
559
+ Compute and return a `BestCandidateResult` instance.
560
+ """
561
+ applicable_candidates = self.get_applicable_candidates(candidates)
562
+
563
+ best_candidate = self.sort_best_candidate(applicable_candidates)
564
+
565
+ return BestCandidateResult(
566
+ candidates,
567
+ applicable_candidates=applicable_candidates,
568
+ best_candidate=best_candidate,
569
+ )
570
+
571
+
572
+ class PackageFinder:
573
+ """This finds packages.
574
+
575
+ This is meant to match easy_install's technique for looking for
576
+ packages, by reading pages and looking for appropriate links.
577
+ """
578
+
579
+ def __init__(
580
+ self,
581
+ link_collector: LinkCollector,
582
+ target_python: TargetPython,
583
+ allow_yanked: bool,
584
+ format_control: Optional[FormatControl] = None,
585
+ candidate_prefs: Optional[CandidatePreferences] = None,
586
+ ignore_requires_python: Optional[bool] = None,
587
+ ) -> None:
588
+ """
589
+ This constructor is primarily meant to be used by the create() class
590
+ method and from tests.
591
+
592
+ :param format_control: A FormatControl object, used to control
593
+ the selection of source packages / binary packages when consulting
594
+ the index and links.
595
+ :param candidate_prefs: Options to use when creating a
596
+ CandidateEvaluator object.
597
+ """
598
+ if candidate_prefs is None:
599
+ candidate_prefs = CandidatePreferences()
600
+
601
+ format_control = format_control or FormatControl(set(), set())
602
+
603
+ self._allow_yanked = allow_yanked
604
+ self._candidate_prefs = candidate_prefs
605
+ self._ignore_requires_python = ignore_requires_python
606
+ self._link_collector = link_collector
607
+ self._target_python = target_python
608
+
609
+ self.format_control = format_control
610
+
611
+ # These are boring links that have already been logged somehow.
612
+ self._logged_links: Set[Tuple[Link, LinkType, str]] = set()
613
+
614
+ # Cache of the result of finding candidates
615
+ self._all_candidates: Dict[str, List[InstallationCandidate]] = {}
616
+ self._best_candidates: Dict[
617
+ Tuple[str, Optional[specifiers.BaseSpecifier], Optional[Hashes]],
618
+ BestCandidateResult,
619
+ ] = {}
620
+
621
+ # Don't include an allow_yanked default value to make sure each call
622
+ # site considers whether yanked releases are allowed. This also causes
623
+ # that decision to be made explicit in the calling code, which helps
624
+ # people when reading the code.
625
+ @classmethod
626
+ def create(
627
+ cls,
628
+ link_collector: LinkCollector,
629
+ selection_prefs: SelectionPreferences,
630
+ target_python: Optional[TargetPython] = None,
631
+ ) -> "PackageFinder":
632
+ """Create a PackageFinder.
633
+
634
+ :param selection_prefs: The candidate selection preferences, as a
635
+ SelectionPreferences object.
636
+ :param target_python: The target Python interpreter to use when
637
+ checking compatibility. If None (the default), a TargetPython
638
+ object will be constructed from the running Python.
639
+ """
640
+ if target_python is None:
641
+ target_python = TargetPython()
642
+
643
+ candidate_prefs = CandidatePreferences(
644
+ prefer_binary=selection_prefs.prefer_binary,
645
+ allow_all_prereleases=selection_prefs.allow_all_prereleases,
646
+ )
647
+
648
+ return cls(
649
+ candidate_prefs=candidate_prefs,
650
+ link_collector=link_collector,
651
+ target_python=target_python,
652
+ allow_yanked=selection_prefs.allow_yanked,
653
+ format_control=selection_prefs.format_control,
654
+ ignore_requires_python=selection_prefs.ignore_requires_python,
655
+ )
656
+
657
+ @property
658
+ def target_python(self) -> TargetPython:
659
+ return self._target_python
660
+
661
+ @property
662
+ def search_scope(self) -> SearchScope:
663
+ return self._link_collector.search_scope
664
+
665
+ @search_scope.setter
666
+ def search_scope(self, search_scope: SearchScope) -> None:
667
+ self._link_collector.search_scope = search_scope
668
+
669
+ @property
670
+ def find_links(self) -> List[str]:
671
+ return self._link_collector.find_links
672
+
673
+ @property
674
+ def index_urls(self) -> List[str]:
675
+ return self.search_scope.index_urls
676
+
677
+ @property
678
+ def proxy(self) -> Optional[str]:
679
+ return self._link_collector.session.pip_proxy
680
+
681
+ @property
682
+ def trusted_hosts(self) -> Iterable[str]:
683
+ for host_port in self._link_collector.session.pip_trusted_origins:
684
+ yield build_netloc(*host_port)
685
+
686
+ @property
687
+ def custom_cert(self) -> Optional[str]:
688
+ # session.verify is either a boolean (use default bundle/no SSL
689
+ # verification) or a string path to a custom CA bundle to use. We only
690
+ # care about the latter.
691
+ verify = self._link_collector.session.verify
692
+ return verify if isinstance(verify, str) else None
693
+
694
+ @property
695
+ def client_cert(self) -> Optional[str]:
696
+ cert = self._link_collector.session.cert
697
+ assert not isinstance(cert, tuple), "pip only supports PEM client certs"
698
+ return cert
699
+
700
+ @property
701
+ def allow_all_prereleases(self) -> bool:
702
+ return self._candidate_prefs.allow_all_prereleases
703
+
704
+ def set_allow_all_prereleases(self) -> None:
705
+ self._candidate_prefs.allow_all_prereleases = True
706
+
707
+ @property
708
+ def prefer_binary(self) -> bool:
709
+ return self._candidate_prefs.prefer_binary
710
+
711
+ def set_prefer_binary(self) -> None:
712
+ self._candidate_prefs.prefer_binary = True
713
+
714
+ def requires_python_skipped_reasons(self) -> List[str]:
715
+ reasons = {
716
+ detail
717
+ for _, result, detail in self._logged_links
718
+ if result == LinkType.requires_python_mismatch
719
+ }
720
+ return sorted(reasons)
721
+
722
+ def make_link_evaluator(self, project_name: str) -> LinkEvaluator:
723
+ canonical_name = canonicalize_name(project_name)
724
+ formats = self.format_control.get_allowed_formats(canonical_name)
725
+
726
+ return LinkEvaluator(
727
+ project_name=project_name,
728
+ canonical_name=canonical_name,
729
+ formats=formats,
730
+ target_python=self._target_python,
731
+ allow_yanked=self._allow_yanked,
732
+ ignore_requires_python=self._ignore_requires_python,
733
+ )
734
+
735
+ def _sort_links(self, links: Iterable[Link]) -> List[Link]:
736
+ """
737
+ Returns elements of links in order, non-egg links first, egg links
738
+ second, while eliminating duplicates
739
+ """
740
+ eggs, no_eggs = [], []
741
+ seen: Set[Link] = set()
742
+ for link in links:
743
+ if link not in seen:
744
+ seen.add(link)
745
+ if link.egg_fragment:
746
+ eggs.append(link)
747
+ else:
748
+ no_eggs.append(link)
749
+ return no_eggs + eggs
750
+
751
+ def _log_skipped_link(self, link: Link, result: LinkType, detail: str) -> None:
752
+ entry = (link, result, detail)
753
+ if entry not in self._logged_links:
754
+ # Put the link at the end so the reason is more visible and because
755
+ # the link string is usually very long.
756
+ logger.debug("Skipping link: %s: %s", detail, link)
757
+ self._logged_links.add(entry)
758
+
759
+ def get_install_candidate(
760
+ self, link_evaluator: LinkEvaluator, link: Link
761
+ ) -> Optional[InstallationCandidate]:
762
+ """
763
+ If the link is a candidate for install, convert it to an
764
+ InstallationCandidate and return it. Otherwise, return None.
765
+ """
766
+ result, detail = link_evaluator.evaluate_link(link)
767
+ if result != LinkType.candidate:
768
+ self._log_skipped_link(link, result, detail)
769
+ return None
770
+
771
+ try:
772
+ return InstallationCandidate(
773
+ name=link_evaluator.project_name,
774
+ link=link,
775
+ version=detail,
776
+ )
777
+ except InvalidVersion:
778
+ return None
779
+
780
+ def evaluate_links(
781
+ self, link_evaluator: LinkEvaluator, links: Iterable[Link]
782
+ ) -> List[InstallationCandidate]:
783
+ """
784
+ Convert links that are candidates to InstallationCandidate objects.
785
+ """
786
+ candidates = []
787
+ for link in self._sort_links(links):
788
+ candidate = self.get_install_candidate(link_evaluator, link)
789
+ if candidate is not None:
790
+ candidates.append(candidate)
791
+
792
+ return candidates
793
+
794
+ def process_project_url(
795
+ self, project_url: Link, link_evaluator: LinkEvaluator
796
+ ) -> List[InstallationCandidate]:
797
+ logger.debug(
798
+ "Fetching project page and analyzing links: %s",
799
+ project_url,
800
+ )
801
+ index_response = self._link_collector.fetch_response(project_url)
802
+ if index_response is None:
803
+ return []
804
+
805
+ page_links = list(parse_links(index_response))
806
+
807
+ with indent_log():
808
+ package_links = self.evaluate_links(
809
+ link_evaluator,
810
+ links=page_links,
811
+ )
812
+
813
+ return package_links
814
+
815
+ def find_all_candidates(self, project_name: str) -> List[InstallationCandidate]:
816
+ """Find all available InstallationCandidate for project_name
817
+
818
+ This checks index_urls and find_links.
819
+ All versions found are returned as an InstallationCandidate list.
820
+
821
+ See LinkEvaluator.evaluate_link() for details on which files
822
+ are accepted.
823
+ """
824
+ if project_name in self._all_candidates:
825
+ return self._all_candidates[project_name]
826
+
827
+ link_evaluator = self.make_link_evaluator(project_name)
828
+
829
+ collected_sources = self._link_collector.collect_sources(
830
+ project_name=project_name,
831
+ candidates_from_page=functools.partial(
832
+ self.process_project_url,
833
+ link_evaluator=link_evaluator,
834
+ ),
835
+ )
836
+
837
+ page_candidates_it = itertools.chain.from_iterable(
838
+ source.page_candidates()
839
+ for sources in collected_sources
840
+ for source in sources
841
+ if source is not None
842
+ )
843
+ page_candidates = list(page_candidates_it)
844
+
845
+ file_links_it = itertools.chain.from_iterable(
846
+ source.file_links()
847
+ for sources in collected_sources
848
+ for source in sources
849
+ if source is not None
850
+ )
851
+ file_candidates = self.evaluate_links(
852
+ link_evaluator,
853
+ sorted(file_links_it, reverse=True),
854
+ )
855
+
856
+ if logger.isEnabledFor(logging.DEBUG) and file_candidates:
857
+ paths = []
858
+ for candidate in file_candidates:
859
+ assert candidate.link.url # we need to have a URL
860
+ try:
861
+ paths.append(candidate.link.file_path)
862
+ except Exception:
863
+ paths.append(candidate.link.url) # it's not a local file
864
+
865
+ logger.debug("Local files found: %s", ", ".join(paths))
866
+
867
+ # This is an intentional priority ordering
868
+ self._all_candidates[project_name] = file_candidates + page_candidates
869
+
870
+ return self._all_candidates[project_name]
871
+
872
+ def make_candidate_evaluator(
873
+ self,
874
+ project_name: str,
875
+ specifier: Optional[specifiers.BaseSpecifier] = None,
876
+ hashes: Optional[Hashes] = None,
877
+ ) -> CandidateEvaluator:
878
+ """Create a CandidateEvaluator object to use."""
879
+ candidate_prefs = self._candidate_prefs
880
+ return CandidateEvaluator.create(
881
+ project_name=project_name,
882
+ target_python=self._target_python,
883
+ prefer_binary=candidate_prefs.prefer_binary,
884
+ allow_all_prereleases=candidate_prefs.allow_all_prereleases,
885
+ specifier=specifier,
886
+ hashes=hashes,
887
+ )
888
+
889
+ def find_best_candidate(
890
+ self,
891
+ project_name: str,
892
+ specifier: Optional[specifiers.BaseSpecifier] = None,
893
+ hashes: Optional[Hashes] = None,
894
+ ) -> BestCandidateResult:
895
+ """Find matches for the given project and specifier.
896
+
897
+ :param specifier: An optional object implementing `filter`
898
+ (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable
899
+ versions.
900
+
901
+ :return: A `BestCandidateResult` instance.
902
+ """
903
+ if (project_name, specifier, hashes) in self._best_candidates:
904
+ return self._best_candidates[project_name, specifier, hashes]
905
+
906
+ candidates = self.find_all_candidates(project_name)
907
+ candidate_evaluator = self.make_candidate_evaluator(
908
+ project_name=project_name,
909
+ specifier=specifier,
910
+ hashes=hashes,
911
+ )
912
+ self._best_candidates[project_name, specifier, hashes] = (
913
+ candidate_evaluator.compute_best_candidate(candidates)
914
+ )
915
+
916
+ return self._best_candidates[project_name, specifier, hashes]
917
+
918
+ def find_requirement(
919
+ self, req: InstallRequirement, upgrade: bool
920
+ ) -> Optional[InstallationCandidate]:
921
+ """Try to find a Link matching req
922
+
923
+ Expects req, an InstallRequirement and upgrade, a boolean
924
+ Returns a InstallationCandidate if found,
925
+ Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise
926
+ """
927
+ name = req.name
928
+ assert name is not None, "find_requirement() called with no name"
929
+
930
+ hashes = req.hashes(trust_internet=False)
931
+ best_candidate_result = self.find_best_candidate(
932
+ name,
933
+ specifier=req.specifier,
934
+ hashes=hashes,
935
+ )
936
+ best_candidate = best_candidate_result.best_candidate
937
+
938
+ installed_version: Optional[_BaseVersion] = None
939
+ if req.satisfied_by is not None:
940
+ installed_version = req.satisfied_by.version
941
+
942
+ def _format_versions(cand_iter: Iterable[InstallationCandidate]) -> str:
943
+ # This repeated parse_version and str() conversion is needed to
944
+ # handle different vendoring sources from pip and pkg_resources.
945
+ # If we stop using the pkg_resources provided specifier and start
946
+ # using our own, we can drop the cast to str().
947
+ return (
948
+ ", ".join(
949
+ sorted(
950
+ {str(c.version) for c in cand_iter},
951
+ key=parse_version,
952
+ )
953
+ )
954
+ or "none"
955
+ )
956
+
957
+ if installed_version is None and best_candidate is None:
958
+ logger.critical(
959
+ "Could not find a version that satisfies the requirement %s "
960
+ "(from versions: %s)",
961
+ req,
962
+ _format_versions(best_candidate_result.all_candidates),
963
+ )
964
+
965
+ raise DistributionNotFound(f"No matching distribution found for {req}")
966
+
967
+ def _should_install_candidate(
968
+ candidate: Optional[InstallationCandidate],
969
+ ) -> "TypeGuard[InstallationCandidate]":
970
+ if installed_version is None:
971
+ return True
972
+ if best_candidate is None:
973
+ return False
974
+ return best_candidate.version > installed_version
975
+
976
+ if not upgrade and installed_version is not None:
977
+ if _should_install_candidate(best_candidate):
978
+ logger.debug(
979
+ "Existing installed version (%s) satisfies requirement "
980
+ "(most up-to-date version is %s)",
981
+ installed_version,
982
+ best_candidate.version,
983
+ )
984
+ else:
985
+ logger.debug(
986
+ "Existing installed version (%s) is most up-to-date and "
987
+ "satisfies requirement",
988
+ installed_version,
989
+ )
990
+ return None
991
+
992
+ if _should_install_candidate(best_candidate):
993
+ logger.debug(
994
+ "Using version %s (newest of versions: %s)",
995
+ best_candidate.version,
996
+ _format_versions(best_candidate_result.applicable_candidates),
997
+ )
998
+ return best_candidate
999
+
1000
+ # We have an existing version, and its the best version
1001
+ logger.debug(
1002
+ "Installed version (%s) is most up-to-date (past versions: %s)",
1003
+ installed_version,
1004
+ _format_versions(best_candidate_result.applicable_candidates),
1005
+ )
1006
+ raise BestVersionAlreadyInstalled
1007
+
1008
+
1009
+ def _find_name_version_sep(fragment: str, canonical_name: str) -> int:
1010
+ """Find the separator's index based on the package's canonical name.
1011
+
1012
+ :param fragment: A <package>+<version> filename "fragment" (stem) or
1013
+ egg fragment.
1014
+ :param canonical_name: The package's canonical name.
1015
+
1016
+ This function is needed since the canonicalized name does not necessarily
1017
+ have the same length as the egg info's name part. An example::
1018
+
1019
+ >>> fragment = 'foo__bar-1.0'
1020
+ >>> canonical_name = 'foo-bar'
1021
+ >>> _find_name_version_sep(fragment, canonical_name)
1022
+ 8
1023
+ """
1024
+ # Project name and version must be separated by one single dash. Find all
1025
+ # occurrences of dashes; if the string in front of it matches the canonical
1026
+ # name, this is the one separating the name and version parts.
1027
+ for i, c in enumerate(fragment):
1028
+ if c != "-":
1029
+ continue
1030
+ if canonicalize_name(fragment[:i]) == canonical_name:
1031
+ return i
1032
+ raise ValueError(f"{fragment} does not match {canonical_name}")
1033
+
1034
+
1035
+ def _extract_version_from_fragment(fragment: str, canonical_name: str) -> Optional[str]:
1036
+ """Parse the version string from a <package>+<version> filename
1037
+ "fragment" (stem) or egg fragment.
1038
+
1039
+ :param fragment: The string to parse. E.g. foo-2.1
1040
+ :param canonical_name: The canonicalized name of the package this
1041
+ belongs to.
1042
+ """
1043
+ try:
1044
+ version_start = _find_name_version_sep(fragment, canonical_name) + 1
1045
+ except ValueError:
1046
+ return None
1047
+ version = fragment[version_start:]
1048
+ if not version:
1049
+ return None
1050
+ return version
python_embeded/Lib/site-packages/pip/_internal/index/sources.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import mimetypes
3
+ import os
4
+ from collections import defaultdict
5
+ from typing import Callable, Dict, Iterable, List, Optional, Tuple
6
+
7
+ from pip._vendor.packaging.utils import (
8
+ InvalidSdistFilename,
9
+ InvalidWheelFilename,
10
+ canonicalize_name,
11
+ parse_sdist_filename,
12
+ parse_wheel_filename,
13
+ )
14
+
15
+ from pip._internal.models.candidate import InstallationCandidate
16
+ from pip._internal.models.link import Link
17
+ from pip._internal.utils.urls import path_to_url, url_to_path
18
+ from pip._internal.vcs import is_url
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ FoundCandidates = Iterable[InstallationCandidate]
23
+ FoundLinks = Iterable[Link]
24
+ CandidatesFromPage = Callable[[Link], Iterable[InstallationCandidate]]
25
+ PageValidator = Callable[[Link], bool]
26
+
27
+
28
+ class LinkSource:
29
+ @property
30
+ def link(self) -> Optional[Link]:
31
+ """Returns the underlying link, if there's one."""
32
+ raise NotImplementedError()
33
+
34
+ def page_candidates(self) -> FoundCandidates:
35
+ """Candidates found by parsing an archive listing HTML file."""
36
+ raise NotImplementedError()
37
+
38
+ def file_links(self) -> FoundLinks:
39
+ """Links found by specifying archives directly."""
40
+ raise NotImplementedError()
41
+
42
+
43
+ def _is_html_file(file_url: str) -> bool:
44
+ return mimetypes.guess_type(file_url, strict=False)[0] == "text/html"
45
+
46
+
47
+ class _FlatDirectoryToUrls:
48
+ """Scans directory and caches results"""
49
+
50
+ def __init__(self, path: str) -> None:
51
+ self._path = path
52
+ self._page_candidates: List[str] = []
53
+ self._project_name_to_urls: Dict[str, List[str]] = defaultdict(list)
54
+ self._scanned_directory = False
55
+
56
+ def _scan_directory(self) -> None:
57
+ """Scans directory once and populates both page_candidates
58
+ and project_name_to_urls at the same time
59
+ """
60
+ for entry in os.scandir(self._path):
61
+ url = path_to_url(entry.path)
62
+ if _is_html_file(url):
63
+ self._page_candidates.append(url)
64
+ continue
65
+
66
+ # File must have a valid wheel or sdist name,
67
+ # otherwise not worth considering as a package
68
+ try:
69
+ project_filename = parse_wheel_filename(entry.name)[0]
70
+ except InvalidWheelFilename:
71
+ try:
72
+ project_filename = parse_sdist_filename(entry.name)[0]
73
+ except InvalidSdistFilename:
74
+ continue
75
+
76
+ self._project_name_to_urls[project_filename].append(url)
77
+ self._scanned_directory = True
78
+
79
+ @property
80
+ def page_candidates(self) -> List[str]:
81
+ if not self._scanned_directory:
82
+ self._scan_directory()
83
+
84
+ return self._page_candidates
85
+
86
+ @property
87
+ def project_name_to_urls(self) -> Dict[str, List[str]]:
88
+ if not self._scanned_directory:
89
+ self._scan_directory()
90
+
91
+ return self._project_name_to_urls
92
+
93
+
94
+ class _FlatDirectorySource(LinkSource):
95
+ """Link source specified by ``--find-links=<path-to-dir>``.
96
+
97
+ This looks the content of the directory, and returns:
98
+
99
+ * ``page_candidates``: Links listed on each HTML file in the directory.
100
+ * ``file_candidates``: Archives in the directory.
101
+ """
102
+
103
+ _paths_to_urls: Dict[str, _FlatDirectoryToUrls] = {}
104
+
105
+ def __init__(
106
+ self,
107
+ candidates_from_page: CandidatesFromPage,
108
+ path: str,
109
+ project_name: str,
110
+ ) -> None:
111
+ self._candidates_from_page = candidates_from_page
112
+ self._project_name = canonicalize_name(project_name)
113
+
114
+ # Get existing instance of _FlatDirectoryToUrls if it exists
115
+ if path in self._paths_to_urls:
116
+ self._path_to_urls = self._paths_to_urls[path]
117
+ else:
118
+ self._path_to_urls = _FlatDirectoryToUrls(path=path)
119
+ self._paths_to_urls[path] = self._path_to_urls
120
+
121
+ @property
122
+ def link(self) -> Optional[Link]:
123
+ return None
124
+
125
+ def page_candidates(self) -> FoundCandidates:
126
+ for url in self._path_to_urls.page_candidates:
127
+ yield from self._candidates_from_page(Link(url))
128
+
129
+ def file_links(self) -> FoundLinks:
130
+ for url in self._path_to_urls.project_name_to_urls[self._project_name]:
131
+ yield Link(url)
132
+
133
+
134
+ class _LocalFileSource(LinkSource):
135
+ """``--find-links=<path-or-url>`` or ``--[extra-]index-url=<path-or-url>``.
136
+
137
+ If a URL is supplied, it must be a ``file:`` URL. If a path is supplied to
138
+ the option, it is converted to a URL first. This returns:
139
+
140
+ * ``page_candidates``: Links listed on an HTML file.
141
+ * ``file_candidates``: The non-HTML file.
142
+ """
143
+
144
+ def __init__(
145
+ self,
146
+ candidates_from_page: CandidatesFromPage,
147
+ link: Link,
148
+ ) -> None:
149
+ self._candidates_from_page = candidates_from_page
150
+ self._link = link
151
+
152
+ @property
153
+ def link(self) -> Optional[Link]:
154
+ return self._link
155
+
156
+ def page_candidates(self) -> FoundCandidates:
157
+ if not _is_html_file(self._link.url):
158
+ return
159
+ yield from self._candidates_from_page(self._link)
160
+
161
+ def file_links(self) -> FoundLinks:
162
+ if _is_html_file(self._link.url):
163
+ return
164
+ yield self._link
165
+
166
+
167
+ class _RemoteFileSource(LinkSource):
168
+ """``--find-links=<url>`` or ``--[extra-]index-url=<url>``.
169
+
170
+ This returns:
171
+
172
+ * ``page_candidates``: Links listed on an HTML file.
173
+ * ``file_candidates``: The non-HTML file.
174
+ """
175
+
176
+ def __init__(
177
+ self,
178
+ candidates_from_page: CandidatesFromPage,
179
+ page_validator: PageValidator,
180
+ link: Link,
181
+ ) -> None:
182
+ self._candidates_from_page = candidates_from_page
183
+ self._page_validator = page_validator
184
+ self._link = link
185
+
186
+ @property
187
+ def link(self) -> Optional[Link]:
188
+ return self._link
189
+
190
+ def page_candidates(self) -> FoundCandidates:
191
+ if not self._page_validator(self._link):
192
+ return
193
+ yield from self._candidates_from_page(self._link)
194
+
195
+ def file_links(self) -> FoundLinks:
196
+ yield self._link
197
+
198
+
199
+ class _IndexDirectorySource(LinkSource):
200
+ """``--[extra-]index-url=<path-to-directory>``.
201
+
202
+ This is treated like a remote URL; ``candidates_from_page`` contains logic
203
+ for this by appending ``index.html`` to the link.
204
+ """
205
+
206
+ def __init__(
207
+ self,
208
+ candidates_from_page: CandidatesFromPage,
209
+ link: Link,
210
+ ) -> None:
211
+ self._candidates_from_page = candidates_from_page
212
+ self._link = link
213
+
214
+ @property
215
+ def link(self) -> Optional[Link]:
216
+ return self._link
217
+
218
+ def page_candidates(self) -> FoundCandidates:
219
+ yield from self._candidates_from_page(self._link)
220
+
221
+ def file_links(self) -> FoundLinks:
222
+ return ()
223
+
224
+
225
+ def build_source(
226
+ location: str,
227
+ *,
228
+ candidates_from_page: CandidatesFromPage,
229
+ page_validator: PageValidator,
230
+ expand_dir: bool,
231
+ cache_link_parsing: bool,
232
+ project_name: str,
233
+ ) -> Tuple[Optional[str], Optional[LinkSource]]:
234
+ path: Optional[str] = None
235
+ url: Optional[str] = None
236
+ if os.path.exists(location): # Is a local path.
237
+ url = path_to_url(location)
238
+ path = location
239
+ elif location.startswith("file:"): # A file: URL.
240
+ url = location
241
+ path = url_to_path(location)
242
+ elif is_url(location):
243
+ url = location
244
+
245
+ if url is None:
246
+ msg = (
247
+ "Location '%s' is ignored: "
248
+ "it is either a non-existing path or lacks a specific scheme."
249
+ )
250
+ logger.warning(msg, location)
251
+ return (None, None)
252
+
253
+ if path is None:
254
+ source: LinkSource = _RemoteFileSource(
255
+ candidates_from_page=candidates_from_page,
256
+ page_validator=page_validator,
257
+ link=Link(url, cache_link_parsing=cache_link_parsing),
258
+ )
259
+ return (url, source)
260
+
261
+ if os.path.isdir(path):
262
+ if expand_dir:
263
+ source = _FlatDirectorySource(
264
+ candidates_from_page=candidates_from_page,
265
+ path=path,
266
+ project_name=project_name,
267
+ )
268
+ else:
269
+ source = _IndexDirectorySource(
270
+ candidates_from_page=candidates_from_page,
271
+ link=Link(url, cache_link_parsing=cache_link_parsing),
272
+ )
273
+ return (url, source)
274
+ elif os.path.isfile(path):
275
+ source = _LocalFileSource(
276
+ candidates_from_page=candidates_from_page,
277
+ link=Link(url, cache_link_parsing=cache_link_parsing),
278
+ )
279
+ return (url, source)
280
+ logger.warning(
281
+ "Location '%s' is ignored: it is neither a file nor a directory.",
282
+ location,
283
+ )
284
+ return (url, None)
python_embeded/Lib/site-packages/pip/_internal/locations/__init__.py ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import logging
3
+ import os
4
+ import pathlib
5
+ import sys
6
+ import sysconfig
7
+ from typing import Any, Dict, Optional
8
+
9
+ from pip._internal.models.scheme import SCHEME_KEYS, Scheme
10
+ from pip._internal.utils.compat import WINDOWS
11
+ from pip._internal.utils.deprecation import deprecated
12
+ from pip._internal.utils.virtualenv import running_under_virtualenv
13
+
14
+ from . import _sysconfig
15
+ from .base import (
16
+ USER_CACHE_DIR,
17
+ get_major_minor_version,
18
+ get_src_prefix,
19
+ is_osx_framework,
20
+ site_packages,
21
+ user_site,
22
+ )
23
+
24
+ __all__ = [
25
+ "USER_CACHE_DIR",
26
+ "get_bin_prefix",
27
+ "get_bin_user",
28
+ "get_major_minor_version",
29
+ "get_platlib",
30
+ "get_purelib",
31
+ "get_scheme",
32
+ "get_src_prefix",
33
+ "site_packages",
34
+ "user_site",
35
+ ]
36
+
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+
41
+ _PLATLIBDIR: str = getattr(sys, "platlibdir", "lib")
42
+
43
+ _USE_SYSCONFIG_DEFAULT = sys.version_info >= (3, 10)
44
+
45
+
46
+ def _should_use_sysconfig() -> bool:
47
+ """This function determines the value of _USE_SYSCONFIG.
48
+
49
+ By default, pip uses sysconfig on Python 3.10+.
50
+ But Python distributors can override this decision by setting:
51
+ sysconfig._PIP_USE_SYSCONFIG = True / False
52
+ Rationale in https://github.com/pypa/pip/issues/10647
53
+
54
+ This is a function for testability, but should be constant during any one
55
+ run.
56
+ """
57
+ return bool(getattr(sysconfig, "_PIP_USE_SYSCONFIG", _USE_SYSCONFIG_DEFAULT))
58
+
59
+
60
+ _USE_SYSCONFIG = _should_use_sysconfig()
61
+
62
+ if not _USE_SYSCONFIG:
63
+ # Import distutils lazily to avoid deprecation warnings,
64
+ # but import it soon enough that it is in memory and available during
65
+ # a pip reinstall.
66
+ from . import _distutils
67
+
68
+ # Be noisy about incompatibilities if this platforms "should" be using
69
+ # sysconfig, but is explicitly opting out and using distutils instead.
70
+ if _USE_SYSCONFIG_DEFAULT and not _USE_SYSCONFIG:
71
+ _MISMATCH_LEVEL = logging.WARNING
72
+ else:
73
+ _MISMATCH_LEVEL = logging.DEBUG
74
+
75
+
76
+ def _looks_like_bpo_44860() -> bool:
77
+ """The resolution to bpo-44860 will change this incorrect platlib.
78
+
79
+ See <https://bugs.python.org/issue44860>.
80
+ """
81
+ from distutils.command.install import INSTALL_SCHEMES
82
+
83
+ try:
84
+ unix_user_platlib = INSTALL_SCHEMES["unix_user"]["platlib"]
85
+ except KeyError:
86
+ return False
87
+ return unix_user_platlib == "$usersite"
88
+
89
+
90
+ def _looks_like_red_hat_patched_platlib_purelib(scheme: Dict[str, str]) -> bool:
91
+ platlib = scheme["platlib"]
92
+ if "/$platlibdir/" in platlib:
93
+ platlib = platlib.replace("/$platlibdir/", f"/{_PLATLIBDIR}/")
94
+ if "/lib64/" not in platlib:
95
+ return False
96
+ unpatched = platlib.replace("/lib64/", "/lib/")
97
+ return unpatched.replace("$platbase/", "$base/") == scheme["purelib"]
98
+
99
+
100
+ @functools.lru_cache(maxsize=None)
101
+ def _looks_like_red_hat_lib() -> bool:
102
+ """Red Hat patches platlib in unix_prefix and unix_home, but not purelib.
103
+
104
+ This is the only way I can see to tell a Red Hat-patched Python.
105
+ """
106
+ from distutils.command.install import INSTALL_SCHEMES
107
+
108
+ return all(
109
+ k in INSTALL_SCHEMES
110
+ and _looks_like_red_hat_patched_platlib_purelib(INSTALL_SCHEMES[k])
111
+ for k in ("unix_prefix", "unix_home")
112
+ )
113
+
114
+
115
+ @functools.lru_cache(maxsize=None)
116
+ def _looks_like_debian_scheme() -> bool:
117
+ """Debian adds two additional schemes."""
118
+ from distutils.command.install import INSTALL_SCHEMES
119
+
120
+ return "deb_system" in INSTALL_SCHEMES and "unix_local" in INSTALL_SCHEMES
121
+
122
+
123
+ @functools.lru_cache(maxsize=None)
124
+ def _looks_like_red_hat_scheme() -> bool:
125
+ """Red Hat patches ``sys.prefix`` and ``sys.exec_prefix``.
126
+
127
+ Red Hat's ``00251-change-user-install-location.patch`` changes the install
128
+ command's ``prefix`` and ``exec_prefix`` to append ``"/local"``. This is
129
+ (fortunately?) done quite unconditionally, so we create a default command
130
+ object without any configuration to detect this.
131
+ """
132
+ from distutils.command.install import install
133
+ from distutils.dist import Distribution
134
+
135
+ cmd: Any = install(Distribution())
136
+ cmd.finalize_options()
137
+ return (
138
+ cmd.exec_prefix == f"{os.path.normpath(sys.exec_prefix)}/local"
139
+ and cmd.prefix == f"{os.path.normpath(sys.prefix)}/local"
140
+ )
141
+
142
+
143
+ @functools.lru_cache(maxsize=None)
144
+ def _looks_like_slackware_scheme() -> bool:
145
+ """Slackware patches sysconfig but fails to patch distutils and site.
146
+
147
+ Slackware changes sysconfig's user scheme to use ``"lib64"`` for the lib
148
+ path, but does not do the same to the site module.
149
+ """
150
+ if user_site is None: # User-site not available.
151
+ return False
152
+ try:
153
+ paths = sysconfig.get_paths(scheme="posix_user", expand=False)
154
+ except KeyError: # User-site not available.
155
+ return False
156
+ return "/lib64/" in paths["purelib"] and "/lib64/" not in user_site
157
+
158
+
159
+ @functools.lru_cache(maxsize=None)
160
+ def _looks_like_msys2_mingw_scheme() -> bool:
161
+ """MSYS2 patches distutils and sysconfig to use a UNIX-like scheme.
162
+
163
+ However, MSYS2 incorrectly patches sysconfig ``nt`` scheme. The fix is
164
+ likely going to be included in their 3.10 release, so we ignore the warning.
165
+ See msys2/MINGW-packages#9319.
166
+
167
+ MSYS2 MINGW's patch uses lowercase ``"lib"`` instead of the usual uppercase,
168
+ and is missing the final ``"site-packages"``.
169
+ """
170
+ paths = sysconfig.get_paths("nt", expand=False)
171
+ return all(
172
+ "Lib" not in p and "lib" in p and not p.endswith("site-packages")
173
+ for p in (paths[key] for key in ("platlib", "purelib"))
174
+ )
175
+
176
+
177
+ @functools.lru_cache(maxsize=None)
178
+ def _warn_mismatched(old: pathlib.Path, new: pathlib.Path, *, key: str) -> None:
179
+ issue_url = "https://github.com/pypa/pip/issues/10151"
180
+ message = (
181
+ "Value for %s does not match. Please report this to <%s>"
182
+ "\ndistutils: %s"
183
+ "\nsysconfig: %s"
184
+ )
185
+ logger.log(_MISMATCH_LEVEL, message, key, issue_url, old, new)
186
+
187
+
188
+ def _warn_if_mismatch(old: pathlib.Path, new: pathlib.Path, *, key: str) -> bool:
189
+ if old == new:
190
+ return False
191
+ _warn_mismatched(old, new, key=key)
192
+ return True
193
+
194
+
195
+ @functools.lru_cache(maxsize=None)
196
+ def _log_context(
197
+ *,
198
+ user: bool = False,
199
+ home: Optional[str] = None,
200
+ root: Optional[str] = None,
201
+ prefix: Optional[str] = None,
202
+ ) -> None:
203
+ parts = [
204
+ "Additional context:",
205
+ "user = %r",
206
+ "home = %r",
207
+ "root = %r",
208
+ "prefix = %r",
209
+ ]
210
+
211
+ logger.log(_MISMATCH_LEVEL, "\n".join(parts), user, home, root, prefix)
212
+
213
+
214
+ def get_scheme(
215
+ dist_name: str,
216
+ user: bool = False,
217
+ home: Optional[str] = None,
218
+ root: Optional[str] = None,
219
+ isolated: bool = False,
220
+ prefix: Optional[str] = None,
221
+ ) -> Scheme:
222
+ new = _sysconfig.get_scheme(
223
+ dist_name,
224
+ user=user,
225
+ home=home,
226
+ root=root,
227
+ isolated=isolated,
228
+ prefix=prefix,
229
+ )
230
+ if _USE_SYSCONFIG:
231
+ return new
232
+
233
+ old = _distutils.get_scheme(
234
+ dist_name,
235
+ user=user,
236
+ home=home,
237
+ root=root,
238
+ isolated=isolated,
239
+ prefix=prefix,
240
+ )
241
+
242
+ warning_contexts = []
243
+ for k in SCHEME_KEYS:
244
+ old_v = pathlib.Path(getattr(old, k))
245
+ new_v = pathlib.Path(getattr(new, k))
246
+
247
+ if old_v == new_v:
248
+ continue
249
+
250
+ # distutils incorrectly put PyPy packages under ``site-packages/python``
251
+ # in the ``posix_home`` scheme, but PyPy devs said they expect the
252
+ # directory name to be ``pypy`` instead. So we treat this as a bug fix
253
+ # and not warn about it. See bpo-43307 and python/cpython#24628.
254
+ skip_pypy_special_case = (
255
+ sys.implementation.name == "pypy"
256
+ and home is not None
257
+ and k in ("platlib", "purelib")
258
+ and old_v.parent == new_v.parent
259
+ and old_v.name.startswith("python")
260
+ and new_v.name.startswith("pypy")
261
+ )
262
+ if skip_pypy_special_case:
263
+ continue
264
+
265
+ # sysconfig's ``osx_framework_user`` does not include ``pythonX.Y`` in
266
+ # the ``include`` value, but distutils's ``headers`` does. We'll let
267
+ # CPython decide whether this is a bug or feature. See bpo-43948.
268
+ skip_osx_framework_user_special_case = (
269
+ user
270
+ and is_osx_framework()
271
+ and k == "headers"
272
+ and old_v.parent.parent == new_v.parent
273
+ and old_v.parent.name.startswith("python")
274
+ )
275
+ if skip_osx_framework_user_special_case:
276
+ continue
277
+
278
+ # On Red Hat and derived Linux distributions, distutils is patched to
279
+ # use "lib64" instead of "lib" for platlib.
280
+ if k == "platlib" and _looks_like_red_hat_lib():
281
+ continue
282
+
283
+ # On Python 3.9+, sysconfig's posix_user scheme sets platlib against
284
+ # sys.platlibdir, but distutils's unix_user incorrectly coninutes
285
+ # using the same $usersite for both platlib and purelib. This creates a
286
+ # mismatch when sys.platlibdir is not "lib".
287
+ skip_bpo_44860 = (
288
+ user
289
+ and k == "platlib"
290
+ and not WINDOWS
291
+ and _PLATLIBDIR != "lib"
292
+ and _looks_like_bpo_44860()
293
+ )
294
+ if skip_bpo_44860:
295
+ continue
296
+
297
+ # Slackware incorrectly patches posix_user to use lib64 instead of lib,
298
+ # but not usersite to match the location.
299
+ skip_slackware_user_scheme = (
300
+ user
301
+ and k in ("platlib", "purelib")
302
+ and not WINDOWS
303
+ and _looks_like_slackware_scheme()
304
+ )
305
+ if skip_slackware_user_scheme:
306
+ continue
307
+
308
+ # Both Debian and Red Hat patch Python to place the system site under
309
+ # /usr/local instead of /usr. Debian also places lib in dist-packages
310
+ # instead of site-packages, but the /usr/local check should cover it.
311
+ skip_linux_system_special_case = (
312
+ not (user or home or prefix or running_under_virtualenv())
313
+ and old_v.parts[1:3] == ("usr", "local")
314
+ and len(new_v.parts) > 1
315
+ and new_v.parts[1] == "usr"
316
+ and (len(new_v.parts) < 3 or new_v.parts[2] != "local")
317
+ and (_looks_like_red_hat_scheme() or _looks_like_debian_scheme())
318
+ )
319
+ if skip_linux_system_special_case:
320
+ continue
321
+
322
+ # MSYS2 MINGW's sysconfig patch does not include the "site-packages"
323
+ # part of the path. This is incorrect and will be fixed in MSYS.
324
+ skip_msys2_mingw_bug = (
325
+ WINDOWS and k in ("platlib", "purelib") and _looks_like_msys2_mingw_scheme()
326
+ )
327
+ if skip_msys2_mingw_bug:
328
+ continue
329
+
330
+ # CPython's POSIX install script invokes pip (via ensurepip) against the
331
+ # interpreter located in the source tree, not the install site. This
332
+ # triggers special logic in sysconfig that's not present in distutils.
333
+ # https://github.com/python/cpython/blob/8c21941ddaf/Lib/sysconfig.py#L178-L194
334
+ skip_cpython_build = (
335
+ sysconfig.is_python_build(check_home=True)
336
+ and not WINDOWS
337
+ and k in ("headers", "include", "platinclude")
338
+ )
339
+ if skip_cpython_build:
340
+ continue
341
+
342
+ warning_contexts.append((old_v, new_v, f"scheme.{k}"))
343
+
344
+ if not warning_contexts:
345
+ return old
346
+
347
+ # Check if this path mismatch is caused by distutils config files. Those
348
+ # files will no longer work once we switch to sysconfig, so this raises a
349
+ # deprecation message for them.
350
+ default_old = _distutils.distutils_scheme(
351
+ dist_name,
352
+ user,
353
+ home,
354
+ root,
355
+ isolated,
356
+ prefix,
357
+ ignore_config_files=True,
358
+ )
359
+ if any(default_old[k] != getattr(old, k) for k in SCHEME_KEYS):
360
+ deprecated(
361
+ reason=(
362
+ "Configuring installation scheme with distutils config files "
363
+ "is deprecated and will no longer work in the near future. If you "
364
+ "are using a Homebrew or Linuxbrew Python, please see discussion "
365
+ "at https://github.com/Homebrew/homebrew-core/issues/76621"
366
+ ),
367
+ replacement=None,
368
+ gone_in=None,
369
+ )
370
+ return old
371
+
372
+ # Post warnings about this mismatch so user can report them back.
373
+ for old_v, new_v, key in warning_contexts:
374
+ _warn_mismatched(old_v, new_v, key=key)
375
+ _log_context(user=user, home=home, root=root, prefix=prefix)
376
+
377
+ return old
378
+
379
+
380
+ def get_bin_prefix() -> str:
381
+ new = _sysconfig.get_bin_prefix()
382
+ if _USE_SYSCONFIG:
383
+ return new
384
+
385
+ old = _distutils.get_bin_prefix()
386
+ if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="bin_prefix"):
387
+ _log_context()
388
+ return old
389
+
390
+
391
+ def get_bin_user() -> str:
392
+ return _sysconfig.get_scheme("", user=True).scripts
393
+
394
+
395
+ def _looks_like_deb_system_dist_packages(value: str) -> bool:
396
+ """Check if the value is Debian's APT-controlled dist-packages.
397
+
398
+ Debian's ``distutils.sysconfig.get_python_lib()`` implementation returns the
399
+ default package path controlled by APT, but does not patch ``sysconfig`` to
400
+ do the same. This is similar to the bug worked around in ``get_scheme()``,
401
+ but here the default is ``deb_system`` instead of ``unix_local``. Ultimately
402
+ we can't do anything about this Debian bug, and this detection allows us to
403
+ skip the warning when needed.
404
+ """
405
+ if not _looks_like_debian_scheme():
406
+ return False
407
+ if value == "/usr/lib/python3/dist-packages":
408
+ return True
409
+ return False
410
+
411
+
412
+ def get_purelib() -> str:
413
+ """Return the default pure-Python lib location."""
414
+ new = _sysconfig.get_purelib()
415
+ if _USE_SYSCONFIG:
416
+ return new
417
+
418
+ old = _distutils.get_purelib()
419
+ if _looks_like_deb_system_dist_packages(old):
420
+ return old
421
+ if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="purelib"):
422
+ _log_context()
423
+ return old
424
+
425
+
426
+ def get_platlib() -> str:
427
+ """Return the default platform-shared lib location."""
428
+ new = _sysconfig.get_platlib()
429
+ if _USE_SYSCONFIG:
430
+ return new
431
+
432
+ from . import _distutils
433
+
434
+ old = _distutils.get_platlib()
435
+ if _looks_like_deb_system_dist_packages(old):
436
+ return old
437
+ if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="platlib"):
438
+ _log_context()
439
+ return old