ZTWHHH commited on
Commit
5e5728e
·
verified ·
1 Parent(s): b5118a3

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. evalkit_llava/lib/libgcc_s.so.1 +3 -0
  3. evalkit_llava/lib/libtinfo.so.6 +3 -0
  4. evalkit_llava/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/__init__.cpython-310.pyc +0 -0
  5. evalkit_llava/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-310.pyc +0 -0
  6. evalkit_llava/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-310.pyc +0 -0
  7. evalkit_llava/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/index_command.cpython-310.pyc +0 -0
  8. evalkit_llava/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/main.cpython-310.pyc +0 -0
  9. evalkit_llava/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/main_parser.cpython-310.pyc +0 -0
  10. evalkit_llava/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-310.pyc +0 -0
  11. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/__init__.py +116 -0
  12. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__init__.py +33 -0
  13. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/__init__.cpython-310.pyc +0 -0
  14. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/compat.cpython-310.pyc +0 -0
  15. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/database.cpython-310.pyc +0 -0
  16. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/index.cpython-310.pyc +0 -0
  17. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/locators.cpython-310.pyc +0 -0
  18. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/manifest.cpython-310.pyc +0 -0
  19. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/markers.cpython-310.pyc +0 -0
  20. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/metadata.cpython-310.pyc +0 -0
  21. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/resources.cpython-310.pyc +0 -0
  22. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/scripts.cpython-310.pyc +0 -0
  23. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/util.cpython-310.pyc +0 -0
  24. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/version.cpython-310.pyc +0 -0
  25. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/wheel.cpython-310.pyc +0 -0
  26. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/compat.py +1137 -0
  27. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/index.py +508 -0
  28. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/manifest.py +384 -0
  29. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/markers.py +162 -0
  30. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/resources.py +358 -0
  31. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/scripts.py +447 -0
  32. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/util.py +1984 -0
  33. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/version.py +750 -0
  34. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/wheel.py +1100 -0
  35. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/__pycache__/codec.cpython-310.pyc +0 -0
  36. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/__pycache__/intranges.cpython-310.pyc +0 -0
  37. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/__pycache__/package_data.cpython-310.pyc +0 -0
  38. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/codec.py +122 -0
  39. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/core.py +437 -0
  40. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/intranges.py +57 -0
  41. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/package_data.py +1 -0
  42. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/py.typed +0 -0
  43. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/uts46data.py +0 -0
  44. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/packaging/__init__.py +15 -0
  45. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/packaging/__pycache__/_musllinux.cpython-310.pyc +0 -0
  46. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/packaging/__pycache__/_parser.cpython-310.pyc +0 -0
  47. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/packaging/__pycache__/_structures.cpython-310.pyc +0 -0
  48. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/packaging/__pycache__/_tokenizer.cpython-310.pyc +0 -0
  49. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/packaging/__pycache__/requirements.cpython-310.pyc +0 -0
  50. evalkit_llava/lib/python3.10/site-packages/pip/_vendor/packaging/__pycache__/tags.cpython-310.pyc +0 -0
.gitattributes CHANGED
@@ -64,3 +64,5 @@ evalkit_llava/lib/libatomic.so filter=lfs diff=lfs merge=lfs -text
64
  evalkit_llava/bin/lzcat filter=lfs diff=lfs merge=lfs -text
65
  evalkit_llava/lib/libtinfow.a filter=lfs diff=lfs merge=lfs -text
66
  evalkit_llava/lib/python3.10/tkinter/__pycache__/__init__.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
64
  evalkit_llava/bin/lzcat filter=lfs diff=lfs merge=lfs -text
65
  evalkit_llava/lib/libtinfow.a filter=lfs diff=lfs merge=lfs -text
66
  evalkit_llava/lib/python3.10/tkinter/__pycache__/__init__.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
67
+ evalkit_llava/lib/libgcc_s.so.1 filter=lfs diff=lfs merge=lfs -text
68
+ evalkit_llava/lib/libtinfo.so.6 filter=lfs diff=lfs merge=lfs -text
evalkit_llava/lib/libgcc_s.so.1 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d912bad5e511194c15b506fe7eafe4454bc2dc4073a0fdebc60e86af59a0f2bc
3
+ size 475272
evalkit_llava/lib/libtinfo.so.6 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51494fcb866849b976d106c411dbad65e42a659567e383a4f3c5edf2ebe63506
3
+ size 287080
evalkit_llava/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (259 Bytes). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-310.pyc ADDED
Binary file (6.56 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-310.pyc ADDED
Binary file (23.5 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/index_command.cpython-310.pyc ADDED
Binary file (4.95 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/main.cpython-310.pyc ADDED
Binary file (1.49 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/main_parser.cpython-310.pyc ADDED
Binary file (2.98 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-310.pyc ADDED
Binary file (2.62 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/__init__.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pip._vendor is for vendoring dependencies of pip to prevent needing pip to
3
+ depend on something external.
4
+
5
+ Files inside of pip._vendor should be considered immutable and should only be
6
+ updated to versions from upstream.
7
+ """
8
+ from __future__ import absolute_import
9
+
10
+ import glob
11
+ import os.path
12
+ import sys
13
+
14
+ # Downstream redistributors which have debundled our dependencies should also
15
+ # patch this value to be true. This will trigger the additional patching
16
+ # to cause things like "six" to be available as pip.
17
+ DEBUNDLED = False
18
+
19
+ # By default, look in this directory for a bunch of .whl files which we will
20
+ # add to the beginning of sys.path before attempting to import anything. This
21
+ # is done to support downstream re-distributors like Debian and Fedora who
22
+ # wish to create their own Wheels for our dependencies to aid in debundling.
23
+ WHEEL_DIR = os.path.abspath(os.path.dirname(__file__))
24
+
25
+
26
+ # Define a small helper function to alias our vendored modules to the real ones
27
+ # if the vendored ones do not exist. This idea of this was taken from
28
+ # https://github.com/kennethreitz/requests/pull/2567.
29
+ def vendored(modulename):
30
+ vendored_name = "{0}.{1}".format(__name__, modulename)
31
+
32
+ try:
33
+ __import__(modulename, globals(), locals(), level=0)
34
+ except ImportError:
35
+ # We can just silently allow import failures to pass here. If we
36
+ # got to this point it means that ``import pip._vendor.whatever``
37
+ # failed and so did ``import whatever``. Since we're importing this
38
+ # upfront in an attempt to alias imports, not erroring here will
39
+ # just mean we get a regular import error whenever pip *actually*
40
+ # tries to import one of these modules to use it, which actually
41
+ # gives us a better error message than we would have otherwise
42
+ # gotten.
43
+ pass
44
+ else:
45
+ sys.modules[vendored_name] = sys.modules[modulename]
46
+ base, head = vendored_name.rsplit(".", 1)
47
+ setattr(sys.modules[base], head, sys.modules[modulename])
48
+
49
+
50
+ # If we're operating in a debundled setup, then we want to go ahead and trigger
51
+ # the aliasing of our vendored libraries as well as looking for wheels to add
52
+ # to our sys.path. This will cause all of this code to be a no-op typically
53
+ # however downstream redistributors can enable it in a consistent way across
54
+ # all platforms.
55
+ if DEBUNDLED:
56
+ # Actually look inside of WHEEL_DIR to find .whl files and add them to the
57
+ # front of our sys.path.
58
+ sys.path[:] = glob.glob(os.path.join(WHEEL_DIR, "*.whl")) + sys.path
59
+
60
+ # Actually alias all of our vendored dependencies.
61
+ vendored("cachecontrol")
62
+ vendored("certifi")
63
+ vendored("distlib")
64
+ vendored("distro")
65
+ vendored("packaging")
66
+ vendored("packaging.version")
67
+ vendored("packaging.specifiers")
68
+ vendored("pkg_resources")
69
+ vendored("platformdirs")
70
+ vendored("progress")
71
+ vendored("pyproject_hooks")
72
+ vendored("requests")
73
+ vendored("requests.exceptions")
74
+ vendored("requests.packages")
75
+ vendored("requests.packages.urllib3")
76
+ vendored("requests.packages.urllib3._collections")
77
+ vendored("requests.packages.urllib3.connection")
78
+ vendored("requests.packages.urllib3.connectionpool")
79
+ vendored("requests.packages.urllib3.contrib")
80
+ vendored("requests.packages.urllib3.contrib.ntlmpool")
81
+ vendored("requests.packages.urllib3.contrib.pyopenssl")
82
+ vendored("requests.packages.urllib3.exceptions")
83
+ vendored("requests.packages.urllib3.fields")
84
+ vendored("requests.packages.urllib3.filepost")
85
+ vendored("requests.packages.urllib3.packages")
86
+ vendored("requests.packages.urllib3.packages.ordered_dict")
87
+ vendored("requests.packages.urllib3.packages.six")
88
+ vendored("requests.packages.urllib3.packages.ssl_match_hostname")
89
+ vendored("requests.packages.urllib3.packages.ssl_match_hostname."
90
+ "_implementation")
91
+ vendored("requests.packages.urllib3.poolmanager")
92
+ vendored("requests.packages.urllib3.request")
93
+ vendored("requests.packages.urllib3.response")
94
+ vendored("requests.packages.urllib3.util")
95
+ vendored("requests.packages.urllib3.util.connection")
96
+ vendored("requests.packages.urllib3.util.request")
97
+ vendored("requests.packages.urllib3.util.response")
98
+ vendored("requests.packages.urllib3.util.retry")
99
+ vendored("requests.packages.urllib3.util.ssl_")
100
+ vendored("requests.packages.urllib3.util.timeout")
101
+ vendored("requests.packages.urllib3.util.url")
102
+ vendored("resolvelib")
103
+ vendored("rich")
104
+ vendored("rich.console")
105
+ vendored("rich.highlighter")
106
+ vendored("rich.logging")
107
+ vendored("rich.markup")
108
+ vendored("rich.progress")
109
+ vendored("rich.segment")
110
+ vendored("rich.style")
111
+ vendored("rich.text")
112
+ vendored("rich.traceback")
113
+ if sys.version_info < (3, 11):
114
+ vendored("tomli")
115
+ vendored("truststore")
116
+ vendored("urllib3")
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2012-2023 Vinay Sajip.
4
+ # Licensed to the Python Software Foundation under a contributor agreement.
5
+ # See LICENSE.txt and CONTRIBUTORS.txt.
6
+ #
7
+ import logging
8
+
9
+ __version__ = '0.3.9'
10
+
11
+
12
+ class DistlibException(Exception):
13
+ pass
14
+
15
+
16
+ try:
17
+ from logging import NullHandler
18
+ except ImportError: # pragma: no cover
19
+
20
+ class NullHandler(logging.Handler):
21
+
22
+ def handle(self, record):
23
+ pass
24
+
25
+ def emit(self, record):
26
+ pass
27
+
28
+ def createLock(self):
29
+ self.lock = None
30
+
31
+
32
+ logger = logging.getLogger(__name__)
33
+ logger.addHandler(NullHandler())
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.05 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/compat.cpython-310.pyc ADDED
Binary file (31.4 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/database.cpython-310.pyc ADDED
Binary file (43.1 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/index.cpython-310.pyc ADDED
Binary file (17.3 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/locators.cpython-310.pyc ADDED
Binary file (38.2 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/manifest.cpython-310.pyc ADDED
Binary file (10.2 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/markers.cpython-310.pyc ADDED
Binary file (5.28 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/metadata.cpython-310.pyc ADDED
Binary file (26.9 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/resources.cpython-310.pyc ADDED
Binary file (11 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/scripts.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/util.cpython-310.pyc ADDED
Binary file (52.1 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/version.cpython-310.pyc ADDED
Binary file (20.3 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/wheel.cpython-310.pyc ADDED
Binary file (28.5 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/compat.py ADDED
@@ -0,0 +1,1137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2013-2017 Vinay Sajip.
4
+ # Licensed to the Python Software Foundation under a contributor agreement.
5
+ # See LICENSE.txt and CONTRIBUTORS.txt.
6
+ #
7
+ from __future__ import absolute_import
8
+
9
+ import os
10
+ import re
11
+ import shutil
12
+ import sys
13
+
14
+ try:
15
+ import ssl
16
+ except ImportError: # pragma: no cover
17
+ ssl = None
18
+
19
+ if sys.version_info[0] < 3: # pragma: no cover
20
+ from StringIO import StringIO
21
+ string_types = basestring,
22
+ text_type = unicode
23
+ from types import FileType as file_type
24
+ import __builtin__ as builtins
25
+ import ConfigParser as configparser
26
+ from urlparse import urlparse, urlunparse, urljoin, urlsplit, urlunsplit
27
+ from urllib import (urlretrieve, quote as _quote, unquote, url2pathname,
28
+ pathname2url, ContentTooShortError, splittype)
29
+
30
+ def quote(s):
31
+ if isinstance(s, unicode):
32
+ s = s.encode('utf-8')
33
+ return _quote(s)
34
+
35
+ import urllib2
36
+ from urllib2 import (Request, urlopen, URLError, HTTPError,
37
+ HTTPBasicAuthHandler, HTTPPasswordMgr, HTTPHandler,
38
+ HTTPRedirectHandler, build_opener)
39
+ if ssl:
40
+ from urllib2 import HTTPSHandler
41
+ import httplib
42
+ import xmlrpclib
43
+ import Queue as queue
44
+ from HTMLParser import HTMLParser
45
+ import htmlentitydefs
46
+ raw_input = raw_input
47
+ from itertools import ifilter as filter
48
+ from itertools import ifilterfalse as filterfalse
49
+
50
+ # Leaving this around for now, in case it needs resurrecting in some way
51
+ # _userprog = None
52
+ # def splituser(host):
53
+ # """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
54
+ # global _userprog
55
+ # if _userprog is None:
56
+ # import re
57
+ # _userprog = re.compile('^(.*)@(.*)$')
58
+
59
+ # match = _userprog.match(host)
60
+ # if match: return match.group(1, 2)
61
+ # return None, host
62
+
63
+ else: # pragma: no cover
64
+ from io import StringIO
65
+ string_types = str,
66
+ text_type = str
67
+ from io import TextIOWrapper as file_type
68
+ import builtins
69
+ import configparser
70
+ from urllib.parse import (urlparse, urlunparse, urljoin, quote, unquote,
71
+ urlsplit, urlunsplit, splittype)
72
+ from urllib.request import (urlopen, urlretrieve, Request, url2pathname,
73
+ pathname2url, HTTPBasicAuthHandler,
74
+ HTTPPasswordMgr, HTTPHandler,
75
+ HTTPRedirectHandler, build_opener)
76
+ if ssl:
77
+ from urllib.request import HTTPSHandler
78
+ from urllib.error import HTTPError, URLError, ContentTooShortError
79
+ import http.client as httplib
80
+ import urllib.request as urllib2
81
+ import xmlrpc.client as xmlrpclib
82
+ import queue
83
+ from html.parser import HTMLParser
84
+ import html.entities as htmlentitydefs
85
+ raw_input = input
86
+ from itertools import filterfalse
87
+ filter = filter
88
+
89
+ try:
90
+ from ssl import match_hostname, CertificateError
91
+ except ImportError: # pragma: no cover
92
+
93
+ class CertificateError(ValueError):
94
+ pass
95
+
96
+ def _dnsname_match(dn, hostname, max_wildcards=1):
97
+ """Matching according to RFC 6125, section 6.4.3
98
+
99
+ http://tools.ietf.org/html/rfc6125#section-6.4.3
100
+ """
101
+ pats = []
102
+ if not dn:
103
+ return False
104
+
105
+ parts = dn.split('.')
106
+ leftmost, remainder = parts[0], parts[1:]
107
+
108
+ wildcards = leftmost.count('*')
109
+ if wildcards > max_wildcards:
110
+ # Issue #17980: avoid denials of service by refusing more
111
+ # than one wildcard per fragment. A survey of established
112
+ # policy among SSL implementations showed it to be a
113
+ # reasonable choice.
114
+ raise CertificateError(
115
+ "too many wildcards in certificate DNS name: " + repr(dn))
116
+
117
+ # speed up common case w/o wildcards
118
+ if not wildcards:
119
+ return dn.lower() == hostname.lower()
120
+
121
+ # RFC 6125, section 6.4.3, subitem 1.
122
+ # The client SHOULD NOT attempt to match a presented identifier in which
123
+ # the wildcard character comprises a label other than the left-most label.
124
+ if leftmost == '*':
125
+ # When '*' is a fragment by itself, it matches a non-empty dotless
126
+ # fragment.
127
+ pats.append('[^.]+')
128
+ elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
129
+ # RFC 6125, section 6.4.3, subitem 3.
130
+ # The client SHOULD NOT attempt to match a presented identifier
131
+ # where the wildcard character is embedded within an A-label or
132
+ # U-label of an internationalized domain name.
133
+ pats.append(re.escape(leftmost))
134
+ else:
135
+ # Otherwise, '*' matches any dotless string, e.g. www*
136
+ pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
137
+
138
+ # add the remaining fragments, ignore any wildcards
139
+ for frag in remainder:
140
+ pats.append(re.escape(frag))
141
+
142
+ pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
143
+ return pat.match(hostname)
144
+
145
+ def match_hostname(cert, hostname):
146
+ """Verify that *cert* (in decoded format as returned by
147
+ SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
148
+ rules are followed, but IP addresses are not accepted for *hostname*.
149
+
150
+ CertificateError is raised on failure. On success, the function
151
+ returns nothing.
152
+ """
153
+ if not cert:
154
+ raise ValueError("empty or no certificate, match_hostname needs a "
155
+ "SSL socket or SSL context with either "
156
+ "CERT_OPTIONAL or CERT_REQUIRED")
157
+ dnsnames = []
158
+ san = cert.get('subjectAltName', ())
159
+ for key, value in san:
160
+ if key == 'DNS':
161
+ if _dnsname_match(value, hostname):
162
+ return
163
+ dnsnames.append(value)
164
+ if not dnsnames:
165
+ # The subject is only checked when there is no dNSName entry
166
+ # in subjectAltName
167
+ for sub in cert.get('subject', ()):
168
+ for key, value in sub:
169
+ # XXX according to RFC 2818, the most specific Common Name
170
+ # must be used.
171
+ if key == 'commonName':
172
+ if _dnsname_match(value, hostname):
173
+ return
174
+ dnsnames.append(value)
175
+ if len(dnsnames) > 1:
176
+ raise CertificateError("hostname %r "
177
+ "doesn't match either of %s" %
178
+ (hostname, ', '.join(map(repr, dnsnames))))
179
+ elif len(dnsnames) == 1:
180
+ raise CertificateError("hostname %r "
181
+ "doesn't match %r" %
182
+ (hostname, dnsnames[0]))
183
+ else:
184
+ raise CertificateError("no appropriate commonName or "
185
+ "subjectAltName fields were found")
186
+
187
+
188
+ try:
189
+ from types import SimpleNamespace as Container
190
+ except ImportError: # pragma: no cover
191
+
192
+ class Container(object):
193
+ """
194
+ A generic container for when multiple values need to be returned
195
+ """
196
+
197
+ def __init__(self, **kwargs):
198
+ self.__dict__.update(kwargs)
199
+
200
+
201
+ try:
202
+ from shutil import which
203
+ except ImportError: # pragma: no cover
204
+ # Implementation from Python 3.3
205
+ def which(cmd, mode=os.F_OK | os.X_OK, path=None):
206
+ """Given a command, mode, and a PATH string, return the path which
207
+ conforms to the given mode on the PATH, or None if there is no such
208
+ file.
209
+
210
+ `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
211
+ of os.environ.get("PATH"), or can be overridden with a custom search
212
+ path.
213
+
214
+ """
215
+
216
+ # Check that a given file can be accessed with the correct mode.
217
+ # Additionally check that `file` is not a directory, as on Windows
218
+ # directories pass the os.access check.
219
+ def _access_check(fn, mode):
220
+ return (os.path.exists(fn) and os.access(fn, mode) and not os.path.isdir(fn))
221
+
222
+ # If we're given a path with a directory part, look it up directly rather
223
+ # than referring to PATH directories. This includes checking relative to the
224
+ # current directory, e.g. ./script
225
+ if os.path.dirname(cmd):
226
+ if _access_check(cmd, mode):
227
+ return cmd
228
+ return None
229
+
230
+ if path is None:
231
+ path = os.environ.get("PATH", os.defpath)
232
+ if not path:
233
+ return None
234
+ path = path.split(os.pathsep)
235
+
236
+ if sys.platform == "win32":
237
+ # The current directory takes precedence on Windows.
238
+ if os.curdir not in path:
239
+ path.insert(0, os.curdir)
240
+
241
+ # PATHEXT is necessary to check on Windows.
242
+ pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
243
+ # See if the given file matches any of the expected path extensions.
244
+ # This will allow us to short circuit when given "python.exe".
245
+ # If it does match, only test that one, otherwise we have to try
246
+ # others.
247
+ if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
248
+ files = [cmd]
249
+ else:
250
+ files = [cmd + ext for ext in pathext]
251
+ else:
252
+ # On other platforms you don't have things like PATHEXT to tell you
253
+ # what file suffixes are executable, so just pass on cmd as-is.
254
+ files = [cmd]
255
+
256
+ seen = set()
257
+ for dir in path:
258
+ normdir = os.path.normcase(dir)
259
+ if normdir not in seen:
260
+ seen.add(normdir)
261
+ for thefile in files:
262
+ name = os.path.join(dir, thefile)
263
+ if _access_check(name, mode):
264
+ return name
265
+ return None
266
+
267
+
268
+ # ZipFile is a context manager in 2.7, but not in 2.6
269
+
270
+ from zipfile import ZipFile as BaseZipFile
271
+
272
+ if hasattr(BaseZipFile, '__enter__'): # pragma: no cover
273
+ ZipFile = BaseZipFile
274
+ else: # pragma: no cover
275
+ from zipfile import ZipExtFile as BaseZipExtFile
276
+
277
+ class ZipExtFile(BaseZipExtFile):
278
+
279
+ def __init__(self, base):
280
+ self.__dict__.update(base.__dict__)
281
+
282
+ def __enter__(self):
283
+ return self
284
+
285
+ def __exit__(self, *exc_info):
286
+ self.close()
287
+ # return None, so if an exception occurred, it will propagate
288
+
289
+ class ZipFile(BaseZipFile):
290
+
291
+ def __enter__(self):
292
+ return self
293
+
294
+ def __exit__(self, *exc_info):
295
+ self.close()
296
+ # return None, so if an exception occurred, it will propagate
297
+
298
+ def open(self, *args, **kwargs):
299
+ base = BaseZipFile.open(self, *args, **kwargs)
300
+ return ZipExtFile(base)
301
+
302
+
303
+ try:
304
+ from platform import python_implementation
305
+ except ImportError: # pragma: no cover
306
+
307
+ def python_implementation():
308
+ """Return a string identifying the Python implementation."""
309
+ if 'PyPy' in sys.version:
310
+ return 'PyPy'
311
+ if os.name == 'java':
312
+ return 'Jython'
313
+ if sys.version.startswith('IronPython'):
314
+ return 'IronPython'
315
+ return 'CPython'
316
+
317
+
318
+ import sysconfig
319
+
320
+ try:
321
+ callable = callable
322
+ except NameError: # pragma: no cover
323
+ from collections.abc import Callable
324
+
325
+ def callable(obj):
326
+ return isinstance(obj, Callable)
327
+
328
+
329
+ try:
330
+ fsencode = os.fsencode
331
+ fsdecode = os.fsdecode
332
+ except AttributeError: # pragma: no cover
333
+ # Issue #99: on some systems (e.g. containerised),
334
+ # sys.getfilesystemencoding() returns None, and we need a real value,
335
+ # so fall back to utf-8. From the CPython 2.7 docs relating to Unix and
336
+ # sys.getfilesystemencoding(): the return value is "the user’s preference
337
+ # according to the result of nl_langinfo(CODESET), or None if the
338
+ # nl_langinfo(CODESET) failed."
339
+ _fsencoding = sys.getfilesystemencoding() or 'utf-8'
340
+ if _fsencoding == 'mbcs':
341
+ _fserrors = 'strict'
342
+ else:
343
+ _fserrors = 'surrogateescape'
344
+
345
+ def fsencode(filename):
346
+ if isinstance(filename, bytes):
347
+ return filename
348
+ elif isinstance(filename, text_type):
349
+ return filename.encode(_fsencoding, _fserrors)
350
+ else:
351
+ raise TypeError("expect bytes or str, not %s" %
352
+ type(filename).__name__)
353
+
354
+ def fsdecode(filename):
355
+ if isinstance(filename, text_type):
356
+ return filename
357
+ elif isinstance(filename, bytes):
358
+ return filename.decode(_fsencoding, _fserrors)
359
+ else:
360
+ raise TypeError("expect bytes or str, not %s" %
361
+ type(filename).__name__)
362
+
363
+
364
+ try:
365
+ from tokenize import detect_encoding
366
+ except ImportError: # pragma: no cover
367
+ from codecs import BOM_UTF8, lookup
368
+
369
+ cookie_re = re.compile(r"coding[:=]\s*([-\w.]+)")
370
+
371
+ def _get_normal_name(orig_enc):
372
+ """Imitates get_normal_name in tokenizer.c."""
373
+ # Only care about the first 12 characters.
374
+ enc = orig_enc[:12].lower().replace("_", "-")
375
+ if enc == "utf-8" or enc.startswith("utf-8-"):
376
+ return "utf-8"
377
+ if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
378
+ enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
379
+ return "iso-8859-1"
380
+ return orig_enc
381
+
382
+ def detect_encoding(readline):
383
+ """
384
+ The detect_encoding() function is used to detect the encoding that should
385
+ be used to decode a Python source file. It requires one argument, readline,
386
+ in the same way as the tokenize() generator.
387
+
388
+ It will call readline a maximum of twice, and return the encoding used
389
+ (as a string) and a list of any lines (left as bytes) it has read in.
390
+
391
+ It detects the encoding from the presence of a utf-8 bom or an encoding
392
+ cookie as specified in pep-0263. If both a bom and a cookie are present,
393
+ but disagree, a SyntaxError will be raised. If the encoding cookie is an
394
+ invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
395
+ 'utf-8-sig' is returned.
396
+
397
+ If no encoding is specified, then the default of 'utf-8' will be returned.
398
+ """
399
+ try:
400
+ filename = readline.__self__.name
401
+ except AttributeError:
402
+ filename = None
403
+ bom_found = False
404
+ encoding = None
405
+ default = 'utf-8'
406
+
407
+ def read_or_stop():
408
+ try:
409
+ return readline()
410
+ except StopIteration:
411
+ return b''
412
+
413
+ def find_cookie(line):
414
+ try:
415
+ # Decode as UTF-8. Either the line is an encoding declaration,
416
+ # in which case it should be pure ASCII, or it must be UTF-8
417
+ # per default encoding.
418
+ line_string = line.decode('utf-8')
419
+ except UnicodeDecodeError:
420
+ msg = "invalid or missing encoding declaration"
421
+ if filename is not None:
422
+ msg = '{} for {!r}'.format(msg, filename)
423
+ raise SyntaxError(msg)
424
+
425
+ matches = cookie_re.findall(line_string)
426
+ if not matches:
427
+ return None
428
+ encoding = _get_normal_name(matches[0])
429
+ try:
430
+ codec = lookup(encoding)
431
+ except LookupError:
432
+ # This behaviour mimics the Python interpreter
433
+ if filename is None:
434
+ msg = "unknown encoding: " + encoding
435
+ else:
436
+ msg = "unknown encoding for {!r}: {}".format(
437
+ filename, encoding)
438
+ raise SyntaxError(msg)
439
+
440
+ if bom_found:
441
+ if codec.name != 'utf-8':
442
+ # This behaviour mimics the Python interpreter
443
+ if filename is None:
444
+ msg = 'encoding problem: utf-8'
445
+ else:
446
+ msg = 'encoding problem for {!r}: utf-8'.format(
447
+ filename)
448
+ raise SyntaxError(msg)
449
+ encoding += '-sig'
450
+ return encoding
451
+
452
+ first = read_or_stop()
453
+ if first.startswith(BOM_UTF8):
454
+ bom_found = True
455
+ first = first[3:]
456
+ default = 'utf-8-sig'
457
+ if not first:
458
+ return default, []
459
+
460
+ encoding = find_cookie(first)
461
+ if encoding:
462
+ return encoding, [first]
463
+
464
+ second = read_or_stop()
465
+ if not second:
466
+ return default, [first]
467
+
468
+ encoding = find_cookie(second)
469
+ if encoding:
470
+ return encoding, [first, second]
471
+
472
+ return default, [first, second]
473
+
474
+
475
+ # For converting & <-> &amp; etc.
476
+ try:
477
+ from html import escape
478
+ except ImportError:
479
+ from cgi import escape
480
+ if sys.version_info[:2] < (3, 4):
481
+ unescape = HTMLParser().unescape
482
+ else:
483
+ from html import unescape
484
+
485
+ try:
486
+ from collections import ChainMap
487
+ except ImportError: # pragma: no cover
488
+ from collections import MutableMapping
489
+
490
+ try:
491
+ from reprlib import recursive_repr as _recursive_repr
492
+ except ImportError:
493
+
494
+ def _recursive_repr(fillvalue='...'):
495
+ '''
496
+ Decorator to make a repr function return fillvalue for a recursive
497
+ call
498
+ '''
499
+
500
+ def decorating_function(user_function):
501
+ repr_running = set()
502
+
503
+ def wrapper(self):
504
+ key = id(self), get_ident()
505
+ if key in repr_running:
506
+ return fillvalue
507
+ repr_running.add(key)
508
+ try:
509
+ result = user_function(self)
510
+ finally:
511
+ repr_running.discard(key)
512
+ return result
513
+
514
+ # Can't use functools.wraps() here because of bootstrap issues
515
+ wrapper.__module__ = getattr(user_function, '__module__')
516
+ wrapper.__doc__ = getattr(user_function, '__doc__')
517
+ wrapper.__name__ = getattr(user_function, '__name__')
518
+ wrapper.__annotations__ = getattr(user_function,
519
+ '__annotations__', {})
520
+ return wrapper
521
+
522
+ return decorating_function
523
+
524
+ class ChainMap(MutableMapping):
525
+ '''
526
+ A ChainMap groups multiple dicts (or other mappings) together
527
+ to create a single, updateable view.
528
+
529
+ The underlying mappings are stored in a list. That list is public and can
530
+ accessed or updated using the *maps* attribute. There is no other state.
531
+
532
+ Lookups search the underlying mappings successively until a key is found.
533
+ In contrast, writes, updates, and deletions only operate on the first
534
+ mapping.
535
+ '''
536
+
537
+ def __init__(self, *maps):
538
+ '''Initialize a ChainMap by setting *maps* to the given mappings.
539
+ If no mappings are provided, a single empty dictionary is used.
540
+
541
+ '''
542
+ self.maps = list(maps) or [{}] # always at least one map
543
+
544
+ def __missing__(self, key):
545
+ raise KeyError(key)
546
+
547
+ def __getitem__(self, key):
548
+ for mapping in self.maps:
549
+ try:
550
+ return mapping[
551
+ key] # can't use 'key in mapping' with defaultdict
552
+ except KeyError:
553
+ pass
554
+ return self.__missing__(
555
+ key) # support subclasses that define __missing__
556
+
557
+ def get(self, key, default=None):
558
+ return self[key] if key in self else default
559
+
560
+ def __len__(self):
561
+ return len(set().union(
562
+ *self.maps)) # reuses stored hash values if possible
563
+
564
+ def __iter__(self):
565
+ return iter(set().union(*self.maps))
566
+
567
+ def __contains__(self, key):
568
+ return any(key in m for m in self.maps)
569
+
570
+ def __bool__(self):
571
+ return any(self.maps)
572
+
573
+ @_recursive_repr()
574
+ def __repr__(self):
575
+ return '{0.__class__.__name__}({1})'.format(
576
+ self, ', '.join(map(repr, self.maps)))
577
+
578
+ @classmethod
579
+ def fromkeys(cls, iterable, *args):
580
+ 'Create a ChainMap with a single dict created from the iterable.'
581
+ return cls(dict.fromkeys(iterable, *args))
582
+
583
+ def copy(self):
584
+ 'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
585
+ return self.__class__(self.maps[0].copy(), *self.maps[1:])
586
+
587
+ __copy__ = copy
588
+
589
+ def new_child(self): # like Django's Context.push()
590
+ 'New ChainMap with a new dict followed by all previous maps.'
591
+ return self.__class__({}, *self.maps)
592
+
593
+ @property
594
+ def parents(self): # like Django's Context.pop()
595
+ 'New ChainMap from maps[1:].'
596
+ return self.__class__(*self.maps[1:])
597
+
598
+ def __setitem__(self, key, value):
599
+ self.maps[0][key] = value
600
+
601
+ def __delitem__(self, key):
602
+ try:
603
+ del self.maps[0][key]
604
+ except KeyError:
605
+ raise KeyError(
606
+ 'Key not found in the first mapping: {!r}'.format(key))
607
+
608
+ def popitem(self):
609
+ 'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.'
610
+ try:
611
+ return self.maps[0].popitem()
612
+ except KeyError:
613
+ raise KeyError('No keys found in the first mapping.')
614
+
615
+ def pop(self, key, *args):
616
+ 'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
617
+ try:
618
+ return self.maps[0].pop(key, *args)
619
+ except KeyError:
620
+ raise KeyError(
621
+ 'Key not found in the first mapping: {!r}'.format(key))
622
+
623
+ def clear(self):
624
+ 'Clear maps[0], leaving maps[1:] intact.'
625
+ self.maps[0].clear()
626
+
627
+
628
+ try:
629
+ from importlib.util import cache_from_source # Python >= 3.4
630
+ except ImportError: # pragma: no cover
631
+
632
+ def cache_from_source(path, debug_override=None):
633
+ assert path.endswith('.py')
634
+ if debug_override is None:
635
+ debug_override = __debug__
636
+ if debug_override:
637
+ suffix = 'c'
638
+ else:
639
+ suffix = 'o'
640
+ return path + suffix
641
+
642
+
643
+ try:
644
+ from collections import OrderedDict
645
+ except ImportError: # pragma: no cover
646
+ # {{{ http://code.activestate.com/recipes/576693/ (r9)
647
+ # Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
648
+ # Passes Python2.7's test suite and incorporates all the latest updates.
649
+ try:
650
+ from thread import get_ident as _get_ident
651
+ except ImportError:
652
+ from dummy_thread import get_ident as _get_ident
653
+
654
+ try:
655
+ from _abcoll import KeysView, ValuesView, ItemsView
656
+ except ImportError:
657
+ pass
658
+
659
+ class OrderedDict(dict):
660
+ 'Dictionary that remembers insertion order'
661
+
662
+ # An inherited dict maps keys to values.
663
+ # The inherited dict provides __getitem__, __len__, __contains__, and get.
664
+ # The remaining methods are order-aware.
665
+ # Big-O running times for all methods are the same as for regular dictionaries.
666
+
667
+ # The internal self.__map dictionary maps keys to links in a doubly linked list.
668
+ # The circular doubly linked list starts and ends with a sentinel element.
669
+ # The sentinel element never gets deleted (this simplifies the algorithm).
670
+ # Each link is stored as a list of length three: [PREV, NEXT, KEY].
671
+
672
+ def __init__(self, *args, **kwds):
673
+ '''Initialize an ordered dictionary. Signature is the same as for
674
+ regular dictionaries, but keyword arguments are not recommended
675
+ because their insertion order is arbitrary.
676
+
677
+ '''
678
+ if len(args) > 1:
679
+ raise TypeError('expected at most 1 arguments, got %d' %
680
+ len(args))
681
+ try:
682
+ self.__root
683
+ except AttributeError:
684
+ self.__root = root = [] # sentinel node
685
+ root[:] = [root, root, None]
686
+ self.__map = {}
687
+ self.__update(*args, **kwds)
688
+
689
+ def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
690
+ 'od.__setitem__(i, y) <==> od[i]=y'
691
+ # Setting a new item creates a new link which goes at the end of the linked
692
+ # list, and the inherited dictionary is updated with the new key/value pair.
693
+ if key not in self:
694
+ root = self.__root
695
+ last = root[0]
696
+ last[1] = root[0] = self.__map[key] = [last, root, key]
697
+ dict_setitem(self, key, value)
698
+
699
+ def __delitem__(self, key, dict_delitem=dict.__delitem__):
700
+ 'od.__delitem__(y) <==> del od[y]'
701
+ # Deleting an existing item uses self.__map to find the link which is
702
+ # then removed by updating the links in the predecessor and successor nodes.
703
+ dict_delitem(self, key)
704
+ link_prev, link_next, key = self.__map.pop(key)
705
+ link_prev[1] = link_next
706
+ link_next[0] = link_prev
707
+
708
+ def __iter__(self):
709
+ 'od.__iter__() <==> iter(od)'
710
+ root = self.__root
711
+ curr = root[1]
712
+ while curr is not root:
713
+ yield curr[2]
714
+ curr = curr[1]
715
+
716
+ def __reversed__(self):
717
+ 'od.__reversed__() <==> reversed(od)'
718
+ root = self.__root
719
+ curr = root[0]
720
+ while curr is not root:
721
+ yield curr[2]
722
+ curr = curr[0]
723
+
724
+ def clear(self):
725
+ 'od.clear() -> None. Remove all items from od.'
726
+ try:
727
+ for node in self.__map.itervalues():
728
+ del node[:]
729
+ root = self.__root
730
+ root[:] = [root, root, None]
731
+ self.__map.clear()
732
+ except AttributeError:
733
+ pass
734
+ dict.clear(self)
735
+
736
+ def popitem(self, last=True):
737
+ '''od.popitem() -> (k, v), return and remove a (key, value) pair.
738
+ Pairs are returned in LIFO order if last is true or FIFO order if false.
739
+
740
+ '''
741
+ if not self:
742
+ raise KeyError('dictionary is empty')
743
+ root = self.__root
744
+ if last:
745
+ link = root[0]
746
+ link_prev = link[0]
747
+ link_prev[1] = root
748
+ root[0] = link_prev
749
+ else:
750
+ link = root[1]
751
+ link_next = link[1]
752
+ root[1] = link_next
753
+ link_next[0] = root
754
+ key = link[2]
755
+ del self.__map[key]
756
+ value = dict.pop(self, key)
757
+ return key, value
758
+
759
+ # -- the following methods do not depend on the internal structure --
760
+
761
+ def keys(self):
762
+ 'od.keys() -> list of keys in od'
763
+ return list(self)
764
+
765
+ def values(self):
766
+ 'od.values() -> list of values in od'
767
+ return [self[key] for key in self]
768
+
769
+ def items(self):
770
+ 'od.items() -> list of (key, value) pairs in od'
771
+ return [(key, self[key]) for key in self]
772
+
773
+ def iterkeys(self):
774
+ 'od.iterkeys() -> an iterator over the keys in od'
775
+ return iter(self)
776
+
777
+ def itervalues(self):
778
+ 'od.itervalues -> an iterator over the values in od'
779
+ for k in self:
780
+ yield self[k]
781
+
782
+ def iteritems(self):
783
+ 'od.iteritems -> an iterator over the (key, value) items in od'
784
+ for k in self:
785
+ yield (k, self[k])
786
+
787
+ def update(*args, **kwds):
788
+ '''od.update(E, **F) -> None. Update od from dict/iterable E and F.
789
+
790
+ If E is a dict instance, does: for k in E: od[k] = E[k]
791
+ If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
792
+ Or if E is an iterable of items, does: for k, v in E: od[k] = v
793
+ In either case, this is followed by: for k, v in F.items(): od[k] = v
794
+
795
+ '''
796
+ if len(args) > 2:
797
+ raise TypeError('update() takes at most 2 positional '
798
+ 'arguments (%d given)' % (len(args), ))
799
+ elif not args:
800
+ raise TypeError('update() takes at least 1 argument (0 given)')
801
+ self = args[0]
802
+ # Make progressively weaker assumptions about "other"
803
+ other = ()
804
+ if len(args) == 2:
805
+ other = args[1]
806
+ if isinstance(other, dict):
807
+ for key in other:
808
+ self[key] = other[key]
809
+ elif hasattr(other, 'keys'):
810
+ for key in other.keys():
811
+ self[key] = other[key]
812
+ else:
813
+ for key, value in other:
814
+ self[key] = value
815
+ for key, value in kwds.items():
816
+ self[key] = value
817
+
818
+ __update = update # let subclasses override update without breaking __init__
819
+
820
+ __marker = object()
821
+
822
+ def pop(self, key, default=__marker):
823
+ '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
824
+ If key is not found, d is returned if given, otherwise KeyError is raised.
825
+
826
+ '''
827
+ if key in self:
828
+ result = self[key]
829
+ del self[key]
830
+ return result
831
+ if default is self.__marker:
832
+ raise KeyError(key)
833
+ return default
834
+
835
+ def setdefault(self, key, default=None):
836
+ 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
837
+ if key in self:
838
+ return self[key]
839
+ self[key] = default
840
+ return default
841
+
842
+ def __repr__(self, _repr_running=None):
843
+ 'od.__repr__() <==> repr(od)'
844
+ if not _repr_running:
845
+ _repr_running = {}
846
+ call_key = id(self), _get_ident()
847
+ if call_key in _repr_running:
848
+ return '...'
849
+ _repr_running[call_key] = 1
850
+ try:
851
+ if not self:
852
+ return '%s()' % (self.__class__.__name__, )
853
+ return '%s(%r)' % (self.__class__.__name__, self.items())
854
+ finally:
855
+ del _repr_running[call_key]
856
+
857
+ def __reduce__(self):
858
+ 'Return state information for pickling'
859
+ items = [[k, self[k]] for k in self]
860
+ inst_dict = vars(self).copy()
861
+ for k in vars(OrderedDict()):
862
+ inst_dict.pop(k, None)
863
+ if inst_dict:
864
+ return (self.__class__, (items, ), inst_dict)
865
+ return self.__class__, (items, )
866
+
867
+ def copy(self):
868
+ 'od.copy() -> a shallow copy of od'
869
+ return self.__class__(self)
870
+
871
+ @classmethod
872
+ def fromkeys(cls, iterable, value=None):
873
+ '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
874
+ and values equal to v (which defaults to None).
875
+
876
+ '''
877
+ d = cls()
878
+ for key in iterable:
879
+ d[key] = value
880
+ return d
881
+
882
+ def __eq__(self, other):
883
+ '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
884
+ while comparison to a regular mapping is order-insensitive.
885
+
886
+ '''
887
+ if isinstance(other, OrderedDict):
888
+ return len(self) == len(
889
+ other) and self.items() == other.items()
890
+ return dict.__eq__(self, other)
891
+
892
+ def __ne__(self, other):
893
+ return not self == other
894
+
895
+ # -- the following methods are only used in Python 2.7 --
896
+
897
+ def viewkeys(self):
898
+ "od.viewkeys() -> a set-like object providing a view on od's keys"
899
+ return KeysView(self)
900
+
901
+ def viewvalues(self):
902
+ "od.viewvalues() -> an object providing a view on od's values"
903
+ return ValuesView(self)
904
+
905
+ def viewitems(self):
906
+ "od.viewitems() -> a set-like object providing a view on od's items"
907
+ return ItemsView(self)
908
+
909
+
910
+ try:
911
+ from logging.config import BaseConfigurator, valid_ident
912
+ except ImportError: # pragma: no cover
913
+ IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)
914
+
915
+ def valid_ident(s):
916
+ m = IDENTIFIER.match(s)
917
+ if not m:
918
+ raise ValueError('Not a valid Python identifier: %r' % s)
919
+ return True
920
+
921
+ # The ConvertingXXX classes are wrappers around standard Python containers,
922
+ # and they serve to convert any suitable values in the container. The
923
+ # conversion converts base dicts, lists and tuples to their wrapped
924
+ # equivalents, whereas strings which match a conversion format are converted
925
+ # appropriately.
926
+ #
927
+ # Each wrapper should have a configurator attribute holding the actual
928
+ # configurator to use for conversion.
929
+
930
+ class ConvertingDict(dict):
931
+ """A converting dictionary wrapper."""
932
+
933
+ def __getitem__(self, key):
934
+ value = dict.__getitem__(self, key)
935
+ result = self.configurator.convert(value)
936
+ # If the converted value is different, save for next time
937
+ if value is not result:
938
+ self[key] = result
939
+ if type(result) in (ConvertingDict, ConvertingList,
940
+ ConvertingTuple):
941
+ result.parent = self
942
+ result.key = key
943
+ return result
944
+
945
+ def get(self, key, default=None):
946
+ value = dict.get(self, key, default)
947
+ result = self.configurator.convert(value)
948
+ # If the converted value is different, save for next time
949
+ if value is not result:
950
+ self[key] = result
951
+ if type(result) in (ConvertingDict, ConvertingList,
952
+ ConvertingTuple):
953
+ result.parent = self
954
+ result.key = key
955
+ return result
956
+
957
+ def pop(self, key, default=None):
958
+ value = dict.pop(self, key, default)
959
+ result = self.configurator.convert(value)
960
+ if value is not result:
961
+ if type(result) in (ConvertingDict, ConvertingList,
962
+ ConvertingTuple):
963
+ result.parent = self
964
+ result.key = key
965
+ return result
966
+
967
+ class ConvertingList(list):
968
+ """A converting list wrapper."""
969
+
970
+ def __getitem__(self, key):
971
+ value = list.__getitem__(self, key)
972
+ result = self.configurator.convert(value)
973
+ # If the converted value is different, save for next time
974
+ if value is not result:
975
+ self[key] = result
976
+ if type(result) in (ConvertingDict, ConvertingList,
977
+ ConvertingTuple):
978
+ result.parent = self
979
+ result.key = key
980
+ return result
981
+
982
+ def pop(self, idx=-1):
983
+ value = list.pop(self, idx)
984
+ result = self.configurator.convert(value)
985
+ if value is not result:
986
+ if type(result) in (ConvertingDict, ConvertingList,
987
+ ConvertingTuple):
988
+ result.parent = self
989
+ return result
990
+
991
+ class ConvertingTuple(tuple):
992
+ """A converting tuple wrapper."""
993
+
994
+ def __getitem__(self, key):
995
+ value = tuple.__getitem__(self, key)
996
+ result = self.configurator.convert(value)
997
+ if value is not result:
998
+ if type(result) in (ConvertingDict, ConvertingList,
999
+ ConvertingTuple):
1000
+ result.parent = self
1001
+ result.key = key
1002
+ return result
1003
+
1004
+ class BaseConfigurator(object):
1005
+ """
1006
+ The configurator base class which defines some useful defaults.
1007
+ """
1008
+
1009
+ CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$')
1010
+
1011
+ WORD_PATTERN = re.compile(r'^\s*(\w+)\s*')
1012
+ DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*')
1013
+ INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*')
1014
+ DIGIT_PATTERN = re.compile(r'^\d+$')
1015
+
1016
+ value_converters = {
1017
+ 'ext': 'ext_convert',
1018
+ 'cfg': 'cfg_convert',
1019
+ }
1020
+
1021
+ # We might want to use a different one, e.g. importlib
1022
+ importer = staticmethod(__import__)
1023
+
1024
+ def __init__(self, config):
1025
+ self.config = ConvertingDict(config)
1026
+ self.config.configurator = self
1027
+
1028
+ def resolve(self, s):
1029
+ """
1030
+ Resolve strings to objects using standard import and attribute
1031
+ syntax.
1032
+ """
1033
+ name = s.split('.')
1034
+ used = name.pop(0)
1035
+ try:
1036
+ found = self.importer(used)
1037
+ for frag in name:
1038
+ used += '.' + frag
1039
+ try:
1040
+ found = getattr(found, frag)
1041
+ except AttributeError:
1042
+ self.importer(used)
1043
+ found = getattr(found, frag)
1044
+ return found
1045
+ except ImportError:
1046
+ e, tb = sys.exc_info()[1:]
1047
+ v = ValueError('Cannot resolve %r: %s' % (s, e))
1048
+ v.__cause__, v.__traceback__ = e, tb
1049
+ raise v
1050
+
1051
+ def ext_convert(self, value):
1052
+ """Default converter for the ext:// protocol."""
1053
+ return self.resolve(value)
1054
+
1055
+ def cfg_convert(self, value):
1056
+ """Default converter for the cfg:// protocol."""
1057
+ rest = value
1058
+ m = self.WORD_PATTERN.match(rest)
1059
+ if m is None:
1060
+ raise ValueError("Unable to convert %r" % value)
1061
+ else:
1062
+ rest = rest[m.end():]
1063
+ d = self.config[m.groups()[0]]
1064
+ while rest:
1065
+ m = self.DOT_PATTERN.match(rest)
1066
+ if m:
1067
+ d = d[m.groups()[0]]
1068
+ else:
1069
+ m = self.INDEX_PATTERN.match(rest)
1070
+ if m:
1071
+ idx = m.groups()[0]
1072
+ if not self.DIGIT_PATTERN.match(idx):
1073
+ d = d[idx]
1074
+ else:
1075
+ try:
1076
+ n = int(
1077
+ idx
1078
+ ) # try as number first (most likely)
1079
+ d = d[n]
1080
+ except TypeError:
1081
+ d = d[idx]
1082
+ if m:
1083
+ rest = rest[m.end():]
1084
+ else:
1085
+ raise ValueError('Unable to convert '
1086
+ '%r at %r' % (value, rest))
1087
+ # rest should be empty
1088
+ return d
1089
+
1090
+ def convert(self, value):
1091
+ """
1092
+ Convert values to an appropriate type. dicts, lists and tuples are
1093
+ replaced by their converting alternatives. Strings are checked to
1094
+ see if they have a conversion format and are converted if they do.
1095
+ """
1096
+ if not isinstance(value, ConvertingDict) and isinstance(
1097
+ value, dict):
1098
+ value = ConvertingDict(value)
1099
+ value.configurator = self
1100
+ elif not isinstance(value, ConvertingList) and isinstance(
1101
+ value, list):
1102
+ value = ConvertingList(value)
1103
+ value.configurator = self
1104
+ elif not isinstance(value, ConvertingTuple) and isinstance(value, tuple):
1105
+ value = ConvertingTuple(value)
1106
+ value.configurator = self
1107
+ elif isinstance(value, string_types):
1108
+ m = self.CONVERT_PATTERN.match(value)
1109
+ if m:
1110
+ d = m.groupdict()
1111
+ prefix = d['prefix']
1112
+ converter = self.value_converters.get(prefix, None)
1113
+ if converter:
1114
+ suffix = d['suffix']
1115
+ converter = getattr(self, converter)
1116
+ value = converter(suffix)
1117
+ return value
1118
+
1119
+ def configure_custom(self, config):
1120
+ """Configure an object with a user-supplied factory."""
1121
+ c = config.pop('()')
1122
+ if not callable(c):
1123
+ c = self.resolve(c)
1124
+ props = config.pop('.', None)
1125
+ # Check for valid identifiers
1126
+ kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
1127
+ result = c(**kwargs)
1128
+ if props:
1129
+ for name, value in props.items():
1130
+ setattr(result, name, value)
1131
+ return result
1132
+
1133
+ def as_tuple(self, value):
1134
+ """Utility function which converts lists to tuples."""
1135
+ if isinstance(value, list):
1136
+ value = tuple(value)
1137
+ return value
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/index.py ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2013-2023 Vinay Sajip.
4
+ # Licensed to the Python Software Foundation under a contributor agreement.
5
+ # See LICENSE.txt and CONTRIBUTORS.txt.
6
+ #
7
+ import hashlib
8
+ import logging
9
+ import os
10
+ import shutil
11
+ import subprocess
12
+ import tempfile
13
+ try:
14
+ from threading import Thread
15
+ except ImportError: # pragma: no cover
16
+ from dummy_threading import Thread
17
+
18
+ from . import DistlibException
19
+ from .compat import (HTTPBasicAuthHandler, Request, HTTPPasswordMgr,
20
+ urlparse, build_opener, string_types)
21
+ from .util import zip_dir, ServerProxy
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ DEFAULT_INDEX = 'https://pypi.org/pypi'
26
+ DEFAULT_REALM = 'pypi'
27
+
28
+
29
+ class PackageIndex(object):
30
+ """
31
+ This class represents a package index compatible with PyPI, the Python
32
+ Package Index.
33
+ """
34
+
35
+ boundary = b'----------ThIs_Is_tHe_distlib_index_bouNdaRY_$'
36
+
37
+ def __init__(self, url=None):
38
+ """
39
+ Initialise an instance.
40
+
41
+ :param url: The URL of the index. If not specified, the URL for PyPI is
42
+ used.
43
+ """
44
+ self.url = url or DEFAULT_INDEX
45
+ self.read_configuration()
46
+ scheme, netloc, path, params, query, frag = urlparse(self.url)
47
+ if params or query or frag or scheme not in ('http', 'https'):
48
+ raise DistlibException('invalid repository: %s' % self.url)
49
+ self.password_handler = None
50
+ self.ssl_verifier = None
51
+ self.gpg = None
52
+ self.gpg_home = None
53
+ with open(os.devnull, 'w') as sink:
54
+ # Use gpg by default rather than gpg2, as gpg2 insists on
55
+ # prompting for passwords
56
+ for s in ('gpg', 'gpg2'):
57
+ try:
58
+ rc = subprocess.check_call([s, '--version'], stdout=sink,
59
+ stderr=sink)
60
+ if rc == 0:
61
+ self.gpg = s
62
+ break
63
+ except OSError:
64
+ pass
65
+
66
+ def _get_pypirc_command(self):
67
+ """
68
+ Get the distutils command for interacting with PyPI configurations.
69
+ :return: the command.
70
+ """
71
+ from .util import _get_pypirc_command as cmd
72
+ return cmd()
73
+
74
+ def read_configuration(self):
75
+ """
76
+ Read the PyPI access configuration as supported by distutils. This populates
77
+ ``username``, ``password``, ``realm`` and ``url`` attributes from the
78
+ configuration.
79
+ """
80
+ from .util import _load_pypirc
81
+ cfg = _load_pypirc(self)
82
+ self.username = cfg.get('username')
83
+ self.password = cfg.get('password')
84
+ self.realm = cfg.get('realm', 'pypi')
85
+ self.url = cfg.get('repository', self.url)
86
+
87
+ def save_configuration(self):
88
+ """
89
+ Save the PyPI access configuration. You must have set ``username`` and
90
+ ``password`` attributes before calling this method.
91
+ """
92
+ self.check_credentials()
93
+ from .util import _store_pypirc
94
+ _store_pypirc(self)
95
+
96
+ def check_credentials(self):
97
+ """
98
+ Check that ``username`` and ``password`` have been set, and raise an
99
+ exception if not.
100
+ """
101
+ if self.username is None or self.password is None:
102
+ raise DistlibException('username and password must be set')
103
+ pm = HTTPPasswordMgr()
104
+ _, netloc, _, _, _, _ = urlparse(self.url)
105
+ pm.add_password(self.realm, netloc, self.username, self.password)
106
+ self.password_handler = HTTPBasicAuthHandler(pm)
107
+
108
+ def register(self, metadata): # pragma: no cover
109
+ """
110
+ Register a distribution on PyPI, using the provided metadata.
111
+
112
+ :param metadata: A :class:`Metadata` instance defining at least a name
113
+ and version number for the distribution to be
114
+ registered.
115
+ :return: The HTTP response received from PyPI upon submission of the
116
+ request.
117
+ """
118
+ self.check_credentials()
119
+ metadata.validate()
120
+ d = metadata.todict()
121
+ d[':action'] = 'verify'
122
+ request = self.encode_request(d.items(), [])
123
+ self.send_request(request)
124
+ d[':action'] = 'submit'
125
+ request = self.encode_request(d.items(), [])
126
+ return self.send_request(request)
127
+
128
+ def _reader(self, name, stream, outbuf):
129
+ """
130
+ Thread runner for reading lines of from a subprocess into a buffer.
131
+
132
+ :param name: The logical name of the stream (used for logging only).
133
+ :param stream: The stream to read from. This will typically a pipe
134
+ connected to the output stream of a subprocess.
135
+ :param outbuf: The list to append the read lines to.
136
+ """
137
+ while True:
138
+ s = stream.readline()
139
+ if not s:
140
+ break
141
+ s = s.decode('utf-8').rstrip()
142
+ outbuf.append(s)
143
+ logger.debug('%s: %s' % (name, s))
144
+ stream.close()
145
+
146
+ def get_sign_command(self, filename, signer, sign_password, keystore=None): # pragma: no cover
147
+ """
148
+ Return a suitable command for signing a file.
149
+
150
+ :param filename: The pathname to the file to be signed.
151
+ :param signer: The identifier of the signer of the file.
152
+ :param sign_password: The passphrase for the signer's
153
+ private key used for signing.
154
+ :param keystore: The path to a directory which contains the keys
155
+ used in verification. If not specified, the
156
+ instance's ``gpg_home`` attribute is used instead.
157
+ :return: The signing command as a list suitable to be
158
+ passed to :class:`subprocess.Popen`.
159
+ """
160
+ cmd = [self.gpg, '--status-fd', '2', '--no-tty']
161
+ if keystore is None:
162
+ keystore = self.gpg_home
163
+ if keystore:
164
+ cmd.extend(['--homedir', keystore])
165
+ if sign_password is not None:
166
+ cmd.extend(['--batch', '--passphrase-fd', '0'])
167
+ td = tempfile.mkdtemp()
168
+ sf = os.path.join(td, os.path.basename(filename) + '.asc')
169
+ cmd.extend(['--detach-sign', '--armor', '--local-user',
170
+ signer, '--output', sf, filename])
171
+ logger.debug('invoking: %s', ' '.join(cmd))
172
+ return cmd, sf
173
+
174
+ def run_command(self, cmd, input_data=None):
175
+ """
176
+ Run a command in a child process , passing it any input data specified.
177
+
178
+ :param cmd: The command to run.
179
+ :param input_data: If specified, this must be a byte string containing
180
+ data to be sent to the child process.
181
+ :return: A tuple consisting of the subprocess' exit code, a list of
182
+ lines read from the subprocess' ``stdout``, and a list of
183
+ lines read from the subprocess' ``stderr``.
184
+ """
185
+ kwargs = {
186
+ 'stdout': subprocess.PIPE,
187
+ 'stderr': subprocess.PIPE,
188
+ }
189
+ if input_data is not None:
190
+ kwargs['stdin'] = subprocess.PIPE
191
+ stdout = []
192
+ stderr = []
193
+ p = subprocess.Popen(cmd, **kwargs)
194
+ # We don't use communicate() here because we may need to
195
+ # get clever with interacting with the command
196
+ t1 = Thread(target=self._reader, args=('stdout', p.stdout, stdout))
197
+ t1.start()
198
+ t2 = Thread(target=self._reader, args=('stderr', p.stderr, stderr))
199
+ t2.start()
200
+ if input_data is not None:
201
+ p.stdin.write(input_data)
202
+ p.stdin.close()
203
+
204
+ p.wait()
205
+ t1.join()
206
+ t2.join()
207
+ return p.returncode, stdout, stderr
208
+
209
+ def sign_file(self, filename, signer, sign_password, keystore=None): # pragma: no cover
210
+ """
211
+ Sign a file.
212
+
213
+ :param filename: The pathname to the file to be signed.
214
+ :param signer: The identifier of the signer of the file.
215
+ :param sign_password: The passphrase for the signer's
216
+ private key used for signing.
217
+ :param keystore: The path to a directory which contains the keys
218
+ used in signing. If not specified, the instance's
219
+ ``gpg_home`` attribute is used instead.
220
+ :return: The absolute pathname of the file where the signature is
221
+ stored.
222
+ """
223
+ cmd, sig_file = self.get_sign_command(filename, signer, sign_password,
224
+ keystore)
225
+ rc, stdout, stderr = self.run_command(cmd,
226
+ sign_password.encode('utf-8'))
227
+ if rc != 0:
228
+ raise DistlibException('sign command failed with error '
229
+ 'code %s' % rc)
230
+ return sig_file
231
+
232
+ def upload_file(self, metadata, filename, signer=None, sign_password=None,
233
+ filetype='sdist', pyversion='source', keystore=None):
234
+ """
235
+ Upload a release file to the index.
236
+
237
+ :param metadata: A :class:`Metadata` instance defining at least a name
238
+ and version number for the file to be uploaded.
239
+ :param filename: The pathname of the file to be uploaded.
240
+ :param signer: The identifier of the signer of the file.
241
+ :param sign_password: The passphrase for the signer's
242
+ private key used for signing.
243
+ :param filetype: The type of the file being uploaded. This is the
244
+ distutils command which produced that file, e.g.
245
+ ``sdist`` or ``bdist_wheel``.
246
+ :param pyversion: The version of Python which the release relates
247
+ to. For code compatible with any Python, this would
248
+ be ``source``, otherwise it would be e.g. ``3.2``.
249
+ :param keystore: The path to a directory which contains the keys
250
+ used in signing. If not specified, the instance's
251
+ ``gpg_home`` attribute is used instead.
252
+ :return: The HTTP response received from PyPI upon submission of the
253
+ request.
254
+ """
255
+ self.check_credentials()
256
+ if not os.path.exists(filename):
257
+ raise DistlibException('not found: %s' % filename)
258
+ metadata.validate()
259
+ d = metadata.todict()
260
+ sig_file = None
261
+ if signer:
262
+ if not self.gpg:
263
+ logger.warning('no signing program available - not signed')
264
+ else:
265
+ sig_file = self.sign_file(filename, signer, sign_password,
266
+ keystore)
267
+ with open(filename, 'rb') as f:
268
+ file_data = f.read()
269
+ md5_digest = hashlib.md5(file_data).hexdigest()
270
+ sha256_digest = hashlib.sha256(file_data).hexdigest()
271
+ d.update({
272
+ ':action': 'file_upload',
273
+ 'protocol_version': '1',
274
+ 'filetype': filetype,
275
+ 'pyversion': pyversion,
276
+ 'md5_digest': md5_digest,
277
+ 'sha256_digest': sha256_digest,
278
+ })
279
+ files = [('content', os.path.basename(filename), file_data)]
280
+ if sig_file:
281
+ with open(sig_file, 'rb') as f:
282
+ sig_data = f.read()
283
+ files.append(('gpg_signature', os.path.basename(sig_file),
284
+ sig_data))
285
+ shutil.rmtree(os.path.dirname(sig_file))
286
+ request = self.encode_request(d.items(), files)
287
+ return self.send_request(request)
288
+
289
+ def upload_documentation(self, metadata, doc_dir): # pragma: no cover
290
+ """
291
+ Upload documentation to the index.
292
+
293
+ :param metadata: A :class:`Metadata` instance defining at least a name
294
+ and version number for the documentation to be
295
+ uploaded.
296
+ :param doc_dir: The pathname of the directory which contains the
297
+ documentation. This should be the directory that
298
+ contains the ``index.html`` for the documentation.
299
+ :return: The HTTP response received from PyPI upon submission of the
300
+ request.
301
+ """
302
+ self.check_credentials()
303
+ if not os.path.isdir(doc_dir):
304
+ raise DistlibException('not a directory: %r' % doc_dir)
305
+ fn = os.path.join(doc_dir, 'index.html')
306
+ if not os.path.exists(fn):
307
+ raise DistlibException('not found: %r' % fn)
308
+ metadata.validate()
309
+ name, version = metadata.name, metadata.version
310
+ zip_data = zip_dir(doc_dir).getvalue()
311
+ fields = [(':action', 'doc_upload'),
312
+ ('name', name), ('version', version)]
313
+ files = [('content', name, zip_data)]
314
+ request = self.encode_request(fields, files)
315
+ return self.send_request(request)
316
+
317
+ def get_verify_command(self, signature_filename, data_filename,
318
+ keystore=None):
319
+ """
320
+ Return a suitable command for verifying a file.
321
+
322
+ :param signature_filename: The pathname to the file containing the
323
+ signature.
324
+ :param data_filename: The pathname to the file containing the
325
+ signed data.
326
+ :param keystore: The path to a directory which contains the keys
327
+ used in verification. If not specified, the
328
+ instance's ``gpg_home`` attribute is used instead.
329
+ :return: The verifying command as a list suitable to be
330
+ passed to :class:`subprocess.Popen`.
331
+ """
332
+ cmd = [self.gpg, '--status-fd', '2', '--no-tty']
333
+ if keystore is None:
334
+ keystore = self.gpg_home
335
+ if keystore:
336
+ cmd.extend(['--homedir', keystore])
337
+ cmd.extend(['--verify', signature_filename, data_filename])
338
+ logger.debug('invoking: %s', ' '.join(cmd))
339
+ return cmd
340
+
341
+ def verify_signature(self, signature_filename, data_filename,
342
+ keystore=None):
343
+ """
344
+ Verify a signature for a file.
345
+
346
+ :param signature_filename: The pathname to the file containing the
347
+ signature.
348
+ :param data_filename: The pathname to the file containing the
349
+ signed data.
350
+ :param keystore: The path to a directory which contains the keys
351
+ used in verification. If not specified, the
352
+ instance's ``gpg_home`` attribute is used instead.
353
+ :return: True if the signature was verified, else False.
354
+ """
355
+ if not self.gpg:
356
+ raise DistlibException('verification unavailable because gpg '
357
+ 'unavailable')
358
+ cmd = self.get_verify_command(signature_filename, data_filename,
359
+ keystore)
360
+ rc, stdout, stderr = self.run_command(cmd)
361
+ if rc not in (0, 1):
362
+ raise DistlibException('verify command failed with error code %s' % rc)
363
+ return rc == 0
364
+
365
+ def download_file(self, url, destfile, digest=None, reporthook=None):
366
+ """
367
+ This is a convenience method for downloading a file from an URL.
368
+ Normally, this will be a file from the index, though currently
369
+ no check is made for this (i.e. a file can be downloaded from
370
+ anywhere).
371
+
372
+ The method is just like the :func:`urlretrieve` function in the
373
+ standard library, except that it allows digest computation to be
374
+ done during download and checking that the downloaded data
375
+ matched any expected value.
376
+
377
+ :param url: The URL of the file to be downloaded (assumed to be
378
+ available via an HTTP GET request).
379
+ :param destfile: The pathname where the downloaded file is to be
380
+ saved.
381
+ :param digest: If specified, this must be a (hasher, value)
382
+ tuple, where hasher is the algorithm used (e.g.
383
+ ``'md5'``) and ``value`` is the expected value.
384
+ :param reporthook: The same as for :func:`urlretrieve` in the
385
+ standard library.
386
+ """
387
+ if digest is None:
388
+ digester = None
389
+ logger.debug('No digest specified')
390
+ else:
391
+ if isinstance(digest, (list, tuple)):
392
+ hasher, digest = digest
393
+ else:
394
+ hasher = 'md5'
395
+ digester = getattr(hashlib, hasher)()
396
+ logger.debug('Digest specified: %s' % digest)
397
+ # The following code is equivalent to urlretrieve.
398
+ # We need to do it this way so that we can compute the
399
+ # digest of the file as we go.
400
+ with open(destfile, 'wb') as dfp:
401
+ # addinfourl is not a context manager on 2.x
402
+ # so we have to use try/finally
403
+ sfp = self.send_request(Request(url))
404
+ try:
405
+ headers = sfp.info()
406
+ blocksize = 8192
407
+ size = -1
408
+ read = 0
409
+ blocknum = 0
410
+ if "content-length" in headers:
411
+ size = int(headers["Content-Length"])
412
+ if reporthook:
413
+ reporthook(blocknum, blocksize, size)
414
+ while True:
415
+ block = sfp.read(blocksize)
416
+ if not block:
417
+ break
418
+ read += len(block)
419
+ dfp.write(block)
420
+ if digester:
421
+ digester.update(block)
422
+ blocknum += 1
423
+ if reporthook:
424
+ reporthook(blocknum, blocksize, size)
425
+ finally:
426
+ sfp.close()
427
+
428
+ # check that we got the whole file, if we can
429
+ if size >= 0 and read < size:
430
+ raise DistlibException(
431
+ 'retrieval incomplete: got only %d out of %d bytes'
432
+ % (read, size))
433
+ # if we have a digest, it must match.
434
+ if digester:
435
+ actual = digester.hexdigest()
436
+ if digest != actual:
437
+ raise DistlibException('%s digest mismatch for %s: expected '
438
+ '%s, got %s' % (hasher, destfile,
439
+ digest, actual))
440
+ logger.debug('Digest verified: %s', digest)
441
+
442
+ def send_request(self, req):
443
+ """
444
+ Send a standard library :class:`Request` to PyPI and return its
445
+ response.
446
+
447
+ :param req: The request to send.
448
+ :return: The HTTP response from PyPI (a standard library HTTPResponse).
449
+ """
450
+ handlers = []
451
+ if self.password_handler:
452
+ handlers.append(self.password_handler)
453
+ if self.ssl_verifier:
454
+ handlers.append(self.ssl_verifier)
455
+ opener = build_opener(*handlers)
456
+ return opener.open(req)
457
+
458
+ def encode_request(self, fields, files):
459
+ """
460
+ Encode fields and files for posting to an HTTP server.
461
+
462
+ :param fields: The fields to send as a list of (fieldname, value)
463
+ tuples.
464
+ :param files: The files to send as a list of (fieldname, filename,
465
+ file_bytes) tuple.
466
+ """
467
+ # Adapted from packaging, which in turn was adapted from
468
+ # http://code.activestate.com/recipes/146306
469
+
470
+ parts = []
471
+ boundary = self.boundary
472
+ for k, values in fields:
473
+ if not isinstance(values, (list, tuple)):
474
+ values = [values]
475
+
476
+ for v in values:
477
+ parts.extend((
478
+ b'--' + boundary,
479
+ ('Content-Disposition: form-data; name="%s"' %
480
+ k).encode('utf-8'),
481
+ b'',
482
+ v.encode('utf-8')))
483
+ for key, filename, value in files:
484
+ parts.extend((
485
+ b'--' + boundary,
486
+ ('Content-Disposition: form-data; name="%s"; filename="%s"' %
487
+ (key, filename)).encode('utf-8'),
488
+ b'',
489
+ value))
490
+
491
+ parts.extend((b'--' + boundary + b'--', b''))
492
+
493
+ body = b'\r\n'.join(parts)
494
+ ct = b'multipart/form-data; boundary=' + boundary
495
+ headers = {
496
+ 'Content-type': ct,
497
+ 'Content-length': str(len(body))
498
+ }
499
+ return Request(self.url, body, headers)
500
+
501
+ def search(self, terms, operator=None): # pragma: no cover
502
+ if isinstance(terms, string_types):
503
+ terms = {'name': terms}
504
+ rpc_proxy = ServerProxy(self.url, timeout=3.0)
505
+ try:
506
+ return rpc_proxy.search(terms, operator or 'and')
507
+ finally:
508
+ rpc_proxy('close')()
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/manifest.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2012-2023 Python Software Foundation.
4
+ # See LICENSE.txt and CONTRIBUTORS.txt.
5
+ #
6
+ """
7
+ Class representing the list of files in a distribution.
8
+
9
+ Equivalent to distutils.filelist, but fixes some problems.
10
+ """
11
+ import fnmatch
12
+ import logging
13
+ import os
14
+ import re
15
+ import sys
16
+
17
+ from . import DistlibException
18
+ from .compat import fsdecode
19
+ from .util import convert_path
20
+
21
+
22
+ __all__ = ['Manifest']
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ # a \ followed by some spaces + EOL
27
+ _COLLAPSE_PATTERN = re.compile('\\\\w*\n', re.M)
28
+ _COMMENTED_LINE = re.compile('#.*?(?=\n)|\n(?=$)', re.M | re.S)
29
+
30
+ #
31
+ # Due to the different results returned by fnmatch.translate, we need
32
+ # to do slightly different processing for Python 2.7 and 3.2 ... this needed
33
+ # to be brought in for Python 3.6 onwards.
34
+ #
35
+ _PYTHON_VERSION = sys.version_info[:2]
36
+
37
+
38
+ class Manifest(object):
39
+ """
40
+ A list of files built by exploring the filesystem and filtered by applying various
41
+ patterns to what we find there.
42
+ """
43
+
44
+ def __init__(self, base=None):
45
+ """
46
+ Initialise an instance.
47
+
48
+ :param base: The base directory to explore under.
49
+ """
50
+ self.base = os.path.abspath(os.path.normpath(base or os.getcwd()))
51
+ self.prefix = self.base + os.sep
52
+ self.allfiles = None
53
+ self.files = set()
54
+
55
+ #
56
+ # Public API
57
+ #
58
+
59
+ def findall(self):
60
+ """Find all files under the base and set ``allfiles`` to the absolute
61
+ pathnames of files found.
62
+ """
63
+ from stat import S_ISREG, S_ISDIR, S_ISLNK
64
+
65
+ self.allfiles = allfiles = []
66
+ root = self.base
67
+ stack = [root]
68
+ pop = stack.pop
69
+ push = stack.append
70
+
71
+ while stack:
72
+ root = pop()
73
+ names = os.listdir(root)
74
+
75
+ for name in names:
76
+ fullname = os.path.join(root, name)
77
+
78
+ # Avoid excess stat calls -- just one will do, thank you!
79
+ stat = os.stat(fullname)
80
+ mode = stat.st_mode
81
+ if S_ISREG(mode):
82
+ allfiles.append(fsdecode(fullname))
83
+ elif S_ISDIR(mode) and not S_ISLNK(mode):
84
+ push(fullname)
85
+
86
+ def add(self, item):
87
+ """
88
+ Add a file to the manifest.
89
+
90
+ :param item: The pathname to add. This can be relative to the base.
91
+ """
92
+ if not item.startswith(self.prefix):
93
+ item = os.path.join(self.base, item)
94
+ self.files.add(os.path.normpath(item))
95
+
96
+ def add_many(self, items):
97
+ """
98
+ Add a list of files to the manifest.
99
+
100
+ :param items: The pathnames to add. These can be relative to the base.
101
+ """
102
+ for item in items:
103
+ self.add(item)
104
+
105
+ def sorted(self, wantdirs=False):
106
+ """
107
+ Return sorted files in directory order
108
+ """
109
+
110
+ def add_dir(dirs, d):
111
+ dirs.add(d)
112
+ logger.debug('add_dir added %s', d)
113
+ if d != self.base:
114
+ parent, _ = os.path.split(d)
115
+ assert parent not in ('', '/')
116
+ add_dir(dirs, parent)
117
+
118
+ result = set(self.files) # make a copy!
119
+ if wantdirs:
120
+ dirs = set()
121
+ for f in result:
122
+ add_dir(dirs, os.path.dirname(f))
123
+ result |= dirs
124
+ return [os.path.join(*path_tuple) for path_tuple in
125
+ sorted(os.path.split(path) for path in result)]
126
+
127
+ def clear(self):
128
+ """Clear all collected files."""
129
+ self.files = set()
130
+ self.allfiles = []
131
+
132
+ def process_directive(self, directive):
133
+ """
134
+ Process a directive which either adds some files from ``allfiles`` to
135
+ ``files``, or removes some files from ``files``.
136
+
137
+ :param directive: The directive to process. This should be in a format
138
+ compatible with distutils ``MANIFEST.in`` files:
139
+
140
+ http://docs.python.org/distutils/sourcedist.html#commands
141
+ """
142
+ # Parse the line: split it up, make sure the right number of words
143
+ # is there, and return the relevant words. 'action' is always
144
+ # defined: it's the first word of the line. Which of the other
145
+ # three are defined depends on the action; it'll be either
146
+ # patterns, (dir and patterns), or (dirpattern).
147
+ action, patterns, thedir, dirpattern = self._parse_directive(directive)
148
+
149
+ # OK, now we know that the action is valid and we have the
150
+ # right number of words on the line for that action -- so we
151
+ # can proceed with minimal error-checking.
152
+ if action == 'include':
153
+ for pattern in patterns:
154
+ if not self._include_pattern(pattern, anchor=True):
155
+ logger.warning('no files found matching %r', pattern)
156
+
157
+ elif action == 'exclude':
158
+ for pattern in patterns:
159
+ self._exclude_pattern(pattern, anchor=True)
160
+
161
+ elif action == 'global-include':
162
+ for pattern in patterns:
163
+ if not self._include_pattern(pattern, anchor=False):
164
+ logger.warning('no files found matching %r '
165
+ 'anywhere in distribution', pattern)
166
+
167
+ elif action == 'global-exclude':
168
+ for pattern in patterns:
169
+ self._exclude_pattern(pattern, anchor=False)
170
+
171
+ elif action == 'recursive-include':
172
+ for pattern in patterns:
173
+ if not self._include_pattern(pattern, prefix=thedir):
174
+ logger.warning('no files found matching %r '
175
+ 'under directory %r', pattern, thedir)
176
+
177
+ elif action == 'recursive-exclude':
178
+ for pattern in patterns:
179
+ self._exclude_pattern(pattern, prefix=thedir)
180
+
181
+ elif action == 'graft':
182
+ if not self._include_pattern(None, prefix=dirpattern):
183
+ logger.warning('no directories found matching %r',
184
+ dirpattern)
185
+
186
+ elif action == 'prune':
187
+ if not self._exclude_pattern(None, prefix=dirpattern):
188
+ logger.warning('no previously-included directories found '
189
+ 'matching %r', dirpattern)
190
+ else: # pragma: no cover
191
+ # This should never happen, as it should be caught in
192
+ # _parse_template_line
193
+ raise DistlibException(
194
+ 'invalid action %r' % action)
195
+
196
+ #
197
+ # Private API
198
+ #
199
+
200
+ def _parse_directive(self, directive):
201
+ """
202
+ Validate a directive.
203
+ :param directive: The directive to validate.
204
+ :return: A tuple of action, patterns, thedir, dir_patterns
205
+ """
206
+ words = directive.split()
207
+ if len(words) == 1 and words[0] not in ('include', 'exclude',
208
+ 'global-include',
209
+ 'global-exclude',
210
+ 'recursive-include',
211
+ 'recursive-exclude',
212
+ 'graft', 'prune'):
213
+ # no action given, let's use the default 'include'
214
+ words.insert(0, 'include')
215
+
216
+ action = words[0]
217
+ patterns = thedir = dir_pattern = None
218
+
219
+ if action in ('include', 'exclude',
220
+ 'global-include', 'global-exclude'):
221
+ if len(words) < 2:
222
+ raise DistlibException(
223
+ '%r expects <pattern1> <pattern2> ...' % action)
224
+
225
+ patterns = [convert_path(word) for word in words[1:]]
226
+
227
+ elif action in ('recursive-include', 'recursive-exclude'):
228
+ if len(words) < 3:
229
+ raise DistlibException(
230
+ '%r expects <dir> <pattern1> <pattern2> ...' % action)
231
+
232
+ thedir = convert_path(words[1])
233
+ patterns = [convert_path(word) for word in words[2:]]
234
+
235
+ elif action in ('graft', 'prune'):
236
+ if len(words) != 2:
237
+ raise DistlibException(
238
+ '%r expects a single <dir_pattern>' % action)
239
+
240
+ dir_pattern = convert_path(words[1])
241
+
242
+ else:
243
+ raise DistlibException('unknown action %r' % action)
244
+
245
+ return action, patterns, thedir, dir_pattern
246
+
247
+ def _include_pattern(self, pattern, anchor=True, prefix=None,
248
+ is_regex=False):
249
+ """Select strings (presumably filenames) from 'self.files' that
250
+ match 'pattern', a Unix-style wildcard (glob) pattern.
251
+
252
+ Patterns are not quite the same as implemented by the 'fnmatch'
253
+ module: '*' and '?' match non-special characters, where "special"
254
+ is platform-dependent: slash on Unix; colon, slash, and backslash on
255
+ DOS/Windows; and colon on Mac OS.
256
+
257
+ If 'anchor' is true (the default), then the pattern match is more
258
+ stringent: "*.py" will match "foo.py" but not "foo/bar.py". If
259
+ 'anchor' is false, both of these will match.
260
+
261
+ If 'prefix' is supplied, then only filenames starting with 'prefix'
262
+ (itself a pattern) and ending with 'pattern', with anything in between
263
+ them, will match. 'anchor' is ignored in this case.
264
+
265
+ If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and
266
+ 'pattern' is assumed to be either a string containing a regex or a
267
+ regex object -- no translation is done, the regex is just compiled
268
+ and used as-is.
269
+
270
+ Selected strings will be added to self.files.
271
+
272
+ Return True if files are found.
273
+ """
274
+ # XXX docstring lying about what the special chars are?
275
+ found = False
276
+ pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex)
277
+
278
+ # delayed loading of allfiles list
279
+ if self.allfiles is None:
280
+ self.findall()
281
+
282
+ for name in self.allfiles:
283
+ if pattern_re.search(name):
284
+ self.files.add(name)
285
+ found = True
286
+ return found
287
+
288
+ def _exclude_pattern(self, pattern, anchor=True, prefix=None,
289
+ is_regex=False):
290
+ """Remove strings (presumably filenames) from 'files' that match
291
+ 'pattern'.
292
+
293
+ Other parameters are the same as for 'include_pattern()', above.
294
+ The list 'self.files' is modified in place. Return True if files are
295
+ found.
296
+
297
+ This API is public to allow e.g. exclusion of SCM subdirs, e.g. when
298
+ packaging source distributions
299
+ """
300
+ found = False
301
+ pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex)
302
+ for f in list(self.files):
303
+ if pattern_re.search(f):
304
+ self.files.remove(f)
305
+ found = True
306
+ return found
307
+
308
+ def _translate_pattern(self, pattern, anchor=True, prefix=None,
309
+ is_regex=False):
310
+ """Translate a shell-like wildcard pattern to a compiled regular
311
+ expression.
312
+
313
+ Return the compiled regex. If 'is_regex' true,
314
+ then 'pattern' is directly compiled to a regex (if it's a string)
315
+ or just returned as-is (assumes it's a regex object).
316
+ """
317
+ if is_regex:
318
+ if isinstance(pattern, str):
319
+ return re.compile(pattern)
320
+ else:
321
+ return pattern
322
+
323
+ if _PYTHON_VERSION > (3, 2):
324
+ # ditch start and end characters
325
+ start, _, end = self._glob_to_re('_').partition('_')
326
+
327
+ if pattern:
328
+ pattern_re = self._glob_to_re(pattern)
329
+ if _PYTHON_VERSION > (3, 2):
330
+ assert pattern_re.startswith(start) and pattern_re.endswith(end)
331
+ else:
332
+ pattern_re = ''
333
+
334
+ base = re.escape(os.path.join(self.base, ''))
335
+ if prefix is not None:
336
+ # ditch end of pattern character
337
+ if _PYTHON_VERSION <= (3, 2):
338
+ empty_pattern = self._glob_to_re('')
339
+ prefix_re = self._glob_to_re(prefix)[:-len(empty_pattern)]
340
+ else:
341
+ prefix_re = self._glob_to_re(prefix)
342
+ assert prefix_re.startswith(start) and prefix_re.endswith(end)
343
+ prefix_re = prefix_re[len(start): len(prefix_re) - len(end)]
344
+ sep = os.sep
345
+ if os.sep == '\\':
346
+ sep = r'\\'
347
+ if _PYTHON_VERSION <= (3, 2):
348
+ pattern_re = '^' + base + sep.join((prefix_re,
349
+ '.*' + pattern_re))
350
+ else:
351
+ pattern_re = pattern_re[len(start): len(pattern_re) - len(end)]
352
+ pattern_re = r'%s%s%s%s.*%s%s' % (start, base, prefix_re, sep,
353
+ pattern_re, end)
354
+ else: # no prefix -- respect anchor flag
355
+ if anchor:
356
+ if _PYTHON_VERSION <= (3, 2):
357
+ pattern_re = '^' + base + pattern_re
358
+ else:
359
+ pattern_re = r'%s%s%s' % (start, base, pattern_re[len(start):])
360
+
361
+ return re.compile(pattern_re)
362
+
363
+ def _glob_to_re(self, pattern):
364
+ """Translate a shell-like glob pattern to a regular expression.
365
+
366
+ Return a string containing the regex. Differs from
367
+ 'fnmatch.translate()' in that '*' does not match "special characters"
368
+ (which are platform-specific).
369
+ """
370
+ pattern_re = fnmatch.translate(pattern)
371
+
372
+ # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which
373
+ # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,
374
+ # and by extension they shouldn't match such "special characters" under
375
+ # any OS. So change all non-escaped dots in the RE to match any
376
+ # character except the special characters (currently: just os.sep).
377
+ sep = os.sep
378
+ if os.sep == '\\':
379
+ # we're using a regex to manipulate a regex, so we need
380
+ # to escape the backslash twice
381
+ sep = r'\\\\'
382
+ escaped = r'\1[^%s]' % sep
383
+ pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re)
384
+ return pattern_re
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/markers.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2012-2023 Vinay Sajip.
4
+ # Licensed to the Python Software Foundation under a contributor agreement.
5
+ # See LICENSE.txt and CONTRIBUTORS.txt.
6
+ #
7
+ """
8
+ Parser for the environment markers micro-language defined in PEP 508.
9
+ """
10
+
11
+ # Note: In PEP 345, the micro-language was Python compatible, so the ast
12
+ # module could be used to parse it. However, PEP 508 introduced operators such
13
+ # as ~= and === which aren't in Python, necessitating a different approach.
14
+
15
+ import os
16
+ import re
17
+ import sys
18
+ import platform
19
+
20
+ from .compat import string_types
21
+ from .util import in_venv, parse_marker
22
+ from .version import LegacyVersion as LV
23
+
24
+ __all__ = ['interpret']
25
+
26
+ _VERSION_PATTERN = re.compile(r'((\d+(\.\d+)*\w*)|\'(\d+(\.\d+)*\w*)\'|\"(\d+(\.\d+)*\w*)\")')
27
+ _VERSION_MARKERS = {'python_version', 'python_full_version'}
28
+
29
+
30
+ def _is_version_marker(s):
31
+ return isinstance(s, string_types) and s in _VERSION_MARKERS
32
+
33
+
34
+ def _is_literal(o):
35
+ if not isinstance(o, string_types) or not o:
36
+ return False
37
+ return o[0] in '\'"'
38
+
39
+
40
+ def _get_versions(s):
41
+ return {LV(m.groups()[0]) for m in _VERSION_PATTERN.finditer(s)}
42
+
43
+
44
+ class Evaluator(object):
45
+ """
46
+ This class is used to evaluate marker expressions.
47
+ """
48
+
49
+ operations = {
50
+ '==': lambda x, y: x == y,
51
+ '===': lambda x, y: x == y,
52
+ '~=': lambda x, y: x == y or x > y,
53
+ '!=': lambda x, y: x != y,
54
+ '<': lambda x, y: x < y,
55
+ '<=': lambda x, y: x == y or x < y,
56
+ '>': lambda x, y: x > y,
57
+ '>=': lambda x, y: x == y or x > y,
58
+ 'and': lambda x, y: x and y,
59
+ 'or': lambda x, y: x or y,
60
+ 'in': lambda x, y: x in y,
61
+ 'not in': lambda x, y: x not in y,
62
+ }
63
+
64
+ def evaluate(self, expr, context):
65
+ """
66
+ Evaluate a marker expression returned by the :func:`parse_requirement`
67
+ function in the specified context.
68
+ """
69
+ if isinstance(expr, string_types):
70
+ if expr[0] in '\'"':
71
+ result = expr[1:-1]
72
+ else:
73
+ if expr not in context:
74
+ raise SyntaxError('unknown variable: %s' % expr)
75
+ result = context[expr]
76
+ else:
77
+ assert isinstance(expr, dict)
78
+ op = expr['op']
79
+ if op not in self.operations:
80
+ raise NotImplementedError('op not implemented: %s' % op)
81
+ elhs = expr['lhs']
82
+ erhs = expr['rhs']
83
+ if _is_literal(expr['lhs']) and _is_literal(expr['rhs']):
84
+ raise SyntaxError('invalid comparison: %s %s %s' % (elhs, op, erhs))
85
+
86
+ lhs = self.evaluate(elhs, context)
87
+ rhs = self.evaluate(erhs, context)
88
+ if ((_is_version_marker(elhs) or _is_version_marker(erhs)) and
89
+ op in ('<', '<=', '>', '>=', '===', '==', '!=', '~=')):
90
+ lhs = LV(lhs)
91
+ rhs = LV(rhs)
92
+ elif _is_version_marker(elhs) and op in ('in', 'not in'):
93
+ lhs = LV(lhs)
94
+ rhs = _get_versions(rhs)
95
+ result = self.operations[op](lhs, rhs)
96
+ return result
97
+
98
+
99
+ _DIGITS = re.compile(r'\d+\.\d+')
100
+
101
+
102
+ def default_context():
103
+
104
+ def format_full_version(info):
105
+ version = '%s.%s.%s' % (info.major, info.minor, info.micro)
106
+ kind = info.releaselevel
107
+ if kind != 'final':
108
+ version += kind[0] + str(info.serial)
109
+ return version
110
+
111
+ if hasattr(sys, 'implementation'):
112
+ implementation_version = format_full_version(sys.implementation.version)
113
+ implementation_name = sys.implementation.name
114
+ else:
115
+ implementation_version = '0'
116
+ implementation_name = ''
117
+
118
+ ppv = platform.python_version()
119
+ m = _DIGITS.match(ppv)
120
+ pv = m.group(0)
121
+ result = {
122
+ 'implementation_name': implementation_name,
123
+ 'implementation_version': implementation_version,
124
+ 'os_name': os.name,
125
+ 'platform_machine': platform.machine(),
126
+ 'platform_python_implementation': platform.python_implementation(),
127
+ 'platform_release': platform.release(),
128
+ 'platform_system': platform.system(),
129
+ 'platform_version': platform.version(),
130
+ 'platform_in_venv': str(in_venv()),
131
+ 'python_full_version': ppv,
132
+ 'python_version': pv,
133
+ 'sys_platform': sys.platform,
134
+ }
135
+ return result
136
+
137
+
138
+ DEFAULT_CONTEXT = default_context()
139
+ del default_context
140
+
141
+ evaluator = Evaluator()
142
+
143
+
144
+ def interpret(marker, execution_context=None):
145
+ """
146
+ Interpret a marker and return a result depending on environment.
147
+
148
+ :param marker: The marker to interpret.
149
+ :type marker: str
150
+ :param execution_context: The context used for name lookup.
151
+ :type execution_context: mapping
152
+ """
153
+ try:
154
+ expr, rest = parse_marker(marker)
155
+ except Exception as e:
156
+ raise SyntaxError('Unable to interpret marker syntax: %s: %s' % (marker, e))
157
+ if rest and rest[0] != '#':
158
+ raise SyntaxError('unexpected trailing data in marker: %s: %s' % (marker, rest))
159
+ context = dict(DEFAULT_CONTEXT)
160
+ if execution_context:
161
+ context.update(execution_context)
162
+ return evaluator.evaluate(expr, context)
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/resources.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2013-2017 Vinay Sajip.
4
+ # Licensed to the Python Software Foundation under a contributor agreement.
5
+ # See LICENSE.txt and CONTRIBUTORS.txt.
6
+ #
7
+ from __future__ import unicode_literals
8
+
9
+ import bisect
10
+ import io
11
+ import logging
12
+ import os
13
+ import pkgutil
14
+ import sys
15
+ import types
16
+ import zipimport
17
+
18
+ from . import DistlibException
19
+ from .util import cached_property, get_cache_base, Cache
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ cache = None # created when needed
25
+
26
+
27
+ class ResourceCache(Cache):
28
+ def __init__(self, base=None):
29
+ if base is None:
30
+ # Use native string to avoid issues on 2.x: see Python #20140.
31
+ base = os.path.join(get_cache_base(), str('resource-cache'))
32
+ super(ResourceCache, self).__init__(base)
33
+
34
+ def is_stale(self, resource, path):
35
+ """
36
+ Is the cache stale for the given resource?
37
+
38
+ :param resource: The :class:`Resource` being cached.
39
+ :param path: The path of the resource in the cache.
40
+ :return: True if the cache is stale.
41
+ """
42
+ # Cache invalidation is a hard problem :-)
43
+ return True
44
+
45
+ def get(self, resource):
46
+ """
47
+ Get a resource into the cache,
48
+
49
+ :param resource: A :class:`Resource` instance.
50
+ :return: The pathname of the resource in the cache.
51
+ """
52
+ prefix, path = resource.finder.get_cache_info(resource)
53
+ if prefix is None:
54
+ result = path
55
+ else:
56
+ result = os.path.join(self.base, self.prefix_to_dir(prefix), path)
57
+ dirname = os.path.dirname(result)
58
+ if not os.path.isdir(dirname):
59
+ os.makedirs(dirname)
60
+ if not os.path.exists(result):
61
+ stale = True
62
+ else:
63
+ stale = self.is_stale(resource, path)
64
+ if stale:
65
+ # write the bytes of the resource to the cache location
66
+ with open(result, 'wb') as f:
67
+ f.write(resource.bytes)
68
+ return result
69
+
70
+
71
+ class ResourceBase(object):
72
+ def __init__(self, finder, name):
73
+ self.finder = finder
74
+ self.name = name
75
+
76
+
77
+ class Resource(ResourceBase):
78
+ """
79
+ A class representing an in-package resource, such as a data file. This is
80
+ not normally instantiated by user code, but rather by a
81
+ :class:`ResourceFinder` which manages the resource.
82
+ """
83
+ is_container = False # Backwards compatibility
84
+
85
+ def as_stream(self):
86
+ """
87
+ Get the resource as a stream.
88
+
89
+ This is not a property to make it obvious that it returns a new stream
90
+ each time.
91
+ """
92
+ return self.finder.get_stream(self)
93
+
94
+ @cached_property
95
+ def file_path(self):
96
+ global cache
97
+ if cache is None:
98
+ cache = ResourceCache()
99
+ return cache.get(self)
100
+
101
+ @cached_property
102
+ def bytes(self):
103
+ return self.finder.get_bytes(self)
104
+
105
+ @cached_property
106
+ def size(self):
107
+ return self.finder.get_size(self)
108
+
109
+
110
+ class ResourceContainer(ResourceBase):
111
+ is_container = True # Backwards compatibility
112
+
113
+ @cached_property
114
+ def resources(self):
115
+ return self.finder.get_resources(self)
116
+
117
+
118
+ class ResourceFinder(object):
119
+ """
120
+ Resource finder for file system resources.
121
+ """
122
+
123
+ if sys.platform.startswith('java'):
124
+ skipped_extensions = ('.pyc', '.pyo', '.class')
125
+ else:
126
+ skipped_extensions = ('.pyc', '.pyo')
127
+
128
+ def __init__(self, module):
129
+ self.module = module
130
+ self.loader = getattr(module, '__loader__', None)
131
+ self.base = os.path.dirname(getattr(module, '__file__', ''))
132
+
133
+ def _adjust_path(self, path):
134
+ return os.path.realpath(path)
135
+
136
+ def _make_path(self, resource_name):
137
+ # Issue #50: need to preserve type of path on Python 2.x
138
+ # like os.path._get_sep
139
+ if isinstance(resource_name, bytes): # should only happen on 2.x
140
+ sep = b'/'
141
+ else:
142
+ sep = '/'
143
+ parts = resource_name.split(sep)
144
+ parts.insert(0, self.base)
145
+ result = os.path.join(*parts)
146
+ return self._adjust_path(result)
147
+
148
+ def _find(self, path):
149
+ return os.path.exists(path)
150
+
151
+ def get_cache_info(self, resource):
152
+ return None, resource.path
153
+
154
+ def find(self, resource_name):
155
+ path = self._make_path(resource_name)
156
+ if not self._find(path):
157
+ result = None
158
+ else:
159
+ if self._is_directory(path):
160
+ result = ResourceContainer(self, resource_name)
161
+ else:
162
+ result = Resource(self, resource_name)
163
+ result.path = path
164
+ return result
165
+
166
+ def get_stream(self, resource):
167
+ return open(resource.path, 'rb')
168
+
169
+ def get_bytes(self, resource):
170
+ with open(resource.path, 'rb') as f:
171
+ return f.read()
172
+
173
+ def get_size(self, resource):
174
+ return os.path.getsize(resource.path)
175
+
176
+ def get_resources(self, resource):
177
+ def allowed(f):
178
+ return (f != '__pycache__' and not
179
+ f.endswith(self.skipped_extensions))
180
+ return set([f for f in os.listdir(resource.path) if allowed(f)])
181
+
182
+ def is_container(self, resource):
183
+ return self._is_directory(resource.path)
184
+
185
+ _is_directory = staticmethod(os.path.isdir)
186
+
187
+ def iterator(self, resource_name):
188
+ resource = self.find(resource_name)
189
+ if resource is not None:
190
+ todo = [resource]
191
+ while todo:
192
+ resource = todo.pop(0)
193
+ yield resource
194
+ if resource.is_container:
195
+ rname = resource.name
196
+ for name in resource.resources:
197
+ if not rname:
198
+ new_name = name
199
+ else:
200
+ new_name = '/'.join([rname, name])
201
+ child = self.find(new_name)
202
+ if child.is_container:
203
+ todo.append(child)
204
+ else:
205
+ yield child
206
+
207
+
208
+ class ZipResourceFinder(ResourceFinder):
209
+ """
210
+ Resource finder for resources in .zip files.
211
+ """
212
+ def __init__(self, module):
213
+ super(ZipResourceFinder, self).__init__(module)
214
+ archive = self.loader.archive
215
+ self.prefix_len = 1 + len(archive)
216
+ # PyPy doesn't have a _files attr on zipimporter, and you can't set one
217
+ if hasattr(self.loader, '_files'):
218
+ self._files = self.loader._files
219
+ else:
220
+ self._files = zipimport._zip_directory_cache[archive]
221
+ self.index = sorted(self._files)
222
+
223
+ def _adjust_path(self, path):
224
+ return path
225
+
226
+ def _find(self, path):
227
+ path = path[self.prefix_len:]
228
+ if path in self._files:
229
+ result = True
230
+ else:
231
+ if path and path[-1] != os.sep:
232
+ path = path + os.sep
233
+ i = bisect.bisect(self.index, path)
234
+ try:
235
+ result = self.index[i].startswith(path)
236
+ except IndexError:
237
+ result = False
238
+ if not result:
239
+ logger.debug('_find failed: %r %r', path, self.loader.prefix)
240
+ else:
241
+ logger.debug('_find worked: %r %r', path, self.loader.prefix)
242
+ return result
243
+
244
+ def get_cache_info(self, resource):
245
+ prefix = self.loader.archive
246
+ path = resource.path[1 + len(prefix):]
247
+ return prefix, path
248
+
249
+ def get_bytes(self, resource):
250
+ return self.loader.get_data(resource.path)
251
+
252
+ def get_stream(self, resource):
253
+ return io.BytesIO(self.get_bytes(resource))
254
+
255
+ def get_size(self, resource):
256
+ path = resource.path[self.prefix_len:]
257
+ return self._files[path][3]
258
+
259
+ def get_resources(self, resource):
260
+ path = resource.path[self.prefix_len:]
261
+ if path and path[-1] != os.sep:
262
+ path += os.sep
263
+ plen = len(path)
264
+ result = set()
265
+ i = bisect.bisect(self.index, path)
266
+ while i < len(self.index):
267
+ if not self.index[i].startswith(path):
268
+ break
269
+ s = self.index[i][plen:]
270
+ result.add(s.split(os.sep, 1)[0]) # only immediate children
271
+ i += 1
272
+ return result
273
+
274
+ def _is_directory(self, path):
275
+ path = path[self.prefix_len:]
276
+ if path and path[-1] != os.sep:
277
+ path += os.sep
278
+ i = bisect.bisect(self.index, path)
279
+ try:
280
+ result = self.index[i].startswith(path)
281
+ except IndexError:
282
+ result = False
283
+ return result
284
+
285
+
286
+ _finder_registry = {
287
+ type(None): ResourceFinder,
288
+ zipimport.zipimporter: ZipResourceFinder
289
+ }
290
+
291
+ try:
292
+ # In Python 3.6, _frozen_importlib -> _frozen_importlib_external
293
+ try:
294
+ import _frozen_importlib_external as _fi
295
+ except ImportError:
296
+ import _frozen_importlib as _fi
297
+ _finder_registry[_fi.SourceFileLoader] = ResourceFinder
298
+ _finder_registry[_fi.FileFinder] = ResourceFinder
299
+ # See issue #146
300
+ _finder_registry[_fi.SourcelessFileLoader] = ResourceFinder
301
+ del _fi
302
+ except (ImportError, AttributeError):
303
+ pass
304
+
305
+
306
+ def register_finder(loader, finder_maker):
307
+ _finder_registry[type(loader)] = finder_maker
308
+
309
+
310
+ _finder_cache = {}
311
+
312
+
313
+ def finder(package):
314
+ """
315
+ Return a resource finder for a package.
316
+ :param package: The name of the package.
317
+ :return: A :class:`ResourceFinder` instance for the package.
318
+ """
319
+ if package in _finder_cache:
320
+ result = _finder_cache[package]
321
+ else:
322
+ if package not in sys.modules:
323
+ __import__(package)
324
+ module = sys.modules[package]
325
+ path = getattr(module, '__path__', None)
326
+ if path is None:
327
+ raise DistlibException('You cannot get a finder for a module, '
328
+ 'only for a package')
329
+ loader = getattr(module, '__loader__', None)
330
+ finder_maker = _finder_registry.get(type(loader))
331
+ if finder_maker is None:
332
+ raise DistlibException('Unable to locate finder for %r' % package)
333
+ result = finder_maker(module)
334
+ _finder_cache[package] = result
335
+ return result
336
+
337
+
338
+ _dummy_module = types.ModuleType(str('__dummy__'))
339
+
340
+
341
+ def finder_for_path(path):
342
+ """
343
+ Return a resource finder for a path, which should represent a container.
344
+
345
+ :param path: The path.
346
+ :return: A :class:`ResourceFinder` instance for the path.
347
+ """
348
+ result = None
349
+ # calls any path hooks, gets importer into cache
350
+ pkgutil.get_importer(path)
351
+ loader = sys.path_importer_cache.get(path)
352
+ finder = _finder_registry.get(type(loader))
353
+ if finder:
354
+ module = _dummy_module
355
+ module.__file__ = os.path.join(path, '')
356
+ module.__loader__ = loader
357
+ result = finder(module)
358
+ return result
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/scripts.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2013-2023 Vinay Sajip.
4
+ # Licensed to the Python Software Foundation under a contributor agreement.
5
+ # See LICENSE.txt and CONTRIBUTORS.txt.
6
+ #
7
+ from io import BytesIO
8
+ import logging
9
+ import os
10
+ import re
11
+ import struct
12
+ import sys
13
+ import time
14
+ from zipfile import ZipInfo
15
+
16
+ from .compat import sysconfig, detect_encoding, ZipFile
17
+ from .resources import finder
18
+ from .util import (FileOperator, get_export_entry, convert_path, get_executable, get_platform, in_venv)
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ _DEFAULT_MANIFEST = '''
23
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
24
+ <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
25
+ <assemblyIdentity version="1.0.0.0"
26
+ processorArchitecture="X86"
27
+ name="%s"
28
+ type="win32"/>
29
+
30
+ <!-- Identify the application security requirements. -->
31
+ <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
32
+ <security>
33
+ <requestedPrivileges>
34
+ <requestedExecutionLevel level="asInvoker" uiAccess="false"/>
35
+ </requestedPrivileges>
36
+ </security>
37
+ </trustInfo>
38
+ </assembly>'''.strip()
39
+
40
+ # check if Python is called on the first line with this expression
41
+ FIRST_LINE_RE = re.compile(b'^#!.*pythonw?[0-9.]*([ \t].*)?$')
42
+ SCRIPT_TEMPLATE = r'''# -*- coding: utf-8 -*-
43
+ import re
44
+ import sys
45
+ from %(module)s import %(import_name)s
46
+ if __name__ == '__main__':
47
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
48
+ sys.exit(%(func)s())
49
+ '''
50
+
51
+ # Pre-fetch the contents of all executable wrapper stubs.
52
+ # This is to address https://github.com/pypa/pip/issues/12666.
53
+ # When updating pip, we rename the old pip in place before installing the
54
+ # new version. If we try to fetch a wrapper *after* that rename, the finder
55
+ # machinery will be confused as the package is no longer available at the
56
+ # location where it was imported from. So we load everything into memory in
57
+ # advance.
58
+
59
+ if os.name == 'nt' or (os.name == 'java' and os._name == 'nt'):
60
+ # Issue 31: don't hardcode an absolute package name, but
61
+ # determine it relative to the current package
62
+ DISTLIB_PACKAGE = __name__.rsplit('.', 1)[0]
63
+
64
+ WRAPPERS = {
65
+ r.name: r.bytes
66
+ for r in finder(DISTLIB_PACKAGE).iterator("")
67
+ if r.name.endswith(".exe")
68
+ }
69
+
70
+
71
+ def enquote_executable(executable):
72
+ if ' ' in executable:
73
+ # make sure we quote only the executable in case of env
74
+ # for example /usr/bin/env "/dir with spaces/bin/jython"
75
+ # instead of "/usr/bin/env /dir with spaces/bin/jython"
76
+ # otherwise whole
77
+ if executable.startswith('/usr/bin/env '):
78
+ env, _executable = executable.split(' ', 1)
79
+ if ' ' in _executable and not _executable.startswith('"'):
80
+ executable = '%s "%s"' % (env, _executable)
81
+ else:
82
+ if not executable.startswith('"'):
83
+ executable = '"%s"' % executable
84
+ return executable
85
+
86
+
87
+ # Keep the old name around (for now), as there is at least one project using it!
88
+ _enquote_executable = enquote_executable
89
+
90
+
91
+ class ScriptMaker(object):
92
+ """
93
+ A class to copy or create scripts from source scripts or callable
94
+ specifications.
95
+ """
96
+ script_template = SCRIPT_TEMPLATE
97
+
98
+ executable = None # for shebangs
99
+
100
+ def __init__(self, source_dir, target_dir, add_launchers=True, dry_run=False, fileop=None):
101
+ self.source_dir = source_dir
102
+ self.target_dir = target_dir
103
+ self.add_launchers = add_launchers
104
+ self.force = False
105
+ self.clobber = False
106
+ # It only makes sense to set mode bits on POSIX.
107
+ self.set_mode = (os.name == 'posix') or (os.name == 'java' and os._name == 'posix')
108
+ self.variants = set(('', 'X.Y'))
109
+ self._fileop = fileop or FileOperator(dry_run)
110
+
111
+ self._is_nt = os.name == 'nt' or (os.name == 'java' and os._name == 'nt')
112
+ self.version_info = sys.version_info
113
+
114
+ def _get_alternate_executable(self, executable, options):
115
+ if options.get('gui', False) and self._is_nt: # pragma: no cover
116
+ dn, fn = os.path.split(executable)
117
+ fn = fn.replace('python', 'pythonw')
118
+ executable = os.path.join(dn, fn)
119
+ return executable
120
+
121
+ if sys.platform.startswith('java'): # pragma: no cover
122
+
123
+ def _is_shell(self, executable):
124
+ """
125
+ Determine if the specified executable is a script
126
+ (contains a #! line)
127
+ """
128
+ try:
129
+ with open(executable) as fp:
130
+ return fp.read(2) == '#!'
131
+ except (OSError, IOError):
132
+ logger.warning('Failed to open %s', executable)
133
+ return False
134
+
135
+ def _fix_jython_executable(self, executable):
136
+ if self._is_shell(executable):
137
+ # Workaround for Jython is not needed on Linux systems.
138
+ import java
139
+
140
+ if java.lang.System.getProperty('os.name') == 'Linux':
141
+ return executable
142
+ elif executable.lower().endswith('jython.exe'):
143
+ # Use wrapper exe for Jython on Windows
144
+ return executable
145
+ return '/usr/bin/env %s' % executable
146
+
147
+ def _build_shebang(self, executable, post_interp):
148
+ """
149
+ Build a shebang line. In the simple case (on Windows, or a shebang line
150
+ which is not too long or contains spaces) use a simple formulation for
151
+ the shebang. Otherwise, use /bin/sh as the executable, with a contrived
152
+ shebang which allows the script to run either under Python or sh, using
153
+ suitable quoting. Thanks to Harald Nordgren for his input.
154
+
155
+ See also: http://www.in-ulm.de/~mascheck/various/shebang/#length
156
+ https://hg.mozilla.org/mozilla-central/file/tip/mach
157
+ """
158
+ if os.name != 'posix':
159
+ simple_shebang = True
160
+ elif getattr(sys, "cross_compiling", False):
161
+ # In a cross-compiling environment, the shebang will likely be a
162
+ # script; this *must* be invoked with the "safe" version of the
163
+ # shebang, or else using os.exec() to run the entry script will
164
+ # fail, raising "OSError 8 [Errno 8] Exec format error".
165
+ simple_shebang = False
166
+ else:
167
+ # Add 3 for '#!' prefix and newline suffix.
168
+ shebang_length = len(executable) + len(post_interp) + 3
169
+ if sys.platform == 'darwin':
170
+ max_shebang_length = 512
171
+ else:
172
+ max_shebang_length = 127
173
+ simple_shebang = ((b' ' not in executable) and (shebang_length <= max_shebang_length))
174
+
175
+ if simple_shebang:
176
+ result = b'#!' + executable + post_interp + b'\n'
177
+ else:
178
+ result = b'#!/bin/sh\n'
179
+ result += b"'''exec' " + executable + post_interp + b' "$0" "$@"\n'
180
+ result += b"' '''\n"
181
+ return result
182
+
183
+ def _get_shebang(self, encoding, post_interp=b'', options=None):
184
+ enquote = True
185
+ if self.executable:
186
+ executable = self.executable
187
+ enquote = False # assume this will be taken care of
188
+ elif not sysconfig.is_python_build():
189
+ executable = get_executable()
190
+ elif in_venv(): # pragma: no cover
191
+ executable = os.path.join(sysconfig.get_path('scripts'), 'python%s' % sysconfig.get_config_var('EXE'))
192
+ else: # pragma: no cover
193
+ if os.name == 'nt':
194
+ # for Python builds from source on Windows, no Python executables with
195
+ # a version suffix are created, so we use python.exe
196
+ executable = os.path.join(sysconfig.get_config_var('BINDIR'),
197
+ 'python%s' % (sysconfig.get_config_var('EXE')))
198
+ else:
199
+ executable = os.path.join(
200
+ sysconfig.get_config_var('BINDIR'),
201
+ 'python%s%s' % (sysconfig.get_config_var('VERSION'), sysconfig.get_config_var('EXE')))
202
+ if options:
203
+ executable = self._get_alternate_executable(executable, options)
204
+
205
+ if sys.platform.startswith('java'): # pragma: no cover
206
+ executable = self._fix_jython_executable(executable)
207
+
208
+ # Normalise case for Windows - COMMENTED OUT
209
+ # executable = os.path.normcase(executable)
210
+ # N.B. The normalising operation above has been commented out: See
211
+ # issue #124. Although paths in Windows are generally case-insensitive,
212
+ # they aren't always. For example, a path containing a ẞ (which is a
213
+ # LATIN CAPITAL LETTER SHARP S - U+1E9E) is normcased to ß (which is a
214
+ # LATIN SMALL LETTER SHARP S' - U+00DF). The two are not considered by
215
+ # Windows as equivalent in path names.
216
+
217
+ # If the user didn't specify an executable, it may be necessary to
218
+ # cater for executable paths with spaces (not uncommon on Windows)
219
+ if enquote:
220
+ executable = enquote_executable(executable)
221
+ # Issue #51: don't use fsencode, since we later try to
222
+ # check that the shebang is decodable using utf-8.
223
+ executable = executable.encode('utf-8')
224
+ # in case of IronPython, play safe and enable frames support
225
+ if (sys.platform == 'cli' and '-X:Frames' not in post_interp and
226
+ '-X:FullFrames' not in post_interp): # pragma: no cover
227
+ post_interp += b' -X:Frames'
228
+ shebang = self._build_shebang(executable, post_interp)
229
+ # Python parser starts to read a script using UTF-8 until
230
+ # it gets a #coding:xxx cookie. The shebang has to be the
231
+ # first line of a file, the #coding:xxx cookie cannot be
232
+ # written before. So the shebang has to be decodable from
233
+ # UTF-8.
234
+ try:
235
+ shebang.decode('utf-8')
236
+ except UnicodeDecodeError: # pragma: no cover
237
+ raise ValueError('The shebang (%r) is not decodable from utf-8' % shebang)
238
+ # If the script is encoded to a custom encoding (use a
239
+ # #coding:xxx cookie), the shebang has to be decodable from
240
+ # the script encoding too.
241
+ if encoding != 'utf-8':
242
+ try:
243
+ shebang.decode(encoding)
244
+ except UnicodeDecodeError: # pragma: no cover
245
+ raise ValueError('The shebang (%r) is not decodable '
246
+ 'from the script encoding (%r)' % (shebang, encoding))
247
+ return shebang
248
+
249
+ def _get_script_text(self, entry):
250
+ return self.script_template % dict(
251
+ module=entry.prefix, import_name=entry.suffix.split('.')[0], func=entry.suffix)
252
+
253
+ manifest = _DEFAULT_MANIFEST
254
+
255
+ def get_manifest(self, exename):
256
+ base = os.path.basename(exename)
257
+ return self.manifest % base
258
+
259
+ def _write_script(self, names, shebang, script_bytes, filenames, ext):
260
+ use_launcher = self.add_launchers and self._is_nt
261
+ if not use_launcher:
262
+ script_bytes = shebang + script_bytes
263
+ else: # pragma: no cover
264
+ if ext == 'py':
265
+ launcher = self._get_launcher('t')
266
+ else:
267
+ launcher = self._get_launcher('w')
268
+ stream = BytesIO()
269
+ with ZipFile(stream, 'w') as zf:
270
+ source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH')
271
+ if source_date_epoch:
272
+ date_time = time.gmtime(int(source_date_epoch))[:6]
273
+ zinfo = ZipInfo(filename='__main__.py', date_time=date_time)
274
+ zf.writestr(zinfo, script_bytes)
275
+ else:
276
+ zf.writestr('__main__.py', script_bytes)
277
+ zip_data = stream.getvalue()
278
+ script_bytes = launcher + shebang + zip_data
279
+ for name in names:
280
+ outname = os.path.join(self.target_dir, name)
281
+ if use_launcher: # pragma: no cover
282
+ n, e = os.path.splitext(outname)
283
+ if e.startswith('.py'):
284
+ outname = n
285
+ outname = '%s.exe' % outname
286
+ try:
287
+ self._fileop.write_binary_file(outname, script_bytes)
288
+ except Exception:
289
+ # Failed writing an executable - it might be in use.
290
+ logger.warning('Failed to write executable - trying to '
291
+ 'use .deleteme logic')
292
+ dfname = '%s.deleteme' % outname
293
+ if os.path.exists(dfname):
294
+ os.remove(dfname) # Not allowed to fail here
295
+ os.rename(outname, dfname) # nor here
296
+ self._fileop.write_binary_file(outname, script_bytes)
297
+ logger.debug('Able to replace executable using '
298
+ '.deleteme logic')
299
+ try:
300
+ os.remove(dfname)
301
+ except Exception:
302
+ pass # still in use - ignore error
303
+ else:
304
+ if self._is_nt and not outname.endswith('.' + ext): # pragma: no cover
305
+ outname = '%s.%s' % (outname, ext)
306
+ if os.path.exists(outname) and not self.clobber:
307
+ logger.warning('Skipping existing file %s', outname)
308
+ continue
309
+ self._fileop.write_binary_file(outname, script_bytes)
310
+ if self.set_mode:
311
+ self._fileop.set_executable_mode([outname])
312
+ filenames.append(outname)
313
+
314
+ variant_separator = '-'
315
+
316
+ def get_script_filenames(self, name):
317
+ result = set()
318
+ if '' in self.variants:
319
+ result.add(name)
320
+ if 'X' in self.variants:
321
+ result.add('%s%s' % (name, self.version_info[0]))
322
+ if 'X.Y' in self.variants:
323
+ result.add('%s%s%s.%s' % (name, self.variant_separator, self.version_info[0], self.version_info[1]))
324
+ return result
325
+
326
+ def _make_script(self, entry, filenames, options=None):
327
+ post_interp = b''
328
+ if options:
329
+ args = options.get('interpreter_args', [])
330
+ if args:
331
+ args = ' %s' % ' '.join(args)
332
+ post_interp = args.encode('utf-8')
333
+ shebang = self._get_shebang('utf-8', post_interp, options=options)
334
+ script = self._get_script_text(entry).encode('utf-8')
335
+ scriptnames = self.get_script_filenames(entry.name)
336
+ if options and options.get('gui', False):
337
+ ext = 'pyw'
338
+ else:
339
+ ext = 'py'
340
+ self._write_script(scriptnames, shebang, script, filenames, ext)
341
+
342
+ def _copy_script(self, script, filenames):
343
+ adjust = False
344
+ script = os.path.join(self.source_dir, convert_path(script))
345
+ outname = os.path.join(self.target_dir, os.path.basename(script))
346
+ if not self.force and not self._fileop.newer(script, outname):
347
+ logger.debug('not copying %s (up-to-date)', script)
348
+ return
349
+
350
+ # Always open the file, but ignore failures in dry-run mode --
351
+ # that way, we'll get accurate feedback if we can read the
352
+ # script.
353
+ try:
354
+ f = open(script, 'rb')
355
+ except IOError: # pragma: no cover
356
+ if not self.dry_run:
357
+ raise
358
+ f = None
359
+ else:
360
+ first_line = f.readline()
361
+ if not first_line: # pragma: no cover
362
+ logger.warning('%s is an empty file (skipping)', script)
363
+ return
364
+
365
+ match = FIRST_LINE_RE.match(first_line.replace(b'\r\n', b'\n'))
366
+ if match:
367
+ adjust = True
368
+ post_interp = match.group(1) or b''
369
+
370
+ if not adjust:
371
+ if f:
372
+ f.close()
373
+ self._fileop.copy_file(script, outname)
374
+ if self.set_mode:
375
+ self._fileop.set_executable_mode([outname])
376
+ filenames.append(outname)
377
+ else:
378
+ logger.info('copying and adjusting %s -> %s', script, self.target_dir)
379
+ if not self._fileop.dry_run:
380
+ encoding, lines = detect_encoding(f.readline)
381
+ f.seek(0)
382
+ shebang = self._get_shebang(encoding, post_interp)
383
+ if b'pythonw' in first_line: # pragma: no cover
384
+ ext = 'pyw'
385
+ else:
386
+ ext = 'py'
387
+ n = os.path.basename(outname)
388
+ self._write_script([n], shebang, f.read(), filenames, ext)
389
+ if f:
390
+ f.close()
391
+
392
+ @property
393
+ def dry_run(self):
394
+ return self._fileop.dry_run
395
+
396
+ @dry_run.setter
397
+ def dry_run(self, value):
398
+ self._fileop.dry_run = value
399
+
400
+ if os.name == 'nt' or (os.name == 'java' and os._name == 'nt'): # pragma: no cover
401
+ # Executable launcher support.
402
+ # Launchers are from https://bitbucket.org/vinay.sajip/simple_launcher/
403
+
404
+ def _get_launcher(self, kind):
405
+ if struct.calcsize('P') == 8: # 64-bit
406
+ bits = '64'
407
+ else:
408
+ bits = '32'
409
+ platform_suffix = '-arm' if get_platform() == 'win-arm64' else ''
410
+ name = '%s%s%s.exe' % (kind, bits, platform_suffix)
411
+ if name not in WRAPPERS:
412
+ msg = ('Unable to find resource %s in package %s' %
413
+ (name, DISTLIB_PACKAGE))
414
+ raise ValueError(msg)
415
+ return WRAPPERS[name]
416
+
417
+ # Public API follows
418
+
419
+ def make(self, specification, options=None):
420
+ """
421
+ Make a script.
422
+
423
+ :param specification: The specification, which is either a valid export
424
+ entry specification (to make a script from a
425
+ callable) or a filename (to make a script by
426
+ copying from a source location).
427
+ :param options: A dictionary of options controlling script generation.
428
+ :return: A list of all absolute pathnames written to.
429
+ """
430
+ filenames = []
431
+ entry = get_export_entry(specification)
432
+ if entry is None:
433
+ self._copy_script(specification, filenames)
434
+ else:
435
+ self._make_script(entry, filenames, options=options)
436
+ return filenames
437
+
438
+ def make_multiple(self, specifications, options=None):
439
+ """
440
+ Take a list of specifications and make scripts from them,
441
+ :param specifications: A list of specifications.
442
+ :return: A list of all absolute pathnames written to,
443
+ """
444
+ filenames = []
445
+ for specification in specifications:
446
+ filenames.extend(self.make(specification, options))
447
+ return filenames
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/util.py ADDED
@@ -0,0 +1,1984 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2012-2023 The Python Software Foundation.
3
+ # See LICENSE.txt and CONTRIBUTORS.txt.
4
+ #
5
+ import codecs
6
+ from collections import deque
7
+ import contextlib
8
+ import csv
9
+ from glob import iglob as std_iglob
10
+ import io
11
+ import json
12
+ import logging
13
+ import os
14
+ import py_compile
15
+ import re
16
+ import socket
17
+ try:
18
+ import ssl
19
+ except ImportError: # pragma: no cover
20
+ ssl = None
21
+ import subprocess
22
+ import sys
23
+ import tarfile
24
+ import tempfile
25
+ import textwrap
26
+
27
+ try:
28
+ import threading
29
+ except ImportError: # pragma: no cover
30
+ import dummy_threading as threading
31
+ import time
32
+
33
+ from . import DistlibException
34
+ from .compat import (string_types, text_type, shutil, raw_input, StringIO, cache_from_source, urlopen, urljoin, httplib,
35
+ xmlrpclib, HTTPHandler, BaseConfigurator, valid_ident, Container, configparser, URLError, ZipFile,
36
+ fsdecode, unquote, urlparse)
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+ #
41
+ # Requirement parsing code as per PEP 508
42
+ #
43
+
44
+ IDENTIFIER = re.compile(r'^([\w\.-]+)\s*')
45
+ VERSION_IDENTIFIER = re.compile(r'^([\w\.*+-]+)\s*')
46
+ COMPARE_OP = re.compile(r'^(<=?|>=?|={2,3}|[~!]=)\s*')
47
+ MARKER_OP = re.compile(r'^((<=?)|(>=?)|={2,3}|[~!]=|in|not\s+in)\s*')
48
+ OR = re.compile(r'^or\b\s*')
49
+ AND = re.compile(r'^and\b\s*')
50
+ NON_SPACE = re.compile(r'(\S+)\s*')
51
+ STRING_CHUNK = re.compile(r'([\s\w\.{}()*+#:;,/?!~`@$%^&=|<>\[\]-]+)')
52
+
53
+
54
+ def parse_marker(marker_string):
55
+ """
56
+ Parse a marker string and return a dictionary containing a marker expression.
57
+
58
+ The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in
59
+ the expression grammar, or strings. A string contained in quotes is to be
60
+ interpreted as a literal string, and a string not contained in quotes is a
61
+ variable (such as os_name).
62
+ """
63
+
64
+ def marker_var(remaining):
65
+ # either identifier, or literal string
66
+ m = IDENTIFIER.match(remaining)
67
+ if m:
68
+ result = m.groups()[0]
69
+ remaining = remaining[m.end():]
70
+ elif not remaining:
71
+ raise SyntaxError('unexpected end of input')
72
+ else:
73
+ q = remaining[0]
74
+ if q not in '\'"':
75
+ raise SyntaxError('invalid expression: %s' % remaining)
76
+ oq = '\'"'.replace(q, '')
77
+ remaining = remaining[1:]
78
+ parts = [q]
79
+ while remaining:
80
+ # either a string chunk, or oq, or q to terminate
81
+ if remaining[0] == q:
82
+ break
83
+ elif remaining[0] == oq:
84
+ parts.append(oq)
85
+ remaining = remaining[1:]
86
+ else:
87
+ m = STRING_CHUNK.match(remaining)
88
+ if not m:
89
+ raise SyntaxError('error in string literal: %s' % remaining)
90
+ parts.append(m.groups()[0])
91
+ remaining = remaining[m.end():]
92
+ else:
93
+ s = ''.join(parts)
94
+ raise SyntaxError('unterminated string: %s' % s)
95
+ parts.append(q)
96
+ result = ''.join(parts)
97
+ remaining = remaining[1:].lstrip() # skip past closing quote
98
+ return result, remaining
99
+
100
+ def marker_expr(remaining):
101
+ if remaining and remaining[0] == '(':
102
+ result, remaining = marker(remaining[1:].lstrip())
103
+ if remaining[0] != ')':
104
+ raise SyntaxError('unterminated parenthesis: %s' % remaining)
105
+ remaining = remaining[1:].lstrip()
106
+ else:
107
+ lhs, remaining = marker_var(remaining)
108
+ while remaining:
109
+ m = MARKER_OP.match(remaining)
110
+ if not m:
111
+ break
112
+ op = m.groups()[0]
113
+ remaining = remaining[m.end():]
114
+ rhs, remaining = marker_var(remaining)
115
+ lhs = {'op': op, 'lhs': lhs, 'rhs': rhs}
116
+ result = lhs
117
+ return result, remaining
118
+
119
+ def marker_and(remaining):
120
+ lhs, remaining = marker_expr(remaining)
121
+ while remaining:
122
+ m = AND.match(remaining)
123
+ if not m:
124
+ break
125
+ remaining = remaining[m.end():]
126
+ rhs, remaining = marker_expr(remaining)
127
+ lhs = {'op': 'and', 'lhs': lhs, 'rhs': rhs}
128
+ return lhs, remaining
129
+
130
+ def marker(remaining):
131
+ lhs, remaining = marker_and(remaining)
132
+ while remaining:
133
+ m = OR.match(remaining)
134
+ if not m:
135
+ break
136
+ remaining = remaining[m.end():]
137
+ rhs, remaining = marker_and(remaining)
138
+ lhs = {'op': 'or', 'lhs': lhs, 'rhs': rhs}
139
+ return lhs, remaining
140
+
141
+ return marker(marker_string)
142
+
143
+
144
+ def parse_requirement(req):
145
+ """
146
+ Parse a requirement passed in as a string. Return a Container
147
+ whose attributes contain the various parts of the requirement.
148
+ """
149
+ remaining = req.strip()
150
+ if not remaining or remaining.startswith('#'):
151
+ return None
152
+ m = IDENTIFIER.match(remaining)
153
+ if not m:
154
+ raise SyntaxError('name expected: %s' % remaining)
155
+ distname = m.groups()[0]
156
+ remaining = remaining[m.end():]
157
+ extras = mark_expr = versions = uri = None
158
+ if remaining and remaining[0] == '[':
159
+ i = remaining.find(']', 1)
160
+ if i < 0:
161
+ raise SyntaxError('unterminated extra: %s' % remaining)
162
+ s = remaining[1:i]
163
+ remaining = remaining[i + 1:].lstrip()
164
+ extras = []
165
+ while s:
166
+ m = IDENTIFIER.match(s)
167
+ if not m:
168
+ raise SyntaxError('malformed extra: %s' % s)
169
+ extras.append(m.groups()[0])
170
+ s = s[m.end():]
171
+ if not s:
172
+ break
173
+ if s[0] != ',':
174
+ raise SyntaxError('comma expected in extras: %s' % s)
175
+ s = s[1:].lstrip()
176
+ if not extras:
177
+ extras = None
178
+ if remaining:
179
+ if remaining[0] == '@':
180
+ # it's a URI
181
+ remaining = remaining[1:].lstrip()
182
+ m = NON_SPACE.match(remaining)
183
+ if not m:
184
+ raise SyntaxError('invalid URI: %s' % remaining)
185
+ uri = m.groups()[0]
186
+ t = urlparse(uri)
187
+ # there are issues with Python and URL parsing, so this test
188
+ # is a bit crude. See bpo-20271, bpo-23505. Python doesn't
189
+ # always parse invalid URLs correctly - it should raise
190
+ # exceptions for malformed URLs
191
+ if not (t.scheme and t.netloc):
192
+ raise SyntaxError('Invalid URL: %s' % uri)
193
+ remaining = remaining[m.end():].lstrip()
194
+ else:
195
+
196
+ def get_versions(ver_remaining):
197
+ """
198
+ Return a list of operator, version tuples if any are
199
+ specified, else None.
200
+ """
201
+ m = COMPARE_OP.match(ver_remaining)
202
+ versions = None
203
+ if m:
204
+ versions = []
205
+ while True:
206
+ op = m.groups()[0]
207
+ ver_remaining = ver_remaining[m.end():]
208
+ m = VERSION_IDENTIFIER.match(ver_remaining)
209
+ if not m:
210
+ raise SyntaxError('invalid version: %s' % ver_remaining)
211
+ v = m.groups()[0]
212
+ versions.append((op, v))
213
+ ver_remaining = ver_remaining[m.end():]
214
+ if not ver_remaining or ver_remaining[0] != ',':
215
+ break
216
+ ver_remaining = ver_remaining[1:].lstrip()
217
+ # Some packages have a trailing comma which would break things
218
+ # See issue #148
219
+ if not ver_remaining:
220
+ break
221
+ m = COMPARE_OP.match(ver_remaining)
222
+ if not m:
223
+ raise SyntaxError('invalid constraint: %s' % ver_remaining)
224
+ if not versions:
225
+ versions = None
226
+ return versions, ver_remaining
227
+
228
+ if remaining[0] != '(':
229
+ versions, remaining = get_versions(remaining)
230
+ else:
231
+ i = remaining.find(')', 1)
232
+ if i < 0:
233
+ raise SyntaxError('unterminated parenthesis: %s' % remaining)
234
+ s = remaining[1:i]
235
+ remaining = remaining[i + 1:].lstrip()
236
+ # As a special diversion from PEP 508, allow a version number
237
+ # a.b.c in parentheses as a synonym for ~= a.b.c (because this
238
+ # is allowed in earlier PEPs)
239
+ if COMPARE_OP.match(s):
240
+ versions, _ = get_versions(s)
241
+ else:
242
+ m = VERSION_IDENTIFIER.match(s)
243
+ if not m:
244
+ raise SyntaxError('invalid constraint: %s' % s)
245
+ v = m.groups()[0]
246
+ s = s[m.end():].lstrip()
247
+ if s:
248
+ raise SyntaxError('invalid constraint: %s' % s)
249
+ versions = [('~=', v)]
250
+
251
+ if remaining:
252
+ if remaining[0] != ';':
253
+ raise SyntaxError('invalid requirement: %s' % remaining)
254
+ remaining = remaining[1:].lstrip()
255
+
256
+ mark_expr, remaining = parse_marker(remaining)
257
+
258
+ if remaining and remaining[0] != '#':
259
+ raise SyntaxError('unexpected trailing data: %s' % remaining)
260
+
261
+ if not versions:
262
+ rs = distname
263
+ else:
264
+ rs = '%s %s' % (distname, ', '.join(['%s %s' % con for con in versions]))
265
+ return Container(name=distname, extras=extras, constraints=versions, marker=mark_expr, url=uri, requirement=rs)
266
+
267
+
268
+ def get_resources_dests(resources_root, rules):
269
+ """Find destinations for resources files"""
270
+
271
+ def get_rel_path(root, path):
272
+ # normalizes and returns a lstripped-/-separated path
273
+ root = root.replace(os.path.sep, '/')
274
+ path = path.replace(os.path.sep, '/')
275
+ assert path.startswith(root)
276
+ return path[len(root):].lstrip('/')
277
+
278
+ destinations = {}
279
+ for base, suffix, dest in rules:
280
+ prefix = os.path.join(resources_root, base)
281
+ for abs_base in iglob(prefix):
282
+ abs_glob = os.path.join(abs_base, suffix)
283
+ for abs_path in iglob(abs_glob):
284
+ resource_file = get_rel_path(resources_root, abs_path)
285
+ if dest is None: # remove the entry if it was here
286
+ destinations.pop(resource_file, None)
287
+ else:
288
+ rel_path = get_rel_path(abs_base, abs_path)
289
+ rel_dest = dest.replace(os.path.sep, '/').rstrip('/')
290
+ destinations[resource_file] = rel_dest + '/' + rel_path
291
+ return destinations
292
+
293
+
294
+ def in_venv():
295
+ if hasattr(sys, 'real_prefix'):
296
+ # virtualenv venvs
297
+ result = True
298
+ else:
299
+ # PEP 405 venvs
300
+ result = sys.prefix != getattr(sys, 'base_prefix', sys.prefix)
301
+ return result
302
+
303
+
304
+ def get_executable():
305
+ # The __PYVENV_LAUNCHER__ dance is apparently no longer needed, as
306
+ # changes to the stub launcher mean that sys.executable always points
307
+ # to the stub on OS X
308
+ # if sys.platform == 'darwin' and ('__PYVENV_LAUNCHER__'
309
+ # in os.environ):
310
+ # result = os.environ['__PYVENV_LAUNCHER__']
311
+ # else:
312
+ # result = sys.executable
313
+ # return result
314
+ # Avoid normcasing: see issue #143
315
+ # result = os.path.normcase(sys.executable)
316
+ result = sys.executable
317
+ if not isinstance(result, text_type):
318
+ result = fsdecode(result)
319
+ return result
320
+
321
+
322
+ def proceed(prompt, allowed_chars, error_prompt=None, default=None):
323
+ p = prompt
324
+ while True:
325
+ s = raw_input(p)
326
+ p = prompt
327
+ if not s and default:
328
+ s = default
329
+ if s:
330
+ c = s[0].lower()
331
+ if c in allowed_chars:
332
+ break
333
+ if error_prompt:
334
+ p = '%c: %s\n%s' % (c, error_prompt, prompt)
335
+ return c
336
+
337
+
338
+ def extract_by_key(d, keys):
339
+ if isinstance(keys, string_types):
340
+ keys = keys.split()
341
+ result = {}
342
+ for key in keys:
343
+ if key in d:
344
+ result[key] = d[key]
345
+ return result
346
+
347
+
348
+ def read_exports(stream):
349
+ if sys.version_info[0] >= 3:
350
+ # needs to be a text stream
351
+ stream = codecs.getreader('utf-8')(stream)
352
+ # Try to load as JSON, falling back on legacy format
353
+ data = stream.read()
354
+ stream = StringIO(data)
355
+ try:
356
+ jdata = json.load(stream)
357
+ result = jdata['extensions']['python.exports']['exports']
358
+ for group, entries in result.items():
359
+ for k, v in entries.items():
360
+ s = '%s = %s' % (k, v)
361
+ entry = get_export_entry(s)
362
+ assert entry is not None
363
+ entries[k] = entry
364
+ return result
365
+ except Exception:
366
+ stream.seek(0, 0)
367
+
368
+ def read_stream(cp, stream):
369
+ if hasattr(cp, 'read_file'):
370
+ cp.read_file(stream)
371
+ else:
372
+ cp.readfp(stream)
373
+
374
+ cp = configparser.ConfigParser()
375
+ try:
376
+ read_stream(cp, stream)
377
+ except configparser.MissingSectionHeaderError:
378
+ stream.close()
379
+ data = textwrap.dedent(data)
380
+ stream = StringIO(data)
381
+ read_stream(cp, stream)
382
+
383
+ result = {}
384
+ for key in cp.sections():
385
+ result[key] = entries = {}
386
+ for name, value in cp.items(key):
387
+ s = '%s = %s' % (name, value)
388
+ entry = get_export_entry(s)
389
+ assert entry is not None
390
+ # entry.dist = self
391
+ entries[name] = entry
392
+ return result
393
+
394
+
395
+ def write_exports(exports, stream):
396
+ if sys.version_info[0] >= 3:
397
+ # needs to be a text stream
398
+ stream = codecs.getwriter('utf-8')(stream)
399
+ cp = configparser.ConfigParser()
400
+ for k, v in exports.items():
401
+ # TODO check k, v for valid values
402
+ cp.add_section(k)
403
+ for entry in v.values():
404
+ if entry.suffix is None:
405
+ s = entry.prefix
406
+ else:
407
+ s = '%s:%s' % (entry.prefix, entry.suffix)
408
+ if entry.flags:
409
+ s = '%s [%s]' % (s, ', '.join(entry.flags))
410
+ cp.set(k, entry.name, s)
411
+ cp.write(stream)
412
+
413
+
414
+ @contextlib.contextmanager
415
+ def tempdir():
416
+ td = tempfile.mkdtemp()
417
+ try:
418
+ yield td
419
+ finally:
420
+ shutil.rmtree(td)
421
+
422
+
423
+ @contextlib.contextmanager
424
+ def chdir(d):
425
+ cwd = os.getcwd()
426
+ try:
427
+ os.chdir(d)
428
+ yield
429
+ finally:
430
+ os.chdir(cwd)
431
+
432
+
433
+ @contextlib.contextmanager
434
+ def socket_timeout(seconds=15):
435
+ cto = socket.getdefaulttimeout()
436
+ try:
437
+ socket.setdefaulttimeout(seconds)
438
+ yield
439
+ finally:
440
+ socket.setdefaulttimeout(cto)
441
+
442
+
443
+ class cached_property(object):
444
+
445
+ def __init__(self, func):
446
+ self.func = func
447
+ # for attr in ('__name__', '__module__', '__doc__'):
448
+ # setattr(self, attr, getattr(func, attr, None))
449
+
450
+ def __get__(self, obj, cls=None):
451
+ if obj is None:
452
+ return self
453
+ value = self.func(obj)
454
+ object.__setattr__(obj, self.func.__name__, value)
455
+ # obj.__dict__[self.func.__name__] = value = self.func(obj)
456
+ return value
457
+
458
+
459
+ def convert_path(pathname):
460
+ """Return 'pathname' as a name that will work on the native filesystem.
461
+
462
+ The path is split on '/' and put back together again using the current
463
+ directory separator. Needed because filenames in the setup script are
464
+ always supplied in Unix style, and have to be converted to the local
465
+ convention before we can actually use them in the filesystem. Raises
466
+ ValueError on non-Unix-ish systems if 'pathname' either starts or
467
+ ends with a slash.
468
+ """
469
+ if os.sep == '/':
470
+ return pathname
471
+ if not pathname:
472
+ return pathname
473
+ if pathname[0] == '/':
474
+ raise ValueError("path '%s' cannot be absolute" % pathname)
475
+ if pathname[-1] == '/':
476
+ raise ValueError("path '%s' cannot end with '/'" % pathname)
477
+
478
+ paths = pathname.split('/')
479
+ while os.curdir in paths:
480
+ paths.remove(os.curdir)
481
+ if not paths:
482
+ return os.curdir
483
+ return os.path.join(*paths)
484
+
485
+
486
+ class FileOperator(object):
487
+
488
+ def __init__(self, dry_run=False):
489
+ self.dry_run = dry_run
490
+ self.ensured = set()
491
+ self._init_record()
492
+
493
+ def _init_record(self):
494
+ self.record = False
495
+ self.files_written = set()
496
+ self.dirs_created = set()
497
+
498
+ def record_as_written(self, path):
499
+ if self.record:
500
+ self.files_written.add(path)
501
+
502
+ def newer(self, source, target):
503
+ """Tell if the target is newer than the source.
504
+
505
+ Returns true if 'source' exists and is more recently modified than
506
+ 'target', or if 'source' exists and 'target' doesn't.
507
+
508
+ Returns false if both exist and 'target' is the same age or younger
509
+ than 'source'. Raise PackagingFileError if 'source' does not exist.
510
+
511
+ Note that this test is not very accurate: files created in the same
512
+ second will have the same "age".
513
+ """
514
+ if not os.path.exists(source):
515
+ raise DistlibException("file '%r' does not exist" % os.path.abspath(source))
516
+ if not os.path.exists(target):
517
+ return True
518
+
519
+ return os.stat(source).st_mtime > os.stat(target).st_mtime
520
+
521
+ def copy_file(self, infile, outfile, check=True):
522
+ """Copy a file respecting dry-run and force flags.
523
+ """
524
+ self.ensure_dir(os.path.dirname(outfile))
525
+ logger.info('Copying %s to %s', infile, outfile)
526
+ if not self.dry_run:
527
+ msg = None
528
+ if check:
529
+ if os.path.islink(outfile):
530
+ msg = '%s is a symlink' % outfile
531
+ elif os.path.exists(outfile) and not os.path.isfile(outfile):
532
+ msg = '%s is a non-regular file' % outfile
533
+ if msg:
534
+ raise ValueError(msg + ' which would be overwritten')
535
+ shutil.copyfile(infile, outfile)
536
+ self.record_as_written(outfile)
537
+
538
+ def copy_stream(self, instream, outfile, encoding=None):
539
+ assert not os.path.isdir(outfile)
540
+ self.ensure_dir(os.path.dirname(outfile))
541
+ logger.info('Copying stream %s to %s', instream, outfile)
542
+ if not self.dry_run:
543
+ if encoding is None:
544
+ outstream = open(outfile, 'wb')
545
+ else:
546
+ outstream = codecs.open(outfile, 'w', encoding=encoding)
547
+ try:
548
+ shutil.copyfileobj(instream, outstream)
549
+ finally:
550
+ outstream.close()
551
+ self.record_as_written(outfile)
552
+
553
+ def write_binary_file(self, path, data):
554
+ self.ensure_dir(os.path.dirname(path))
555
+ if not self.dry_run:
556
+ if os.path.exists(path):
557
+ os.remove(path)
558
+ with open(path, 'wb') as f:
559
+ f.write(data)
560
+ self.record_as_written(path)
561
+
562
+ def write_text_file(self, path, data, encoding):
563
+ self.write_binary_file(path, data.encode(encoding))
564
+
565
+ def set_mode(self, bits, mask, files):
566
+ if os.name == 'posix' or (os.name == 'java' and os._name == 'posix'):
567
+ # Set the executable bits (owner, group, and world) on
568
+ # all the files specified.
569
+ for f in files:
570
+ if self.dry_run:
571
+ logger.info("changing mode of %s", f)
572
+ else:
573
+ mode = (os.stat(f).st_mode | bits) & mask
574
+ logger.info("changing mode of %s to %o", f, mode)
575
+ os.chmod(f, mode)
576
+
577
+ set_executable_mode = lambda s, f: s.set_mode(0o555, 0o7777, f)
578
+
579
+ def ensure_dir(self, path):
580
+ path = os.path.abspath(path)
581
+ if path not in self.ensured and not os.path.exists(path):
582
+ self.ensured.add(path)
583
+ d, f = os.path.split(path)
584
+ self.ensure_dir(d)
585
+ logger.info('Creating %s' % path)
586
+ if not self.dry_run:
587
+ os.mkdir(path)
588
+ if self.record:
589
+ self.dirs_created.add(path)
590
+
591
+ def byte_compile(self, path, optimize=False, force=False, prefix=None, hashed_invalidation=False):
592
+ dpath = cache_from_source(path, not optimize)
593
+ logger.info('Byte-compiling %s to %s', path, dpath)
594
+ if not self.dry_run:
595
+ if force or self.newer(path, dpath):
596
+ if not prefix:
597
+ diagpath = None
598
+ else:
599
+ assert path.startswith(prefix)
600
+ diagpath = path[len(prefix):]
601
+ compile_kwargs = {}
602
+ if hashed_invalidation and hasattr(py_compile, 'PycInvalidationMode'):
603
+ if not isinstance(hashed_invalidation, py_compile.PycInvalidationMode):
604
+ hashed_invalidation = py_compile.PycInvalidationMode.CHECKED_HASH
605
+ compile_kwargs['invalidation_mode'] = hashed_invalidation
606
+ py_compile.compile(path, dpath, diagpath, True, **compile_kwargs) # raise error
607
+ self.record_as_written(dpath)
608
+ return dpath
609
+
610
+ def ensure_removed(self, path):
611
+ if os.path.exists(path):
612
+ if os.path.isdir(path) and not os.path.islink(path):
613
+ logger.debug('Removing directory tree at %s', path)
614
+ if not self.dry_run:
615
+ shutil.rmtree(path)
616
+ if self.record:
617
+ if path in self.dirs_created:
618
+ self.dirs_created.remove(path)
619
+ else:
620
+ if os.path.islink(path):
621
+ s = 'link'
622
+ else:
623
+ s = 'file'
624
+ logger.debug('Removing %s %s', s, path)
625
+ if not self.dry_run:
626
+ os.remove(path)
627
+ if self.record:
628
+ if path in self.files_written:
629
+ self.files_written.remove(path)
630
+
631
+ def is_writable(self, path):
632
+ result = False
633
+ while not result:
634
+ if os.path.exists(path):
635
+ result = os.access(path, os.W_OK)
636
+ break
637
+ parent = os.path.dirname(path)
638
+ if parent == path:
639
+ break
640
+ path = parent
641
+ return result
642
+
643
+ def commit(self):
644
+ """
645
+ Commit recorded changes, turn off recording, return
646
+ changes.
647
+ """
648
+ assert self.record
649
+ result = self.files_written, self.dirs_created
650
+ self._init_record()
651
+ return result
652
+
653
+ def rollback(self):
654
+ if not self.dry_run:
655
+ for f in list(self.files_written):
656
+ if os.path.exists(f):
657
+ os.remove(f)
658
+ # dirs should all be empty now, except perhaps for
659
+ # __pycache__ subdirs
660
+ # reverse so that subdirs appear before their parents
661
+ dirs = sorted(self.dirs_created, reverse=True)
662
+ for d in dirs:
663
+ flist = os.listdir(d)
664
+ if flist:
665
+ assert flist == ['__pycache__']
666
+ sd = os.path.join(d, flist[0])
667
+ os.rmdir(sd)
668
+ os.rmdir(d) # should fail if non-empty
669
+ self._init_record()
670
+
671
+
672
+ def resolve(module_name, dotted_path):
673
+ if module_name in sys.modules:
674
+ mod = sys.modules[module_name]
675
+ else:
676
+ mod = __import__(module_name)
677
+ if dotted_path is None:
678
+ result = mod
679
+ else:
680
+ parts = dotted_path.split('.')
681
+ result = getattr(mod, parts.pop(0))
682
+ for p in parts:
683
+ result = getattr(result, p)
684
+ return result
685
+
686
+
687
+ class ExportEntry(object):
688
+
689
+ def __init__(self, name, prefix, suffix, flags):
690
+ self.name = name
691
+ self.prefix = prefix
692
+ self.suffix = suffix
693
+ self.flags = flags
694
+
695
+ @cached_property
696
+ def value(self):
697
+ return resolve(self.prefix, self.suffix)
698
+
699
+ def __repr__(self): # pragma: no cover
700
+ return '<ExportEntry %s = %s:%s %s>' % (self.name, self.prefix, self.suffix, self.flags)
701
+
702
+ def __eq__(self, other):
703
+ if not isinstance(other, ExportEntry):
704
+ result = False
705
+ else:
706
+ result = (self.name == other.name and self.prefix == other.prefix and self.suffix == other.suffix and
707
+ self.flags == other.flags)
708
+ return result
709
+
710
+ __hash__ = object.__hash__
711
+
712
+
713
+ ENTRY_RE = re.compile(
714
+ r'''(?P<name>([^\[]\S*))
715
+ \s*=\s*(?P<callable>(\w+)([:\.]\w+)*)
716
+ \s*(\[\s*(?P<flags>[\w-]+(=\w+)?(,\s*\w+(=\w+)?)*)\s*\])?
717
+ ''', re.VERBOSE)
718
+
719
+
720
+ def get_export_entry(specification):
721
+ m = ENTRY_RE.search(specification)
722
+ if not m:
723
+ result = None
724
+ if '[' in specification or ']' in specification:
725
+ raise DistlibException("Invalid specification "
726
+ "'%s'" % specification)
727
+ else:
728
+ d = m.groupdict()
729
+ name = d['name']
730
+ path = d['callable']
731
+ colons = path.count(':')
732
+ if colons == 0:
733
+ prefix, suffix = path, None
734
+ else:
735
+ if colons != 1:
736
+ raise DistlibException("Invalid specification "
737
+ "'%s'" % specification)
738
+ prefix, suffix = path.split(':')
739
+ flags = d['flags']
740
+ if flags is None:
741
+ if '[' in specification or ']' in specification:
742
+ raise DistlibException("Invalid specification "
743
+ "'%s'" % specification)
744
+ flags = []
745
+ else:
746
+ flags = [f.strip() for f in flags.split(',')]
747
+ result = ExportEntry(name, prefix, suffix, flags)
748
+ return result
749
+
750
+
751
+ def get_cache_base(suffix=None):
752
+ """
753
+ Return the default base location for distlib caches. If the directory does
754
+ not exist, it is created. Use the suffix provided for the base directory,
755
+ and default to '.distlib' if it isn't provided.
756
+
757
+ On Windows, if LOCALAPPDATA is defined in the environment, then it is
758
+ assumed to be a directory, and will be the parent directory of the result.
759
+ On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home
760
+ directory - using os.expanduser('~') - will be the parent directory of
761
+ the result.
762
+
763
+ The result is just the directory '.distlib' in the parent directory as
764
+ determined above, or with the name specified with ``suffix``.
765
+ """
766
+ if suffix is None:
767
+ suffix = '.distlib'
768
+ if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:
769
+ result = os.path.expandvars('$localappdata')
770
+ else:
771
+ # Assume posix, or old Windows
772
+ result = os.path.expanduser('~')
773
+ # we use 'isdir' instead of 'exists', because we want to
774
+ # fail if there's a file with that name
775
+ if os.path.isdir(result):
776
+ usable = os.access(result, os.W_OK)
777
+ if not usable:
778
+ logger.warning('Directory exists but is not writable: %s', result)
779
+ else:
780
+ try:
781
+ os.makedirs(result)
782
+ usable = True
783
+ except OSError:
784
+ logger.warning('Unable to create %s', result, exc_info=True)
785
+ usable = False
786
+ if not usable:
787
+ result = tempfile.mkdtemp()
788
+ logger.warning('Default location unusable, using %s', result)
789
+ return os.path.join(result, suffix)
790
+
791
+
792
+ def path_to_cache_dir(path, use_abspath=True):
793
+ """
794
+ Convert an absolute path to a directory name for use in a cache.
795
+
796
+ The algorithm used is:
797
+
798
+ #. On Windows, any ``':'`` in the drive is replaced with ``'---'``.
799
+ #. Any occurrence of ``os.sep`` is replaced with ``'--'``.
800
+ #. ``'.cache'`` is appended.
801
+ """
802
+ d, p = os.path.splitdrive(os.path.abspath(path) if use_abspath else path)
803
+ if d:
804
+ d = d.replace(':', '---')
805
+ p = p.replace(os.sep, '--')
806
+ return d + p + '.cache'
807
+
808
+
809
+ def ensure_slash(s):
810
+ if not s.endswith('/'):
811
+ return s + '/'
812
+ return s
813
+
814
+
815
+ def parse_credentials(netloc):
816
+ username = password = None
817
+ if '@' in netloc:
818
+ prefix, netloc = netloc.rsplit('@', 1)
819
+ if ':' not in prefix:
820
+ username = prefix
821
+ else:
822
+ username, password = prefix.split(':', 1)
823
+ if username:
824
+ username = unquote(username)
825
+ if password:
826
+ password = unquote(password)
827
+ return username, password, netloc
828
+
829
+
830
+ def get_process_umask():
831
+ result = os.umask(0o22)
832
+ os.umask(result)
833
+ return result
834
+
835
+
836
+ def is_string_sequence(seq):
837
+ result = True
838
+ i = None
839
+ for i, s in enumerate(seq):
840
+ if not isinstance(s, string_types):
841
+ result = False
842
+ break
843
+ assert i is not None
844
+ return result
845
+
846
+
847
+ PROJECT_NAME_AND_VERSION = re.compile('([a-z0-9_]+([.-][a-z_][a-z0-9_]*)*)-'
848
+ '([a-z0-9_.+-]+)', re.I)
849
+ PYTHON_VERSION = re.compile(r'-py(\d\.?\d?)')
850
+
851
+
852
+ def split_filename(filename, project_name=None):
853
+ """
854
+ Extract name, version, python version from a filename (no extension)
855
+
856
+ Return name, version, pyver or None
857
+ """
858
+ result = None
859
+ pyver = None
860
+ filename = unquote(filename).replace(' ', '-')
861
+ m = PYTHON_VERSION.search(filename)
862
+ if m:
863
+ pyver = m.group(1)
864
+ filename = filename[:m.start()]
865
+ if project_name and len(filename) > len(project_name) + 1:
866
+ m = re.match(re.escape(project_name) + r'\b', filename)
867
+ if m:
868
+ n = m.end()
869
+ result = filename[:n], filename[n + 1:], pyver
870
+ if result is None:
871
+ m = PROJECT_NAME_AND_VERSION.match(filename)
872
+ if m:
873
+ result = m.group(1), m.group(3), pyver
874
+ return result
875
+
876
+
877
+ # Allow spaces in name because of legacy dists like "Twisted Core"
878
+ NAME_VERSION_RE = re.compile(r'(?P<name>[\w .-]+)\s*'
879
+ r'\(\s*(?P<ver>[^\s)]+)\)$')
880
+
881
+
882
+ def parse_name_and_version(p):
883
+ """
884
+ A utility method used to get name and version from a string.
885
+
886
+ From e.g. a Provides-Dist value.
887
+
888
+ :param p: A value in a form 'foo (1.0)'
889
+ :return: The name and version as a tuple.
890
+ """
891
+ m = NAME_VERSION_RE.match(p)
892
+ if not m:
893
+ raise DistlibException('Ill-formed name/version string: \'%s\'' % p)
894
+ d = m.groupdict()
895
+ return d['name'].strip().lower(), d['ver']
896
+
897
+
898
+ def get_extras(requested, available):
899
+ result = set()
900
+ requested = set(requested or [])
901
+ available = set(available or [])
902
+ if '*' in requested:
903
+ requested.remove('*')
904
+ result |= available
905
+ for r in requested:
906
+ if r == '-':
907
+ result.add(r)
908
+ elif r.startswith('-'):
909
+ unwanted = r[1:]
910
+ if unwanted not in available:
911
+ logger.warning('undeclared extra: %s' % unwanted)
912
+ if unwanted in result:
913
+ result.remove(unwanted)
914
+ else:
915
+ if r not in available:
916
+ logger.warning('undeclared extra: %s' % r)
917
+ result.add(r)
918
+ return result
919
+
920
+
921
+ #
922
+ # Extended metadata functionality
923
+ #
924
+
925
+
926
+ def _get_external_data(url):
927
+ result = {}
928
+ try:
929
+ # urlopen might fail if it runs into redirections,
930
+ # because of Python issue #13696. Fixed in locators
931
+ # using a custom redirect handler.
932
+ resp = urlopen(url)
933
+ headers = resp.info()
934
+ ct = headers.get('Content-Type')
935
+ if not ct.startswith('application/json'):
936
+ logger.debug('Unexpected response for JSON request: %s', ct)
937
+ else:
938
+ reader = codecs.getreader('utf-8')(resp)
939
+ # data = reader.read().decode('utf-8')
940
+ # result = json.loads(data)
941
+ result = json.load(reader)
942
+ except Exception as e:
943
+ logger.exception('Failed to get external data for %s: %s', url, e)
944
+ return result
945
+
946
+
947
+ _external_data_base_url = 'https://www.red-dove.com/pypi/projects/'
948
+
949
+
950
+ def get_project_data(name):
951
+ url = '%s/%s/project.json' % (name[0].upper(), name)
952
+ url = urljoin(_external_data_base_url, url)
953
+ result = _get_external_data(url)
954
+ return result
955
+
956
+
957
+ def get_package_data(name, version):
958
+ url = '%s/%s/package-%s.json' % (name[0].upper(), name, version)
959
+ url = urljoin(_external_data_base_url, url)
960
+ return _get_external_data(url)
961
+
962
+
963
+ class Cache(object):
964
+ """
965
+ A class implementing a cache for resources that need to live in the file system
966
+ e.g. shared libraries. This class was moved from resources to here because it
967
+ could be used by other modules, e.g. the wheel module.
968
+ """
969
+
970
+ def __init__(self, base):
971
+ """
972
+ Initialise an instance.
973
+
974
+ :param base: The base directory where the cache should be located.
975
+ """
976
+ # we use 'isdir' instead of 'exists', because we want to
977
+ # fail if there's a file with that name
978
+ if not os.path.isdir(base): # pragma: no cover
979
+ os.makedirs(base)
980
+ if (os.stat(base).st_mode & 0o77) != 0:
981
+ logger.warning('Directory \'%s\' is not private', base)
982
+ self.base = os.path.abspath(os.path.normpath(base))
983
+
984
+ def prefix_to_dir(self, prefix, use_abspath=True):
985
+ """
986
+ Converts a resource prefix to a directory name in the cache.
987
+ """
988
+ return path_to_cache_dir(prefix, use_abspath=use_abspath)
989
+
990
+ def clear(self):
991
+ """
992
+ Clear the cache.
993
+ """
994
+ not_removed = []
995
+ for fn in os.listdir(self.base):
996
+ fn = os.path.join(self.base, fn)
997
+ try:
998
+ if os.path.islink(fn) or os.path.isfile(fn):
999
+ os.remove(fn)
1000
+ elif os.path.isdir(fn):
1001
+ shutil.rmtree(fn)
1002
+ except Exception:
1003
+ not_removed.append(fn)
1004
+ return not_removed
1005
+
1006
+
1007
+ class EventMixin(object):
1008
+ """
1009
+ A very simple publish/subscribe system.
1010
+ """
1011
+
1012
+ def __init__(self):
1013
+ self._subscribers = {}
1014
+
1015
+ def add(self, event, subscriber, append=True):
1016
+ """
1017
+ Add a subscriber for an event.
1018
+
1019
+ :param event: The name of an event.
1020
+ :param subscriber: The subscriber to be added (and called when the
1021
+ event is published).
1022
+ :param append: Whether to append or prepend the subscriber to an
1023
+ existing subscriber list for the event.
1024
+ """
1025
+ subs = self._subscribers
1026
+ if event not in subs:
1027
+ subs[event] = deque([subscriber])
1028
+ else:
1029
+ sq = subs[event]
1030
+ if append:
1031
+ sq.append(subscriber)
1032
+ else:
1033
+ sq.appendleft(subscriber)
1034
+
1035
+ def remove(self, event, subscriber):
1036
+ """
1037
+ Remove a subscriber for an event.
1038
+
1039
+ :param event: The name of an event.
1040
+ :param subscriber: The subscriber to be removed.
1041
+ """
1042
+ subs = self._subscribers
1043
+ if event not in subs:
1044
+ raise ValueError('No subscribers: %r' % event)
1045
+ subs[event].remove(subscriber)
1046
+
1047
+ def get_subscribers(self, event):
1048
+ """
1049
+ Return an iterator for the subscribers for an event.
1050
+ :param event: The event to return subscribers for.
1051
+ """
1052
+ return iter(self._subscribers.get(event, ()))
1053
+
1054
+ def publish(self, event, *args, **kwargs):
1055
+ """
1056
+ Publish a event and return a list of values returned by its
1057
+ subscribers.
1058
+
1059
+ :param event: The event to publish.
1060
+ :param args: The positional arguments to pass to the event's
1061
+ subscribers.
1062
+ :param kwargs: The keyword arguments to pass to the event's
1063
+ subscribers.
1064
+ """
1065
+ result = []
1066
+ for subscriber in self.get_subscribers(event):
1067
+ try:
1068
+ value = subscriber(event, *args, **kwargs)
1069
+ except Exception:
1070
+ logger.exception('Exception during event publication')
1071
+ value = None
1072
+ result.append(value)
1073
+ logger.debug('publish %s: args = %s, kwargs = %s, result = %s', event, args, kwargs, result)
1074
+ return result
1075
+
1076
+
1077
+ #
1078
+ # Simple sequencing
1079
+ #
1080
+ class Sequencer(object):
1081
+
1082
+ def __init__(self):
1083
+ self._preds = {}
1084
+ self._succs = {}
1085
+ self._nodes = set() # nodes with no preds/succs
1086
+
1087
+ def add_node(self, node):
1088
+ self._nodes.add(node)
1089
+
1090
+ def remove_node(self, node, edges=False):
1091
+ if node in self._nodes:
1092
+ self._nodes.remove(node)
1093
+ if edges:
1094
+ for p in set(self._preds.get(node, ())):
1095
+ self.remove(p, node)
1096
+ for s in set(self._succs.get(node, ())):
1097
+ self.remove(node, s)
1098
+ # Remove empties
1099
+ for k, v in list(self._preds.items()):
1100
+ if not v:
1101
+ del self._preds[k]
1102
+ for k, v in list(self._succs.items()):
1103
+ if not v:
1104
+ del self._succs[k]
1105
+
1106
+ def add(self, pred, succ):
1107
+ assert pred != succ
1108
+ self._preds.setdefault(succ, set()).add(pred)
1109
+ self._succs.setdefault(pred, set()).add(succ)
1110
+
1111
+ def remove(self, pred, succ):
1112
+ assert pred != succ
1113
+ try:
1114
+ preds = self._preds[succ]
1115
+ succs = self._succs[pred]
1116
+ except KeyError: # pragma: no cover
1117
+ raise ValueError('%r not a successor of anything' % succ)
1118
+ try:
1119
+ preds.remove(pred)
1120
+ succs.remove(succ)
1121
+ except KeyError: # pragma: no cover
1122
+ raise ValueError('%r not a successor of %r' % (succ, pred))
1123
+
1124
+ def is_step(self, step):
1125
+ return (step in self._preds or step in self._succs or step in self._nodes)
1126
+
1127
+ def get_steps(self, final):
1128
+ if not self.is_step(final):
1129
+ raise ValueError('Unknown: %r' % final)
1130
+ result = []
1131
+ todo = []
1132
+ seen = set()
1133
+ todo.append(final)
1134
+ while todo:
1135
+ step = todo.pop(0)
1136
+ if step in seen:
1137
+ # if a step was already seen,
1138
+ # move it to the end (so it will appear earlier
1139
+ # when reversed on return) ... but not for the
1140
+ # final step, as that would be confusing for
1141
+ # users
1142
+ if step != final:
1143
+ result.remove(step)
1144
+ result.append(step)
1145
+ else:
1146
+ seen.add(step)
1147
+ result.append(step)
1148
+ preds = self._preds.get(step, ())
1149
+ todo.extend(preds)
1150
+ return reversed(result)
1151
+
1152
+ @property
1153
+ def strong_connections(self):
1154
+ # http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
1155
+ index_counter = [0]
1156
+ stack = []
1157
+ lowlinks = {}
1158
+ index = {}
1159
+ result = []
1160
+
1161
+ graph = self._succs
1162
+
1163
+ def strongconnect(node):
1164
+ # set the depth index for this node to the smallest unused index
1165
+ index[node] = index_counter[0]
1166
+ lowlinks[node] = index_counter[0]
1167
+ index_counter[0] += 1
1168
+ stack.append(node)
1169
+
1170
+ # Consider successors
1171
+ try:
1172
+ successors = graph[node]
1173
+ except Exception:
1174
+ successors = []
1175
+ for successor in successors:
1176
+ if successor not in lowlinks:
1177
+ # Successor has not yet been visited
1178
+ strongconnect(successor)
1179
+ lowlinks[node] = min(lowlinks[node], lowlinks[successor])
1180
+ elif successor in stack:
1181
+ # the successor is in the stack and hence in the current
1182
+ # strongly connected component (SCC)
1183
+ lowlinks[node] = min(lowlinks[node], index[successor])
1184
+
1185
+ # If `node` is a root node, pop the stack and generate an SCC
1186
+ if lowlinks[node] == index[node]:
1187
+ connected_component = []
1188
+
1189
+ while True:
1190
+ successor = stack.pop()
1191
+ connected_component.append(successor)
1192
+ if successor == node:
1193
+ break
1194
+ component = tuple(connected_component)
1195
+ # storing the result
1196
+ result.append(component)
1197
+
1198
+ for node in graph:
1199
+ if node not in lowlinks:
1200
+ strongconnect(node)
1201
+
1202
+ return result
1203
+
1204
+ @property
1205
+ def dot(self):
1206
+ result = ['digraph G {']
1207
+ for succ in self._preds:
1208
+ preds = self._preds[succ]
1209
+ for pred in preds:
1210
+ result.append(' %s -> %s;' % (pred, succ))
1211
+ for node in self._nodes:
1212
+ result.append(' %s;' % node)
1213
+ result.append('}')
1214
+ return '\n'.join(result)
1215
+
1216
+
1217
+ #
1218
+ # Unarchiving functionality for zip, tar, tgz, tbz, whl
1219
+ #
1220
+
1221
+ ARCHIVE_EXTENSIONS = ('.tar.gz', '.tar.bz2', '.tar', '.zip', '.tgz', '.tbz', '.whl')
1222
+
1223
+
1224
+ def unarchive(archive_filename, dest_dir, format=None, check=True):
1225
+
1226
+ def check_path(path):
1227
+ if not isinstance(path, text_type):
1228
+ path = path.decode('utf-8')
1229
+ p = os.path.abspath(os.path.join(dest_dir, path))
1230
+ if not p.startswith(dest_dir) or p[plen] != os.sep:
1231
+ raise ValueError('path outside destination: %r' % p)
1232
+
1233
+ dest_dir = os.path.abspath(dest_dir)
1234
+ plen = len(dest_dir)
1235
+ archive = None
1236
+ if format is None:
1237
+ if archive_filename.endswith(('.zip', '.whl')):
1238
+ format = 'zip'
1239
+ elif archive_filename.endswith(('.tar.gz', '.tgz')):
1240
+ format = 'tgz'
1241
+ mode = 'r:gz'
1242
+ elif archive_filename.endswith(('.tar.bz2', '.tbz')):
1243
+ format = 'tbz'
1244
+ mode = 'r:bz2'
1245
+ elif archive_filename.endswith('.tar'):
1246
+ format = 'tar'
1247
+ mode = 'r'
1248
+ else: # pragma: no cover
1249
+ raise ValueError('Unknown format for %r' % archive_filename)
1250
+ try:
1251
+ if format == 'zip':
1252
+ archive = ZipFile(archive_filename, 'r')
1253
+ if check:
1254
+ names = archive.namelist()
1255
+ for name in names:
1256
+ check_path(name)
1257
+ else:
1258
+ archive = tarfile.open(archive_filename, mode)
1259
+ if check:
1260
+ names = archive.getnames()
1261
+ for name in names:
1262
+ check_path(name)
1263
+ if format != 'zip' and sys.version_info[0] < 3:
1264
+ # See Python issue 17153. If the dest path contains Unicode,
1265
+ # tarfile extraction fails on Python 2.x if a member path name
1266
+ # contains non-ASCII characters - it leads to an implicit
1267
+ # bytes -> unicode conversion using ASCII to decode.
1268
+ for tarinfo in archive.getmembers():
1269
+ if not isinstance(tarinfo.name, text_type):
1270
+ tarinfo.name = tarinfo.name.decode('utf-8')
1271
+
1272
+ # Limit extraction of dangerous items, if this Python
1273
+ # allows it easily. If not, just trust the input.
1274
+ # See: https://docs.python.org/3/library/tarfile.html#extraction-filters
1275
+ def extraction_filter(member, path):
1276
+ """Run tarfile.tar_filter, but raise the expected ValueError"""
1277
+ # This is only called if the current Python has tarfile filters
1278
+ try:
1279
+ return tarfile.tar_filter(member, path)
1280
+ except tarfile.FilterError as exc:
1281
+ raise ValueError(str(exc))
1282
+
1283
+ archive.extraction_filter = extraction_filter
1284
+
1285
+ archive.extractall(dest_dir)
1286
+
1287
+ finally:
1288
+ if archive:
1289
+ archive.close()
1290
+
1291
+
1292
+ def zip_dir(directory):
1293
+ """zip a directory tree into a BytesIO object"""
1294
+ result = io.BytesIO()
1295
+ dlen = len(directory)
1296
+ with ZipFile(result, "w") as zf:
1297
+ for root, dirs, files in os.walk(directory):
1298
+ for name in files:
1299
+ full = os.path.join(root, name)
1300
+ rel = root[dlen:]
1301
+ dest = os.path.join(rel, name)
1302
+ zf.write(full, dest)
1303
+ return result
1304
+
1305
+
1306
+ #
1307
+ # Simple progress bar
1308
+ #
1309
+
1310
+ UNITS = ('', 'K', 'M', 'G', 'T', 'P')
1311
+
1312
+
1313
+ class Progress(object):
1314
+ unknown = 'UNKNOWN'
1315
+
1316
+ def __init__(self, minval=0, maxval=100):
1317
+ assert maxval is None or maxval >= minval
1318
+ self.min = self.cur = minval
1319
+ self.max = maxval
1320
+ self.started = None
1321
+ self.elapsed = 0
1322
+ self.done = False
1323
+
1324
+ def update(self, curval):
1325
+ assert self.min <= curval
1326
+ assert self.max is None or curval <= self.max
1327
+ self.cur = curval
1328
+ now = time.time()
1329
+ if self.started is None:
1330
+ self.started = now
1331
+ else:
1332
+ self.elapsed = now - self.started
1333
+
1334
+ def increment(self, incr):
1335
+ assert incr >= 0
1336
+ self.update(self.cur + incr)
1337
+
1338
+ def start(self):
1339
+ self.update(self.min)
1340
+ return self
1341
+
1342
+ def stop(self):
1343
+ if self.max is not None:
1344
+ self.update(self.max)
1345
+ self.done = True
1346
+
1347
+ @property
1348
+ def maximum(self):
1349
+ return self.unknown if self.max is None else self.max
1350
+
1351
+ @property
1352
+ def percentage(self):
1353
+ if self.done:
1354
+ result = '100 %'
1355
+ elif self.max is None:
1356
+ result = ' ?? %'
1357
+ else:
1358
+ v = 100.0 * (self.cur - self.min) / (self.max - self.min)
1359
+ result = '%3d %%' % v
1360
+ return result
1361
+
1362
+ def format_duration(self, duration):
1363
+ if (duration <= 0) and self.max is None or self.cur == self.min:
1364
+ result = '??:??:??'
1365
+ # elif duration < 1:
1366
+ # result = '--:--:--'
1367
+ else:
1368
+ result = time.strftime('%H:%M:%S', time.gmtime(duration))
1369
+ return result
1370
+
1371
+ @property
1372
+ def ETA(self):
1373
+ if self.done:
1374
+ prefix = 'Done'
1375
+ t = self.elapsed
1376
+ # import pdb; pdb.set_trace()
1377
+ else:
1378
+ prefix = 'ETA '
1379
+ if self.max is None:
1380
+ t = -1
1381
+ elif self.elapsed == 0 or (self.cur == self.min):
1382
+ t = 0
1383
+ else:
1384
+ # import pdb; pdb.set_trace()
1385
+ t = float(self.max - self.min)
1386
+ t /= self.cur - self.min
1387
+ t = (t - 1) * self.elapsed
1388
+ return '%s: %s' % (prefix, self.format_duration(t))
1389
+
1390
+ @property
1391
+ def speed(self):
1392
+ if self.elapsed == 0:
1393
+ result = 0.0
1394
+ else:
1395
+ result = (self.cur - self.min) / self.elapsed
1396
+ for unit in UNITS:
1397
+ if result < 1000:
1398
+ break
1399
+ result /= 1000.0
1400
+ return '%d %sB/s' % (result, unit)
1401
+
1402
+
1403
+ #
1404
+ # Glob functionality
1405
+ #
1406
+
1407
+ RICH_GLOB = re.compile(r'\{([^}]*)\}')
1408
+ _CHECK_RECURSIVE_GLOB = re.compile(r'[^/\\,{]\*\*|\*\*[^/\\,}]')
1409
+ _CHECK_MISMATCH_SET = re.compile(r'^[^{]*\}|\{[^}]*$')
1410
+
1411
+
1412
+ def iglob(path_glob):
1413
+ """Extended globbing function that supports ** and {opt1,opt2,opt3}."""
1414
+ if _CHECK_RECURSIVE_GLOB.search(path_glob):
1415
+ msg = """invalid glob %r: recursive glob "**" must be used alone"""
1416
+ raise ValueError(msg % path_glob)
1417
+ if _CHECK_MISMATCH_SET.search(path_glob):
1418
+ msg = """invalid glob %r: mismatching set marker '{' or '}'"""
1419
+ raise ValueError(msg % path_glob)
1420
+ return _iglob(path_glob)
1421
+
1422
+
1423
+ def _iglob(path_glob):
1424
+ rich_path_glob = RICH_GLOB.split(path_glob, 1)
1425
+ if len(rich_path_glob) > 1:
1426
+ assert len(rich_path_glob) == 3, rich_path_glob
1427
+ prefix, set, suffix = rich_path_glob
1428
+ for item in set.split(','):
1429
+ for path in _iglob(''.join((prefix, item, suffix))):
1430
+ yield path
1431
+ else:
1432
+ if '**' not in path_glob:
1433
+ for item in std_iglob(path_glob):
1434
+ yield item
1435
+ else:
1436
+ prefix, radical = path_glob.split('**', 1)
1437
+ if prefix == '':
1438
+ prefix = '.'
1439
+ if radical == '':
1440
+ radical = '*'
1441
+ else:
1442
+ # we support both
1443
+ radical = radical.lstrip('/')
1444
+ radical = radical.lstrip('\\')
1445
+ for path, dir, files in os.walk(prefix):
1446
+ path = os.path.normpath(path)
1447
+ for fn in _iglob(os.path.join(path, radical)):
1448
+ yield fn
1449
+
1450
+
1451
+ if ssl:
1452
+ from .compat import (HTTPSHandler as BaseHTTPSHandler, match_hostname, CertificateError)
1453
+
1454
+ #
1455
+ # HTTPSConnection which verifies certificates/matches domains
1456
+ #
1457
+
1458
+ class HTTPSConnection(httplib.HTTPSConnection):
1459
+ ca_certs = None # set this to the path to the certs file (.pem)
1460
+ check_domain = True # only used if ca_certs is not None
1461
+
1462
+ # noinspection PyPropertyAccess
1463
+ def connect(self):
1464
+ sock = socket.create_connection((self.host, self.port), self.timeout)
1465
+ if getattr(self, '_tunnel_host', False):
1466
+ self.sock = sock
1467
+ self._tunnel()
1468
+
1469
+ context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1470
+ if hasattr(ssl, 'OP_NO_SSLv2'):
1471
+ context.options |= ssl.OP_NO_SSLv2
1472
+ if getattr(self, 'cert_file', None):
1473
+ context.load_cert_chain(self.cert_file, self.key_file)
1474
+ kwargs = {}
1475
+ if self.ca_certs:
1476
+ context.verify_mode = ssl.CERT_REQUIRED
1477
+ context.load_verify_locations(cafile=self.ca_certs)
1478
+ if getattr(ssl, 'HAS_SNI', False):
1479
+ kwargs['server_hostname'] = self.host
1480
+
1481
+ self.sock = context.wrap_socket(sock, **kwargs)
1482
+ if self.ca_certs and self.check_domain:
1483
+ try:
1484
+ match_hostname(self.sock.getpeercert(), self.host)
1485
+ logger.debug('Host verified: %s', self.host)
1486
+ except CertificateError: # pragma: no cover
1487
+ self.sock.shutdown(socket.SHUT_RDWR)
1488
+ self.sock.close()
1489
+ raise
1490
+
1491
+ class HTTPSHandler(BaseHTTPSHandler):
1492
+
1493
+ def __init__(self, ca_certs, check_domain=True):
1494
+ BaseHTTPSHandler.__init__(self)
1495
+ self.ca_certs = ca_certs
1496
+ self.check_domain = check_domain
1497
+
1498
+ def _conn_maker(self, *args, **kwargs):
1499
+ """
1500
+ This is called to create a connection instance. Normally you'd
1501
+ pass a connection class to do_open, but it doesn't actually check for
1502
+ a class, and just expects a callable. As long as we behave just as a
1503
+ constructor would have, we should be OK. If it ever changes so that
1504
+ we *must* pass a class, we'll create an UnsafeHTTPSConnection class
1505
+ which just sets check_domain to False in the class definition, and
1506
+ choose which one to pass to do_open.
1507
+ """
1508
+ result = HTTPSConnection(*args, **kwargs)
1509
+ if self.ca_certs:
1510
+ result.ca_certs = self.ca_certs
1511
+ result.check_domain = self.check_domain
1512
+ return result
1513
+
1514
+ def https_open(self, req):
1515
+ try:
1516
+ return self.do_open(self._conn_maker, req)
1517
+ except URLError as e:
1518
+ if 'certificate verify failed' in str(e.reason):
1519
+ raise CertificateError('Unable to verify server certificate '
1520
+ 'for %s' % req.host)
1521
+ else:
1522
+ raise
1523
+
1524
+ #
1525
+ # To prevent against mixing HTTP traffic with HTTPS (examples: A Man-In-The-
1526
+ # Middle proxy using HTTP listens on port 443, or an index mistakenly serves
1527
+ # HTML containing a http://xyz link when it should be https://xyz),
1528
+ # you can use the following handler class, which does not allow HTTP traffic.
1529
+ #
1530
+ # It works by inheriting from HTTPHandler - so build_opener won't add a
1531
+ # handler for HTTP itself.
1532
+ #
1533
+ class HTTPSOnlyHandler(HTTPSHandler, HTTPHandler):
1534
+
1535
+ def http_open(self, req):
1536
+ raise URLError('Unexpected HTTP request on what should be a secure '
1537
+ 'connection: %s' % req)
1538
+
1539
+
1540
+ #
1541
+ # XML-RPC with timeouts
1542
+ #
1543
+ class Transport(xmlrpclib.Transport):
1544
+
1545
+ def __init__(self, timeout, use_datetime=0):
1546
+ self.timeout = timeout
1547
+ xmlrpclib.Transport.__init__(self, use_datetime)
1548
+
1549
+ def make_connection(self, host):
1550
+ h, eh, x509 = self.get_host_info(host)
1551
+ if not self._connection or host != self._connection[0]:
1552
+ self._extra_headers = eh
1553
+ self._connection = host, httplib.HTTPConnection(h)
1554
+ return self._connection[1]
1555
+
1556
+
1557
+ if ssl:
1558
+
1559
+ class SafeTransport(xmlrpclib.SafeTransport):
1560
+
1561
+ def __init__(self, timeout, use_datetime=0):
1562
+ self.timeout = timeout
1563
+ xmlrpclib.SafeTransport.__init__(self, use_datetime)
1564
+
1565
+ def make_connection(self, host):
1566
+ h, eh, kwargs = self.get_host_info(host)
1567
+ if not kwargs:
1568
+ kwargs = {}
1569
+ kwargs['timeout'] = self.timeout
1570
+ if not self._connection or host != self._connection[0]:
1571
+ self._extra_headers = eh
1572
+ self._connection = host, httplib.HTTPSConnection(h, None, **kwargs)
1573
+ return self._connection[1]
1574
+
1575
+
1576
+ class ServerProxy(xmlrpclib.ServerProxy):
1577
+
1578
+ def __init__(self, uri, **kwargs):
1579
+ self.timeout = timeout = kwargs.pop('timeout', None)
1580
+ # The above classes only come into play if a timeout
1581
+ # is specified
1582
+ if timeout is not None:
1583
+ # scheme = splittype(uri) # deprecated as of Python 3.8
1584
+ scheme = urlparse(uri)[0]
1585
+ use_datetime = kwargs.get('use_datetime', 0)
1586
+ if scheme == 'https':
1587
+ tcls = SafeTransport
1588
+ else:
1589
+ tcls = Transport
1590
+ kwargs['transport'] = t = tcls(timeout, use_datetime=use_datetime)
1591
+ self.transport = t
1592
+ xmlrpclib.ServerProxy.__init__(self, uri, **kwargs)
1593
+
1594
+
1595
+ #
1596
+ # CSV functionality. This is provided because on 2.x, the csv module can't
1597
+ # handle Unicode. However, we need to deal with Unicode in e.g. RECORD files.
1598
+ #
1599
+
1600
+
1601
+ def _csv_open(fn, mode, **kwargs):
1602
+ if sys.version_info[0] < 3:
1603
+ mode += 'b'
1604
+ else:
1605
+ kwargs['newline'] = ''
1606
+ # Python 3 determines encoding from locale. Force 'utf-8'
1607
+ # file encoding to match other forced utf-8 encoding
1608
+ kwargs['encoding'] = 'utf-8'
1609
+ return open(fn, mode, **kwargs)
1610
+
1611
+
1612
+ class CSVBase(object):
1613
+ defaults = {
1614
+ 'delimiter': str(','), # The strs are used because we need native
1615
+ 'quotechar': str('"'), # str in the csv API (2.x won't take
1616
+ 'lineterminator': str('\n') # Unicode)
1617
+ }
1618
+
1619
+ def __enter__(self):
1620
+ return self
1621
+
1622
+ def __exit__(self, *exc_info):
1623
+ self.stream.close()
1624
+
1625
+
1626
+ class CSVReader(CSVBase):
1627
+
1628
+ def __init__(self, **kwargs):
1629
+ if 'stream' in kwargs:
1630
+ stream = kwargs['stream']
1631
+ if sys.version_info[0] >= 3:
1632
+ # needs to be a text stream
1633
+ stream = codecs.getreader('utf-8')(stream)
1634
+ self.stream = stream
1635
+ else:
1636
+ self.stream = _csv_open(kwargs['path'], 'r')
1637
+ self.reader = csv.reader(self.stream, **self.defaults)
1638
+
1639
+ def __iter__(self):
1640
+ return self
1641
+
1642
+ def next(self):
1643
+ result = next(self.reader)
1644
+ if sys.version_info[0] < 3:
1645
+ for i, item in enumerate(result):
1646
+ if not isinstance(item, text_type):
1647
+ result[i] = item.decode('utf-8')
1648
+ return result
1649
+
1650
+ __next__ = next
1651
+
1652
+
1653
+ class CSVWriter(CSVBase):
1654
+
1655
+ def __init__(self, fn, **kwargs):
1656
+ self.stream = _csv_open(fn, 'w')
1657
+ self.writer = csv.writer(self.stream, **self.defaults)
1658
+
1659
+ def writerow(self, row):
1660
+ if sys.version_info[0] < 3:
1661
+ r = []
1662
+ for item in row:
1663
+ if isinstance(item, text_type):
1664
+ item = item.encode('utf-8')
1665
+ r.append(item)
1666
+ row = r
1667
+ self.writer.writerow(row)
1668
+
1669
+
1670
+ #
1671
+ # Configurator functionality
1672
+ #
1673
+
1674
+
1675
+ class Configurator(BaseConfigurator):
1676
+
1677
+ value_converters = dict(BaseConfigurator.value_converters)
1678
+ value_converters['inc'] = 'inc_convert'
1679
+
1680
+ def __init__(self, config, base=None):
1681
+ super(Configurator, self).__init__(config)
1682
+ self.base = base or os.getcwd()
1683
+
1684
+ def configure_custom(self, config):
1685
+
1686
+ def convert(o):
1687
+ if isinstance(o, (list, tuple)):
1688
+ result = type(o)([convert(i) for i in o])
1689
+ elif isinstance(o, dict):
1690
+ if '()' in o:
1691
+ result = self.configure_custom(o)
1692
+ else:
1693
+ result = {}
1694
+ for k in o:
1695
+ result[k] = convert(o[k])
1696
+ else:
1697
+ result = self.convert(o)
1698
+ return result
1699
+
1700
+ c = config.pop('()')
1701
+ if not callable(c):
1702
+ c = self.resolve(c)
1703
+ props = config.pop('.', None)
1704
+ # Check for valid identifiers
1705
+ args = config.pop('[]', ())
1706
+ if args:
1707
+ args = tuple([convert(o) for o in args])
1708
+ items = [(k, convert(config[k])) for k in config if valid_ident(k)]
1709
+ kwargs = dict(items)
1710
+ result = c(*args, **kwargs)
1711
+ if props:
1712
+ for n, v in props.items():
1713
+ setattr(result, n, convert(v))
1714
+ return result
1715
+
1716
+ def __getitem__(self, key):
1717
+ result = self.config[key]
1718
+ if isinstance(result, dict) and '()' in result:
1719
+ self.config[key] = result = self.configure_custom(result)
1720
+ return result
1721
+
1722
+ def inc_convert(self, value):
1723
+ """Default converter for the inc:// protocol."""
1724
+ if not os.path.isabs(value):
1725
+ value = os.path.join(self.base, value)
1726
+ with codecs.open(value, 'r', encoding='utf-8') as f:
1727
+ result = json.load(f)
1728
+ return result
1729
+
1730
+
1731
+ class SubprocessMixin(object):
1732
+ """
1733
+ Mixin for running subprocesses and capturing their output
1734
+ """
1735
+
1736
+ def __init__(self, verbose=False, progress=None):
1737
+ self.verbose = verbose
1738
+ self.progress = progress
1739
+
1740
+ def reader(self, stream, context):
1741
+ """
1742
+ Read lines from a subprocess' output stream and either pass to a progress
1743
+ callable (if specified) or write progress information to sys.stderr.
1744
+ """
1745
+ progress = self.progress
1746
+ verbose = self.verbose
1747
+ while True:
1748
+ s = stream.readline()
1749
+ if not s:
1750
+ break
1751
+ if progress is not None:
1752
+ progress(s, context)
1753
+ else:
1754
+ if not verbose:
1755
+ sys.stderr.write('.')
1756
+ else:
1757
+ sys.stderr.write(s.decode('utf-8'))
1758
+ sys.stderr.flush()
1759
+ stream.close()
1760
+
1761
+ def run_command(self, cmd, **kwargs):
1762
+ p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
1763
+ t1 = threading.Thread(target=self.reader, args=(p.stdout, 'stdout'))
1764
+ t1.start()
1765
+ t2 = threading.Thread(target=self.reader, args=(p.stderr, 'stderr'))
1766
+ t2.start()
1767
+ p.wait()
1768
+ t1.join()
1769
+ t2.join()
1770
+ if self.progress is not None:
1771
+ self.progress('done.', 'main')
1772
+ elif self.verbose:
1773
+ sys.stderr.write('done.\n')
1774
+ return p
1775
+
1776
+
1777
+ def normalize_name(name):
1778
+ """Normalize a python package name a la PEP 503"""
1779
+ # https://www.python.org/dev/peps/pep-0503/#normalized-names
1780
+ return re.sub('[-_.]+', '-', name).lower()
1781
+
1782
+
1783
+ # def _get_pypirc_command():
1784
+ # """
1785
+ # Get the distutils command for interacting with PyPI configurations.
1786
+ # :return: the command.
1787
+ # """
1788
+ # from distutils.core import Distribution
1789
+ # from distutils.config import PyPIRCCommand
1790
+ # d = Distribution()
1791
+ # return PyPIRCCommand(d)
1792
+
1793
+
1794
+ class PyPIRCFile(object):
1795
+
1796
+ DEFAULT_REPOSITORY = 'https://upload.pypi.org/legacy/'
1797
+ DEFAULT_REALM = 'pypi'
1798
+
1799
+ def __init__(self, fn=None, url=None):
1800
+ if fn is None:
1801
+ fn = os.path.join(os.path.expanduser('~'), '.pypirc')
1802
+ self.filename = fn
1803
+ self.url = url
1804
+
1805
+ def read(self):
1806
+ result = {}
1807
+
1808
+ if os.path.exists(self.filename):
1809
+ repository = self.url or self.DEFAULT_REPOSITORY
1810
+
1811
+ config = configparser.RawConfigParser()
1812
+ config.read(self.filename)
1813
+ sections = config.sections()
1814
+ if 'distutils' in sections:
1815
+ # let's get the list of servers
1816
+ index_servers = config.get('distutils', 'index-servers')
1817
+ _servers = [server.strip() for server in index_servers.split('\n') if server.strip() != '']
1818
+ if _servers == []:
1819
+ # nothing set, let's try to get the default pypi
1820
+ if 'pypi' in sections:
1821
+ _servers = ['pypi']
1822
+ else:
1823
+ for server in _servers:
1824
+ result = {'server': server}
1825
+ result['username'] = config.get(server, 'username')
1826
+
1827
+ # optional params
1828
+ for key, default in (('repository', self.DEFAULT_REPOSITORY), ('realm', self.DEFAULT_REALM),
1829
+ ('password', None)):
1830
+ if config.has_option(server, key):
1831
+ result[key] = config.get(server, key)
1832
+ else:
1833
+ result[key] = default
1834
+
1835
+ # work around people having "repository" for the "pypi"
1836
+ # section of their config set to the HTTP (rather than
1837
+ # HTTPS) URL
1838
+ if (server == 'pypi' and repository in (self.DEFAULT_REPOSITORY, 'pypi')):
1839
+ result['repository'] = self.DEFAULT_REPOSITORY
1840
+ elif (result['server'] != repository and result['repository'] != repository):
1841
+ result = {}
1842
+ elif 'server-login' in sections:
1843
+ # old format
1844
+ server = 'server-login'
1845
+ if config.has_option(server, 'repository'):
1846
+ repository = config.get(server, 'repository')
1847
+ else:
1848
+ repository = self.DEFAULT_REPOSITORY
1849
+ result = {
1850
+ 'username': config.get(server, 'username'),
1851
+ 'password': config.get(server, 'password'),
1852
+ 'repository': repository,
1853
+ 'server': server,
1854
+ 'realm': self.DEFAULT_REALM
1855
+ }
1856
+ return result
1857
+
1858
+ def update(self, username, password):
1859
+ # import pdb; pdb.set_trace()
1860
+ config = configparser.RawConfigParser()
1861
+ fn = self.filename
1862
+ config.read(fn)
1863
+ if not config.has_section('pypi'):
1864
+ config.add_section('pypi')
1865
+ config.set('pypi', 'username', username)
1866
+ config.set('pypi', 'password', password)
1867
+ with open(fn, 'w') as f:
1868
+ config.write(f)
1869
+
1870
+
1871
+ def _load_pypirc(index):
1872
+ """
1873
+ Read the PyPI access configuration as supported by distutils.
1874
+ """
1875
+ return PyPIRCFile(url=index.url).read()
1876
+
1877
+
1878
+ def _store_pypirc(index):
1879
+ PyPIRCFile().update(index.username, index.password)
1880
+
1881
+
1882
+ #
1883
+ # get_platform()/get_host_platform() copied from Python 3.10.a0 source, with some minor
1884
+ # tweaks
1885
+ #
1886
+
1887
+
1888
+ def get_host_platform():
1889
+ """Return a string that identifies the current platform. This is used mainly to
1890
+ distinguish platform-specific build directories and platform-specific built
1891
+ distributions. Typically includes the OS name and version and the
1892
+ architecture (as supplied by 'os.uname()'), although the exact information
1893
+ included depends on the OS; eg. on Linux, the kernel version isn't
1894
+ particularly important.
1895
+
1896
+ Examples of returned values:
1897
+ linux-i586
1898
+ linux-alpha (?)
1899
+ solaris-2.6-sun4u
1900
+
1901
+ Windows will return one of:
1902
+ win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
1903
+ win32 (all others - specifically, sys.platform is returned)
1904
+
1905
+ For other non-POSIX platforms, currently just returns 'sys.platform'.
1906
+
1907
+ """
1908
+ if os.name == 'nt':
1909
+ if 'amd64' in sys.version.lower():
1910
+ return 'win-amd64'
1911
+ if '(arm)' in sys.version.lower():
1912
+ return 'win-arm32'
1913
+ if '(arm64)' in sys.version.lower():
1914
+ return 'win-arm64'
1915
+ return sys.platform
1916
+
1917
+ # Set for cross builds explicitly
1918
+ if "_PYTHON_HOST_PLATFORM" in os.environ:
1919
+ return os.environ["_PYTHON_HOST_PLATFORM"]
1920
+
1921
+ if os.name != 'posix' or not hasattr(os, 'uname'):
1922
+ # XXX what about the architecture? NT is Intel or Alpha,
1923
+ # Mac OS is M68k or PPC, etc.
1924
+ return sys.platform
1925
+
1926
+ # Try to distinguish various flavours of Unix
1927
+
1928
+ (osname, host, release, version, machine) = os.uname()
1929
+
1930
+ # Convert the OS name to lowercase, remove '/' characters, and translate
1931
+ # spaces (for "Power Macintosh")
1932
+ osname = osname.lower().replace('/', '')
1933
+ machine = machine.replace(' ', '_').replace('/', '-')
1934
+
1935
+ if osname[:5] == 'linux':
1936
+ # At least on Linux/Intel, 'machine' is the processor --
1937
+ # i386, etc.
1938
+ # XXX what about Alpha, SPARC, etc?
1939
+ return "%s-%s" % (osname, machine)
1940
+
1941
+ elif osname[:5] == 'sunos':
1942
+ if release[0] >= '5': # SunOS 5 == Solaris 2
1943
+ osname = 'solaris'
1944
+ release = '%d.%s' % (int(release[0]) - 3, release[2:])
1945
+ # We can't use 'platform.architecture()[0]' because a
1946
+ # bootstrap problem. We use a dict to get an error
1947
+ # if some suspicious happens.
1948
+ bitness = {2147483647: '32bit', 9223372036854775807: '64bit'}
1949
+ machine += '.%s' % bitness[sys.maxsize]
1950
+ # fall through to standard osname-release-machine representation
1951
+ elif osname[:3] == 'aix':
1952
+ from _aix_support import aix_platform
1953
+ return aix_platform()
1954
+ elif osname[:6] == 'cygwin':
1955
+ osname = 'cygwin'
1956
+ rel_re = re.compile(r'[\d.]+', re.ASCII)
1957
+ m = rel_re.match(release)
1958
+ if m:
1959
+ release = m.group()
1960
+ elif osname[:6] == 'darwin':
1961
+ import _osx_support
1962
+ try:
1963
+ from distutils import sysconfig
1964
+ except ImportError:
1965
+ import sysconfig
1966
+ osname, release, machine = _osx_support.get_platform_osx(sysconfig.get_config_vars(), osname, release, machine)
1967
+
1968
+ return '%s-%s-%s' % (osname, release, machine)
1969
+
1970
+
1971
+ _TARGET_TO_PLAT = {
1972
+ 'x86': 'win32',
1973
+ 'x64': 'win-amd64',
1974
+ 'arm': 'win-arm32',
1975
+ }
1976
+
1977
+
1978
+ def get_platform():
1979
+ if os.name != 'nt':
1980
+ return get_host_platform()
1981
+ cross_compilation_target = os.environ.get('VSCMD_ARG_TGT_ARCH')
1982
+ if cross_compilation_target not in _TARGET_TO_PLAT:
1983
+ return get_host_platform()
1984
+ return _TARGET_TO_PLAT[cross_compilation_target]
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/version.py ADDED
@@ -0,0 +1,750 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2012-2023 The Python Software Foundation.
4
+ # See LICENSE.txt and CONTRIBUTORS.txt.
5
+ #
6
+ """
7
+ Implementation of a flexible versioning scheme providing support for PEP-440,
8
+ setuptools-compatible and semantic versioning.
9
+ """
10
+
11
+ import logging
12
+ import re
13
+
14
+ from .compat import string_types
15
+ from .util import parse_requirement
16
+
17
+ __all__ = ['NormalizedVersion', 'NormalizedMatcher',
18
+ 'LegacyVersion', 'LegacyMatcher',
19
+ 'SemanticVersion', 'SemanticMatcher',
20
+ 'UnsupportedVersionError', 'get_scheme']
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ class UnsupportedVersionError(ValueError):
26
+ """This is an unsupported version."""
27
+ pass
28
+
29
+
30
+ class Version(object):
31
+ def __init__(self, s):
32
+ self._string = s = s.strip()
33
+ self._parts = parts = self.parse(s)
34
+ assert isinstance(parts, tuple)
35
+ assert len(parts) > 0
36
+
37
+ def parse(self, s):
38
+ raise NotImplementedError('please implement in a subclass')
39
+
40
+ def _check_compatible(self, other):
41
+ if type(self) != type(other):
42
+ raise TypeError('cannot compare %r and %r' % (self, other))
43
+
44
+ def __eq__(self, other):
45
+ self._check_compatible(other)
46
+ return self._parts == other._parts
47
+
48
+ def __ne__(self, other):
49
+ return not self.__eq__(other)
50
+
51
+ def __lt__(self, other):
52
+ self._check_compatible(other)
53
+ return self._parts < other._parts
54
+
55
+ def __gt__(self, other):
56
+ return not (self.__lt__(other) or self.__eq__(other))
57
+
58
+ def __le__(self, other):
59
+ return self.__lt__(other) or self.__eq__(other)
60
+
61
+ def __ge__(self, other):
62
+ return self.__gt__(other) or self.__eq__(other)
63
+
64
+ # See http://docs.python.org/reference/datamodel#object.__hash__
65
+ def __hash__(self):
66
+ return hash(self._parts)
67
+
68
+ def __repr__(self):
69
+ return "%s('%s')" % (self.__class__.__name__, self._string)
70
+
71
+ def __str__(self):
72
+ return self._string
73
+
74
+ @property
75
+ def is_prerelease(self):
76
+ raise NotImplementedError('Please implement in subclasses.')
77
+
78
+
79
+ class Matcher(object):
80
+ version_class = None
81
+
82
+ # value is either a callable or the name of a method
83
+ _operators = {
84
+ '<': lambda v, c, p: v < c,
85
+ '>': lambda v, c, p: v > c,
86
+ '<=': lambda v, c, p: v == c or v < c,
87
+ '>=': lambda v, c, p: v == c or v > c,
88
+ '==': lambda v, c, p: v == c,
89
+ '===': lambda v, c, p: v == c,
90
+ # by default, compatible => >=.
91
+ '~=': lambda v, c, p: v == c or v > c,
92
+ '!=': lambda v, c, p: v != c,
93
+ }
94
+
95
+ # this is a method only to support alternative implementations
96
+ # via overriding
97
+ def parse_requirement(self, s):
98
+ return parse_requirement(s)
99
+
100
+ def __init__(self, s):
101
+ if self.version_class is None:
102
+ raise ValueError('Please specify a version class')
103
+ self._string = s = s.strip()
104
+ r = self.parse_requirement(s)
105
+ if not r:
106
+ raise ValueError('Not valid: %r' % s)
107
+ self.name = r.name
108
+ self.key = self.name.lower() # for case-insensitive comparisons
109
+ clist = []
110
+ if r.constraints:
111
+ # import pdb; pdb.set_trace()
112
+ for op, s in r.constraints:
113
+ if s.endswith('.*'):
114
+ if op not in ('==', '!='):
115
+ raise ValueError('\'.*\' not allowed for '
116
+ '%r constraints' % op)
117
+ # Could be a partial version (e.g. for '2.*') which
118
+ # won't parse as a version, so keep it as a string
119
+ vn, prefix = s[:-2], True
120
+ # Just to check that vn is a valid version
121
+ self.version_class(vn)
122
+ else:
123
+ # Should parse as a version, so we can create an
124
+ # instance for the comparison
125
+ vn, prefix = self.version_class(s), False
126
+ clist.append((op, vn, prefix))
127
+ self._parts = tuple(clist)
128
+
129
+ def match(self, version):
130
+ """
131
+ Check if the provided version matches the constraints.
132
+
133
+ :param version: The version to match against this instance.
134
+ :type version: String or :class:`Version` instance.
135
+ """
136
+ if isinstance(version, string_types):
137
+ version = self.version_class(version)
138
+ for operator, constraint, prefix in self._parts:
139
+ f = self._operators.get(operator)
140
+ if isinstance(f, string_types):
141
+ f = getattr(self, f)
142
+ if not f:
143
+ msg = ('%r not implemented '
144
+ 'for %s' % (operator, self.__class__.__name__))
145
+ raise NotImplementedError(msg)
146
+ if not f(version, constraint, prefix):
147
+ return False
148
+ return True
149
+
150
+ @property
151
+ def exact_version(self):
152
+ result = None
153
+ if len(self._parts) == 1 and self._parts[0][0] in ('==', '==='):
154
+ result = self._parts[0][1]
155
+ return result
156
+
157
+ def _check_compatible(self, other):
158
+ if type(self) != type(other) or self.name != other.name:
159
+ raise TypeError('cannot compare %s and %s' % (self, other))
160
+
161
+ def __eq__(self, other):
162
+ self._check_compatible(other)
163
+ return self.key == other.key and self._parts == other._parts
164
+
165
+ def __ne__(self, other):
166
+ return not self.__eq__(other)
167
+
168
+ # See http://docs.python.org/reference/datamodel#object.__hash__
169
+ def __hash__(self):
170
+ return hash(self.key) + hash(self._parts)
171
+
172
+ def __repr__(self):
173
+ return "%s(%r)" % (self.__class__.__name__, self._string)
174
+
175
+ def __str__(self):
176
+ return self._string
177
+
178
+
179
+ PEP440_VERSION_RE = re.compile(r'^v?(\d+!)?(\d+(\.\d+)*)((a|alpha|b|beta|c|rc|pre|preview)(\d+)?)?'
180
+ r'(\.(post|r|rev)(\d+)?)?([._-]?(dev)(\d+)?)?'
181
+ r'(\+([a-zA-Z\d]+(\.[a-zA-Z\d]+)?))?$', re.I)
182
+
183
+
184
+ def _pep_440_key(s):
185
+ s = s.strip()
186
+ m = PEP440_VERSION_RE.match(s)
187
+ if not m:
188
+ raise UnsupportedVersionError('Not a valid version: %s' % s)
189
+ groups = m.groups()
190
+ nums = tuple(int(v) for v in groups[1].split('.'))
191
+ while len(nums) > 1 and nums[-1] == 0:
192
+ nums = nums[:-1]
193
+
194
+ if not groups[0]:
195
+ epoch = 0
196
+ else:
197
+ epoch = int(groups[0][:-1])
198
+ pre = groups[4:6]
199
+ post = groups[7:9]
200
+ dev = groups[10:12]
201
+ local = groups[13]
202
+ if pre == (None, None):
203
+ pre = ()
204
+ else:
205
+ if pre[1] is None:
206
+ pre = pre[0], 0
207
+ else:
208
+ pre = pre[0], int(pre[1])
209
+ if post == (None, None):
210
+ post = ()
211
+ else:
212
+ if post[1] is None:
213
+ post = post[0], 0
214
+ else:
215
+ post = post[0], int(post[1])
216
+ if dev == (None, None):
217
+ dev = ()
218
+ else:
219
+ if dev[1] is None:
220
+ dev = dev[0], 0
221
+ else:
222
+ dev = dev[0], int(dev[1])
223
+ if local is None:
224
+ local = ()
225
+ else:
226
+ parts = []
227
+ for part in local.split('.'):
228
+ # to ensure that numeric compares as > lexicographic, avoid
229
+ # comparing them directly, but encode a tuple which ensures
230
+ # correct sorting
231
+ if part.isdigit():
232
+ part = (1, int(part))
233
+ else:
234
+ part = (0, part)
235
+ parts.append(part)
236
+ local = tuple(parts)
237
+ if not pre:
238
+ # either before pre-release, or final release and after
239
+ if not post and dev:
240
+ # before pre-release
241
+ pre = ('a', -1) # to sort before a0
242
+ else:
243
+ pre = ('z',) # to sort after all pre-releases
244
+ # now look at the state of post and dev.
245
+ if not post:
246
+ post = ('_',) # sort before 'a'
247
+ if not dev:
248
+ dev = ('final',)
249
+
250
+ return epoch, nums, pre, post, dev, local
251
+
252
+
253
+ _normalized_key = _pep_440_key
254
+
255
+
256
+ class NormalizedVersion(Version):
257
+ """A rational version.
258
+
259
+ Good:
260
+ 1.2 # equivalent to "1.2.0"
261
+ 1.2.0
262
+ 1.2a1
263
+ 1.2.3a2
264
+ 1.2.3b1
265
+ 1.2.3c1
266
+ 1.2.3.4
267
+ TODO: fill this out
268
+
269
+ Bad:
270
+ 1 # minimum two numbers
271
+ 1.2a # release level must have a release serial
272
+ 1.2.3b
273
+ """
274
+ def parse(self, s):
275
+ result = _normalized_key(s)
276
+ # _normalized_key loses trailing zeroes in the release
277
+ # clause, since that's needed to ensure that X.Y == X.Y.0 == X.Y.0.0
278
+ # However, PEP 440 prefix matching needs it: for example,
279
+ # (~= 1.4.5.0) matches differently to (~= 1.4.5.0.0).
280
+ m = PEP440_VERSION_RE.match(s) # must succeed
281
+ groups = m.groups()
282
+ self._release_clause = tuple(int(v) for v in groups[1].split('.'))
283
+ return result
284
+
285
+ PREREL_TAGS = set(['a', 'b', 'c', 'rc', 'dev'])
286
+
287
+ @property
288
+ def is_prerelease(self):
289
+ return any(t[0] in self.PREREL_TAGS for t in self._parts if t)
290
+
291
+
292
+ def _match_prefix(x, y):
293
+ x = str(x)
294
+ y = str(y)
295
+ if x == y:
296
+ return True
297
+ if not x.startswith(y):
298
+ return False
299
+ n = len(y)
300
+ return x[n] == '.'
301
+
302
+
303
+ class NormalizedMatcher(Matcher):
304
+ version_class = NormalizedVersion
305
+
306
+ # value is either a callable or the name of a method
307
+ _operators = {
308
+ '~=': '_match_compatible',
309
+ '<': '_match_lt',
310
+ '>': '_match_gt',
311
+ '<=': '_match_le',
312
+ '>=': '_match_ge',
313
+ '==': '_match_eq',
314
+ '===': '_match_arbitrary',
315
+ '!=': '_match_ne',
316
+ }
317
+
318
+ def _adjust_local(self, version, constraint, prefix):
319
+ if prefix:
320
+ strip_local = '+' not in constraint and version._parts[-1]
321
+ else:
322
+ # both constraint and version are
323
+ # NormalizedVersion instances.
324
+ # If constraint does not have a local component,
325
+ # ensure the version doesn't, either.
326
+ strip_local = not constraint._parts[-1] and version._parts[-1]
327
+ if strip_local:
328
+ s = version._string.split('+', 1)[0]
329
+ version = self.version_class(s)
330
+ return version, constraint
331
+
332
+ def _match_lt(self, version, constraint, prefix):
333
+ version, constraint = self._adjust_local(version, constraint, prefix)
334
+ if version >= constraint:
335
+ return False
336
+ release_clause = constraint._release_clause
337
+ pfx = '.'.join([str(i) for i in release_clause])
338
+ return not _match_prefix(version, pfx)
339
+
340
+ def _match_gt(self, version, constraint, prefix):
341
+ version, constraint = self._adjust_local(version, constraint, prefix)
342
+ if version <= constraint:
343
+ return False
344
+ release_clause = constraint._release_clause
345
+ pfx = '.'.join([str(i) for i in release_clause])
346
+ return not _match_prefix(version, pfx)
347
+
348
+ def _match_le(self, version, constraint, prefix):
349
+ version, constraint = self._adjust_local(version, constraint, prefix)
350
+ return version <= constraint
351
+
352
+ def _match_ge(self, version, constraint, prefix):
353
+ version, constraint = self._adjust_local(version, constraint, prefix)
354
+ return version >= constraint
355
+
356
+ def _match_eq(self, version, constraint, prefix):
357
+ version, constraint = self._adjust_local(version, constraint, prefix)
358
+ if not prefix:
359
+ result = (version == constraint)
360
+ else:
361
+ result = _match_prefix(version, constraint)
362
+ return result
363
+
364
+ def _match_arbitrary(self, version, constraint, prefix):
365
+ return str(version) == str(constraint)
366
+
367
+ def _match_ne(self, version, constraint, prefix):
368
+ version, constraint = self._adjust_local(version, constraint, prefix)
369
+ if not prefix:
370
+ result = (version != constraint)
371
+ else:
372
+ result = not _match_prefix(version, constraint)
373
+ return result
374
+
375
+ def _match_compatible(self, version, constraint, prefix):
376
+ version, constraint = self._adjust_local(version, constraint, prefix)
377
+ if version == constraint:
378
+ return True
379
+ if version < constraint:
380
+ return False
381
+ # if not prefix:
382
+ # return True
383
+ release_clause = constraint._release_clause
384
+ if len(release_clause) > 1:
385
+ release_clause = release_clause[:-1]
386
+ pfx = '.'.join([str(i) for i in release_clause])
387
+ return _match_prefix(version, pfx)
388
+
389
+
390
+ _REPLACEMENTS = (
391
+ (re.compile('[.+-]$'), ''), # remove trailing puncts
392
+ (re.compile(r'^[.](\d)'), r'0.\1'), # .N -> 0.N at start
393
+ (re.compile('^[.-]'), ''), # remove leading puncts
394
+ (re.compile(r'^\((.*)\)$'), r'\1'), # remove parentheses
395
+ (re.compile(r'^v(ersion)?\s*(\d+)'), r'\2'), # remove leading v(ersion)
396
+ (re.compile(r'^r(ev)?\s*(\d+)'), r'\2'), # remove leading v(ersion)
397
+ (re.compile('[.]{2,}'), '.'), # multiple runs of '.'
398
+ (re.compile(r'\b(alfa|apha)\b'), 'alpha'), # misspelt alpha
399
+ (re.compile(r'\b(pre-alpha|prealpha)\b'),
400
+ 'pre.alpha'), # standardise
401
+ (re.compile(r'\(beta\)$'), 'beta'), # remove parentheses
402
+ )
403
+
404
+ _SUFFIX_REPLACEMENTS = (
405
+ (re.compile('^[:~._+-]+'), ''), # remove leading puncts
406
+ (re.compile('[,*")([\\]]'), ''), # remove unwanted chars
407
+ (re.compile('[~:+_ -]'), '.'), # replace illegal chars
408
+ (re.compile('[.]{2,}'), '.'), # multiple runs of '.'
409
+ (re.compile(r'\.$'), ''), # trailing '.'
410
+ )
411
+
412
+ _NUMERIC_PREFIX = re.compile(r'(\d+(\.\d+)*)')
413
+
414
+
415
+ def _suggest_semantic_version(s):
416
+ """
417
+ Try to suggest a semantic form for a version for which
418
+ _suggest_normalized_version couldn't come up with anything.
419
+ """
420
+ result = s.strip().lower()
421
+ for pat, repl in _REPLACEMENTS:
422
+ result = pat.sub(repl, result)
423
+ if not result:
424
+ result = '0.0.0'
425
+
426
+ # Now look for numeric prefix, and separate it out from
427
+ # the rest.
428
+ # import pdb; pdb.set_trace()
429
+ m = _NUMERIC_PREFIX.match(result)
430
+ if not m:
431
+ prefix = '0.0.0'
432
+ suffix = result
433
+ else:
434
+ prefix = m.groups()[0].split('.')
435
+ prefix = [int(i) for i in prefix]
436
+ while len(prefix) < 3:
437
+ prefix.append(0)
438
+ if len(prefix) == 3:
439
+ suffix = result[m.end():]
440
+ else:
441
+ suffix = '.'.join([str(i) for i in prefix[3:]]) + result[m.end():]
442
+ prefix = prefix[:3]
443
+ prefix = '.'.join([str(i) for i in prefix])
444
+ suffix = suffix.strip()
445
+ if suffix:
446
+ # import pdb; pdb.set_trace()
447
+ # massage the suffix.
448
+ for pat, repl in _SUFFIX_REPLACEMENTS:
449
+ suffix = pat.sub(repl, suffix)
450
+
451
+ if not suffix:
452
+ result = prefix
453
+ else:
454
+ sep = '-' if 'dev' in suffix else '+'
455
+ result = prefix + sep + suffix
456
+ if not is_semver(result):
457
+ result = None
458
+ return result
459
+
460
+
461
+ def _suggest_normalized_version(s):
462
+ """Suggest a normalized version close to the given version string.
463
+
464
+ If you have a version string that isn't rational (i.e. NormalizedVersion
465
+ doesn't like it) then you might be able to get an equivalent (or close)
466
+ rational version from this function.
467
+
468
+ This does a number of simple normalizations to the given string, based
469
+ on observation of versions currently in use on PyPI. Given a dump of
470
+ those version during PyCon 2009, 4287 of them:
471
+ - 2312 (53.93%) match NormalizedVersion without change
472
+ with the automatic suggestion
473
+ - 3474 (81.04%) match when using this suggestion method
474
+
475
+ @param s {str} An irrational version string.
476
+ @returns A rational version string, or None, if couldn't determine one.
477
+ """
478
+ try:
479
+ _normalized_key(s)
480
+ return s # already rational
481
+ except UnsupportedVersionError:
482
+ pass
483
+
484
+ rs = s.lower()
485
+
486
+ # part of this could use maketrans
487
+ for orig, repl in (('-alpha', 'a'), ('-beta', 'b'), ('alpha', 'a'),
488
+ ('beta', 'b'), ('rc', 'c'), ('-final', ''),
489
+ ('-pre', 'c'),
490
+ ('-release', ''), ('.release', ''), ('-stable', ''),
491
+ ('+', '.'), ('_', '.'), (' ', ''), ('.final', ''),
492
+ ('final', '')):
493
+ rs = rs.replace(orig, repl)
494
+
495
+ # if something ends with dev or pre, we add a 0
496
+ rs = re.sub(r"pre$", r"pre0", rs)
497
+ rs = re.sub(r"dev$", r"dev0", rs)
498
+
499
+ # if we have something like "b-2" or "a.2" at the end of the
500
+ # version, that is probably beta, alpha, etc
501
+ # let's remove the dash or dot
502
+ rs = re.sub(r"([abc]|rc)[\-\.](\d+)$", r"\1\2", rs)
503
+
504
+ # 1.0-dev-r371 -> 1.0.dev371
505
+ # 0.1-dev-r79 -> 0.1.dev79
506
+ rs = re.sub(r"[\-\.](dev)[\-\.]?r?(\d+)$", r".\1\2", rs)
507
+
508
+ # Clean: 2.0.a.3, 2.0.b1, 0.9.0~c1
509
+ rs = re.sub(r"[.~]?([abc])\.?", r"\1", rs)
510
+
511
+ # Clean: v0.3, v1.0
512
+ if rs.startswith('v'):
513
+ rs = rs[1:]
514
+
515
+ # Clean leading '0's on numbers.
516
+ # TODO: unintended side-effect on, e.g., "2003.05.09"
517
+ # PyPI stats: 77 (~2%) better
518
+ rs = re.sub(r"\b0+(\d+)(?!\d)", r"\1", rs)
519
+
520
+ # Clean a/b/c with no version. E.g. "1.0a" -> "1.0a0". Setuptools infers
521
+ # zero.
522
+ # PyPI stats: 245 (7.56%) better
523
+ rs = re.sub(r"(\d+[abc])$", r"\g<1>0", rs)
524
+
525
+ # the 'dev-rNNN' tag is a dev tag
526
+ rs = re.sub(r"\.?(dev-r|dev\.r)\.?(\d+)$", r".dev\2", rs)
527
+
528
+ # clean the - when used as a pre delimiter
529
+ rs = re.sub(r"-(a|b|c)(\d+)$", r"\1\2", rs)
530
+
531
+ # a terminal "dev" or "devel" can be changed into ".dev0"
532
+ rs = re.sub(r"[\.\-](dev|devel)$", r".dev0", rs)
533
+
534
+ # a terminal "dev" can be changed into ".dev0"
535
+ rs = re.sub(r"(?![\.\-])dev$", r".dev0", rs)
536
+
537
+ # a terminal "final" or "stable" can be removed
538
+ rs = re.sub(r"(final|stable)$", "", rs)
539
+
540
+ # The 'r' and the '-' tags are post release tags
541
+ # 0.4a1.r10 -> 0.4a1.post10
542
+ # 0.9.33-17222 -> 0.9.33.post17222
543
+ # 0.9.33-r17222 -> 0.9.33.post17222
544
+ rs = re.sub(r"\.?(r|-|-r)\.?(\d+)$", r".post\2", rs)
545
+
546
+ # Clean 'r' instead of 'dev' usage:
547
+ # 0.9.33+r17222 -> 0.9.33.dev17222
548
+ # 1.0dev123 -> 1.0.dev123
549
+ # 1.0.git123 -> 1.0.dev123
550
+ # 1.0.bzr123 -> 1.0.dev123
551
+ # 0.1a0dev.123 -> 0.1a0.dev123
552
+ # PyPI stats: ~150 (~4%) better
553
+ rs = re.sub(r"\.?(dev|git|bzr)\.?(\d+)$", r".dev\2", rs)
554
+
555
+ # Clean '.pre' (normalized from '-pre' above) instead of 'c' usage:
556
+ # 0.2.pre1 -> 0.2c1
557
+ # 0.2-c1 -> 0.2c1
558
+ # 1.0preview123 -> 1.0c123
559
+ # PyPI stats: ~21 (0.62%) better
560
+ rs = re.sub(r"\.?(pre|preview|-c)(\d+)$", r"c\g<2>", rs)
561
+
562
+ # Tcl/Tk uses "px" for their post release markers
563
+ rs = re.sub(r"p(\d+)$", r".post\1", rs)
564
+
565
+ try:
566
+ _normalized_key(rs)
567
+ except UnsupportedVersionError:
568
+ rs = None
569
+ return rs
570
+
571
+ #
572
+ # Legacy version processing (distribute-compatible)
573
+ #
574
+
575
+
576
+ _VERSION_PART = re.compile(r'([a-z]+|\d+|[\.-])', re.I)
577
+ _VERSION_REPLACE = {
578
+ 'pre': 'c',
579
+ 'preview': 'c',
580
+ '-': 'final-',
581
+ 'rc': 'c',
582
+ 'dev': '@',
583
+ '': None,
584
+ '.': None,
585
+ }
586
+
587
+
588
+ def _legacy_key(s):
589
+ def get_parts(s):
590
+ result = []
591
+ for p in _VERSION_PART.split(s.lower()):
592
+ p = _VERSION_REPLACE.get(p, p)
593
+ if p:
594
+ if '0' <= p[:1] <= '9':
595
+ p = p.zfill(8)
596
+ else:
597
+ p = '*' + p
598
+ result.append(p)
599
+ result.append('*final')
600
+ return result
601
+
602
+ result = []
603
+ for p in get_parts(s):
604
+ if p.startswith('*'):
605
+ if p < '*final':
606
+ while result and result[-1] == '*final-':
607
+ result.pop()
608
+ while result and result[-1] == '00000000':
609
+ result.pop()
610
+ result.append(p)
611
+ return tuple(result)
612
+
613
+
614
+ class LegacyVersion(Version):
615
+ def parse(self, s):
616
+ return _legacy_key(s)
617
+
618
+ @property
619
+ def is_prerelease(self):
620
+ result = False
621
+ for x in self._parts:
622
+ if (isinstance(x, string_types) and x.startswith('*') and x < '*final'):
623
+ result = True
624
+ break
625
+ return result
626
+
627
+
628
+ class LegacyMatcher(Matcher):
629
+ version_class = LegacyVersion
630
+
631
+ _operators = dict(Matcher._operators)
632
+ _operators['~='] = '_match_compatible'
633
+
634
+ numeric_re = re.compile(r'^(\d+(\.\d+)*)')
635
+
636
+ def _match_compatible(self, version, constraint, prefix):
637
+ if version < constraint:
638
+ return False
639
+ m = self.numeric_re.match(str(constraint))
640
+ if not m:
641
+ logger.warning('Cannot compute compatible match for version %s '
642
+ ' and constraint %s', version, constraint)
643
+ return True
644
+ s = m.groups()[0]
645
+ if '.' in s:
646
+ s = s.rsplit('.', 1)[0]
647
+ return _match_prefix(version, s)
648
+
649
+ #
650
+ # Semantic versioning
651
+ #
652
+
653
+
654
+ _SEMVER_RE = re.compile(r'^(\d+)\.(\d+)\.(\d+)'
655
+ r'(-[a-z0-9]+(\.[a-z0-9-]+)*)?'
656
+ r'(\+[a-z0-9]+(\.[a-z0-9-]+)*)?$', re.I)
657
+
658
+
659
+ def is_semver(s):
660
+ return _SEMVER_RE.match(s)
661
+
662
+
663
+ def _semantic_key(s):
664
+ def make_tuple(s, absent):
665
+ if s is None:
666
+ result = (absent,)
667
+ else:
668
+ parts = s[1:].split('.')
669
+ # We can't compare ints and strings on Python 3, so fudge it
670
+ # by zero-filling numeric values so simulate a numeric comparison
671
+ result = tuple([p.zfill(8) if p.isdigit() else p for p in parts])
672
+ return result
673
+
674
+ m = is_semver(s)
675
+ if not m:
676
+ raise UnsupportedVersionError(s)
677
+ groups = m.groups()
678
+ major, minor, patch = [int(i) for i in groups[:3]]
679
+ # choose the '|' and '*' so that versions sort correctly
680
+ pre, build = make_tuple(groups[3], '|'), make_tuple(groups[5], '*')
681
+ return (major, minor, patch), pre, build
682
+
683
+
684
+ class SemanticVersion(Version):
685
+ def parse(self, s):
686
+ return _semantic_key(s)
687
+
688
+ @property
689
+ def is_prerelease(self):
690
+ return self._parts[1][0] != '|'
691
+
692
+
693
+ class SemanticMatcher(Matcher):
694
+ version_class = SemanticVersion
695
+
696
+
697
+ class VersionScheme(object):
698
+ def __init__(self, key, matcher, suggester=None):
699
+ self.key = key
700
+ self.matcher = matcher
701
+ self.suggester = suggester
702
+
703
+ def is_valid_version(self, s):
704
+ try:
705
+ self.matcher.version_class(s)
706
+ result = True
707
+ except UnsupportedVersionError:
708
+ result = False
709
+ return result
710
+
711
+ def is_valid_matcher(self, s):
712
+ try:
713
+ self.matcher(s)
714
+ result = True
715
+ except UnsupportedVersionError:
716
+ result = False
717
+ return result
718
+
719
+ def is_valid_constraint_list(self, s):
720
+ """
721
+ Used for processing some metadata fields
722
+ """
723
+ # See issue #140. Be tolerant of a single trailing comma.
724
+ if s.endswith(','):
725
+ s = s[:-1]
726
+ return self.is_valid_matcher('dummy_name (%s)' % s)
727
+
728
+ def suggest(self, s):
729
+ if self.suggester is None:
730
+ result = None
731
+ else:
732
+ result = self.suggester(s)
733
+ return result
734
+
735
+
736
+ _SCHEMES = {
737
+ 'normalized': VersionScheme(_normalized_key, NormalizedMatcher,
738
+ _suggest_normalized_version),
739
+ 'legacy': VersionScheme(_legacy_key, LegacyMatcher, lambda self, s: s),
740
+ 'semantic': VersionScheme(_semantic_key, SemanticMatcher,
741
+ _suggest_semantic_version),
742
+ }
743
+
744
+ _SCHEMES['default'] = _SCHEMES['normalized']
745
+
746
+
747
+ def get_scheme(name):
748
+ if name not in _SCHEMES:
749
+ raise ValueError('unknown scheme name: %r' % name)
750
+ return _SCHEMES[name]
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/distlib/wheel.py ADDED
@@ -0,0 +1,1100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2013-2023 Vinay Sajip.
4
+ # Licensed to the Python Software Foundation under a contributor agreement.
5
+ # See LICENSE.txt and CONTRIBUTORS.txt.
6
+ #
7
+ from __future__ import unicode_literals
8
+
9
+ import base64
10
+ import codecs
11
+ import datetime
12
+ from email import message_from_file
13
+ import hashlib
14
+ import json
15
+ import logging
16
+ import os
17
+ import posixpath
18
+ import re
19
+ import shutil
20
+ import sys
21
+ import tempfile
22
+ import zipfile
23
+
24
+ from . import __version__, DistlibException
25
+ from .compat import sysconfig, ZipFile, fsdecode, text_type, filter
26
+ from .database import InstalledDistribution
27
+ from .metadata import Metadata, WHEEL_METADATA_FILENAME, LEGACY_METADATA_FILENAME
28
+ from .util import (FileOperator, convert_path, CSVReader, CSVWriter, Cache, cached_property, get_cache_base,
29
+ read_exports, tempdir, get_platform)
30
+ from .version import NormalizedVersion, UnsupportedVersionError
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ cache = None # created when needed
35
+
36
+ if hasattr(sys, 'pypy_version_info'): # pragma: no cover
37
+ IMP_PREFIX = 'pp'
38
+ elif sys.platform.startswith('java'): # pragma: no cover
39
+ IMP_PREFIX = 'jy'
40
+ elif sys.platform == 'cli': # pragma: no cover
41
+ IMP_PREFIX = 'ip'
42
+ else:
43
+ IMP_PREFIX = 'cp'
44
+
45
+ VER_SUFFIX = sysconfig.get_config_var('py_version_nodot')
46
+ if not VER_SUFFIX: # pragma: no cover
47
+ VER_SUFFIX = '%s%s' % sys.version_info[:2]
48
+ PYVER = 'py' + VER_SUFFIX
49
+ IMPVER = IMP_PREFIX + VER_SUFFIX
50
+
51
+ ARCH = get_platform().replace('-', '_').replace('.', '_')
52
+
53
+ ABI = sysconfig.get_config_var('SOABI')
54
+ if ABI and ABI.startswith('cpython-'):
55
+ ABI = ABI.replace('cpython-', 'cp').split('-')[0]
56
+ else:
57
+
58
+ def _derive_abi():
59
+ parts = ['cp', VER_SUFFIX]
60
+ if sysconfig.get_config_var('Py_DEBUG'):
61
+ parts.append('d')
62
+ if IMP_PREFIX == 'cp':
63
+ vi = sys.version_info[:2]
64
+ if vi < (3, 8):
65
+ wpm = sysconfig.get_config_var('WITH_PYMALLOC')
66
+ if wpm is None:
67
+ wpm = True
68
+ if wpm:
69
+ parts.append('m')
70
+ if vi < (3, 3):
71
+ us = sysconfig.get_config_var('Py_UNICODE_SIZE')
72
+ if us == 4 or (us is None and sys.maxunicode == 0x10FFFF):
73
+ parts.append('u')
74
+ return ''.join(parts)
75
+
76
+ ABI = _derive_abi()
77
+ del _derive_abi
78
+
79
+ FILENAME_RE = re.compile(
80
+ r'''
81
+ (?P<nm>[^-]+)
82
+ -(?P<vn>\d+[^-]*)
83
+ (-(?P<bn>\d+[^-]*))?
84
+ -(?P<py>\w+\d+(\.\w+\d+)*)
85
+ -(?P<bi>\w+)
86
+ -(?P<ar>\w+(\.\w+)*)
87
+ \.whl$
88
+ ''', re.IGNORECASE | re.VERBOSE)
89
+
90
+ NAME_VERSION_RE = re.compile(r'''
91
+ (?P<nm>[^-]+)
92
+ -(?P<vn>\d+[^-]*)
93
+ (-(?P<bn>\d+[^-]*))?$
94
+ ''', re.IGNORECASE | re.VERBOSE)
95
+
96
+ SHEBANG_RE = re.compile(br'\s*#![^\r\n]*')
97
+ SHEBANG_DETAIL_RE = re.compile(br'^(\s*#!("[^"]+"|\S+))\s+(.*)$')
98
+ SHEBANG_PYTHON = b'#!python'
99
+ SHEBANG_PYTHONW = b'#!pythonw'
100
+
101
+ if os.sep == '/':
102
+ to_posix = lambda o: o
103
+ else:
104
+ to_posix = lambda o: o.replace(os.sep, '/')
105
+
106
+ if sys.version_info[0] < 3:
107
+ import imp
108
+ else:
109
+ imp = None
110
+ import importlib.machinery
111
+ import importlib.util
112
+
113
+
114
+ def _get_suffixes():
115
+ if imp:
116
+ return [s[0] for s in imp.get_suffixes()]
117
+ else:
118
+ return importlib.machinery.EXTENSION_SUFFIXES
119
+
120
+
121
+ def _load_dynamic(name, path):
122
+ # https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
123
+ if imp:
124
+ return imp.load_dynamic(name, path)
125
+ else:
126
+ spec = importlib.util.spec_from_file_location(name, path)
127
+ module = importlib.util.module_from_spec(spec)
128
+ sys.modules[name] = module
129
+ spec.loader.exec_module(module)
130
+ return module
131
+
132
+
133
+ class Mounter(object):
134
+
135
+ def __init__(self):
136
+ self.impure_wheels = {}
137
+ self.libs = {}
138
+
139
+ def add(self, pathname, extensions):
140
+ self.impure_wheels[pathname] = extensions
141
+ self.libs.update(extensions)
142
+
143
+ def remove(self, pathname):
144
+ extensions = self.impure_wheels.pop(pathname)
145
+ for k, v in extensions:
146
+ if k in self.libs:
147
+ del self.libs[k]
148
+
149
+ def find_module(self, fullname, path=None):
150
+ if fullname in self.libs:
151
+ result = self
152
+ else:
153
+ result = None
154
+ return result
155
+
156
+ def load_module(self, fullname):
157
+ if fullname in sys.modules:
158
+ result = sys.modules[fullname]
159
+ else:
160
+ if fullname not in self.libs:
161
+ raise ImportError('unable to find extension for %s' % fullname)
162
+ result = _load_dynamic(fullname, self.libs[fullname])
163
+ result.__loader__ = self
164
+ parts = fullname.rsplit('.', 1)
165
+ if len(parts) > 1:
166
+ result.__package__ = parts[0]
167
+ return result
168
+
169
+
170
+ _hook = Mounter()
171
+
172
+
173
+ class Wheel(object):
174
+ """
175
+ Class to build and install from Wheel files (PEP 427).
176
+ """
177
+
178
+ wheel_version = (1, 1)
179
+ hash_kind = 'sha256'
180
+
181
+ def __init__(self, filename=None, sign=False, verify=False):
182
+ """
183
+ Initialise an instance using a (valid) filename.
184
+ """
185
+ self.sign = sign
186
+ self.should_verify = verify
187
+ self.buildver = ''
188
+ self.pyver = [PYVER]
189
+ self.abi = ['none']
190
+ self.arch = ['any']
191
+ self.dirname = os.getcwd()
192
+ if filename is None:
193
+ self.name = 'dummy'
194
+ self.version = '0.1'
195
+ self._filename = self.filename
196
+ else:
197
+ m = NAME_VERSION_RE.match(filename)
198
+ if m:
199
+ info = m.groupdict('')
200
+ self.name = info['nm']
201
+ # Reinstate the local version separator
202
+ self.version = info['vn'].replace('_', '-')
203
+ self.buildver = info['bn']
204
+ self._filename = self.filename
205
+ else:
206
+ dirname, filename = os.path.split(filename)
207
+ m = FILENAME_RE.match(filename)
208
+ if not m:
209
+ raise DistlibException('Invalid name or '
210
+ 'filename: %r' % filename)
211
+ if dirname:
212
+ self.dirname = os.path.abspath(dirname)
213
+ self._filename = filename
214
+ info = m.groupdict('')
215
+ self.name = info['nm']
216
+ self.version = info['vn']
217
+ self.buildver = info['bn']
218
+ self.pyver = info['py'].split('.')
219
+ self.abi = info['bi'].split('.')
220
+ self.arch = info['ar'].split('.')
221
+
222
+ @property
223
+ def filename(self):
224
+ """
225
+ Build and return a filename from the various components.
226
+ """
227
+ if self.buildver:
228
+ buildver = '-' + self.buildver
229
+ else:
230
+ buildver = ''
231
+ pyver = '.'.join(self.pyver)
232
+ abi = '.'.join(self.abi)
233
+ arch = '.'.join(self.arch)
234
+ # replace - with _ as a local version separator
235
+ version = self.version.replace('-', '_')
236
+ return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver, pyver, abi, arch)
237
+
238
+ @property
239
+ def exists(self):
240
+ path = os.path.join(self.dirname, self.filename)
241
+ return os.path.isfile(path)
242
+
243
+ @property
244
+ def tags(self):
245
+ for pyver in self.pyver:
246
+ for abi in self.abi:
247
+ for arch in self.arch:
248
+ yield pyver, abi, arch
249
+
250
+ @cached_property
251
+ def metadata(self):
252
+ pathname = os.path.join(self.dirname, self.filename)
253
+ name_ver = '%s-%s' % (self.name, self.version)
254
+ info_dir = '%s.dist-info' % name_ver
255
+ wrapper = codecs.getreader('utf-8')
256
+ with ZipFile(pathname, 'r') as zf:
257
+ self.get_wheel_metadata(zf)
258
+ # wv = wheel_metadata['Wheel-Version'].split('.', 1)
259
+ # file_version = tuple([int(i) for i in wv])
260
+ # if file_version < (1, 1):
261
+ # fns = [WHEEL_METADATA_FILENAME, METADATA_FILENAME,
262
+ # LEGACY_METADATA_FILENAME]
263
+ # else:
264
+ # fns = [WHEEL_METADATA_FILENAME, METADATA_FILENAME]
265
+ fns = [WHEEL_METADATA_FILENAME, LEGACY_METADATA_FILENAME]
266
+ result = None
267
+ for fn in fns:
268
+ try:
269
+ metadata_filename = posixpath.join(info_dir, fn)
270
+ with zf.open(metadata_filename) as bf:
271
+ wf = wrapper(bf)
272
+ result = Metadata(fileobj=wf)
273
+ if result:
274
+ break
275
+ except KeyError:
276
+ pass
277
+ if not result:
278
+ raise ValueError('Invalid wheel, because metadata is '
279
+ 'missing: looked in %s' % ', '.join(fns))
280
+ return result
281
+
282
+ def get_wheel_metadata(self, zf):
283
+ name_ver = '%s-%s' % (self.name, self.version)
284
+ info_dir = '%s.dist-info' % name_ver
285
+ metadata_filename = posixpath.join(info_dir, 'WHEEL')
286
+ with zf.open(metadata_filename) as bf:
287
+ wf = codecs.getreader('utf-8')(bf)
288
+ message = message_from_file(wf)
289
+ return dict(message)
290
+
291
+ @cached_property
292
+ def info(self):
293
+ pathname = os.path.join(self.dirname, self.filename)
294
+ with ZipFile(pathname, 'r') as zf:
295
+ result = self.get_wheel_metadata(zf)
296
+ return result
297
+
298
+ def process_shebang(self, data):
299
+ m = SHEBANG_RE.match(data)
300
+ if m:
301
+ end = m.end()
302
+ shebang, data_after_shebang = data[:end], data[end:]
303
+ # Preserve any arguments after the interpreter
304
+ if b'pythonw' in shebang.lower():
305
+ shebang_python = SHEBANG_PYTHONW
306
+ else:
307
+ shebang_python = SHEBANG_PYTHON
308
+ m = SHEBANG_DETAIL_RE.match(shebang)
309
+ if m:
310
+ args = b' ' + m.groups()[-1]
311
+ else:
312
+ args = b''
313
+ shebang = shebang_python + args
314
+ data = shebang + data_after_shebang
315
+ else:
316
+ cr = data.find(b'\r')
317
+ lf = data.find(b'\n')
318
+ if cr < 0 or cr > lf:
319
+ term = b'\n'
320
+ else:
321
+ if data[cr:cr + 2] == b'\r\n':
322
+ term = b'\r\n'
323
+ else:
324
+ term = b'\r'
325
+ data = SHEBANG_PYTHON + term + data
326
+ return data
327
+
328
+ def get_hash(self, data, hash_kind=None):
329
+ if hash_kind is None:
330
+ hash_kind = self.hash_kind
331
+ try:
332
+ hasher = getattr(hashlib, hash_kind)
333
+ except AttributeError:
334
+ raise DistlibException('Unsupported hash algorithm: %r' % hash_kind)
335
+ result = hasher(data).digest()
336
+ result = base64.urlsafe_b64encode(result).rstrip(b'=').decode('ascii')
337
+ return hash_kind, result
338
+
339
+ def write_record(self, records, record_path, archive_record_path):
340
+ records = list(records) # make a copy, as mutated
341
+ records.append((archive_record_path, '', ''))
342
+ with CSVWriter(record_path) as writer:
343
+ for row in records:
344
+ writer.writerow(row)
345
+
346
+ def write_records(self, info, libdir, archive_paths):
347
+ records = []
348
+ distinfo, info_dir = info
349
+ # hasher = getattr(hashlib, self.hash_kind)
350
+ for ap, p in archive_paths:
351
+ with open(p, 'rb') as f:
352
+ data = f.read()
353
+ digest = '%s=%s' % self.get_hash(data)
354
+ size = os.path.getsize(p)
355
+ records.append((ap, digest, size))
356
+
357
+ p = os.path.join(distinfo, 'RECORD')
358
+ ap = to_posix(os.path.join(info_dir, 'RECORD'))
359
+ self.write_record(records, p, ap)
360
+ archive_paths.append((ap, p))
361
+
362
+ def build_zip(self, pathname, archive_paths):
363
+ with ZipFile(pathname, 'w', zipfile.ZIP_DEFLATED) as zf:
364
+ for ap, p in archive_paths:
365
+ logger.debug('Wrote %s to %s in wheel', p, ap)
366
+ zf.write(p, ap)
367
+
368
+ def build(self, paths, tags=None, wheel_version=None):
369
+ """
370
+ Build a wheel from files in specified paths, and use any specified tags
371
+ when determining the name of the wheel.
372
+ """
373
+ if tags is None:
374
+ tags = {}
375
+
376
+ libkey = list(filter(lambda o: o in paths, ('purelib', 'platlib')))[0]
377
+ if libkey == 'platlib':
378
+ is_pure = 'false'
379
+ default_pyver = [IMPVER]
380
+ default_abi = [ABI]
381
+ default_arch = [ARCH]
382
+ else:
383
+ is_pure = 'true'
384
+ default_pyver = [PYVER]
385
+ default_abi = ['none']
386
+ default_arch = ['any']
387
+
388
+ self.pyver = tags.get('pyver', default_pyver)
389
+ self.abi = tags.get('abi', default_abi)
390
+ self.arch = tags.get('arch', default_arch)
391
+
392
+ libdir = paths[libkey]
393
+
394
+ name_ver = '%s-%s' % (self.name, self.version)
395
+ data_dir = '%s.data' % name_ver
396
+ info_dir = '%s.dist-info' % name_ver
397
+
398
+ archive_paths = []
399
+
400
+ # First, stuff which is not in site-packages
401
+ for key in ('data', 'headers', 'scripts'):
402
+ if key not in paths:
403
+ continue
404
+ path = paths[key]
405
+ if os.path.isdir(path):
406
+ for root, dirs, files in os.walk(path):
407
+ for fn in files:
408
+ p = fsdecode(os.path.join(root, fn))
409
+ rp = os.path.relpath(p, path)
410
+ ap = to_posix(os.path.join(data_dir, key, rp))
411
+ archive_paths.append((ap, p))
412
+ if key == 'scripts' and not p.endswith('.exe'):
413
+ with open(p, 'rb') as f:
414
+ data = f.read()
415
+ data = self.process_shebang(data)
416
+ with open(p, 'wb') as f:
417
+ f.write(data)
418
+
419
+ # Now, stuff which is in site-packages, other than the
420
+ # distinfo stuff.
421
+ path = libdir
422
+ distinfo = None
423
+ for root, dirs, files in os.walk(path):
424
+ if root == path:
425
+ # At the top level only, save distinfo for later
426
+ # and skip it for now
427
+ for i, dn in enumerate(dirs):
428
+ dn = fsdecode(dn)
429
+ if dn.endswith('.dist-info'):
430
+ distinfo = os.path.join(root, dn)
431
+ del dirs[i]
432
+ break
433
+ assert distinfo, '.dist-info directory expected, not found'
434
+
435
+ for fn in files:
436
+ # comment out next suite to leave .pyc files in
437
+ if fsdecode(fn).endswith(('.pyc', '.pyo')):
438
+ continue
439
+ p = os.path.join(root, fn)
440
+ rp = to_posix(os.path.relpath(p, path))
441
+ archive_paths.append((rp, p))
442
+
443
+ # Now distinfo. Assumed to be flat, i.e. os.listdir is enough.
444
+ files = os.listdir(distinfo)
445
+ for fn in files:
446
+ if fn not in ('RECORD', 'INSTALLER', 'SHARED', 'WHEEL'):
447
+ p = fsdecode(os.path.join(distinfo, fn))
448
+ ap = to_posix(os.path.join(info_dir, fn))
449
+ archive_paths.append((ap, p))
450
+
451
+ wheel_metadata = [
452
+ 'Wheel-Version: %d.%d' % (wheel_version or self.wheel_version),
453
+ 'Generator: distlib %s' % __version__,
454
+ 'Root-Is-Purelib: %s' % is_pure,
455
+ ]
456
+ for pyver, abi, arch in self.tags:
457
+ wheel_metadata.append('Tag: %s-%s-%s' % (pyver, abi, arch))
458
+ p = os.path.join(distinfo, 'WHEEL')
459
+ with open(p, 'w') as f:
460
+ f.write('\n'.join(wheel_metadata))
461
+ ap = to_posix(os.path.join(info_dir, 'WHEEL'))
462
+ archive_paths.append((ap, p))
463
+
464
+ # sort the entries by archive path. Not needed by any spec, but it
465
+ # keeps the archive listing and RECORD tidier than they would otherwise
466
+ # be. Use the number of path segments to keep directory entries together,
467
+ # and keep the dist-info stuff at the end.
468
+ def sorter(t):
469
+ ap = t[0]
470
+ n = ap.count('/')
471
+ if '.dist-info' in ap:
472
+ n += 10000
473
+ return (n, ap)
474
+
475
+ archive_paths = sorted(archive_paths, key=sorter)
476
+
477
+ # Now, at last, RECORD.
478
+ # Paths in here are archive paths - nothing else makes sense.
479
+ self.write_records((distinfo, info_dir), libdir, archive_paths)
480
+ # Now, ready to build the zip file
481
+ pathname = os.path.join(self.dirname, self.filename)
482
+ self.build_zip(pathname, archive_paths)
483
+ return pathname
484
+
485
+ def skip_entry(self, arcname):
486
+ """
487
+ Determine whether an archive entry should be skipped when verifying
488
+ or installing.
489
+ """
490
+ # The signature file won't be in RECORD,
491
+ # and we don't currently don't do anything with it
492
+ # We also skip directories, as they won't be in RECORD
493
+ # either. See:
494
+ #
495
+ # https://github.com/pypa/wheel/issues/294
496
+ # https://github.com/pypa/wheel/issues/287
497
+ # https://github.com/pypa/wheel/pull/289
498
+ #
499
+ return arcname.endswith(('/', '/RECORD.jws'))
500
+
501
+ def install(self, paths, maker, **kwargs):
502
+ """
503
+ Install a wheel to the specified paths. If kwarg ``warner`` is
504
+ specified, it should be a callable, which will be called with two
505
+ tuples indicating the wheel version of this software and the wheel
506
+ version in the file, if there is a discrepancy in the versions.
507
+ This can be used to issue any warnings to raise any exceptions.
508
+ If kwarg ``lib_only`` is True, only the purelib/platlib files are
509
+ installed, and the headers, scripts, data and dist-info metadata are
510
+ not written. If kwarg ``bytecode_hashed_invalidation`` is True, written
511
+ bytecode will try to use file-hash based invalidation (PEP-552) on
512
+ supported interpreter versions (CPython 3.7+).
513
+
514
+ The return value is a :class:`InstalledDistribution` instance unless
515
+ ``options.lib_only`` is True, in which case the return value is ``None``.
516
+ """
517
+
518
+ dry_run = maker.dry_run
519
+ warner = kwargs.get('warner')
520
+ lib_only = kwargs.get('lib_only', False)
521
+ bc_hashed_invalidation = kwargs.get('bytecode_hashed_invalidation', False)
522
+
523
+ pathname = os.path.join(self.dirname, self.filename)
524
+ name_ver = '%s-%s' % (self.name, self.version)
525
+ data_dir = '%s.data' % name_ver
526
+ info_dir = '%s.dist-info' % name_ver
527
+
528
+ metadata_name = posixpath.join(info_dir, LEGACY_METADATA_FILENAME)
529
+ wheel_metadata_name = posixpath.join(info_dir, 'WHEEL')
530
+ record_name = posixpath.join(info_dir, 'RECORD')
531
+
532
+ wrapper = codecs.getreader('utf-8')
533
+
534
+ with ZipFile(pathname, 'r') as zf:
535
+ with zf.open(wheel_metadata_name) as bwf:
536
+ wf = wrapper(bwf)
537
+ message = message_from_file(wf)
538
+ wv = message['Wheel-Version'].split('.', 1)
539
+ file_version = tuple([int(i) for i in wv])
540
+ if (file_version != self.wheel_version) and warner:
541
+ warner(self.wheel_version, file_version)
542
+
543
+ if message['Root-Is-Purelib'] == 'true':
544
+ libdir = paths['purelib']
545
+ else:
546
+ libdir = paths['platlib']
547
+
548
+ records = {}
549
+ with zf.open(record_name) as bf:
550
+ with CSVReader(stream=bf) as reader:
551
+ for row in reader:
552
+ p = row[0]
553
+ records[p] = row
554
+
555
+ data_pfx = posixpath.join(data_dir, '')
556
+ info_pfx = posixpath.join(info_dir, '')
557
+ script_pfx = posixpath.join(data_dir, 'scripts', '')
558
+
559
+ # make a new instance rather than a copy of maker's,
560
+ # as we mutate it
561
+ fileop = FileOperator(dry_run=dry_run)
562
+ fileop.record = True # so we can rollback if needed
563
+
564
+ bc = not sys.dont_write_bytecode # Double negatives. Lovely!
565
+
566
+ outfiles = [] # for RECORD writing
567
+
568
+ # for script copying/shebang processing
569
+ workdir = tempfile.mkdtemp()
570
+ # set target dir later
571
+ # we default add_launchers to False, as the
572
+ # Python Launcher should be used instead
573
+ maker.source_dir = workdir
574
+ maker.target_dir = None
575
+ try:
576
+ for zinfo in zf.infolist():
577
+ arcname = zinfo.filename
578
+ if isinstance(arcname, text_type):
579
+ u_arcname = arcname
580
+ else:
581
+ u_arcname = arcname.decode('utf-8')
582
+ if self.skip_entry(u_arcname):
583
+ continue
584
+ row = records[u_arcname]
585
+ if row[2] and str(zinfo.file_size) != row[2]:
586
+ raise DistlibException('size mismatch for '
587
+ '%s' % u_arcname)
588
+ if row[1]:
589
+ kind, value = row[1].split('=', 1)
590
+ with zf.open(arcname) as bf:
591
+ data = bf.read()
592
+ _, digest = self.get_hash(data, kind)
593
+ if digest != value:
594
+ raise DistlibException('digest mismatch for '
595
+ '%s' % arcname)
596
+
597
+ if lib_only and u_arcname.startswith((info_pfx, data_pfx)):
598
+ logger.debug('lib_only: skipping %s', u_arcname)
599
+ continue
600
+ is_script = (u_arcname.startswith(script_pfx) and not u_arcname.endswith('.exe'))
601
+
602
+ if u_arcname.startswith(data_pfx):
603
+ _, where, rp = u_arcname.split('/', 2)
604
+ outfile = os.path.join(paths[where], convert_path(rp))
605
+ else:
606
+ # meant for site-packages.
607
+ if u_arcname in (wheel_metadata_name, record_name):
608
+ continue
609
+ outfile = os.path.join(libdir, convert_path(u_arcname))
610
+ if not is_script:
611
+ with zf.open(arcname) as bf:
612
+ fileop.copy_stream(bf, outfile)
613
+ # Issue #147: permission bits aren't preserved. Using
614
+ # zf.extract(zinfo, libdir) should have worked, but didn't,
615
+ # see https://www.thetopsites.net/article/53834422.shtml
616
+ # So ... manually preserve permission bits as given in zinfo
617
+ if os.name == 'posix':
618
+ # just set the normal permission bits
619
+ os.chmod(outfile, (zinfo.external_attr >> 16) & 0x1FF)
620
+ outfiles.append(outfile)
621
+ # Double check the digest of the written file
622
+ if not dry_run and row[1]:
623
+ with open(outfile, 'rb') as bf:
624
+ data = bf.read()
625
+ _, newdigest = self.get_hash(data, kind)
626
+ if newdigest != digest:
627
+ raise DistlibException('digest mismatch '
628
+ 'on write for '
629
+ '%s' % outfile)
630
+ if bc and outfile.endswith('.py'):
631
+ try:
632
+ pyc = fileop.byte_compile(outfile, hashed_invalidation=bc_hashed_invalidation)
633
+ outfiles.append(pyc)
634
+ except Exception:
635
+ # Don't give up if byte-compilation fails,
636
+ # but log it and perhaps warn the user
637
+ logger.warning('Byte-compilation failed', exc_info=True)
638
+ else:
639
+ fn = os.path.basename(convert_path(arcname))
640
+ workname = os.path.join(workdir, fn)
641
+ with zf.open(arcname) as bf:
642
+ fileop.copy_stream(bf, workname)
643
+
644
+ dn, fn = os.path.split(outfile)
645
+ maker.target_dir = dn
646
+ filenames = maker.make(fn)
647
+ fileop.set_executable_mode(filenames)
648
+ outfiles.extend(filenames)
649
+
650
+ if lib_only:
651
+ logger.debug('lib_only: returning None')
652
+ dist = None
653
+ else:
654
+ # Generate scripts
655
+
656
+ # Try to get pydist.json so we can see if there are
657
+ # any commands to generate. If this fails (e.g. because
658
+ # of a legacy wheel), log a warning but don't give up.
659
+ commands = None
660
+ file_version = self.info['Wheel-Version']
661
+ if file_version == '1.0':
662
+ # Use legacy info
663
+ ep = posixpath.join(info_dir, 'entry_points.txt')
664
+ try:
665
+ with zf.open(ep) as bwf:
666
+ epdata = read_exports(bwf)
667
+ commands = {}
668
+ for key in ('console', 'gui'):
669
+ k = '%s_scripts' % key
670
+ if k in epdata:
671
+ commands['wrap_%s' % key] = d = {}
672
+ for v in epdata[k].values():
673
+ s = '%s:%s' % (v.prefix, v.suffix)
674
+ if v.flags:
675
+ s += ' [%s]' % ','.join(v.flags)
676
+ d[v.name] = s
677
+ except Exception:
678
+ logger.warning('Unable to read legacy script '
679
+ 'metadata, so cannot generate '
680
+ 'scripts')
681
+ else:
682
+ try:
683
+ with zf.open(metadata_name) as bwf:
684
+ wf = wrapper(bwf)
685
+ commands = json.load(wf).get('extensions')
686
+ if commands:
687
+ commands = commands.get('python.commands')
688
+ except Exception:
689
+ logger.warning('Unable to read JSON metadata, so '
690
+ 'cannot generate scripts')
691
+ if commands:
692
+ console_scripts = commands.get('wrap_console', {})
693
+ gui_scripts = commands.get('wrap_gui', {})
694
+ if console_scripts or gui_scripts:
695
+ script_dir = paths.get('scripts', '')
696
+ if not os.path.isdir(script_dir):
697
+ raise ValueError('Valid script path not '
698
+ 'specified')
699
+ maker.target_dir = script_dir
700
+ for k, v in console_scripts.items():
701
+ script = '%s = %s' % (k, v)
702
+ filenames = maker.make(script)
703
+ fileop.set_executable_mode(filenames)
704
+
705
+ if gui_scripts:
706
+ options = {'gui': True}
707
+ for k, v in gui_scripts.items():
708
+ script = '%s = %s' % (k, v)
709
+ filenames = maker.make(script, options)
710
+ fileop.set_executable_mode(filenames)
711
+
712
+ p = os.path.join(libdir, info_dir)
713
+ dist = InstalledDistribution(p)
714
+
715
+ # Write SHARED
716
+ paths = dict(paths) # don't change passed in dict
717
+ del paths['purelib']
718
+ del paths['platlib']
719
+ paths['lib'] = libdir
720
+ p = dist.write_shared_locations(paths, dry_run)
721
+ if p:
722
+ outfiles.append(p)
723
+
724
+ # Write RECORD
725
+ dist.write_installed_files(outfiles, paths['prefix'], dry_run)
726
+ return dist
727
+ except Exception: # pragma: no cover
728
+ logger.exception('installation failed.')
729
+ fileop.rollback()
730
+ raise
731
+ finally:
732
+ shutil.rmtree(workdir)
733
+
734
+ def _get_dylib_cache(self):
735
+ global cache
736
+ if cache is None:
737
+ # Use native string to avoid issues on 2.x: see Python #20140.
738
+ base = os.path.join(get_cache_base(), str('dylib-cache'), '%s.%s' % sys.version_info[:2])
739
+ cache = Cache(base)
740
+ return cache
741
+
742
+ def _get_extensions(self):
743
+ pathname = os.path.join(self.dirname, self.filename)
744
+ name_ver = '%s-%s' % (self.name, self.version)
745
+ info_dir = '%s.dist-info' % name_ver
746
+ arcname = posixpath.join(info_dir, 'EXTENSIONS')
747
+ wrapper = codecs.getreader('utf-8')
748
+ result = []
749
+ with ZipFile(pathname, 'r') as zf:
750
+ try:
751
+ with zf.open(arcname) as bf:
752
+ wf = wrapper(bf)
753
+ extensions = json.load(wf)
754
+ cache = self._get_dylib_cache()
755
+ prefix = cache.prefix_to_dir(self.filename, use_abspath=False)
756
+ cache_base = os.path.join(cache.base, prefix)
757
+ if not os.path.isdir(cache_base):
758
+ os.makedirs(cache_base)
759
+ for name, relpath in extensions.items():
760
+ dest = os.path.join(cache_base, convert_path(relpath))
761
+ if not os.path.exists(dest):
762
+ extract = True
763
+ else:
764
+ file_time = os.stat(dest).st_mtime
765
+ file_time = datetime.datetime.fromtimestamp(file_time)
766
+ info = zf.getinfo(relpath)
767
+ wheel_time = datetime.datetime(*info.date_time)
768
+ extract = wheel_time > file_time
769
+ if extract:
770
+ zf.extract(relpath, cache_base)
771
+ result.append((name, dest))
772
+ except KeyError:
773
+ pass
774
+ return result
775
+
776
+ def is_compatible(self):
777
+ """
778
+ Determine if a wheel is compatible with the running system.
779
+ """
780
+ return is_compatible(self)
781
+
782
+ def is_mountable(self):
783
+ """
784
+ Determine if a wheel is asserted as mountable by its metadata.
785
+ """
786
+ return True # for now - metadata details TBD
787
+
788
+ def mount(self, append=False):
789
+ pathname = os.path.abspath(os.path.join(self.dirname, self.filename))
790
+ if not self.is_compatible():
791
+ msg = 'Wheel %s not compatible with this Python.' % pathname
792
+ raise DistlibException(msg)
793
+ if not self.is_mountable():
794
+ msg = 'Wheel %s is marked as not mountable.' % pathname
795
+ raise DistlibException(msg)
796
+ if pathname in sys.path:
797
+ logger.debug('%s already in path', pathname)
798
+ else:
799
+ if append:
800
+ sys.path.append(pathname)
801
+ else:
802
+ sys.path.insert(0, pathname)
803
+ extensions = self._get_extensions()
804
+ if extensions:
805
+ if _hook not in sys.meta_path:
806
+ sys.meta_path.append(_hook)
807
+ _hook.add(pathname, extensions)
808
+
809
+ def unmount(self):
810
+ pathname = os.path.abspath(os.path.join(self.dirname, self.filename))
811
+ if pathname not in sys.path:
812
+ logger.debug('%s not in path', pathname)
813
+ else:
814
+ sys.path.remove(pathname)
815
+ if pathname in _hook.impure_wheels:
816
+ _hook.remove(pathname)
817
+ if not _hook.impure_wheels:
818
+ if _hook in sys.meta_path:
819
+ sys.meta_path.remove(_hook)
820
+
821
+ def verify(self):
822
+ pathname = os.path.join(self.dirname, self.filename)
823
+ name_ver = '%s-%s' % (self.name, self.version)
824
+ # data_dir = '%s.data' % name_ver
825
+ info_dir = '%s.dist-info' % name_ver
826
+
827
+ # metadata_name = posixpath.join(info_dir, LEGACY_METADATA_FILENAME)
828
+ wheel_metadata_name = posixpath.join(info_dir, 'WHEEL')
829
+ record_name = posixpath.join(info_dir, 'RECORD')
830
+
831
+ wrapper = codecs.getreader('utf-8')
832
+
833
+ with ZipFile(pathname, 'r') as zf:
834
+ with zf.open(wheel_metadata_name) as bwf:
835
+ wf = wrapper(bwf)
836
+ message_from_file(wf)
837
+ # wv = message['Wheel-Version'].split('.', 1)
838
+ # file_version = tuple([int(i) for i in wv])
839
+ # TODO version verification
840
+
841
+ records = {}
842
+ with zf.open(record_name) as bf:
843
+ with CSVReader(stream=bf) as reader:
844
+ for row in reader:
845
+ p = row[0]
846
+ records[p] = row
847
+
848
+ for zinfo in zf.infolist():
849
+ arcname = zinfo.filename
850
+ if isinstance(arcname, text_type):
851
+ u_arcname = arcname
852
+ else:
853
+ u_arcname = arcname.decode('utf-8')
854
+ # See issue #115: some wheels have .. in their entries, but
855
+ # in the filename ... e.g. __main__..py ! So the check is
856
+ # updated to look for .. in the directory portions
857
+ p = u_arcname.split('/')
858
+ if '..' in p:
859
+ raise DistlibException('invalid entry in '
860
+ 'wheel: %r' % u_arcname)
861
+
862
+ if self.skip_entry(u_arcname):
863
+ continue
864
+ row = records[u_arcname]
865
+ if row[2] and str(zinfo.file_size) != row[2]:
866
+ raise DistlibException('size mismatch for '
867
+ '%s' % u_arcname)
868
+ if row[1]:
869
+ kind, value = row[1].split('=', 1)
870
+ with zf.open(arcname) as bf:
871
+ data = bf.read()
872
+ _, digest = self.get_hash(data, kind)
873
+ if digest != value:
874
+ raise DistlibException('digest mismatch for '
875
+ '%s' % arcname)
876
+
877
+ def update(self, modifier, dest_dir=None, **kwargs):
878
+ """
879
+ Update the contents of a wheel in a generic way. The modifier should
880
+ be a callable which expects a dictionary argument: its keys are
881
+ archive-entry paths, and its values are absolute filesystem paths
882
+ where the contents the corresponding archive entries can be found. The
883
+ modifier is free to change the contents of the files pointed to, add
884
+ new entries and remove entries, before returning. This method will
885
+ extract the entire contents of the wheel to a temporary location, call
886
+ the modifier, and then use the passed (and possibly updated)
887
+ dictionary to write a new wheel. If ``dest_dir`` is specified, the new
888
+ wheel is written there -- otherwise, the original wheel is overwritten.
889
+
890
+ The modifier should return True if it updated the wheel, else False.
891
+ This method returns the same value the modifier returns.
892
+ """
893
+
894
+ def get_version(path_map, info_dir):
895
+ version = path = None
896
+ key = '%s/%s' % (info_dir, LEGACY_METADATA_FILENAME)
897
+ if key not in path_map:
898
+ key = '%s/PKG-INFO' % info_dir
899
+ if key in path_map:
900
+ path = path_map[key]
901
+ version = Metadata(path=path).version
902
+ return version, path
903
+
904
+ def update_version(version, path):
905
+ updated = None
906
+ try:
907
+ NormalizedVersion(version)
908
+ i = version.find('-')
909
+ if i < 0:
910
+ updated = '%s+1' % version
911
+ else:
912
+ parts = [int(s) for s in version[i + 1:].split('.')]
913
+ parts[-1] += 1
914
+ updated = '%s+%s' % (version[:i], '.'.join(str(i) for i in parts))
915
+ except UnsupportedVersionError:
916
+ logger.debug('Cannot update non-compliant (PEP-440) '
917
+ 'version %r', version)
918
+ if updated:
919
+ md = Metadata(path=path)
920
+ md.version = updated
921
+ legacy = path.endswith(LEGACY_METADATA_FILENAME)
922
+ md.write(path=path, legacy=legacy)
923
+ logger.debug('Version updated from %r to %r', version, updated)
924
+
925
+ pathname = os.path.join(self.dirname, self.filename)
926
+ name_ver = '%s-%s' % (self.name, self.version)
927
+ info_dir = '%s.dist-info' % name_ver
928
+ record_name = posixpath.join(info_dir, 'RECORD')
929
+ with tempdir() as workdir:
930
+ with ZipFile(pathname, 'r') as zf:
931
+ path_map = {}
932
+ for zinfo in zf.infolist():
933
+ arcname = zinfo.filename
934
+ if isinstance(arcname, text_type):
935
+ u_arcname = arcname
936
+ else:
937
+ u_arcname = arcname.decode('utf-8')
938
+ if u_arcname == record_name:
939
+ continue
940
+ if '..' in u_arcname:
941
+ raise DistlibException('invalid entry in '
942
+ 'wheel: %r' % u_arcname)
943
+ zf.extract(zinfo, workdir)
944
+ path = os.path.join(workdir, convert_path(u_arcname))
945
+ path_map[u_arcname] = path
946
+
947
+ # Remember the version.
948
+ original_version, _ = get_version(path_map, info_dir)
949
+ # Files extracted. Call the modifier.
950
+ modified = modifier(path_map, **kwargs)
951
+ if modified:
952
+ # Something changed - need to build a new wheel.
953
+ current_version, path = get_version(path_map, info_dir)
954
+ if current_version and (current_version == original_version):
955
+ # Add or update local version to signify changes.
956
+ update_version(current_version, path)
957
+ # Decide where the new wheel goes.
958
+ if dest_dir is None:
959
+ fd, newpath = tempfile.mkstemp(suffix='.whl', prefix='wheel-update-', dir=workdir)
960
+ os.close(fd)
961
+ else:
962
+ if not os.path.isdir(dest_dir):
963
+ raise DistlibException('Not a directory: %r' % dest_dir)
964
+ newpath = os.path.join(dest_dir, self.filename)
965
+ archive_paths = list(path_map.items())
966
+ distinfo = os.path.join(workdir, info_dir)
967
+ info = distinfo, info_dir
968
+ self.write_records(info, workdir, archive_paths)
969
+ self.build_zip(newpath, archive_paths)
970
+ if dest_dir is None:
971
+ shutil.copyfile(newpath, pathname)
972
+ return modified
973
+
974
+
975
+ def _get_glibc_version():
976
+ import platform
977
+ ver = platform.libc_ver()
978
+ result = []
979
+ if ver[0] == 'glibc':
980
+ for s in ver[1].split('.'):
981
+ result.append(int(s) if s.isdigit() else 0)
982
+ result = tuple(result)
983
+ return result
984
+
985
+
986
+ def compatible_tags():
987
+ """
988
+ Return (pyver, abi, arch) tuples compatible with this Python.
989
+ """
990
+ class _Version:
991
+ def __init__(self, major, minor):
992
+ self.major = major
993
+ self.major_minor = (major, minor)
994
+ self.string = ''.join((str(major), str(minor)))
995
+
996
+ def __str__(self):
997
+ return self.string
998
+
999
+
1000
+ versions = [
1001
+ _Version(sys.version_info.major, minor_version)
1002
+ for minor_version in range(sys.version_info.minor, -1, -1)
1003
+ ]
1004
+ abis = []
1005
+ for suffix in _get_suffixes():
1006
+ if suffix.startswith('.abi'):
1007
+ abis.append(suffix.split('.', 2)[1])
1008
+ abis.sort()
1009
+ if ABI != 'none':
1010
+ abis.insert(0, ABI)
1011
+ abis.append('none')
1012
+ result = []
1013
+
1014
+ arches = [ARCH]
1015
+ if sys.platform == 'darwin':
1016
+ m = re.match(r'(\w+)_(\d+)_(\d+)_(\w+)$', ARCH)
1017
+ if m:
1018
+ name, major, minor, arch = m.groups()
1019
+ minor = int(minor)
1020
+ matches = [arch]
1021
+ if arch in ('i386', 'ppc'):
1022
+ matches.append('fat')
1023
+ if arch in ('i386', 'ppc', 'x86_64'):
1024
+ matches.append('fat3')
1025
+ if arch in ('ppc64', 'x86_64'):
1026
+ matches.append('fat64')
1027
+ if arch in ('i386', 'x86_64'):
1028
+ matches.append('intel')
1029
+ if arch in ('i386', 'x86_64', 'intel', 'ppc', 'ppc64'):
1030
+ matches.append('universal')
1031
+ while minor >= 0:
1032
+ for match in matches:
1033
+ s = '%s_%s_%s_%s' % (name, major, minor, match)
1034
+ if s != ARCH: # already there
1035
+ arches.append(s)
1036
+ minor -= 1
1037
+
1038
+ # Most specific - our Python version, ABI and arch
1039
+ for i, version_object in enumerate(versions):
1040
+ version = str(version_object)
1041
+ add_abis = []
1042
+
1043
+ if i == 0:
1044
+ add_abis = abis
1045
+
1046
+ if IMP_PREFIX == 'cp' and version_object.major_minor >= (3, 2):
1047
+ limited_api_abi = 'abi' + str(version_object.major)
1048
+ if limited_api_abi not in add_abis:
1049
+ add_abis.append(limited_api_abi)
1050
+
1051
+ for abi in add_abis:
1052
+ for arch in arches:
1053
+ result.append((''.join((IMP_PREFIX, version)), abi, arch))
1054
+ # manylinux
1055
+ if abi != 'none' and sys.platform.startswith('linux'):
1056
+ arch = arch.replace('linux_', '')
1057
+ parts = _get_glibc_version()
1058
+ if len(parts) == 2:
1059
+ if parts >= (2, 5):
1060
+ result.append((''.join((IMP_PREFIX, version)), abi, 'manylinux1_%s' % arch))
1061
+ if parts >= (2, 12):
1062
+ result.append((''.join((IMP_PREFIX, version)), abi, 'manylinux2010_%s' % arch))
1063
+ if parts >= (2, 17):
1064
+ result.append((''.join((IMP_PREFIX, version)), abi, 'manylinux2014_%s' % arch))
1065
+ result.append((''.join(
1066
+ (IMP_PREFIX, version)), abi, 'manylinux_%s_%s_%s' % (parts[0], parts[1], arch)))
1067
+
1068
+ # where no ABI / arch dependency, but IMP_PREFIX dependency
1069
+ for i, version_object in enumerate(versions):
1070
+ version = str(version_object)
1071
+ result.append((''.join((IMP_PREFIX, version)), 'none', 'any'))
1072
+ if i == 0:
1073
+ result.append((''.join((IMP_PREFIX, version[0])), 'none', 'any'))
1074
+
1075
+ # no IMP_PREFIX, ABI or arch dependency
1076
+ for i, version_object in enumerate(versions):
1077
+ version = str(version_object)
1078
+ result.append((''.join(('py', version)), 'none', 'any'))
1079
+ if i == 0:
1080
+ result.append((''.join(('py', version[0])), 'none', 'any'))
1081
+
1082
+ return set(result)
1083
+
1084
+
1085
+ COMPATIBLE_TAGS = compatible_tags()
1086
+
1087
+ del compatible_tags
1088
+
1089
+
1090
+ def is_compatible(wheel, tags=None):
1091
+ if not isinstance(wheel, Wheel):
1092
+ wheel = Wheel(wheel) # assume it's a filename
1093
+ result = False
1094
+ if tags is None:
1095
+ tags = COMPATIBLE_TAGS
1096
+ for ver, abi, arch in tags:
1097
+ if ver in wheel.pyver and abi in wheel.abi and arch in wheel.arch:
1098
+ result = True
1099
+ break
1100
+ return result
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/__pycache__/codec.cpython-310.pyc ADDED
Binary file (3.26 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/__pycache__/intranges.cpython-310.pyc ADDED
Binary file (1.97 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/__pycache__/package_data.cpython-310.pyc ADDED
Binary file (199 Bytes). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/codec.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import codecs
2
+ import re
3
+ from typing import Any, Optional, Tuple
4
+
5
+ from .core import IDNAError, alabel, decode, encode, ulabel
6
+
7
+ _unicode_dots_re = re.compile("[\u002e\u3002\uff0e\uff61]")
8
+
9
+
10
+ class Codec(codecs.Codec):
11
+ def encode(self, data: str, errors: str = "strict") -> Tuple[bytes, int]:
12
+ if errors != "strict":
13
+ raise IDNAError('Unsupported error handling "{}"'.format(errors))
14
+
15
+ if not data:
16
+ return b"", 0
17
+
18
+ return encode(data), len(data)
19
+
20
+ def decode(self, data: bytes, errors: str = "strict") -> Tuple[str, int]:
21
+ if errors != "strict":
22
+ raise IDNAError('Unsupported error handling "{}"'.format(errors))
23
+
24
+ if not data:
25
+ return "", 0
26
+
27
+ return decode(data), len(data)
28
+
29
+
30
+ class IncrementalEncoder(codecs.BufferedIncrementalEncoder):
31
+ def _buffer_encode(self, data: str, errors: str, final: bool) -> Tuple[bytes, int]:
32
+ if errors != "strict":
33
+ raise IDNAError('Unsupported error handling "{}"'.format(errors))
34
+
35
+ if not data:
36
+ return b"", 0
37
+
38
+ labels = _unicode_dots_re.split(data)
39
+ trailing_dot = b""
40
+ if labels:
41
+ if not labels[-1]:
42
+ trailing_dot = b"."
43
+ del labels[-1]
44
+ elif not final:
45
+ # Keep potentially unfinished label until the next call
46
+ del labels[-1]
47
+ if labels:
48
+ trailing_dot = b"."
49
+
50
+ result = []
51
+ size = 0
52
+ for label in labels:
53
+ result.append(alabel(label))
54
+ if size:
55
+ size += 1
56
+ size += len(label)
57
+
58
+ # Join with U+002E
59
+ result_bytes = b".".join(result) + trailing_dot
60
+ size += len(trailing_dot)
61
+ return result_bytes, size
62
+
63
+
64
+ class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
65
+ def _buffer_decode(self, data: Any, errors: str, final: bool) -> Tuple[str, int]:
66
+ if errors != "strict":
67
+ raise IDNAError('Unsupported error handling "{}"'.format(errors))
68
+
69
+ if not data:
70
+ return ("", 0)
71
+
72
+ if not isinstance(data, str):
73
+ data = str(data, "ascii")
74
+
75
+ labels = _unicode_dots_re.split(data)
76
+ trailing_dot = ""
77
+ if labels:
78
+ if not labels[-1]:
79
+ trailing_dot = "."
80
+ del labels[-1]
81
+ elif not final:
82
+ # Keep potentially unfinished label until the next call
83
+ del labels[-1]
84
+ if labels:
85
+ trailing_dot = "."
86
+
87
+ result = []
88
+ size = 0
89
+ for label in labels:
90
+ result.append(ulabel(label))
91
+ if size:
92
+ size += 1
93
+ size += len(label)
94
+
95
+ result_str = ".".join(result) + trailing_dot
96
+ size += len(trailing_dot)
97
+ return (result_str, size)
98
+
99
+
100
+ class StreamWriter(Codec, codecs.StreamWriter):
101
+ pass
102
+
103
+
104
+ class StreamReader(Codec, codecs.StreamReader):
105
+ pass
106
+
107
+
108
+ def search_function(name: str) -> Optional[codecs.CodecInfo]:
109
+ if name != "idna2008":
110
+ return None
111
+ return codecs.CodecInfo(
112
+ name=name,
113
+ encode=Codec().encode,
114
+ decode=Codec().decode,
115
+ incrementalencoder=IncrementalEncoder,
116
+ incrementaldecoder=IncrementalDecoder,
117
+ streamwriter=StreamWriter,
118
+ streamreader=StreamReader,
119
+ )
120
+
121
+
122
+ codecs.register(search_function)
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/core.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import bisect
2
+ import re
3
+ import unicodedata
4
+ from typing import Optional, Union
5
+
6
+ from . import idnadata
7
+ from .intranges import intranges_contain
8
+
9
+ _virama_combining_class = 9
10
+ _alabel_prefix = b"xn--"
11
+ _unicode_dots_re = re.compile("[\u002e\u3002\uff0e\uff61]")
12
+
13
+
14
+ class IDNAError(UnicodeError):
15
+ """Base exception for all IDNA-encoding related problems"""
16
+
17
+ pass
18
+
19
+
20
+ class IDNABidiError(IDNAError):
21
+ """Exception when bidirectional requirements are not satisfied"""
22
+
23
+ pass
24
+
25
+
26
+ class InvalidCodepoint(IDNAError):
27
+ """Exception when a disallowed or unallocated codepoint is used"""
28
+
29
+ pass
30
+
31
+
32
+ class InvalidCodepointContext(IDNAError):
33
+ """Exception when the codepoint is not valid in the context it is used"""
34
+
35
+ pass
36
+
37
+
38
+ def _combining_class(cp: int) -> int:
39
+ v = unicodedata.combining(chr(cp))
40
+ if v == 0:
41
+ if not unicodedata.name(chr(cp)):
42
+ raise ValueError("Unknown character in unicodedata")
43
+ return v
44
+
45
+
46
+ def _is_script(cp: str, script: str) -> bool:
47
+ return intranges_contain(ord(cp), idnadata.scripts[script])
48
+
49
+
50
+ def _punycode(s: str) -> bytes:
51
+ return s.encode("punycode")
52
+
53
+
54
+ def _unot(s: int) -> str:
55
+ return "U+{:04X}".format(s)
56
+
57
+
58
+ def valid_label_length(label: Union[bytes, str]) -> bool:
59
+ if len(label) > 63:
60
+ return False
61
+ return True
62
+
63
+
64
+ def valid_string_length(label: Union[bytes, str], trailing_dot: bool) -> bool:
65
+ if len(label) > (254 if trailing_dot else 253):
66
+ return False
67
+ return True
68
+
69
+
70
+ def check_bidi(label: str, check_ltr: bool = False) -> bool:
71
+ # Bidi rules should only be applied if string contains RTL characters
72
+ bidi_label = False
73
+ for idx, cp in enumerate(label, 1):
74
+ direction = unicodedata.bidirectional(cp)
75
+ if direction == "":
76
+ # String likely comes from a newer version of Unicode
77
+ raise IDNABidiError("Unknown directionality in label {} at position {}".format(repr(label), idx))
78
+ if direction in ["R", "AL", "AN"]:
79
+ bidi_label = True
80
+ if not bidi_label and not check_ltr:
81
+ return True
82
+
83
+ # Bidi rule 1
84
+ direction = unicodedata.bidirectional(label[0])
85
+ if direction in ["R", "AL"]:
86
+ rtl = True
87
+ elif direction == "L":
88
+ rtl = False
89
+ else:
90
+ raise IDNABidiError("First codepoint in label {} must be directionality L, R or AL".format(repr(label)))
91
+
92
+ valid_ending = False
93
+ number_type: Optional[str] = None
94
+ for idx, cp in enumerate(label, 1):
95
+ direction = unicodedata.bidirectional(cp)
96
+
97
+ if rtl:
98
+ # Bidi rule 2
99
+ if direction not in [
100
+ "R",
101
+ "AL",
102
+ "AN",
103
+ "EN",
104
+ "ES",
105
+ "CS",
106
+ "ET",
107
+ "ON",
108
+ "BN",
109
+ "NSM",
110
+ ]:
111
+ raise IDNABidiError("Invalid direction for codepoint at position {} in a right-to-left label".format(idx))
112
+ # Bidi rule 3
113
+ if direction in ["R", "AL", "EN", "AN"]:
114
+ valid_ending = True
115
+ elif direction != "NSM":
116
+ valid_ending = False
117
+ # Bidi rule 4
118
+ if direction in ["AN", "EN"]:
119
+ if not number_type:
120
+ number_type = direction
121
+ else:
122
+ if number_type != direction:
123
+ raise IDNABidiError("Can not mix numeral types in a right-to-left label")
124
+ else:
125
+ # Bidi rule 5
126
+ if direction not in ["L", "EN", "ES", "CS", "ET", "ON", "BN", "NSM"]:
127
+ raise IDNABidiError("Invalid direction for codepoint at position {} in a left-to-right label".format(idx))
128
+ # Bidi rule 6
129
+ if direction in ["L", "EN"]:
130
+ valid_ending = True
131
+ elif direction != "NSM":
132
+ valid_ending = False
133
+
134
+ if not valid_ending:
135
+ raise IDNABidiError("Label ends with illegal codepoint directionality")
136
+
137
+ return True
138
+
139
+
140
+ def check_initial_combiner(label: str) -> bool:
141
+ if unicodedata.category(label[0])[0] == "M":
142
+ raise IDNAError("Label begins with an illegal combining character")
143
+ return True
144
+
145
+
146
+ def check_hyphen_ok(label: str) -> bool:
147
+ if label[2:4] == "--":
148
+ raise IDNAError("Label has disallowed hyphens in 3rd and 4th position")
149
+ if label[0] == "-" or label[-1] == "-":
150
+ raise IDNAError("Label must not start or end with a hyphen")
151
+ return True
152
+
153
+
154
+ def check_nfc(label: str) -> None:
155
+ if unicodedata.normalize("NFC", label) != label:
156
+ raise IDNAError("Label must be in Normalization Form C")
157
+
158
+
159
+ def valid_contextj(label: str, pos: int) -> bool:
160
+ cp_value = ord(label[pos])
161
+
162
+ if cp_value == 0x200C:
163
+ if pos > 0:
164
+ if _combining_class(ord(label[pos - 1])) == _virama_combining_class:
165
+ return True
166
+
167
+ ok = False
168
+ for i in range(pos - 1, -1, -1):
169
+ joining_type = idnadata.joining_types.get(ord(label[i]))
170
+ if joining_type == ord("T"):
171
+ continue
172
+ elif joining_type in [ord("L"), ord("D")]:
173
+ ok = True
174
+ break
175
+ else:
176
+ break
177
+
178
+ if not ok:
179
+ return False
180
+
181
+ ok = False
182
+ for i in range(pos + 1, len(label)):
183
+ joining_type = idnadata.joining_types.get(ord(label[i]))
184
+ if joining_type == ord("T"):
185
+ continue
186
+ elif joining_type in [ord("R"), ord("D")]:
187
+ ok = True
188
+ break
189
+ else:
190
+ break
191
+ return ok
192
+
193
+ if cp_value == 0x200D:
194
+ if pos > 0:
195
+ if _combining_class(ord(label[pos - 1])) == _virama_combining_class:
196
+ return True
197
+ return False
198
+
199
+ else:
200
+ return False
201
+
202
+
203
+ def valid_contexto(label: str, pos: int, exception: bool = False) -> bool:
204
+ cp_value = ord(label[pos])
205
+
206
+ if cp_value == 0x00B7:
207
+ if 0 < pos < len(label) - 1:
208
+ if ord(label[pos - 1]) == 0x006C and ord(label[pos + 1]) == 0x006C:
209
+ return True
210
+ return False
211
+
212
+ elif cp_value == 0x0375:
213
+ if pos < len(label) - 1 and len(label) > 1:
214
+ return _is_script(label[pos + 1], "Greek")
215
+ return False
216
+
217
+ elif cp_value == 0x05F3 or cp_value == 0x05F4:
218
+ if pos > 0:
219
+ return _is_script(label[pos - 1], "Hebrew")
220
+ return False
221
+
222
+ elif cp_value == 0x30FB:
223
+ for cp in label:
224
+ if cp == "\u30fb":
225
+ continue
226
+ if _is_script(cp, "Hiragana") or _is_script(cp, "Katakana") or _is_script(cp, "Han"):
227
+ return True
228
+ return False
229
+
230
+ elif 0x660 <= cp_value <= 0x669:
231
+ for cp in label:
232
+ if 0x6F0 <= ord(cp) <= 0x06F9:
233
+ return False
234
+ return True
235
+
236
+ elif 0x6F0 <= cp_value <= 0x6F9:
237
+ for cp in label:
238
+ if 0x660 <= ord(cp) <= 0x0669:
239
+ return False
240
+ return True
241
+
242
+ return False
243
+
244
+
245
+ def check_label(label: Union[str, bytes, bytearray]) -> None:
246
+ if isinstance(label, (bytes, bytearray)):
247
+ label = label.decode("utf-8")
248
+ if len(label) == 0:
249
+ raise IDNAError("Empty Label")
250
+
251
+ check_nfc(label)
252
+ check_hyphen_ok(label)
253
+ check_initial_combiner(label)
254
+
255
+ for pos, cp in enumerate(label):
256
+ cp_value = ord(cp)
257
+ if intranges_contain(cp_value, idnadata.codepoint_classes["PVALID"]):
258
+ continue
259
+ elif intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTJ"]):
260
+ try:
261
+ if not valid_contextj(label, pos):
262
+ raise InvalidCodepointContext(
263
+ "Joiner {} not allowed at position {} in {}".format(_unot(cp_value), pos + 1, repr(label))
264
+ )
265
+ except ValueError:
266
+ raise IDNAError(
267
+ "Unknown codepoint adjacent to joiner {} at position {} in {}".format(
268
+ _unot(cp_value), pos + 1, repr(label)
269
+ )
270
+ )
271
+ elif intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTO"]):
272
+ if not valid_contexto(label, pos):
273
+ raise InvalidCodepointContext(
274
+ "Codepoint {} not allowed at position {} in {}".format(_unot(cp_value), pos + 1, repr(label))
275
+ )
276
+ else:
277
+ raise InvalidCodepoint(
278
+ "Codepoint {} at position {} of {} not allowed".format(_unot(cp_value), pos + 1, repr(label))
279
+ )
280
+
281
+ check_bidi(label)
282
+
283
+
284
+ def alabel(label: str) -> bytes:
285
+ try:
286
+ label_bytes = label.encode("ascii")
287
+ ulabel(label_bytes)
288
+ if not valid_label_length(label_bytes):
289
+ raise IDNAError("Label too long")
290
+ return label_bytes
291
+ except UnicodeEncodeError:
292
+ pass
293
+
294
+ check_label(label)
295
+ label_bytes = _alabel_prefix + _punycode(label)
296
+
297
+ if not valid_label_length(label_bytes):
298
+ raise IDNAError("Label too long")
299
+
300
+ return label_bytes
301
+
302
+
303
+ def ulabel(label: Union[str, bytes, bytearray]) -> str:
304
+ if not isinstance(label, (bytes, bytearray)):
305
+ try:
306
+ label_bytes = label.encode("ascii")
307
+ except UnicodeEncodeError:
308
+ check_label(label)
309
+ return label
310
+ else:
311
+ label_bytes = label
312
+
313
+ label_bytes = label_bytes.lower()
314
+ if label_bytes.startswith(_alabel_prefix):
315
+ label_bytes = label_bytes[len(_alabel_prefix) :]
316
+ if not label_bytes:
317
+ raise IDNAError("Malformed A-label, no Punycode eligible content found")
318
+ if label_bytes.decode("ascii")[-1] == "-":
319
+ raise IDNAError("A-label must not end with a hyphen")
320
+ else:
321
+ check_label(label_bytes)
322
+ return label_bytes.decode("ascii")
323
+
324
+ try:
325
+ label = label_bytes.decode("punycode")
326
+ except UnicodeError:
327
+ raise IDNAError("Invalid A-label")
328
+ check_label(label)
329
+ return label
330
+
331
+
332
+ def uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str:
333
+ """Re-map the characters in the string according to UTS46 processing."""
334
+ from .uts46data import uts46data
335
+
336
+ output = ""
337
+
338
+ for pos, char in enumerate(domain):
339
+ code_point = ord(char)
340
+ try:
341
+ uts46row = uts46data[code_point if code_point < 256 else bisect.bisect_left(uts46data, (code_point, "Z")) - 1]
342
+ status = uts46row[1]
343
+ replacement: Optional[str] = None
344
+ if len(uts46row) == 3:
345
+ replacement = uts46row[2]
346
+ if (
347
+ status == "V"
348
+ or (status == "D" and not transitional)
349
+ or (status == "3" and not std3_rules and replacement is None)
350
+ ):
351
+ output += char
352
+ elif replacement is not None and (
353
+ status == "M" or (status == "3" and not std3_rules) or (status == "D" and transitional)
354
+ ):
355
+ output += replacement
356
+ elif status != "I":
357
+ raise IndexError()
358
+ except IndexError:
359
+ raise InvalidCodepoint(
360
+ "Codepoint {} not allowed at position {} in {}".format(_unot(code_point), pos + 1, repr(domain))
361
+ )
362
+
363
+ return unicodedata.normalize("NFC", output)
364
+
365
+
366
+ def encode(
367
+ s: Union[str, bytes, bytearray],
368
+ strict: bool = False,
369
+ uts46: bool = False,
370
+ std3_rules: bool = False,
371
+ transitional: bool = False,
372
+ ) -> bytes:
373
+ if not isinstance(s, str):
374
+ try:
375
+ s = str(s, "ascii")
376
+ except UnicodeDecodeError:
377
+ raise IDNAError("should pass a unicode string to the function rather than a byte string.")
378
+ if uts46:
379
+ s = uts46_remap(s, std3_rules, transitional)
380
+ trailing_dot = False
381
+ result = []
382
+ if strict:
383
+ labels = s.split(".")
384
+ else:
385
+ labels = _unicode_dots_re.split(s)
386
+ if not labels or labels == [""]:
387
+ raise IDNAError("Empty domain")
388
+ if labels[-1] == "":
389
+ del labels[-1]
390
+ trailing_dot = True
391
+ for label in labels:
392
+ s = alabel(label)
393
+ if s:
394
+ result.append(s)
395
+ else:
396
+ raise IDNAError("Empty label")
397
+ if trailing_dot:
398
+ result.append(b"")
399
+ s = b".".join(result)
400
+ if not valid_string_length(s, trailing_dot):
401
+ raise IDNAError("Domain too long")
402
+ return s
403
+
404
+
405
+ def decode(
406
+ s: Union[str, bytes, bytearray],
407
+ strict: bool = False,
408
+ uts46: bool = False,
409
+ std3_rules: bool = False,
410
+ ) -> str:
411
+ try:
412
+ if not isinstance(s, str):
413
+ s = str(s, "ascii")
414
+ except UnicodeDecodeError:
415
+ raise IDNAError("Invalid ASCII in A-label")
416
+ if uts46:
417
+ s = uts46_remap(s, std3_rules, False)
418
+ trailing_dot = False
419
+ result = []
420
+ if not strict:
421
+ labels = _unicode_dots_re.split(s)
422
+ else:
423
+ labels = s.split(".")
424
+ if not labels or labels == [""]:
425
+ raise IDNAError("Empty domain")
426
+ if not labels[-1]:
427
+ del labels[-1]
428
+ trailing_dot = True
429
+ for label in labels:
430
+ s = ulabel(label)
431
+ if s:
432
+ result.append(s)
433
+ else:
434
+ raise IDNAError("Empty label")
435
+ if trailing_dot:
436
+ result.append("")
437
+ return ".".join(result)
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/intranges.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Given a list of integers, made up of (hopefully) a small number of long runs
3
+ of consecutive integers, compute a representation of the form
4
+ ((start1, end1), (start2, end2) ...). Then answer the question "was x present
5
+ in the original list?" in time O(log(# runs)).
6
+ """
7
+
8
+ import bisect
9
+ from typing import List, Tuple
10
+
11
+
12
+ def intranges_from_list(list_: List[int]) -> Tuple[int, ...]:
13
+ """Represent a list of integers as a sequence of ranges:
14
+ ((start_0, end_0), (start_1, end_1), ...), such that the original
15
+ integers are exactly those x such that start_i <= x < end_i for some i.
16
+
17
+ Ranges are encoded as single integers (start << 32 | end), not as tuples.
18
+ """
19
+
20
+ sorted_list = sorted(list_)
21
+ ranges = []
22
+ last_write = -1
23
+ for i in range(len(sorted_list)):
24
+ if i + 1 < len(sorted_list):
25
+ if sorted_list[i] == sorted_list[i + 1] - 1:
26
+ continue
27
+ current_range = sorted_list[last_write + 1 : i + 1]
28
+ ranges.append(_encode_range(current_range[0], current_range[-1] + 1))
29
+ last_write = i
30
+
31
+ return tuple(ranges)
32
+
33
+
34
+ def _encode_range(start: int, end: int) -> int:
35
+ return (start << 32) | end
36
+
37
+
38
+ def _decode_range(r: int) -> Tuple[int, int]:
39
+ return (r >> 32), (r & ((1 << 32) - 1))
40
+
41
+
42
+ def intranges_contain(int_: int, ranges: Tuple[int, ...]) -> bool:
43
+ """Determine if `int_` falls into one of the ranges in `ranges`."""
44
+ tuple_ = _encode_range(int_, 0)
45
+ pos = bisect.bisect_left(ranges, tuple_)
46
+ # we could be immediately ahead of a tuple (start, end)
47
+ # with start < int_ <= end
48
+ if pos > 0:
49
+ left, right = _decode_range(ranges[pos - 1])
50
+ if left <= int_ < right:
51
+ return True
52
+ # or we could be immediately behind a tuple (int_, end)
53
+ if pos < len(ranges):
54
+ left, _ = _decode_range(ranges[pos])
55
+ if left == int_:
56
+ return True
57
+ return False
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/package_data.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __version__ = "3.10"
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/py.typed ADDED
File without changes
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/idna/uts46data.py ADDED
The diff for this file is too large to render. See raw diff
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/packaging/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ __title__ = "packaging"
6
+ __summary__ = "Core utilities for Python packages"
7
+ __uri__ = "https://github.com/pypa/packaging"
8
+
9
+ __version__ = "24.2"
10
+
11
+ __author__ = "Donald Stufft and individual contributors"
12
+ __email__ = "donald@stufft.io"
13
+
14
+ __license__ = "BSD-2-Clause or Apache-2.0"
15
+ __copyright__ = f"2014 {__author__}"
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/packaging/__pycache__/_musllinux.cpython-310.pyc ADDED
Binary file (3.43 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/packaging/__pycache__/_parser.cpython-310.pyc ADDED
Binary file (9.25 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/packaging/__pycache__/_structures.cpython-310.pyc ADDED
Binary file (2.69 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/packaging/__pycache__/_tokenizer.cpython-310.pyc ADDED
Binary file (5.9 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/packaging/__pycache__/requirements.cpython-310.pyc ADDED
Binary file (2.9 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/pip/_vendor/packaging/__pycache__/tags.cpython-310.pyc ADDED
Binary file (15.2 kB). View file