plucksquire commited on
Commit
4280ba0
·
verified ·
1 Parent(s): bfa85eb

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. .venv/Lib/site-packages/pip/_vendor/chardet/__init__.py +115 -0
  2. .venv/Lib/site-packages/pip/_vendor/chardet/cli/__init__.py +0 -0
  3. .venv/Lib/site-packages/pip/_vendor/chardet/cli/chardetect.py +112 -0
  4. .venv/Lib/site-packages/pip/_vendor/chardet/metadata/__init__.py +0 -0
  5. .venv/Lib/site-packages/pip/_vendor/chardet/metadata/languages.py +352 -0
  6. .venv/Lib/site-packages/pip/_vendor/chardet/sbcharsetprober.py +162 -0
  7. .venv/Lib/site-packages/pip/_vendor/chardet/sbcsgroupprober.py +88 -0
  8. .venv/Lib/site-packages/pip/_vendor/chardet/sjisprober.py +105 -0
  9. .venv/Lib/site-packages/pip/_vendor/chardet/universaldetector.py +362 -0
  10. .venv/Lib/site-packages/pip/_vendor/chardet/utf1632prober.py +225 -0
  11. .venv/Lib/site-packages/pip/_vendor/chardet/utf8prober.py +82 -0
  12. .venv/Lib/site-packages/pip/_vendor/chardet/version.py +9 -0
  13. .venv/Lib/site-packages/pip/_vendor/colorama/__init__.py +7 -0
  14. .venv/Lib/site-packages/pip/_vendor/colorama/ansi.py +102 -0
  15. .venv/Lib/site-packages/pip/_vendor/colorama/ansitowin32.py +277 -0
  16. .venv/Lib/site-packages/pip/_vendor/colorama/initialise.py +121 -0
  17. .venv/Lib/site-packages/pip/_vendor/colorama/tests/__init__.py +1 -0
  18. .venv/Lib/site-packages/pip/_vendor/colorama/tests/ansi_test.py +76 -0
  19. .venv/Lib/site-packages/pip/_vendor/colorama/tests/ansitowin32_test.py +294 -0
  20. .venv/Lib/site-packages/pip/_vendor/colorama/tests/initialise_test.py +189 -0
  21. .venv/Lib/site-packages/pip/_vendor/colorama/tests/isatty_test.py +57 -0
  22. .venv/Lib/site-packages/pip/_vendor/colorama/tests/utils.py +49 -0
  23. .venv/Lib/site-packages/pip/_vendor/colorama/tests/winterm_test.py +131 -0
  24. .venv/Lib/site-packages/pip/_vendor/colorama/win32.py +180 -0
  25. .venv/Lib/site-packages/pip/_vendor/colorama/winterm.py +195 -0
  26. .venv/Lib/site-packages/pip/_vendor/distlib/compat.py +1116 -0
  27. .venv/Lib/site-packages/pip/_vendor/distlib/database.py +1350 -0
  28. .venv/Lib/site-packages/pip/_vendor/distlib/index.py +508 -0
  29. .venv/Lib/site-packages/pip/_vendor/distlib/locators.py +1300 -0
  30. .venv/Lib/site-packages/pip/_vendor/distlib/manifest.py +393 -0
  31. .venv/Lib/site-packages/pip/_vendor/distlib/markers.py +152 -0
  32. .venv/Lib/site-packages/pip/_vendor/distlib/metadata.py +1076 -0
  33. .venv/Lib/site-packages/pip/_vendor/distlib/resources.py +358 -0
  34. .venv/Lib/site-packages/pip/_vendor/distlib/scripts.py +437 -0
  35. .venv/Lib/site-packages/pip/_vendor/distro/__init__.py +54 -0
  36. .venv/Lib/site-packages/pip/_vendor/distro/__main__.py +4 -0
  37. .venv/Lib/site-packages/pip/_vendor/distro/distro.py +1399 -0
  38. .venv/Lib/site-packages/pip/_vendor/idna/__init__.py +44 -0
  39. .venv/Lib/site-packages/pip/_vendor/idna/codec.py +112 -0
  40. .venv/Lib/site-packages/pip/_vendor/idna/compat.py +13 -0
  41. .venv/Lib/site-packages/pip/_vendor/idna/core.py +400 -0
  42. .venv/Lib/site-packages/pip/_vendor/idna/idnadata.py +2151 -0
  43. .venv/Lib/site-packages/pip/_vendor/idna/intranges.py +54 -0
  44. .venv/Lib/site-packages/pip/_vendor/idna/package_data.py +2 -0
  45. .venv/Lib/site-packages/pip/_vendor/idna/uts46data.py +0 -0
  46. .venv/Lib/site-packages/pip/_vendor/msgpack/__init__.py +57 -0
  47. .venv/Lib/site-packages/pip/_vendor/msgpack/exceptions.py +48 -0
  48. .venv/Lib/site-packages/pip/_vendor/msgpack/ext.py +193 -0
  49. .venv/Lib/site-packages/pip/_vendor/msgpack/fallback.py +1010 -0
  50. .venv/Lib/site-packages/pip/_vendor/packaging/__about__.py +26 -0
.venv/Lib/site-packages/pip/_vendor/chardet/__init__.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ######################## BEGIN LICENSE BLOCK ########################
2
+ # This library is free software; you can redistribute it and/or
3
+ # modify it under the terms of the GNU Lesser General Public
4
+ # License as published by the Free Software Foundation; either
5
+ # version 2.1 of the License, or (at your option) any later version.
6
+ #
7
+ # This library is distributed in the hope that it will be useful,
8
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
9
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10
+ # Lesser General Public License for more details.
11
+ #
12
+ # You should have received a copy of the GNU Lesser General Public
13
+ # License along with this library; if not, write to the Free Software
14
+ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
15
+ # 02110-1301 USA
16
+ ######################### END LICENSE BLOCK #########################
17
+
18
+ from typing import List, Union
19
+
20
+ from .charsetgroupprober import CharSetGroupProber
21
+ from .charsetprober import CharSetProber
22
+ from .enums import InputState
23
+ from .resultdict import ResultDict
24
+ from .universaldetector import UniversalDetector
25
+ from .version import VERSION, __version__
26
+
27
+ __all__ = ["UniversalDetector", "detect", "detect_all", "__version__", "VERSION"]
28
+
29
+
30
+ def detect(
31
+ byte_str: Union[bytes, bytearray], should_rename_legacy: bool = False
32
+ ) -> ResultDict:
33
+ """
34
+ Detect the encoding of the given byte string.
35
+
36
+ :param byte_str: The byte sequence to examine.
37
+ :type byte_str: ``bytes`` or ``bytearray``
38
+ :param should_rename_legacy: Should we rename legacy encodings
39
+ to their more modern equivalents?
40
+ :type should_rename_legacy: ``bool``
41
+ """
42
+ if not isinstance(byte_str, bytearray):
43
+ if not isinstance(byte_str, bytes):
44
+ raise TypeError(
45
+ f"Expected object of type bytes or bytearray, got: {type(byte_str)}"
46
+ )
47
+ byte_str = bytearray(byte_str)
48
+ detector = UniversalDetector(should_rename_legacy=should_rename_legacy)
49
+ detector.feed(byte_str)
50
+ return detector.close()
51
+
52
+
53
+ def detect_all(
54
+ byte_str: Union[bytes, bytearray],
55
+ ignore_threshold: bool = False,
56
+ should_rename_legacy: bool = False,
57
+ ) -> List[ResultDict]:
58
+ """
59
+ Detect all the possible encodings of the given byte string.
60
+
61
+ :param byte_str: The byte sequence to examine.
62
+ :type byte_str: ``bytes`` or ``bytearray``
63
+ :param ignore_threshold: Include encodings that are below
64
+ ``UniversalDetector.MINIMUM_THRESHOLD``
65
+ in results.
66
+ :type ignore_threshold: ``bool``
67
+ :param should_rename_legacy: Should we rename legacy encodings
68
+ to their more modern equivalents?
69
+ :type should_rename_legacy: ``bool``
70
+ """
71
+ if not isinstance(byte_str, bytearray):
72
+ if not isinstance(byte_str, bytes):
73
+ raise TypeError(
74
+ f"Expected object of type bytes or bytearray, got: {type(byte_str)}"
75
+ )
76
+ byte_str = bytearray(byte_str)
77
+
78
+ detector = UniversalDetector(should_rename_legacy=should_rename_legacy)
79
+ detector.feed(byte_str)
80
+ detector.close()
81
+
82
+ if detector.input_state == InputState.HIGH_BYTE:
83
+ results: List[ResultDict] = []
84
+ probers: List[CharSetProber] = []
85
+ for prober in detector.charset_probers:
86
+ if isinstance(prober, CharSetGroupProber):
87
+ probers.extend(p for p in prober.probers)
88
+ else:
89
+ probers.append(prober)
90
+ for prober in probers:
91
+ if ignore_threshold or prober.get_confidence() > detector.MINIMUM_THRESHOLD:
92
+ charset_name = prober.charset_name or ""
93
+ lower_charset_name = charset_name.lower()
94
+ # Use Windows encoding name instead of ISO-8859 if we saw any
95
+ # extra Windows-specific bytes
96
+ if lower_charset_name.startswith("iso-8859") and detector.has_win_bytes:
97
+ charset_name = detector.ISO_WIN_MAP.get(
98
+ lower_charset_name, charset_name
99
+ )
100
+ # Rename legacy encodings with superset encodings if asked
101
+ if should_rename_legacy:
102
+ charset_name = detector.LEGACY_MAP.get(
103
+ charset_name.lower(), charset_name
104
+ )
105
+ results.append(
106
+ {
107
+ "encoding": charset_name,
108
+ "confidence": prober.get_confidence(),
109
+ "language": prober.language,
110
+ }
111
+ )
112
+ if len(results) > 0:
113
+ return sorted(results, key=lambda result: -result["confidence"])
114
+
115
+ return [detector.result]
.venv/Lib/site-packages/pip/_vendor/chardet/cli/__init__.py ADDED
File without changes
.venv/Lib/site-packages/pip/_vendor/chardet/cli/chardetect.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Script which takes one or more file paths and reports on their detected
3
+ encodings
4
+
5
+ Example::
6
+
7
+ % chardetect somefile someotherfile
8
+ somefile: windows-1252 with confidence 0.5
9
+ someotherfile: ascii with confidence 1.0
10
+
11
+ If no paths are provided, it takes its input from stdin.
12
+
13
+ """
14
+
15
+
16
+ import argparse
17
+ import sys
18
+ from typing import Iterable, List, Optional
19
+
20
+ from .. import __version__
21
+ from ..universaldetector import UniversalDetector
22
+
23
+
24
+ def description_of(
25
+ lines: Iterable[bytes],
26
+ name: str = "stdin",
27
+ minimal: bool = False,
28
+ should_rename_legacy: bool = False,
29
+ ) -> Optional[str]:
30
+ """
31
+ Return a string describing the probable encoding of a file or
32
+ list of strings.
33
+
34
+ :param lines: The lines to get the encoding of.
35
+ :type lines: Iterable of bytes
36
+ :param name: Name of file or collection of lines
37
+ :type name: str
38
+ :param should_rename_legacy: Should we rename legacy encodings to
39
+ their more modern equivalents?
40
+ :type should_rename_legacy: ``bool``
41
+ """
42
+ u = UniversalDetector(should_rename_legacy=should_rename_legacy)
43
+ for line in lines:
44
+ line = bytearray(line)
45
+ u.feed(line)
46
+ # shortcut out of the loop to save reading further - particularly useful if we read a BOM.
47
+ if u.done:
48
+ break
49
+ u.close()
50
+ result = u.result
51
+ if minimal:
52
+ return result["encoding"]
53
+ if result["encoding"]:
54
+ return f'{name}: {result["encoding"]} with confidence {result["confidence"]}'
55
+ return f"{name}: no result"
56
+
57
+
58
+ def main(argv: Optional[List[str]] = None) -> None:
59
+ """
60
+ Handles command line arguments and gets things started.
61
+
62
+ :param argv: List of arguments, as if specified on the command-line.
63
+ If None, ``sys.argv[1:]`` is used instead.
64
+ :type argv: list of str
65
+ """
66
+ # Get command line arguments
67
+ parser = argparse.ArgumentParser(
68
+ description=(
69
+ "Takes one or more file paths and reports their detected encodings"
70
+ )
71
+ )
72
+ parser.add_argument(
73
+ "input",
74
+ help="File whose encoding we would like to determine. (default: stdin)",
75
+ type=argparse.FileType("rb"),
76
+ nargs="*",
77
+ default=[sys.stdin.buffer],
78
+ )
79
+ parser.add_argument(
80
+ "--minimal",
81
+ help="Print only the encoding to standard output",
82
+ action="store_true",
83
+ )
84
+ parser.add_argument(
85
+ "-l",
86
+ "--legacy",
87
+ help="Rename legacy encodings to more modern ones.",
88
+ action="store_true",
89
+ )
90
+ parser.add_argument(
91
+ "--version", action="version", version=f"%(prog)s {__version__}"
92
+ )
93
+ args = parser.parse_args(argv)
94
+
95
+ for f in args.input:
96
+ if f.isatty():
97
+ print(
98
+ "You are running chardetect interactively. Press "
99
+ "CTRL-D twice at the start of a blank line to signal the "
100
+ "end of your input. If you want help, run chardetect "
101
+ "--help\n",
102
+ file=sys.stderr,
103
+ )
104
+ print(
105
+ description_of(
106
+ f, f.name, minimal=args.minimal, should_rename_legacy=args.legacy
107
+ )
108
+ )
109
+
110
+
111
+ if __name__ == "__main__":
112
+ main()
.venv/Lib/site-packages/pip/_vendor/chardet/metadata/__init__.py ADDED
File without changes
.venv/Lib/site-packages/pip/_vendor/chardet/metadata/languages.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Metadata about languages used by our model training code for our
3
+ SingleByteCharSetProbers. Could be used for other things in the future.
4
+
5
+ This code is based on the language metadata from the uchardet project.
6
+ """
7
+
8
+ from string import ascii_letters
9
+ from typing import List, Optional
10
+
11
+ # TODO: Add Ukrainian (KOI8-U)
12
+
13
+
14
+ class Language:
15
+ """Metadata about a language useful for training models
16
+
17
+ :ivar name: The human name for the language, in English.
18
+ :type name: str
19
+ :ivar iso_code: 2-letter ISO 639-1 if possible, 3-letter ISO code otherwise,
20
+ or use another catalog as a last resort.
21
+ :type iso_code: str
22
+ :ivar use_ascii: Whether or not ASCII letters should be included in trained
23
+ models.
24
+ :type use_ascii: bool
25
+ :ivar charsets: The charsets we want to support and create data for.
26
+ :type charsets: list of str
27
+ :ivar alphabet: The characters in the language's alphabet. If `use_ascii` is
28
+ `True`, you only need to add those not in the ASCII set.
29
+ :type alphabet: str
30
+ :ivar wiki_start_pages: The Wikipedia pages to start from if we're crawling
31
+ Wikipedia for training data.
32
+ :type wiki_start_pages: list of str
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ name: Optional[str] = None,
38
+ iso_code: Optional[str] = None,
39
+ use_ascii: bool = True,
40
+ charsets: Optional[List[str]] = None,
41
+ alphabet: Optional[str] = None,
42
+ wiki_start_pages: Optional[List[str]] = None,
43
+ ) -> None:
44
+ super().__init__()
45
+ self.name = name
46
+ self.iso_code = iso_code
47
+ self.use_ascii = use_ascii
48
+ self.charsets = charsets
49
+ if self.use_ascii:
50
+ if alphabet:
51
+ alphabet += ascii_letters
52
+ else:
53
+ alphabet = ascii_letters
54
+ elif not alphabet:
55
+ raise ValueError("Must supply alphabet if use_ascii is False")
56
+ self.alphabet = "".join(sorted(set(alphabet))) if alphabet else None
57
+ self.wiki_start_pages = wiki_start_pages
58
+
59
+ def __repr__(self) -> str:
60
+ param_str = ", ".join(
61
+ f"{k}={v!r}" for k, v in self.__dict__.items() if not k.startswith("_")
62
+ )
63
+ return f"{self.__class__.__name__}({param_str})"
64
+
65
+
66
+ LANGUAGES = {
67
+ "Arabic": Language(
68
+ name="Arabic",
69
+ iso_code="ar",
70
+ use_ascii=False,
71
+ # We only support encodings that use isolated
72
+ # forms, because the current recommendation is
73
+ # that the rendering system handles presentation
74
+ # forms. This means we purposefully skip IBM864.
75
+ charsets=["ISO-8859-6", "WINDOWS-1256", "CP720", "CP864"],
76
+ alphabet="ءآأؤإئابةتثجحخدذرزسشصضطظعغػؼؽؾؿـفقكلمنهوىيًٌٍَُِّ",
77
+ wiki_start_pages=["الصفحة_الرئيسية"],
78
+ ),
79
+ "Belarusian": Language(
80
+ name="Belarusian",
81
+ iso_code="be",
82
+ use_ascii=False,
83
+ charsets=["ISO-8859-5", "WINDOWS-1251", "IBM866", "MacCyrillic"],
84
+ alphabet="АБВГДЕЁЖЗІЙКЛМНОПРСТУЎФХЦЧШЫЬЭЮЯабвгдеёжзійклмнопрстуўфхцчшыьэюяʼ",
85
+ wiki_start_pages=["Галоўная_старонка"],
86
+ ),
87
+ "Bulgarian": Language(
88
+ name="Bulgarian",
89
+ iso_code="bg",
90
+ use_ascii=False,
91
+ charsets=["ISO-8859-5", "WINDOWS-1251", "IBM855"],
92
+ alphabet="АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЬЮЯабвгдежзийклмнопрстуфхцчшщъьюя",
93
+ wiki_start_pages=["Начална_страница"],
94
+ ),
95
+ "Czech": Language(
96
+ name="Czech",
97
+ iso_code="cz",
98
+ use_ascii=True,
99
+ charsets=["ISO-8859-2", "WINDOWS-1250"],
100
+ alphabet="áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ",
101
+ wiki_start_pages=["Hlavní_strana"],
102
+ ),
103
+ "Danish": Language(
104
+ name="Danish",
105
+ iso_code="da",
106
+ use_ascii=True,
107
+ charsets=["ISO-8859-1", "ISO-8859-15", "WINDOWS-1252", "MacRoman"],
108
+ alphabet="æøåÆØÅ",
109
+ wiki_start_pages=["Forside"],
110
+ ),
111
+ "German": Language(
112
+ name="German",
113
+ iso_code="de",
114
+ use_ascii=True,
115
+ charsets=["ISO-8859-1", "ISO-8859-15", "WINDOWS-1252", "MacRoman"],
116
+ alphabet="äöüßẞÄÖÜ",
117
+ wiki_start_pages=["Wikipedia:Hauptseite"],
118
+ ),
119
+ "Greek": Language(
120
+ name="Greek",
121
+ iso_code="el",
122
+ use_ascii=False,
123
+ charsets=["ISO-8859-7", "WINDOWS-1253"],
124
+ alphabet="αβγδεζηθικλμνξοπρσςτυφχψωάέήίόύώΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΣΤΥΦΧΨΩΆΈΉΊΌΎΏ",
125
+ wiki_start_pages=["Πύλη:Κύρια"],
126
+ ),
127
+ "English": Language(
128
+ name="English",
129
+ iso_code="en",
130
+ use_ascii=True,
131
+ charsets=["ISO-8859-1", "WINDOWS-1252", "MacRoman"],
132
+ wiki_start_pages=["Main_Page"],
133
+ ),
134
+ "Esperanto": Language(
135
+ name="Esperanto",
136
+ iso_code="eo",
137
+ # Q, W, X, and Y not used at all
138
+ use_ascii=False,
139
+ charsets=["ISO-8859-3"],
140
+ alphabet="abcĉdefgĝhĥijĵklmnoprsŝtuŭvzABCĈDEFGĜHĤIJĴKLMNOPRSŜTUŬVZ",
141
+ wiki_start_pages=["Vikipedio:Ĉefpaĝo"],
142
+ ),
143
+ "Spanish": Language(
144
+ name="Spanish",
145
+ iso_code="es",
146
+ use_ascii=True,
147
+ charsets=["ISO-8859-1", "ISO-8859-15", "WINDOWS-1252", "MacRoman"],
148
+ alphabet="ñáéíóúüÑÁÉÍÓÚÜ",
149
+ wiki_start_pages=["Wikipedia:Portada"],
150
+ ),
151
+ "Estonian": Language(
152
+ name="Estonian",
153
+ iso_code="et",
154
+ use_ascii=False,
155
+ charsets=["ISO-8859-4", "ISO-8859-13", "WINDOWS-1257"],
156
+ # C, F, Š, Q, W, X, Y, Z, Ž are only for
157
+ # loanwords
158
+ alphabet="ABDEGHIJKLMNOPRSTUVÕÄÖÜabdeghijklmnoprstuvõäöü",
159
+ wiki_start_pages=["Esileht"],
160
+ ),
161
+ "Finnish": Language(
162
+ name="Finnish",
163
+ iso_code="fi",
164
+ use_ascii=True,
165
+ charsets=["ISO-8859-1", "ISO-8859-15", "WINDOWS-1252", "MacRoman"],
166
+ alphabet="ÅÄÖŠŽåäöšž",
167
+ wiki_start_pages=["Wikipedia:Etusivu"],
168
+ ),
169
+ "French": Language(
170
+ name="French",
171
+ iso_code="fr",
172
+ use_ascii=True,
173
+ charsets=["ISO-8859-1", "ISO-8859-15", "WINDOWS-1252", "MacRoman"],
174
+ alphabet="œàâçèéîïùûêŒÀÂÇÈÉÎÏÙÛÊ",
175
+ wiki_start_pages=["Wikipédia:Accueil_principal", "Bœuf (animal)"],
176
+ ),
177
+ "Hebrew": Language(
178
+ name="Hebrew",
179
+ iso_code="he",
180
+ use_ascii=False,
181
+ charsets=["ISO-8859-8", "WINDOWS-1255"],
182
+ alphabet="אבגדהוזחטיךכלםמןנסעףפץצקרשתװױײ",
183
+ wiki_start_pages=["עמוד_ראשי"],
184
+ ),
185
+ "Croatian": Language(
186
+ name="Croatian",
187
+ iso_code="hr",
188
+ # Q, W, X, Y are only used for foreign words.
189
+ use_ascii=False,
190
+ charsets=["ISO-8859-2", "WINDOWS-1250"],
191
+ alphabet="abcčćdđefghijklmnoprsštuvzžABCČĆDĐEFGHIJKLMNOPRSŠTUVZŽ",
192
+ wiki_start_pages=["Glavna_stranica"],
193
+ ),
194
+ "Hungarian": Language(
195
+ name="Hungarian",
196
+ iso_code="hu",
197
+ # Q, W, X, Y are only used for foreign words.
198
+ use_ascii=False,
199
+ charsets=["ISO-8859-2", "WINDOWS-1250"],
200
+ alphabet="abcdefghijklmnoprstuvzáéíóöőúüűABCDEFGHIJKLMNOPRSTUVZÁÉÍÓÖŐÚÜŰ",
201
+ wiki_start_pages=["Kezdőlap"],
202
+ ),
203
+ "Italian": Language(
204
+ name="Italian",
205
+ iso_code="it",
206
+ use_ascii=True,
207
+ charsets=["ISO-8859-1", "ISO-8859-15", "WINDOWS-1252", "MacRoman"],
208
+ alphabet="ÀÈÉÌÒÓÙàèéìòóù",
209
+ wiki_start_pages=["Pagina_principale"],
210
+ ),
211
+ "Lithuanian": Language(
212
+ name="Lithuanian",
213
+ iso_code="lt",
214
+ use_ascii=False,
215
+ charsets=["ISO-8859-13", "WINDOWS-1257", "ISO-8859-4"],
216
+ # Q, W, and X not used at all
217
+ alphabet="AĄBCČDEĘĖFGHIĮYJKLMNOPRSŠTUŲŪVZŽaąbcčdeęėfghiįyjklmnoprsštuųūvzž",
218
+ wiki_start_pages=["Pagrindinis_puslapis"],
219
+ ),
220
+ "Latvian": Language(
221
+ name="Latvian",
222
+ iso_code="lv",
223
+ use_ascii=False,
224
+ charsets=["ISO-8859-13", "WINDOWS-1257", "ISO-8859-4"],
225
+ # Q, W, X, Y are only for loanwords
226
+ alphabet="AĀBCČDEĒFGĢHIĪJKĶLĻMNŅOPRSŠTUŪVZŽaābcčdeēfgģhiījkķlļmnņoprsštuūvzž",
227
+ wiki_start_pages=["Sākumlapa"],
228
+ ),
229
+ "Macedonian": Language(
230
+ name="Macedonian",
231
+ iso_code="mk",
232
+ use_ascii=False,
233
+ charsets=["ISO-8859-5", "WINDOWS-1251", "MacCyrillic", "IBM855"],
234
+ alphabet="АБВГДЃЕЖЗЅИЈКЛЉМНЊОПРСТЌУФХЦЧЏШабвгдѓежзѕијклљмнњопрстќуфхцчџш",
235
+ wiki_start_pages=["Главна_страница"],
236
+ ),
237
+ "Dutch": Language(
238
+ name="Dutch",
239
+ iso_code="nl",
240
+ use_ascii=True,
241
+ charsets=["ISO-8859-1", "WINDOWS-1252", "MacRoman"],
242
+ wiki_start_pages=["Hoofdpagina"],
243
+ ),
244
+ "Polish": Language(
245
+ name="Polish",
246
+ iso_code="pl",
247
+ # Q and X are only used for foreign words.
248
+ use_ascii=False,
249
+ charsets=["ISO-8859-2", "WINDOWS-1250"],
250
+ alphabet="AĄBCĆDEĘFGHIJKLŁMNŃOÓPRSŚTUWYZŹŻaąbcćdeęfghijklłmnńoóprsśtuwyzźż",
251
+ wiki_start_pages=["Wikipedia:Strona_główna"],
252
+ ),
253
+ "Portuguese": Language(
254
+ name="Portuguese",
255
+ iso_code="pt",
256
+ use_ascii=True,
257
+ charsets=["ISO-8859-1", "ISO-8859-15", "WINDOWS-1252", "MacRoman"],
258
+ alphabet="ÁÂÃÀÇÉÊÍÓÔÕÚáâãàçéêíóôõú",
259
+ wiki_start_pages=["Wikipédia:Página_principal"],
260
+ ),
261
+ "Romanian": Language(
262
+ name="Romanian",
263
+ iso_code="ro",
264
+ use_ascii=True,
265
+ charsets=["ISO-8859-2", "WINDOWS-1250"],
266
+ alphabet="ăâîșțĂÂÎȘȚ",
267
+ wiki_start_pages=["Pagina_principală"],
268
+ ),
269
+ "Russian": Language(
270
+ name="Russian",
271
+ iso_code="ru",
272
+ use_ascii=False,
273
+ charsets=[
274
+ "ISO-8859-5",
275
+ "WINDOWS-1251",
276
+ "KOI8-R",
277
+ "MacCyrillic",
278
+ "IBM866",
279
+ "IBM855",
280
+ ],
281
+ alphabet="абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ",
282
+ wiki_start_pages=["Заглавная_страница"],
283
+ ),
284
+ "Slovak": Language(
285
+ name="Slovak",
286
+ iso_code="sk",
287
+ use_ascii=True,
288
+ charsets=["ISO-8859-2", "WINDOWS-1250"],
289
+ alphabet="áäčďéíĺľňóôŕšťúýžÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽ",
290
+ wiki_start_pages=["Hlavná_stránka"],
291
+ ),
292
+ "Slovene": Language(
293
+ name="Slovene",
294
+ iso_code="sl",
295
+ # Q, W, X, Y are only used for foreign words.
296
+ use_ascii=False,
297
+ charsets=["ISO-8859-2", "WINDOWS-1250"],
298
+ alphabet="abcčdefghijklmnoprsštuvzžABCČDEFGHIJKLMNOPRSŠTUVZŽ",
299
+ wiki_start_pages=["Glavna_stran"],
300
+ ),
301
+ # Serbian can be written in both Latin and Cyrillic, but there's no
302
+ # simple way to get the Latin alphabet pages from Wikipedia through
303
+ # the API, so for now we just support Cyrillic.
304
+ "Serbian": Language(
305
+ name="Serbian",
306
+ iso_code="sr",
307
+ alphabet="АБВГДЂЕЖЗИЈКЛЉМНЊОПРСТЋУФХЦЧЏШабвгдђежзијклљмнњопрстћуфхцчџш",
308
+ charsets=["ISO-8859-5", "WINDOWS-1251", "MacCyrillic", "IBM855"],
309
+ wiki_start_pages=["Главна_страна"],
310
+ ),
311
+ "Thai": Language(
312
+ name="Thai",
313
+ iso_code="th",
314
+ use_ascii=False,
315
+ charsets=["ISO-8859-11", "TIS-620", "CP874"],
316
+ alphabet="กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛",
317
+ wiki_start_pages=["หน้าหลัก"],
318
+ ),
319
+ "Turkish": Language(
320
+ name="Turkish",
321
+ iso_code="tr",
322
+ # Q, W, and X are not used by Turkish
323
+ use_ascii=False,
324
+ charsets=["ISO-8859-3", "ISO-8859-9", "WINDOWS-1254"],
325
+ alphabet="abcçdefgğhıijklmnoöprsştuüvyzâîûABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZÂÎÛ",
326
+ wiki_start_pages=["Ana_Sayfa"],
327
+ ),
328
+ "Vietnamese": Language(
329
+ name="Vietnamese",
330
+ iso_code="vi",
331
+ use_ascii=False,
332
+ # Windows-1258 is the only common 8-bit
333
+ # Vietnamese encoding supported by Python.
334
+ # From Wikipedia:
335
+ # For systems that lack support for Unicode,
336
+ # dozens of 8-bit Vietnamese code pages are
337
+ # available.[1] The most common are VISCII
338
+ # (TCVN 5712:1993), VPS, and Windows-1258.[3]
339
+ # Where ASCII is required, such as when
340
+ # ensuring readability in plain text e-mail,
341
+ # Vietnamese letters are often encoded
342
+ # according to Vietnamese Quoted-Readable
343
+ # (VIQR) or VSCII Mnemonic (VSCII-MNEM),[4]
344
+ # though usage of either variable-width
345
+ # scheme has declined dramatically following
346
+ # the adoption of Unicode on the World Wide
347
+ # Web.
348
+ charsets=["WINDOWS-1258"],
349
+ alphabet="aăâbcdđeêghiklmnoôơpqrstuưvxyAĂÂBCDĐEÊGHIKLMNOÔƠPQRSTUƯVXY",
350
+ wiki_start_pages=["Chữ_Quốc_ngữ"],
351
+ ),
352
+ }
.venv/Lib/site-packages/pip/_vendor/chardet/sbcharsetprober.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ######################## BEGIN LICENSE BLOCK ########################
2
+ # The Original Code is Mozilla Universal charset detector code.
3
+ #
4
+ # The Initial Developer of the Original Code is
5
+ # Netscape Communications Corporation.
6
+ # Portions created by the Initial Developer are Copyright (C) 2001
7
+ # the Initial Developer. All Rights Reserved.
8
+ #
9
+ # Contributor(s):
10
+ # Mark Pilgrim - port to Python
11
+ # Shy Shalom - original C code
12
+ #
13
+ # This library is free software; you can redistribute it and/or
14
+ # modify it under the terms of the GNU Lesser General Public
15
+ # License as published by the Free Software Foundation; either
16
+ # version 2.1 of the License, or (at your option) any later version.
17
+ #
18
+ # This library is distributed in the hope that it will be useful,
19
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
20
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21
+ # Lesser General Public License for more details.
22
+ #
23
+ # You should have received a copy of the GNU Lesser General Public
24
+ # License along with this library; if not, write to the Free Software
25
+ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
26
+ # 02110-1301 USA
27
+ ######################### END LICENSE BLOCK #########################
28
+
29
+ from typing import Dict, List, NamedTuple, Optional, Union
30
+
31
+ from .charsetprober import CharSetProber
32
+ from .enums import CharacterCategory, ProbingState, SequenceLikelihood
33
+
34
+
35
+ class SingleByteCharSetModel(NamedTuple):
36
+ charset_name: str
37
+ language: str
38
+ char_to_order_map: Dict[int, int]
39
+ language_model: Dict[int, Dict[int, int]]
40
+ typical_positive_ratio: float
41
+ keep_ascii_letters: bool
42
+ alphabet: str
43
+
44
+
45
+ class SingleByteCharSetProber(CharSetProber):
46
+ SAMPLE_SIZE = 64
47
+ SB_ENOUGH_REL_THRESHOLD = 1024 # 0.25 * SAMPLE_SIZE^2
48
+ POSITIVE_SHORTCUT_THRESHOLD = 0.95
49
+ NEGATIVE_SHORTCUT_THRESHOLD = 0.05
50
+
51
+ def __init__(
52
+ self,
53
+ model: SingleByteCharSetModel,
54
+ is_reversed: bool = False,
55
+ name_prober: Optional[CharSetProber] = None,
56
+ ) -> None:
57
+ super().__init__()
58
+ self._model = model
59
+ # TRUE if we need to reverse every pair in the model lookup
60
+ self._reversed = is_reversed
61
+ # Optional auxiliary prober for name decision
62
+ self._name_prober = name_prober
63
+ self._last_order = 255
64
+ self._seq_counters: List[int] = []
65
+ self._total_seqs = 0
66
+ self._total_char = 0
67
+ self._control_char = 0
68
+ self._freq_char = 0
69
+ self.reset()
70
+
71
+ def reset(self) -> None:
72
+ super().reset()
73
+ # char order of last character
74
+ self._last_order = 255
75
+ self._seq_counters = [0] * SequenceLikelihood.get_num_categories()
76
+ self._total_seqs = 0
77
+ self._total_char = 0
78
+ self._control_char = 0
79
+ # characters that fall in our sampling range
80
+ self._freq_char = 0
81
+
82
+ @property
83
+ def charset_name(self) -> Optional[str]:
84
+ if self._name_prober:
85
+ return self._name_prober.charset_name
86
+ return self._model.charset_name
87
+
88
+ @property
89
+ def language(self) -> Optional[str]:
90
+ if self._name_prober:
91
+ return self._name_prober.language
92
+ return self._model.language
93
+
94
+ def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
95
+ # TODO: Make filter_international_words keep things in self.alphabet
96
+ if not self._model.keep_ascii_letters:
97
+ byte_str = self.filter_international_words(byte_str)
98
+ else:
99
+ byte_str = self.remove_xml_tags(byte_str)
100
+ if not byte_str:
101
+ return self.state
102
+ char_to_order_map = self._model.char_to_order_map
103
+ language_model = self._model.language_model
104
+ for char in byte_str:
105
+ order = char_to_order_map.get(char, CharacterCategory.UNDEFINED)
106
+ # XXX: This was SYMBOL_CAT_ORDER before, with a value of 250, but
107
+ # CharacterCategory.SYMBOL is actually 253, so we use CONTROL
108
+ # to make it closer to the original intent. The only difference
109
+ # is whether or not we count digits and control characters for
110
+ # _total_char purposes.
111
+ if order < CharacterCategory.CONTROL:
112
+ self._total_char += 1
113
+ if order < self.SAMPLE_SIZE:
114
+ self._freq_char += 1
115
+ if self._last_order < self.SAMPLE_SIZE:
116
+ self._total_seqs += 1
117
+ if not self._reversed:
118
+ lm_cat = language_model[self._last_order][order]
119
+ else:
120
+ lm_cat = language_model[order][self._last_order]
121
+ self._seq_counters[lm_cat] += 1
122
+ self._last_order = order
123
+
124
+ charset_name = self._model.charset_name
125
+ if self.state == ProbingState.DETECTING:
126
+ if self._total_seqs > self.SB_ENOUGH_REL_THRESHOLD:
127
+ confidence = self.get_confidence()
128
+ if confidence > self.POSITIVE_SHORTCUT_THRESHOLD:
129
+ self.logger.debug(
130
+ "%s confidence = %s, we have a winner", charset_name, confidence
131
+ )
132
+ self._state = ProbingState.FOUND_IT
133
+ elif confidence < self.NEGATIVE_SHORTCUT_THRESHOLD:
134
+ self.logger.debug(
135
+ "%s confidence = %s, below negative shortcut threshold %s",
136
+ charset_name,
137
+ confidence,
138
+ self.NEGATIVE_SHORTCUT_THRESHOLD,
139
+ )
140
+ self._state = ProbingState.NOT_ME
141
+
142
+ return self.state
143
+
144
+ def get_confidence(self) -> float:
145
+ r = 0.01
146
+ if self._total_seqs > 0:
147
+ r = (
148
+ (
149
+ self._seq_counters[SequenceLikelihood.POSITIVE]
150
+ + 0.25 * self._seq_counters[SequenceLikelihood.LIKELY]
151
+ )
152
+ / self._total_seqs
153
+ / self._model.typical_positive_ratio
154
+ )
155
+ # The more control characters (proportionnaly to the size
156
+ # of the text), the less confident we become in the current
157
+ # charset.
158
+ r = r * (self._total_char - self._control_char) / self._total_char
159
+ r = r * self._freq_char / self._total_char
160
+ if r >= 1.0:
161
+ r = 0.99
162
+ return r
.venv/Lib/site-packages/pip/_vendor/chardet/sbcsgroupprober.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ######################## BEGIN LICENSE BLOCK ########################
2
+ # The Original Code is Mozilla Universal charset detector code.
3
+ #
4
+ # The Initial Developer of the Original Code is
5
+ # Netscape Communications Corporation.
6
+ # Portions created by the Initial Developer are Copyright (C) 2001
7
+ # the Initial Developer. All Rights Reserved.
8
+ #
9
+ # Contributor(s):
10
+ # Mark Pilgrim - port to Python
11
+ # Shy Shalom - original C code
12
+ #
13
+ # This library is free software; you can redistribute it and/or
14
+ # modify it under the terms of the GNU Lesser General Public
15
+ # License as published by the Free Software Foundation; either
16
+ # version 2.1 of the License, or (at your option) any later version.
17
+ #
18
+ # This library is distributed in the hope that it will be useful,
19
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
20
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21
+ # Lesser General Public License for more details.
22
+ #
23
+ # You should have received a copy of the GNU Lesser General Public
24
+ # License along with this library; if not, write to the Free Software
25
+ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
26
+ # 02110-1301 USA
27
+ ######################### END LICENSE BLOCK #########################
28
+
29
+ from .charsetgroupprober import CharSetGroupProber
30
+ from .hebrewprober import HebrewProber
31
+ from .langbulgarianmodel import ISO_8859_5_BULGARIAN_MODEL, WINDOWS_1251_BULGARIAN_MODEL
32
+ from .langgreekmodel import ISO_8859_7_GREEK_MODEL, WINDOWS_1253_GREEK_MODEL
33
+ from .langhebrewmodel import WINDOWS_1255_HEBREW_MODEL
34
+
35
+ # from .langhungarianmodel import (ISO_8859_2_HUNGARIAN_MODEL,
36
+ # WINDOWS_1250_HUNGARIAN_MODEL)
37
+ from .langrussianmodel import (
38
+ IBM855_RUSSIAN_MODEL,
39
+ IBM866_RUSSIAN_MODEL,
40
+ ISO_8859_5_RUSSIAN_MODEL,
41
+ KOI8_R_RUSSIAN_MODEL,
42
+ MACCYRILLIC_RUSSIAN_MODEL,
43
+ WINDOWS_1251_RUSSIAN_MODEL,
44
+ )
45
+ from .langthaimodel import TIS_620_THAI_MODEL
46
+ from .langturkishmodel import ISO_8859_9_TURKISH_MODEL
47
+ from .sbcharsetprober import SingleByteCharSetProber
48
+
49
+
50
+ class SBCSGroupProber(CharSetGroupProber):
51
+ def __init__(self) -> None:
52
+ super().__init__()
53
+ hebrew_prober = HebrewProber()
54
+ logical_hebrew_prober = SingleByteCharSetProber(
55
+ WINDOWS_1255_HEBREW_MODEL, is_reversed=False, name_prober=hebrew_prober
56
+ )
57
+ # TODO: See if using ISO-8859-8 Hebrew model works better here, since
58
+ # it's actually the visual one
59
+ visual_hebrew_prober = SingleByteCharSetProber(
60
+ WINDOWS_1255_HEBREW_MODEL, is_reversed=True, name_prober=hebrew_prober
61
+ )
62
+ hebrew_prober.set_model_probers(logical_hebrew_prober, visual_hebrew_prober)
63
+ # TODO: ORDER MATTERS HERE. I changed the order vs what was in master
64
+ # and several tests failed that did not before. Some thought
65
+ # should be put into the ordering, and we should consider making
66
+ # order not matter here, because that is very counter-intuitive.
67
+ self.probers = [
68
+ SingleByteCharSetProber(WINDOWS_1251_RUSSIAN_MODEL),
69
+ SingleByteCharSetProber(KOI8_R_RUSSIAN_MODEL),
70
+ SingleByteCharSetProber(ISO_8859_5_RUSSIAN_MODEL),
71
+ SingleByteCharSetProber(MACCYRILLIC_RUSSIAN_MODEL),
72
+ SingleByteCharSetProber(IBM866_RUSSIAN_MODEL),
73
+ SingleByteCharSetProber(IBM855_RUSSIAN_MODEL),
74
+ SingleByteCharSetProber(ISO_8859_7_GREEK_MODEL),
75
+ SingleByteCharSetProber(WINDOWS_1253_GREEK_MODEL),
76
+ SingleByteCharSetProber(ISO_8859_5_BULGARIAN_MODEL),
77
+ SingleByteCharSetProber(WINDOWS_1251_BULGARIAN_MODEL),
78
+ # TODO: Restore Hungarian encodings (iso-8859-2 and windows-1250)
79
+ # after we retrain model.
80
+ # SingleByteCharSetProber(ISO_8859_2_HUNGARIAN_MODEL),
81
+ # SingleByteCharSetProber(WINDOWS_1250_HUNGARIAN_MODEL),
82
+ SingleByteCharSetProber(TIS_620_THAI_MODEL),
83
+ SingleByteCharSetProber(ISO_8859_9_TURKISH_MODEL),
84
+ hebrew_prober,
85
+ logical_hebrew_prober,
86
+ visual_hebrew_prober,
87
+ ]
88
+ self.reset()
.venv/Lib/site-packages/pip/_vendor/chardet/sjisprober.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ######################## BEGIN LICENSE BLOCK ########################
2
+ # The Original Code is mozilla.org code.
3
+ #
4
+ # The Initial Developer of the Original Code is
5
+ # Netscape Communications Corporation.
6
+ # Portions created by the Initial Developer are Copyright (C) 1998
7
+ # the Initial Developer. All Rights Reserved.
8
+ #
9
+ # Contributor(s):
10
+ # Mark Pilgrim - port to Python
11
+ #
12
+ # This library is free software; you can redistribute it and/or
13
+ # modify it under the terms of the GNU Lesser General Public
14
+ # License as published by the Free Software Foundation; either
15
+ # version 2.1 of the License, or (at your option) any later version.
16
+ #
17
+ # This library is distributed in the hope that it will be useful,
18
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20
+ # Lesser General Public License for more details.
21
+ #
22
+ # You should have received a copy of the GNU Lesser General Public
23
+ # License along with this library; if not, write to the Free Software
24
+ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
25
+ # 02110-1301 USA
26
+ ######################### END LICENSE BLOCK #########################
27
+
28
+ from typing import Union
29
+
30
+ from .chardistribution import SJISDistributionAnalysis
31
+ from .codingstatemachine import CodingStateMachine
32
+ from .enums import MachineState, ProbingState
33
+ from .jpcntx import SJISContextAnalysis
34
+ from .mbcharsetprober import MultiByteCharSetProber
35
+ from .mbcssm import SJIS_SM_MODEL
36
+
37
+
38
+ class SJISProber(MultiByteCharSetProber):
39
+ def __init__(self) -> None:
40
+ super().__init__()
41
+ self.coding_sm = CodingStateMachine(SJIS_SM_MODEL)
42
+ self.distribution_analyzer = SJISDistributionAnalysis()
43
+ self.context_analyzer = SJISContextAnalysis()
44
+ self.reset()
45
+
46
+ def reset(self) -> None:
47
+ super().reset()
48
+ self.context_analyzer.reset()
49
+
50
+ @property
51
+ def charset_name(self) -> str:
52
+ return self.context_analyzer.charset_name
53
+
54
+ @property
55
+ def language(self) -> str:
56
+ return "Japanese"
57
+
58
+ def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
59
+ assert self.coding_sm is not None
60
+ assert self.distribution_analyzer is not None
61
+
62
+ for i, byte in enumerate(byte_str):
63
+ coding_state = self.coding_sm.next_state(byte)
64
+ if coding_state == MachineState.ERROR:
65
+ self.logger.debug(
66
+ "%s %s prober hit error at byte %s",
67
+ self.charset_name,
68
+ self.language,
69
+ i,
70
+ )
71
+ self._state = ProbingState.NOT_ME
72
+ break
73
+ if coding_state == MachineState.ITS_ME:
74
+ self._state = ProbingState.FOUND_IT
75
+ break
76
+ if coding_state == MachineState.START:
77
+ char_len = self.coding_sm.get_current_charlen()
78
+ if i == 0:
79
+ self._last_char[1] = byte
80
+ self.context_analyzer.feed(
81
+ self._last_char[2 - char_len :], char_len
82
+ )
83
+ self.distribution_analyzer.feed(self._last_char, char_len)
84
+ else:
85
+ self.context_analyzer.feed(
86
+ byte_str[i + 1 - char_len : i + 3 - char_len], char_len
87
+ )
88
+ self.distribution_analyzer.feed(byte_str[i - 1 : i + 1], char_len)
89
+
90
+ self._last_char[0] = byte_str[-1]
91
+
92
+ if self.state == ProbingState.DETECTING:
93
+ if self.context_analyzer.got_enough_data() and (
94
+ self.get_confidence() > self.SHORTCUT_THRESHOLD
95
+ ):
96
+ self._state = ProbingState.FOUND_IT
97
+
98
+ return self.state
99
+
100
+ def get_confidence(self) -> float:
101
+ assert self.distribution_analyzer is not None
102
+
103
+ context_conf = self.context_analyzer.get_confidence()
104
+ distrib_conf = self.distribution_analyzer.get_confidence()
105
+ return max(context_conf, distrib_conf)
.venv/Lib/site-packages/pip/_vendor/chardet/universaldetector.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ######################## BEGIN LICENSE BLOCK ########################
2
+ # The Original Code is Mozilla Universal charset detector code.
3
+ #
4
+ # The Initial Developer of the Original Code is
5
+ # Netscape Communications Corporation.
6
+ # Portions created by the Initial Developer are Copyright (C) 2001
7
+ # the Initial Developer. All Rights Reserved.
8
+ #
9
+ # Contributor(s):
10
+ # Mark Pilgrim - port to Python
11
+ # Shy Shalom - original C code
12
+ #
13
+ # This library is free software; you can redistribute it and/or
14
+ # modify it under the terms of the GNU Lesser General Public
15
+ # License as published by the Free Software Foundation; either
16
+ # version 2.1 of the License, or (at your option) any later version.
17
+ #
18
+ # This library is distributed in the hope that it will be useful,
19
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
20
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21
+ # Lesser General Public License for more details.
22
+ #
23
+ # You should have received a copy of the GNU Lesser General Public
24
+ # License along with this library; if not, write to the Free Software
25
+ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
26
+ # 02110-1301 USA
27
+ ######################### END LICENSE BLOCK #########################
28
+ """
29
+ Module containing the UniversalDetector detector class, which is the primary
30
+ class a user of ``chardet`` should use.
31
+
32
+ :author: Mark Pilgrim (initial port to Python)
33
+ :author: Shy Shalom (original C code)
34
+ :author: Dan Blanchard (major refactoring for 3.0)
35
+ :author: Ian Cordasco
36
+ """
37
+
38
+
39
+ import codecs
40
+ import logging
41
+ import re
42
+ from typing import List, Optional, Union
43
+
44
+ from .charsetgroupprober import CharSetGroupProber
45
+ from .charsetprober import CharSetProber
46
+ from .enums import InputState, LanguageFilter, ProbingState
47
+ from .escprober import EscCharSetProber
48
+ from .latin1prober import Latin1Prober
49
+ from .macromanprober import MacRomanProber
50
+ from .mbcsgroupprober import MBCSGroupProber
51
+ from .resultdict import ResultDict
52
+ from .sbcsgroupprober import SBCSGroupProber
53
+ from .utf1632prober import UTF1632Prober
54
+
55
+
56
+ class UniversalDetector:
57
+ """
58
+ The ``UniversalDetector`` class underlies the ``chardet.detect`` function
59
+ and coordinates all of the different charset probers.
60
+
61
+ To get a ``dict`` containing an encoding and its confidence, you can simply
62
+ run:
63
+
64
+ .. code::
65
+
66
+ u = UniversalDetector()
67
+ u.feed(some_bytes)
68
+ u.close()
69
+ detected = u.result
70
+
71
+ """
72
+
73
+ MINIMUM_THRESHOLD = 0.20
74
+ HIGH_BYTE_DETECTOR = re.compile(b"[\x80-\xFF]")
75
+ ESC_DETECTOR = re.compile(b"(\033|~{)")
76
+ WIN_BYTE_DETECTOR = re.compile(b"[\x80-\x9F]")
77
+ ISO_WIN_MAP = {
78
+ "iso-8859-1": "Windows-1252",
79
+ "iso-8859-2": "Windows-1250",
80
+ "iso-8859-5": "Windows-1251",
81
+ "iso-8859-6": "Windows-1256",
82
+ "iso-8859-7": "Windows-1253",
83
+ "iso-8859-8": "Windows-1255",
84
+ "iso-8859-9": "Windows-1254",
85
+ "iso-8859-13": "Windows-1257",
86
+ }
87
+ # Based on https://encoding.spec.whatwg.org/#names-and-labels
88
+ # but altered to match Python names for encodings and remove mappings
89
+ # that break tests.
90
+ LEGACY_MAP = {
91
+ "ascii": "Windows-1252",
92
+ "iso-8859-1": "Windows-1252",
93
+ "tis-620": "ISO-8859-11",
94
+ "iso-8859-9": "Windows-1254",
95
+ "gb2312": "GB18030",
96
+ "euc-kr": "CP949",
97
+ "utf-16le": "UTF-16",
98
+ }
99
+
100
+ def __init__(
101
+ self,
102
+ lang_filter: LanguageFilter = LanguageFilter.ALL,
103
+ should_rename_legacy: bool = False,
104
+ ) -> None:
105
+ self._esc_charset_prober: Optional[EscCharSetProber] = None
106
+ self._utf1632_prober: Optional[UTF1632Prober] = None
107
+ self._charset_probers: List[CharSetProber] = []
108
+ self.result: ResultDict = {
109
+ "encoding": None,
110
+ "confidence": 0.0,
111
+ "language": None,
112
+ }
113
+ self.done = False
114
+ self._got_data = False
115
+ self._input_state = InputState.PURE_ASCII
116
+ self._last_char = b""
117
+ self.lang_filter = lang_filter
118
+ self.logger = logging.getLogger(__name__)
119
+ self._has_win_bytes = False
120
+ self.should_rename_legacy = should_rename_legacy
121
+ self.reset()
122
+
123
+ @property
124
+ def input_state(self) -> int:
125
+ return self._input_state
126
+
127
+ @property
128
+ def has_win_bytes(self) -> bool:
129
+ return self._has_win_bytes
130
+
131
+ @property
132
+ def charset_probers(self) -> List[CharSetProber]:
133
+ return self._charset_probers
134
+
135
+ def reset(self) -> None:
136
+ """
137
+ Reset the UniversalDetector and all of its probers back to their
138
+ initial states. This is called by ``__init__``, so you only need to
139
+ call this directly in between analyses of different documents.
140
+ """
141
+ self.result = {"encoding": None, "confidence": 0.0, "language": None}
142
+ self.done = False
143
+ self._got_data = False
144
+ self._has_win_bytes = False
145
+ self._input_state = InputState.PURE_ASCII
146
+ self._last_char = b""
147
+ if self._esc_charset_prober:
148
+ self._esc_charset_prober.reset()
149
+ if self._utf1632_prober:
150
+ self._utf1632_prober.reset()
151
+ for prober in self._charset_probers:
152
+ prober.reset()
153
+
154
+ def feed(self, byte_str: Union[bytes, bytearray]) -> None:
155
+ """
156
+ Takes a chunk of a document and feeds it through all of the relevant
157
+ charset probers.
158
+
159
+ After calling ``feed``, you can check the value of the ``done``
160
+ attribute to see if you need to continue feeding the
161
+ ``UniversalDetector`` more data, or if it has made a prediction
162
+ (in the ``result`` attribute).
163
+
164
+ .. note::
165
+ You should always call ``close`` when you're done feeding in your
166
+ document if ``done`` is not already ``True``.
167
+ """
168
+ if self.done:
169
+ return
170
+
171
+ if not byte_str:
172
+ return
173
+
174
+ if not isinstance(byte_str, bytearray):
175
+ byte_str = bytearray(byte_str)
176
+
177
+ # First check for known BOMs, since these are guaranteed to be correct
178
+ if not self._got_data:
179
+ # If the data starts with BOM, we know it is UTF
180
+ if byte_str.startswith(codecs.BOM_UTF8):
181
+ # EF BB BF UTF-8 with BOM
182
+ self.result = {
183
+ "encoding": "UTF-8-SIG",
184
+ "confidence": 1.0,
185
+ "language": "",
186
+ }
187
+ elif byte_str.startswith((codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)):
188
+ # FF FE 00 00 UTF-32, little-endian BOM
189
+ # 00 00 FE FF UTF-32, big-endian BOM
190
+ self.result = {"encoding": "UTF-32", "confidence": 1.0, "language": ""}
191
+ elif byte_str.startswith(b"\xFE\xFF\x00\x00"):
192
+ # FE FF 00 00 UCS-4, unusual octet order BOM (3412)
193
+ self.result = {
194
+ # TODO: This encoding is not supported by Python. Should remove?
195
+ "encoding": "X-ISO-10646-UCS-4-3412",
196
+ "confidence": 1.0,
197
+ "language": "",
198
+ }
199
+ elif byte_str.startswith(b"\x00\x00\xFF\xFE"):
200
+ # 00 00 FF FE UCS-4, unusual octet order BOM (2143)
201
+ self.result = {
202
+ # TODO: This encoding is not supported by Python. Should remove?
203
+ "encoding": "X-ISO-10646-UCS-4-2143",
204
+ "confidence": 1.0,
205
+ "language": "",
206
+ }
207
+ elif byte_str.startswith((codecs.BOM_LE, codecs.BOM_BE)):
208
+ # FF FE UTF-16, little endian BOM
209
+ # FE FF UTF-16, big endian BOM
210
+ self.result = {"encoding": "UTF-16", "confidence": 1.0, "language": ""}
211
+
212
+ self._got_data = True
213
+ if self.result["encoding"] is not None:
214
+ self.done = True
215
+ return
216
+
217
+ # If none of those matched and we've only see ASCII so far, check
218
+ # for high bytes and escape sequences
219
+ if self._input_state == InputState.PURE_ASCII:
220
+ if self.HIGH_BYTE_DETECTOR.search(byte_str):
221
+ self._input_state = InputState.HIGH_BYTE
222
+ elif (
223
+ self._input_state == InputState.PURE_ASCII
224
+ and self.ESC_DETECTOR.search(self._last_char + byte_str)
225
+ ):
226
+ self._input_state = InputState.ESC_ASCII
227
+
228
+ self._last_char = byte_str[-1:]
229
+
230
+ # next we will look to see if it is appears to be either a UTF-16 or
231
+ # UTF-32 encoding
232
+ if not self._utf1632_prober:
233
+ self._utf1632_prober = UTF1632Prober()
234
+
235
+ if self._utf1632_prober.state == ProbingState.DETECTING:
236
+ if self._utf1632_prober.feed(byte_str) == ProbingState.FOUND_IT:
237
+ self.result = {
238
+ "encoding": self._utf1632_prober.charset_name,
239
+ "confidence": self._utf1632_prober.get_confidence(),
240
+ "language": "",
241
+ }
242
+ self.done = True
243
+ return
244
+
245
+ # If we've seen escape sequences, use the EscCharSetProber, which
246
+ # uses a simple state machine to check for known escape sequences in
247
+ # HZ and ISO-2022 encodings, since those are the only encodings that
248
+ # use such sequences.
249
+ if self._input_state == InputState.ESC_ASCII:
250
+ if not self._esc_charset_prober:
251
+ self._esc_charset_prober = EscCharSetProber(self.lang_filter)
252
+ if self._esc_charset_prober.feed(byte_str) == ProbingState.FOUND_IT:
253
+ self.result = {
254
+ "encoding": self._esc_charset_prober.charset_name,
255
+ "confidence": self._esc_charset_prober.get_confidence(),
256
+ "language": self._esc_charset_prober.language,
257
+ }
258
+ self.done = True
259
+ # If we've seen high bytes (i.e., those with values greater than 127),
260
+ # we need to do more complicated checks using all our multi-byte and
261
+ # single-byte probers that are left. The single-byte probers
262
+ # use character bigram distributions to determine the encoding, whereas
263
+ # the multi-byte probers use a combination of character unigram and
264
+ # bigram distributions.
265
+ elif self._input_state == InputState.HIGH_BYTE:
266
+ if not self._charset_probers:
267
+ self._charset_probers = [MBCSGroupProber(self.lang_filter)]
268
+ # If we're checking non-CJK encodings, use single-byte prober
269
+ if self.lang_filter & LanguageFilter.NON_CJK:
270
+ self._charset_probers.append(SBCSGroupProber())
271
+ self._charset_probers.append(Latin1Prober())
272
+ self._charset_probers.append(MacRomanProber())
273
+ for prober in self._charset_probers:
274
+ if prober.feed(byte_str) == ProbingState.FOUND_IT:
275
+ self.result = {
276
+ "encoding": prober.charset_name,
277
+ "confidence": prober.get_confidence(),
278
+ "language": prober.language,
279
+ }
280
+ self.done = True
281
+ break
282
+ if self.WIN_BYTE_DETECTOR.search(byte_str):
283
+ self._has_win_bytes = True
284
+
285
+ def close(self) -> ResultDict:
286
+ """
287
+ Stop analyzing the current document and come up with a final
288
+ prediction.
289
+
290
+ :returns: The ``result`` attribute, a ``dict`` with the keys
291
+ `encoding`, `confidence`, and `language`.
292
+ """
293
+ # Don't bother with checks if we're already done
294
+ if self.done:
295
+ return self.result
296
+ self.done = True
297
+
298
+ if not self._got_data:
299
+ self.logger.debug("no data received!")
300
+
301
+ # Default to ASCII if it is all we've seen so far
302
+ elif self._input_state == InputState.PURE_ASCII:
303
+ self.result = {"encoding": "ascii", "confidence": 1.0, "language": ""}
304
+
305
+ # If we have seen non-ASCII, return the best that met MINIMUM_THRESHOLD
306
+ elif self._input_state == InputState.HIGH_BYTE:
307
+ prober_confidence = None
308
+ max_prober_confidence = 0.0
309
+ max_prober = None
310
+ for prober in self._charset_probers:
311
+ if not prober:
312
+ continue
313
+ prober_confidence = prober.get_confidence()
314
+ if prober_confidence > max_prober_confidence:
315
+ max_prober_confidence = prober_confidence
316
+ max_prober = prober
317
+ if max_prober and (max_prober_confidence > self.MINIMUM_THRESHOLD):
318
+ charset_name = max_prober.charset_name
319
+ assert charset_name is not None
320
+ lower_charset_name = charset_name.lower()
321
+ confidence = max_prober.get_confidence()
322
+ # Use Windows encoding name instead of ISO-8859 if we saw any
323
+ # extra Windows-specific bytes
324
+ if lower_charset_name.startswith("iso-8859"):
325
+ if self._has_win_bytes:
326
+ charset_name = self.ISO_WIN_MAP.get(
327
+ lower_charset_name, charset_name
328
+ )
329
+ # Rename legacy encodings with superset encodings if asked
330
+ if self.should_rename_legacy:
331
+ charset_name = self.LEGACY_MAP.get(
332
+ (charset_name or "").lower(), charset_name
333
+ )
334
+ self.result = {
335
+ "encoding": charset_name,
336
+ "confidence": confidence,
337
+ "language": max_prober.language,
338
+ }
339
+
340
+ # Log all prober confidences if none met MINIMUM_THRESHOLD
341
+ if self.logger.getEffectiveLevel() <= logging.DEBUG:
342
+ if self.result["encoding"] is None:
343
+ self.logger.debug("no probers hit minimum threshold")
344
+ for group_prober in self._charset_probers:
345
+ if not group_prober:
346
+ continue
347
+ if isinstance(group_prober, CharSetGroupProber):
348
+ for prober in group_prober.probers:
349
+ self.logger.debug(
350
+ "%s %s confidence = %s",
351
+ prober.charset_name,
352
+ prober.language,
353
+ prober.get_confidence(),
354
+ )
355
+ else:
356
+ self.logger.debug(
357
+ "%s %s confidence = %s",
358
+ group_prober.charset_name,
359
+ group_prober.language,
360
+ group_prober.get_confidence(),
361
+ )
362
+ return self.result
.venv/Lib/site-packages/pip/_vendor/chardet/utf1632prober.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ######################## BEGIN LICENSE BLOCK ########################
2
+ #
3
+ # Contributor(s):
4
+ # Jason Zavaglia
5
+ #
6
+ # This library is free software; you can redistribute it and/or
7
+ # modify it under the terms of the GNU Lesser General Public
8
+ # License as published by the Free Software Foundation; either
9
+ # version 2.1 of the License, or (at your option) any later version.
10
+ #
11
+ # This library is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14
+ # Lesser General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU Lesser General Public
17
+ # License along with this library; if not, write to the Free Software
18
+ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
19
+ # 02110-1301 USA
20
+ ######################### END LICENSE BLOCK #########################
21
+ from typing import List, Union
22
+
23
+ from .charsetprober import CharSetProber
24
+ from .enums import ProbingState
25
+
26
+
27
+ class UTF1632Prober(CharSetProber):
28
+ """
29
+ This class simply looks for occurrences of zero bytes, and infers
30
+ whether the file is UTF16 or UTF32 (low-endian or big-endian)
31
+ For instance, files looking like ( \0 \0 \0 [nonzero] )+
32
+ have a good probability to be UTF32BE. Files looking like ( \0 [nonzero] )+
33
+ may be guessed to be UTF16BE, and inversely for little-endian varieties.
34
+ """
35
+
36
+ # how many logical characters to scan before feeling confident of prediction
37
+ MIN_CHARS_FOR_DETECTION = 20
38
+ # a fixed constant ratio of expected zeros or non-zeros in modulo-position.
39
+ EXPECTED_RATIO = 0.94
40
+
41
+ def __init__(self) -> None:
42
+ super().__init__()
43
+ self.position = 0
44
+ self.zeros_at_mod = [0] * 4
45
+ self.nonzeros_at_mod = [0] * 4
46
+ self._state = ProbingState.DETECTING
47
+ self.quad = [0, 0, 0, 0]
48
+ self.invalid_utf16be = False
49
+ self.invalid_utf16le = False
50
+ self.invalid_utf32be = False
51
+ self.invalid_utf32le = False
52
+ self.first_half_surrogate_pair_detected_16be = False
53
+ self.first_half_surrogate_pair_detected_16le = False
54
+ self.reset()
55
+
56
+ def reset(self) -> None:
57
+ super().reset()
58
+ self.position = 0
59
+ self.zeros_at_mod = [0] * 4
60
+ self.nonzeros_at_mod = [0] * 4
61
+ self._state = ProbingState.DETECTING
62
+ self.invalid_utf16be = False
63
+ self.invalid_utf16le = False
64
+ self.invalid_utf32be = False
65
+ self.invalid_utf32le = False
66
+ self.first_half_surrogate_pair_detected_16be = False
67
+ self.first_half_surrogate_pair_detected_16le = False
68
+ self.quad = [0, 0, 0, 0]
69
+
70
+ @property
71
+ def charset_name(self) -> str:
72
+ if self.is_likely_utf32be():
73
+ return "utf-32be"
74
+ if self.is_likely_utf32le():
75
+ return "utf-32le"
76
+ if self.is_likely_utf16be():
77
+ return "utf-16be"
78
+ if self.is_likely_utf16le():
79
+ return "utf-16le"
80
+ # default to something valid
81
+ return "utf-16"
82
+
83
+ @property
84
+ def language(self) -> str:
85
+ return ""
86
+
87
+ def approx_32bit_chars(self) -> float:
88
+ return max(1.0, self.position / 4.0)
89
+
90
+ def approx_16bit_chars(self) -> float:
91
+ return max(1.0, self.position / 2.0)
92
+
93
+ def is_likely_utf32be(self) -> bool:
94
+ approx_chars = self.approx_32bit_chars()
95
+ return approx_chars >= self.MIN_CHARS_FOR_DETECTION and (
96
+ self.zeros_at_mod[0] / approx_chars > self.EXPECTED_RATIO
97
+ and self.zeros_at_mod[1] / approx_chars > self.EXPECTED_RATIO
98
+ and self.zeros_at_mod[2] / approx_chars > self.EXPECTED_RATIO
99
+ and self.nonzeros_at_mod[3] / approx_chars > self.EXPECTED_RATIO
100
+ and not self.invalid_utf32be
101
+ )
102
+
103
+ def is_likely_utf32le(self) -> bool:
104
+ approx_chars = self.approx_32bit_chars()
105
+ return approx_chars >= self.MIN_CHARS_FOR_DETECTION and (
106
+ self.nonzeros_at_mod[0] / approx_chars > self.EXPECTED_RATIO
107
+ and self.zeros_at_mod[1] / approx_chars > self.EXPECTED_RATIO
108
+ and self.zeros_at_mod[2] / approx_chars > self.EXPECTED_RATIO
109
+ and self.zeros_at_mod[3] / approx_chars > self.EXPECTED_RATIO
110
+ and not self.invalid_utf32le
111
+ )
112
+
113
+ def is_likely_utf16be(self) -> bool:
114
+ approx_chars = self.approx_16bit_chars()
115
+ return approx_chars >= self.MIN_CHARS_FOR_DETECTION and (
116
+ (self.nonzeros_at_mod[1] + self.nonzeros_at_mod[3]) / approx_chars
117
+ > self.EXPECTED_RATIO
118
+ and (self.zeros_at_mod[0] + self.zeros_at_mod[2]) / approx_chars
119
+ > self.EXPECTED_RATIO
120
+ and not self.invalid_utf16be
121
+ )
122
+
123
+ def is_likely_utf16le(self) -> bool:
124
+ approx_chars = self.approx_16bit_chars()
125
+ return approx_chars >= self.MIN_CHARS_FOR_DETECTION and (
126
+ (self.nonzeros_at_mod[0] + self.nonzeros_at_mod[2]) / approx_chars
127
+ > self.EXPECTED_RATIO
128
+ and (self.zeros_at_mod[1] + self.zeros_at_mod[3]) / approx_chars
129
+ > self.EXPECTED_RATIO
130
+ and not self.invalid_utf16le
131
+ )
132
+
133
+ def validate_utf32_characters(self, quad: List[int]) -> None:
134
+ """
135
+ Validate if the quad of bytes is valid UTF-32.
136
+
137
+ UTF-32 is valid in the range 0x00000000 - 0x0010FFFF
138
+ excluding 0x0000D800 - 0x0000DFFF
139
+
140
+ https://en.wikipedia.org/wiki/UTF-32
141
+ """
142
+ if (
143
+ quad[0] != 0
144
+ or quad[1] > 0x10
145
+ or (quad[0] == 0 and quad[1] == 0 and 0xD8 <= quad[2] <= 0xDF)
146
+ ):
147
+ self.invalid_utf32be = True
148
+ if (
149
+ quad[3] != 0
150
+ or quad[2] > 0x10
151
+ or (quad[3] == 0 and quad[2] == 0 and 0xD8 <= quad[1] <= 0xDF)
152
+ ):
153
+ self.invalid_utf32le = True
154
+
155
+ def validate_utf16_characters(self, pair: List[int]) -> None:
156
+ """
157
+ Validate if the pair of bytes is valid UTF-16.
158
+
159
+ UTF-16 is valid in the range 0x0000 - 0xFFFF excluding 0xD800 - 0xFFFF
160
+ with an exception for surrogate pairs, which must be in the range
161
+ 0xD800-0xDBFF followed by 0xDC00-0xDFFF
162
+
163
+ https://en.wikipedia.org/wiki/UTF-16
164
+ """
165
+ if not self.first_half_surrogate_pair_detected_16be:
166
+ if 0xD8 <= pair[0] <= 0xDB:
167
+ self.first_half_surrogate_pair_detected_16be = True
168
+ elif 0xDC <= pair[0] <= 0xDF:
169
+ self.invalid_utf16be = True
170
+ else:
171
+ if 0xDC <= pair[0] <= 0xDF:
172
+ self.first_half_surrogate_pair_detected_16be = False
173
+ else:
174
+ self.invalid_utf16be = True
175
+
176
+ if not self.first_half_surrogate_pair_detected_16le:
177
+ if 0xD8 <= pair[1] <= 0xDB:
178
+ self.first_half_surrogate_pair_detected_16le = True
179
+ elif 0xDC <= pair[1] <= 0xDF:
180
+ self.invalid_utf16le = True
181
+ else:
182
+ if 0xDC <= pair[1] <= 0xDF:
183
+ self.first_half_surrogate_pair_detected_16le = False
184
+ else:
185
+ self.invalid_utf16le = True
186
+
187
+ def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
188
+ for c in byte_str:
189
+ mod4 = self.position % 4
190
+ self.quad[mod4] = c
191
+ if mod4 == 3:
192
+ self.validate_utf32_characters(self.quad)
193
+ self.validate_utf16_characters(self.quad[0:2])
194
+ self.validate_utf16_characters(self.quad[2:4])
195
+ if c == 0:
196
+ self.zeros_at_mod[mod4] += 1
197
+ else:
198
+ self.nonzeros_at_mod[mod4] += 1
199
+ self.position += 1
200
+ return self.state
201
+
202
+ @property
203
+ def state(self) -> ProbingState:
204
+ if self._state in {ProbingState.NOT_ME, ProbingState.FOUND_IT}:
205
+ # terminal, decided states
206
+ return self._state
207
+ if self.get_confidence() > 0.80:
208
+ self._state = ProbingState.FOUND_IT
209
+ elif self.position > 4 * 1024:
210
+ # if we get to 4kb into the file, and we can't conclude it's UTF,
211
+ # let's give up
212
+ self._state = ProbingState.NOT_ME
213
+ return self._state
214
+
215
+ def get_confidence(self) -> float:
216
+ return (
217
+ 0.85
218
+ if (
219
+ self.is_likely_utf16le()
220
+ or self.is_likely_utf16be()
221
+ or self.is_likely_utf32le()
222
+ or self.is_likely_utf32be()
223
+ )
224
+ else 0.00
225
+ )
.venv/Lib/site-packages/pip/_vendor/chardet/utf8prober.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ######################## BEGIN LICENSE BLOCK ########################
2
+ # The Original Code is mozilla.org code.
3
+ #
4
+ # The Initial Developer of the Original Code is
5
+ # Netscape Communications Corporation.
6
+ # Portions created by the Initial Developer are Copyright (C) 1998
7
+ # the Initial Developer. All Rights Reserved.
8
+ #
9
+ # Contributor(s):
10
+ # Mark Pilgrim - port to Python
11
+ #
12
+ # This library is free software; you can redistribute it and/or
13
+ # modify it under the terms of the GNU Lesser General Public
14
+ # License as published by the Free Software Foundation; either
15
+ # version 2.1 of the License, or (at your option) any later version.
16
+ #
17
+ # This library is distributed in the hope that it will be useful,
18
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20
+ # Lesser General Public License for more details.
21
+ #
22
+ # You should have received a copy of the GNU Lesser General Public
23
+ # License along with this library; if not, write to the Free Software
24
+ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
25
+ # 02110-1301 USA
26
+ ######################### END LICENSE BLOCK #########################
27
+
28
+ from typing import Union
29
+
30
+ from .charsetprober import CharSetProber
31
+ from .codingstatemachine import CodingStateMachine
32
+ from .enums import MachineState, ProbingState
33
+ from .mbcssm import UTF8_SM_MODEL
34
+
35
+
36
+ class UTF8Prober(CharSetProber):
37
+ ONE_CHAR_PROB = 0.5
38
+
39
+ def __init__(self) -> None:
40
+ super().__init__()
41
+ self.coding_sm = CodingStateMachine(UTF8_SM_MODEL)
42
+ self._num_mb_chars = 0
43
+ self.reset()
44
+
45
+ def reset(self) -> None:
46
+ super().reset()
47
+ self.coding_sm.reset()
48
+ self._num_mb_chars = 0
49
+
50
+ @property
51
+ def charset_name(self) -> str:
52
+ return "utf-8"
53
+
54
+ @property
55
+ def language(self) -> str:
56
+ return ""
57
+
58
+ def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
59
+ for c in byte_str:
60
+ coding_state = self.coding_sm.next_state(c)
61
+ if coding_state == MachineState.ERROR:
62
+ self._state = ProbingState.NOT_ME
63
+ break
64
+ if coding_state == MachineState.ITS_ME:
65
+ self._state = ProbingState.FOUND_IT
66
+ break
67
+ if coding_state == MachineState.START:
68
+ if self.coding_sm.get_current_charlen() >= 2:
69
+ self._num_mb_chars += 1
70
+
71
+ if self.state == ProbingState.DETECTING:
72
+ if self.get_confidence() > self.SHORTCUT_THRESHOLD:
73
+ self._state = ProbingState.FOUND_IT
74
+
75
+ return self.state
76
+
77
+ def get_confidence(self) -> float:
78
+ unlike = 0.99
79
+ if self._num_mb_chars < 6:
80
+ unlike *= self.ONE_CHAR_PROB**self._num_mb_chars
81
+ return 1.0 - unlike
82
+ return unlike
.venv/Lib/site-packages/pip/_vendor/chardet/version.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module exists only to simplify retrieving the version number of chardet
3
+ from within setuptools and from chardet subpackages.
4
+
5
+ :author: Dan Blanchard (dan.blanchard@gmail.com)
6
+ """
7
+
8
+ __version__ = "5.1.0"
9
+ VERSION = __version__.split(".")
.venv/Lib/site-packages/pip/_vendor/colorama/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ from .initialise import init, deinit, reinit, colorama_text, just_fix_windows_console
3
+ from .ansi import Fore, Back, Style, Cursor
4
+ from .ansitowin32 import AnsiToWin32
5
+
6
+ __version__ = '0.4.6'
7
+
.venv/Lib/site-packages/pip/_vendor/colorama/ansi.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ '''
3
+ This module generates ANSI character codes to printing colors to terminals.
4
+ See: http://en.wikipedia.org/wiki/ANSI_escape_code
5
+ '''
6
+
7
+ CSI = '\033['
8
+ OSC = '\033]'
9
+ BEL = '\a'
10
+
11
+
12
+ def code_to_chars(code):
13
+ return CSI + str(code) + 'm'
14
+
15
+ def set_title(title):
16
+ return OSC + '2;' + title + BEL
17
+
18
+ def clear_screen(mode=2):
19
+ return CSI + str(mode) + 'J'
20
+
21
+ def clear_line(mode=2):
22
+ return CSI + str(mode) + 'K'
23
+
24
+
25
+ class AnsiCodes(object):
26
+ def __init__(self):
27
+ # the subclasses declare class attributes which are numbers.
28
+ # Upon instantiation we define instance attributes, which are the same
29
+ # as the class attributes but wrapped with the ANSI escape sequence
30
+ for name in dir(self):
31
+ if not name.startswith('_'):
32
+ value = getattr(self, name)
33
+ setattr(self, name, code_to_chars(value))
34
+
35
+
36
+ class AnsiCursor(object):
37
+ def UP(self, n=1):
38
+ return CSI + str(n) + 'A'
39
+ def DOWN(self, n=1):
40
+ return CSI + str(n) + 'B'
41
+ def FORWARD(self, n=1):
42
+ return CSI + str(n) + 'C'
43
+ def BACK(self, n=1):
44
+ return CSI + str(n) + 'D'
45
+ def POS(self, x=1, y=1):
46
+ return CSI + str(y) + ';' + str(x) + 'H'
47
+
48
+
49
+ class AnsiFore(AnsiCodes):
50
+ BLACK = 30
51
+ RED = 31
52
+ GREEN = 32
53
+ YELLOW = 33
54
+ BLUE = 34
55
+ MAGENTA = 35
56
+ CYAN = 36
57
+ WHITE = 37
58
+ RESET = 39
59
+
60
+ # These are fairly well supported, but not part of the standard.
61
+ LIGHTBLACK_EX = 90
62
+ LIGHTRED_EX = 91
63
+ LIGHTGREEN_EX = 92
64
+ LIGHTYELLOW_EX = 93
65
+ LIGHTBLUE_EX = 94
66
+ LIGHTMAGENTA_EX = 95
67
+ LIGHTCYAN_EX = 96
68
+ LIGHTWHITE_EX = 97
69
+
70
+
71
+ class AnsiBack(AnsiCodes):
72
+ BLACK = 40
73
+ RED = 41
74
+ GREEN = 42
75
+ YELLOW = 43
76
+ BLUE = 44
77
+ MAGENTA = 45
78
+ CYAN = 46
79
+ WHITE = 47
80
+ RESET = 49
81
+
82
+ # These are fairly well supported, but not part of the standard.
83
+ LIGHTBLACK_EX = 100
84
+ LIGHTRED_EX = 101
85
+ LIGHTGREEN_EX = 102
86
+ LIGHTYELLOW_EX = 103
87
+ LIGHTBLUE_EX = 104
88
+ LIGHTMAGENTA_EX = 105
89
+ LIGHTCYAN_EX = 106
90
+ LIGHTWHITE_EX = 107
91
+
92
+
93
+ class AnsiStyle(AnsiCodes):
94
+ BRIGHT = 1
95
+ DIM = 2
96
+ NORMAL = 22
97
+ RESET_ALL = 0
98
+
99
+ Fore = AnsiFore()
100
+ Back = AnsiBack()
101
+ Style = AnsiStyle()
102
+ Cursor = AnsiCursor()
.venv/Lib/site-packages/pip/_vendor/colorama/ansitowin32.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ import re
3
+ import sys
4
+ import os
5
+
6
+ from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL
7
+ from .winterm import enable_vt_processing, WinTerm, WinColor, WinStyle
8
+ from .win32 import windll, winapi_test
9
+
10
+
11
+ winterm = None
12
+ if windll is not None:
13
+ winterm = WinTerm()
14
+
15
+
16
+ class StreamWrapper(object):
17
+ '''
18
+ Wraps a stream (such as stdout), acting as a transparent proxy for all
19
+ attribute access apart from method 'write()', which is delegated to our
20
+ Converter instance.
21
+ '''
22
+ def __init__(self, wrapped, converter):
23
+ # double-underscore everything to prevent clashes with names of
24
+ # attributes on the wrapped stream object.
25
+ self.__wrapped = wrapped
26
+ self.__convertor = converter
27
+
28
+ def __getattr__(self, name):
29
+ return getattr(self.__wrapped, name)
30
+
31
+ def __enter__(self, *args, **kwargs):
32
+ # special method lookup bypasses __getattr__/__getattribute__, see
33
+ # https://stackoverflow.com/questions/12632894/why-doesnt-getattr-work-with-exit
34
+ # thus, contextlib magic methods are not proxied via __getattr__
35
+ return self.__wrapped.__enter__(*args, **kwargs)
36
+
37
+ def __exit__(self, *args, **kwargs):
38
+ return self.__wrapped.__exit__(*args, **kwargs)
39
+
40
+ def __setstate__(self, state):
41
+ self.__dict__ = state
42
+
43
+ def __getstate__(self):
44
+ return self.__dict__
45
+
46
+ def write(self, text):
47
+ self.__convertor.write(text)
48
+
49
+ def isatty(self):
50
+ stream = self.__wrapped
51
+ if 'PYCHARM_HOSTED' in os.environ:
52
+ if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__):
53
+ return True
54
+ try:
55
+ stream_isatty = stream.isatty
56
+ except AttributeError:
57
+ return False
58
+ else:
59
+ return stream_isatty()
60
+
61
+ @property
62
+ def closed(self):
63
+ stream = self.__wrapped
64
+ try:
65
+ return stream.closed
66
+ # AttributeError in the case that the stream doesn't support being closed
67
+ # ValueError for the case that the stream has already been detached when atexit runs
68
+ except (AttributeError, ValueError):
69
+ return True
70
+
71
+
72
+ class AnsiToWin32(object):
73
+ '''
74
+ Implements a 'write()' method which, on Windows, will strip ANSI character
75
+ sequences from the text, and if outputting to a tty, will convert them into
76
+ win32 function calls.
77
+ '''
78
+ ANSI_CSI_RE = re.compile('\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer
79
+ ANSI_OSC_RE = re.compile('\001?\033\\]([^\a]*)(\a)\002?') # Operating System Command
80
+
81
+ def __init__(self, wrapped, convert=None, strip=None, autoreset=False):
82
+ # The wrapped stream (normally sys.stdout or sys.stderr)
83
+ self.wrapped = wrapped
84
+
85
+ # should we reset colors to defaults after every .write()
86
+ self.autoreset = autoreset
87
+
88
+ # create the proxy wrapping our output stream
89
+ self.stream = StreamWrapper(wrapped, self)
90
+
91
+ on_windows = os.name == 'nt'
92
+ # We test if the WinAPI works, because even if we are on Windows
93
+ # we may be using a terminal that doesn't support the WinAPI
94
+ # (e.g. Cygwin Terminal). In this case it's up to the terminal
95
+ # to support the ANSI codes.
96
+ conversion_supported = on_windows and winapi_test()
97
+ try:
98
+ fd = wrapped.fileno()
99
+ except Exception:
100
+ fd = -1
101
+ system_has_native_ansi = not on_windows or enable_vt_processing(fd)
102
+ have_tty = not self.stream.closed and self.stream.isatty()
103
+ need_conversion = conversion_supported and not system_has_native_ansi
104
+
105
+ # should we strip ANSI sequences from our output?
106
+ if strip is None:
107
+ strip = need_conversion or not have_tty
108
+ self.strip = strip
109
+
110
+ # should we should convert ANSI sequences into win32 calls?
111
+ if convert is None:
112
+ convert = need_conversion and have_tty
113
+ self.convert = convert
114
+
115
+ # dict of ansi codes to win32 functions and parameters
116
+ self.win32_calls = self.get_win32_calls()
117
+
118
+ # are we wrapping stderr?
119
+ self.on_stderr = self.wrapped is sys.stderr
120
+
121
+ def should_wrap(self):
122
+ '''
123
+ True if this class is actually needed. If false, then the output
124
+ stream will not be affected, nor will win32 calls be issued, so
125
+ wrapping stdout is not actually required. This will generally be
126
+ False on non-Windows platforms, unless optional functionality like
127
+ autoreset has been requested using kwargs to init()
128
+ '''
129
+ return self.convert or self.strip or self.autoreset
130
+
131
+ def get_win32_calls(self):
132
+ if self.convert and winterm:
133
+ return {
134
+ AnsiStyle.RESET_ALL: (winterm.reset_all, ),
135
+ AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT),
136
+ AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL),
137
+ AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL),
138
+ AnsiFore.BLACK: (winterm.fore, WinColor.BLACK),
139
+ AnsiFore.RED: (winterm.fore, WinColor.RED),
140
+ AnsiFore.GREEN: (winterm.fore, WinColor.GREEN),
141
+ AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW),
142
+ AnsiFore.BLUE: (winterm.fore, WinColor.BLUE),
143
+ AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA),
144
+ AnsiFore.CYAN: (winterm.fore, WinColor.CYAN),
145
+ AnsiFore.WHITE: (winterm.fore, WinColor.GREY),
146
+ AnsiFore.RESET: (winterm.fore, ),
147
+ AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True),
148
+ AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True),
149
+ AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True),
150
+ AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True),
151
+ AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True),
152
+ AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True),
153
+ AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True),
154
+ AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True),
155
+ AnsiBack.BLACK: (winterm.back, WinColor.BLACK),
156
+ AnsiBack.RED: (winterm.back, WinColor.RED),
157
+ AnsiBack.GREEN: (winterm.back, WinColor.GREEN),
158
+ AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW),
159
+ AnsiBack.BLUE: (winterm.back, WinColor.BLUE),
160
+ AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA),
161
+ AnsiBack.CYAN: (winterm.back, WinColor.CYAN),
162
+ AnsiBack.WHITE: (winterm.back, WinColor.GREY),
163
+ AnsiBack.RESET: (winterm.back, ),
164
+ AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True),
165
+ AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True),
166
+ AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True),
167
+ AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True),
168
+ AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True),
169
+ AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True),
170
+ AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True),
171
+ AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True),
172
+ }
173
+ return dict()
174
+
175
+ def write(self, text):
176
+ if self.strip or self.convert:
177
+ self.write_and_convert(text)
178
+ else:
179
+ self.wrapped.write(text)
180
+ self.wrapped.flush()
181
+ if self.autoreset:
182
+ self.reset_all()
183
+
184
+
185
+ def reset_all(self):
186
+ if self.convert:
187
+ self.call_win32('m', (0,))
188
+ elif not self.strip and not self.stream.closed:
189
+ self.wrapped.write(Style.RESET_ALL)
190
+
191
+
192
+ def write_and_convert(self, text):
193
+ '''
194
+ Write the given text to our wrapped stream, stripping any ANSI
195
+ sequences from the text, and optionally converting them into win32
196
+ calls.
197
+ '''
198
+ cursor = 0
199
+ text = self.convert_osc(text)
200
+ for match in self.ANSI_CSI_RE.finditer(text):
201
+ start, end = match.span()
202
+ self.write_plain_text(text, cursor, start)
203
+ self.convert_ansi(*match.groups())
204
+ cursor = end
205
+ self.write_plain_text(text, cursor, len(text))
206
+
207
+
208
+ def write_plain_text(self, text, start, end):
209
+ if start < end:
210
+ self.wrapped.write(text[start:end])
211
+ self.wrapped.flush()
212
+
213
+
214
+ def convert_ansi(self, paramstring, command):
215
+ if self.convert:
216
+ params = self.extract_params(command, paramstring)
217
+ self.call_win32(command, params)
218
+
219
+
220
+ def extract_params(self, command, paramstring):
221
+ if command in 'Hf':
222
+ params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(';'))
223
+ while len(params) < 2:
224
+ # defaults:
225
+ params = params + (1,)
226
+ else:
227
+ params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0)
228
+ if len(params) == 0:
229
+ # defaults:
230
+ if command in 'JKm':
231
+ params = (0,)
232
+ elif command in 'ABCD':
233
+ params = (1,)
234
+
235
+ return params
236
+
237
+
238
+ def call_win32(self, command, params):
239
+ if command == 'm':
240
+ for param in params:
241
+ if param in self.win32_calls:
242
+ func_args = self.win32_calls[param]
243
+ func = func_args[0]
244
+ args = func_args[1:]
245
+ kwargs = dict(on_stderr=self.on_stderr)
246
+ func(*args, **kwargs)
247
+ elif command in 'J':
248
+ winterm.erase_screen(params[0], on_stderr=self.on_stderr)
249
+ elif command in 'K':
250
+ winterm.erase_line(params[0], on_stderr=self.on_stderr)
251
+ elif command in 'Hf': # cursor position - absolute
252
+ winterm.set_cursor_position(params, on_stderr=self.on_stderr)
253
+ elif command in 'ABCD': # cursor position - relative
254
+ n = params[0]
255
+ # A - up, B - down, C - forward, D - back
256
+ x, y = {'A': (0, -n), 'B': (0, n), 'C': (n, 0), 'D': (-n, 0)}[command]
257
+ winterm.cursor_adjust(x, y, on_stderr=self.on_stderr)
258
+
259
+
260
+ def convert_osc(self, text):
261
+ for match in self.ANSI_OSC_RE.finditer(text):
262
+ start, end = match.span()
263
+ text = text[:start] + text[end:]
264
+ paramstring, command = match.groups()
265
+ if command == BEL:
266
+ if paramstring.count(";") == 1:
267
+ params = paramstring.split(";")
268
+ # 0 - change title and icon (we will only change title)
269
+ # 1 - change icon (we don't support this)
270
+ # 2 - change title
271
+ if params[0] in '02':
272
+ winterm.set_title(params[1])
273
+ return text
274
+
275
+
276
+ def flush(self):
277
+ self.wrapped.flush()
.venv/Lib/site-packages/pip/_vendor/colorama/initialise.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ import atexit
3
+ import contextlib
4
+ import sys
5
+
6
+ from .ansitowin32 import AnsiToWin32
7
+
8
+
9
+ def _wipe_internal_state_for_tests():
10
+ global orig_stdout, orig_stderr
11
+ orig_stdout = None
12
+ orig_stderr = None
13
+
14
+ global wrapped_stdout, wrapped_stderr
15
+ wrapped_stdout = None
16
+ wrapped_stderr = None
17
+
18
+ global atexit_done
19
+ atexit_done = False
20
+
21
+ global fixed_windows_console
22
+ fixed_windows_console = False
23
+
24
+ try:
25
+ # no-op if it wasn't registered
26
+ atexit.unregister(reset_all)
27
+ except AttributeError:
28
+ # python 2: no atexit.unregister. Oh well, we did our best.
29
+ pass
30
+
31
+
32
+ def reset_all():
33
+ if AnsiToWin32 is not None: # Issue #74: objects might become None at exit
34
+ AnsiToWin32(orig_stdout).reset_all()
35
+
36
+
37
+ def init(autoreset=False, convert=None, strip=None, wrap=True):
38
+
39
+ if not wrap and any([autoreset, convert, strip]):
40
+ raise ValueError('wrap=False conflicts with any other arg=True')
41
+
42
+ global wrapped_stdout, wrapped_stderr
43
+ global orig_stdout, orig_stderr
44
+
45
+ orig_stdout = sys.stdout
46
+ orig_stderr = sys.stderr
47
+
48
+ if sys.stdout is None:
49
+ wrapped_stdout = None
50
+ else:
51
+ sys.stdout = wrapped_stdout = \
52
+ wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
53
+ if sys.stderr is None:
54
+ wrapped_stderr = None
55
+ else:
56
+ sys.stderr = wrapped_stderr = \
57
+ wrap_stream(orig_stderr, convert, strip, autoreset, wrap)
58
+
59
+ global atexit_done
60
+ if not atexit_done:
61
+ atexit.register(reset_all)
62
+ atexit_done = True
63
+
64
+
65
+ def deinit():
66
+ if orig_stdout is not None:
67
+ sys.stdout = orig_stdout
68
+ if orig_stderr is not None:
69
+ sys.stderr = orig_stderr
70
+
71
+
72
+ def just_fix_windows_console():
73
+ global fixed_windows_console
74
+
75
+ if sys.platform != "win32":
76
+ return
77
+ if fixed_windows_console:
78
+ return
79
+ if wrapped_stdout is not None or wrapped_stderr is not None:
80
+ # Someone already ran init() and it did stuff, so we won't second-guess them
81
+ return
82
+
83
+ # On newer versions of Windows, AnsiToWin32.__init__ will implicitly enable the
84
+ # native ANSI support in the console as a side-effect. We only need to actually
85
+ # replace sys.stdout/stderr if we're in the old-style conversion mode.
86
+ new_stdout = AnsiToWin32(sys.stdout, convert=None, strip=None, autoreset=False)
87
+ if new_stdout.convert:
88
+ sys.stdout = new_stdout
89
+ new_stderr = AnsiToWin32(sys.stderr, convert=None, strip=None, autoreset=False)
90
+ if new_stderr.convert:
91
+ sys.stderr = new_stderr
92
+
93
+ fixed_windows_console = True
94
+
95
+ @contextlib.contextmanager
96
+ def colorama_text(*args, **kwargs):
97
+ init(*args, **kwargs)
98
+ try:
99
+ yield
100
+ finally:
101
+ deinit()
102
+
103
+
104
+ def reinit():
105
+ if wrapped_stdout is not None:
106
+ sys.stdout = wrapped_stdout
107
+ if wrapped_stderr is not None:
108
+ sys.stderr = wrapped_stderr
109
+
110
+
111
+ def wrap_stream(stream, convert, strip, autoreset, wrap):
112
+ if wrap:
113
+ wrapper = AnsiToWin32(stream,
114
+ convert=convert, strip=strip, autoreset=autoreset)
115
+ if wrapper.should_wrap():
116
+ stream = wrapper.stream
117
+ return stream
118
+
119
+
120
+ # Use this for initial setup as well, to reduce code duplication
121
+ _wipe_internal_state_for_tests()
.venv/Lib/site-packages/pip/_vendor/colorama/tests/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
.venv/Lib/site-packages/pip/_vendor/colorama/tests/ansi_test.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ import sys
3
+ from unittest import TestCase, main
4
+
5
+ from ..ansi import Back, Fore, Style
6
+ from ..ansitowin32 import AnsiToWin32
7
+
8
+ stdout_orig = sys.stdout
9
+ stderr_orig = sys.stderr
10
+
11
+
12
+ class AnsiTest(TestCase):
13
+
14
+ def setUp(self):
15
+ # sanity check: stdout should be a file or StringIO object.
16
+ # It will only be AnsiToWin32 if init() has previously wrapped it
17
+ self.assertNotEqual(type(sys.stdout), AnsiToWin32)
18
+ self.assertNotEqual(type(sys.stderr), AnsiToWin32)
19
+
20
+ def tearDown(self):
21
+ sys.stdout = stdout_orig
22
+ sys.stderr = stderr_orig
23
+
24
+
25
+ def testForeAttributes(self):
26
+ self.assertEqual(Fore.BLACK, '\033[30m')
27
+ self.assertEqual(Fore.RED, '\033[31m')
28
+ self.assertEqual(Fore.GREEN, '\033[32m')
29
+ self.assertEqual(Fore.YELLOW, '\033[33m')
30
+ self.assertEqual(Fore.BLUE, '\033[34m')
31
+ self.assertEqual(Fore.MAGENTA, '\033[35m')
32
+ self.assertEqual(Fore.CYAN, '\033[36m')
33
+ self.assertEqual(Fore.WHITE, '\033[37m')
34
+ self.assertEqual(Fore.RESET, '\033[39m')
35
+
36
+ # Check the light, extended versions.
37
+ self.assertEqual(Fore.LIGHTBLACK_EX, '\033[90m')
38
+ self.assertEqual(Fore.LIGHTRED_EX, '\033[91m')
39
+ self.assertEqual(Fore.LIGHTGREEN_EX, '\033[92m')
40
+ self.assertEqual(Fore.LIGHTYELLOW_EX, '\033[93m')
41
+ self.assertEqual(Fore.LIGHTBLUE_EX, '\033[94m')
42
+ self.assertEqual(Fore.LIGHTMAGENTA_EX, '\033[95m')
43
+ self.assertEqual(Fore.LIGHTCYAN_EX, '\033[96m')
44
+ self.assertEqual(Fore.LIGHTWHITE_EX, '\033[97m')
45
+
46
+
47
+ def testBackAttributes(self):
48
+ self.assertEqual(Back.BLACK, '\033[40m')
49
+ self.assertEqual(Back.RED, '\033[41m')
50
+ self.assertEqual(Back.GREEN, '\033[42m')
51
+ self.assertEqual(Back.YELLOW, '\033[43m')
52
+ self.assertEqual(Back.BLUE, '\033[44m')
53
+ self.assertEqual(Back.MAGENTA, '\033[45m')
54
+ self.assertEqual(Back.CYAN, '\033[46m')
55
+ self.assertEqual(Back.WHITE, '\033[47m')
56
+ self.assertEqual(Back.RESET, '\033[49m')
57
+
58
+ # Check the light, extended versions.
59
+ self.assertEqual(Back.LIGHTBLACK_EX, '\033[100m')
60
+ self.assertEqual(Back.LIGHTRED_EX, '\033[101m')
61
+ self.assertEqual(Back.LIGHTGREEN_EX, '\033[102m')
62
+ self.assertEqual(Back.LIGHTYELLOW_EX, '\033[103m')
63
+ self.assertEqual(Back.LIGHTBLUE_EX, '\033[104m')
64
+ self.assertEqual(Back.LIGHTMAGENTA_EX, '\033[105m')
65
+ self.assertEqual(Back.LIGHTCYAN_EX, '\033[106m')
66
+ self.assertEqual(Back.LIGHTWHITE_EX, '\033[107m')
67
+
68
+
69
+ def testStyleAttributes(self):
70
+ self.assertEqual(Style.DIM, '\033[2m')
71
+ self.assertEqual(Style.NORMAL, '\033[22m')
72
+ self.assertEqual(Style.BRIGHT, '\033[1m')
73
+
74
+
75
+ if __name__ == '__main__':
76
+ main()
.venv/Lib/site-packages/pip/_vendor/colorama/tests/ansitowin32_test.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ from io import StringIO, TextIOWrapper
3
+ from unittest import TestCase, main
4
+ try:
5
+ from contextlib import ExitStack
6
+ except ImportError:
7
+ # python 2
8
+ from contextlib2 import ExitStack
9
+
10
+ try:
11
+ from unittest.mock import MagicMock, Mock, patch
12
+ except ImportError:
13
+ from mock import MagicMock, Mock, patch
14
+
15
+ from ..ansitowin32 import AnsiToWin32, StreamWrapper
16
+ from ..win32 import ENABLE_VIRTUAL_TERMINAL_PROCESSING
17
+ from .utils import osname
18
+
19
+
20
+ class StreamWrapperTest(TestCase):
21
+
22
+ def testIsAProxy(self):
23
+ mockStream = Mock()
24
+ wrapper = StreamWrapper(mockStream, None)
25
+ self.assertTrue( wrapper.random_attr is mockStream.random_attr )
26
+
27
+ def testDelegatesWrite(self):
28
+ mockStream = Mock()
29
+ mockConverter = Mock()
30
+ wrapper = StreamWrapper(mockStream, mockConverter)
31
+ wrapper.write('hello')
32
+ self.assertTrue(mockConverter.write.call_args, (('hello',), {}))
33
+
34
+ def testDelegatesContext(self):
35
+ mockConverter = Mock()
36
+ s = StringIO()
37
+ with StreamWrapper(s, mockConverter) as fp:
38
+ fp.write(u'hello')
39
+ self.assertTrue(s.closed)
40
+
41
+ def testProxyNoContextManager(self):
42
+ mockStream = MagicMock()
43
+ mockStream.__enter__.side_effect = AttributeError()
44
+ mockConverter = Mock()
45
+ with self.assertRaises(AttributeError) as excinfo:
46
+ with StreamWrapper(mockStream, mockConverter) as wrapper:
47
+ wrapper.write('hello')
48
+
49
+ def test_closed_shouldnt_raise_on_closed_stream(self):
50
+ stream = StringIO()
51
+ stream.close()
52
+ wrapper = StreamWrapper(stream, None)
53
+ self.assertEqual(wrapper.closed, True)
54
+
55
+ def test_closed_shouldnt_raise_on_detached_stream(self):
56
+ stream = TextIOWrapper(StringIO())
57
+ stream.detach()
58
+ wrapper = StreamWrapper(stream, None)
59
+ self.assertEqual(wrapper.closed, True)
60
+
61
+ class AnsiToWin32Test(TestCase):
62
+
63
+ def testInit(self):
64
+ mockStdout = Mock()
65
+ auto = Mock()
66
+ stream = AnsiToWin32(mockStdout, autoreset=auto)
67
+ self.assertEqual(stream.wrapped, mockStdout)
68
+ self.assertEqual(stream.autoreset, auto)
69
+
70
+ @patch('colorama.ansitowin32.winterm', None)
71
+ @patch('colorama.ansitowin32.winapi_test', lambda *_: True)
72
+ def testStripIsTrueOnWindows(self):
73
+ with osname('nt'):
74
+ mockStdout = Mock()
75
+ stream = AnsiToWin32(mockStdout)
76
+ self.assertTrue(stream.strip)
77
+
78
+ def testStripIsFalseOffWindows(self):
79
+ with osname('posix'):
80
+ mockStdout = Mock(closed=False)
81
+ stream = AnsiToWin32(mockStdout)
82
+ self.assertFalse(stream.strip)
83
+
84
+ def testWriteStripsAnsi(self):
85
+ mockStdout = Mock()
86
+ stream = AnsiToWin32(mockStdout)
87
+ stream.wrapped = Mock()
88
+ stream.write_and_convert = Mock()
89
+ stream.strip = True
90
+
91
+ stream.write('abc')
92
+
93
+ self.assertFalse(stream.wrapped.write.called)
94
+ self.assertEqual(stream.write_and_convert.call_args, (('abc',), {}))
95
+
96
+ def testWriteDoesNotStripAnsi(self):
97
+ mockStdout = Mock()
98
+ stream = AnsiToWin32(mockStdout)
99
+ stream.wrapped = Mock()
100
+ stream.write_and_convert = Mock()
101
+ stream.strip = False
102
+ stream.convert = False
103
+
104
+ stream.write('abc')
105
+
106
+ self.assertFalse(stream.write_and_convert.called)
107
+ self.assertEqual(stream.wrapped.write.call_args, (('abc',), {}))
108
+
109
+ def assert_autoresets(self, convert, autoreset=True):
110
+ stream = AnsiToWin32(Mock())
111
+ stream.convert = convert
112
+ stream.reset_all = Mock()
113
+ stream.autoreset = autoreset
114
+ stream.winterm = Mock()
115
+
116
+ stream.write('abc')
117
+
118
+ self.assertEqual(stream.reset_all.called, autoreset)
119
+
120
+ def testWriteAutoresets(self):
121
+ self.assert_autoresets(convert=True)
122
+ self.assert_autoresets(convert=False)
123
+ self.assert_autoresets(convert=True, autoreset=False)
124
+ self.assert_autoresets(convert=False, autoreset=False)
125
+
126
+ def testWriteAndConvertWritesPlainText(self):
127
+ stream = AnsiToWin32(Mock())
128
+ stream.write_and_convert( 'abc' )
129
+ self.assertEqual( stream.wrapped.write.call_args, (('abc',), {}) )
130
+
131
+ def testWriteAndConvertStripsAllValidAnsi(self):
132
+ stream = AnsiToWin32(Mock())
133
+ stream.call_win32 = Mock()
134
+ data = [
135
+ 'abc\033[mdef',
136
+ 'abc\033[0mdef',
137
+ 'abc\033[2mdef',
138
+ 'abc\033[02mdef',
139
+ 'abc\033[002mdef',
140
+ 'abc\033[40mdef',
141
+ 'abc\033[040mdef',
142
+ 'abc\033[0;1mdef',
143
+ 'abc\033[40;50mdef',
144
+ 'abc\033[50;30;40mdef',
145
+ 'abc\033[Adef',
146
+ 'abc\033[0Gdef',
147
+ 'abc\033[1;20;128Hdef',
148
+ ]
149
+ for datum in data:
150
+ stream.wrapped.write.reset_mock()
151
+ stream.write_and_convert( datum )
152
+ self.assertEqual(
153
+ [args[0] for args in stream.wrapped.write.call_args_list],
154
+ [ ('abc',), ('def',) ]
155
+ )
156
+
157
+ def testWriteAndConvertSkipsEmptySnippets(self):
158
+ stream = AnsiToWin32(Mock())
159
+ stream.call_win32 = Mock()
160
+ stream.write_and_convert( '\033[40m\033[41m' )
161
+ self.assertFalse( stream.wrapped.write.called )
162
+
163
+ def testWriteAndConvertCallsWin32WithParamsAndCommand(self):
164
+ stream = AnsiToWin32(Mock())
165
+ stream.convert = True
166
+ stream.call_win32 = Mock()
167
+ stream.extract_params = Mock(return_value='params')
168
+ data = {
169
+ 'abc\033[adef': ('a', 'params'),
170
+ 'abc\033[;;bdef': ('b', 'params'),
171
+ 'abc\033[0cdef': ('c', 'params'),
172
+ 'abc\033[;;0;;Gdef': ('G', 'params'),
173
+ 'abc\033[1;20;128Hdef': ('H', 'params'),
174
+ }
175
+ for datum, expected in data.items():
176
+ stream.call_win32.reset_mock()
177
+ stream.write_and_convert( datum )
178
+ self.assertEqual( stream.call_win32.call_args[0], expected )
179
+
180
+ def test_reset_all_shouldnt_raise_on_closed_orig_stdout(self):
181
+ stream = StringIO()
182
+ converter = AnsiToWin32(stream)
183
+ stream.close()
184
+
185
+ converter.reset_all()
186
+
187
+ def test_wrap_shouldnt_raise_on_closed_orig_stdout(self):
188
+ stream = StringIO()
189
+ stream.close()
190
+ with \
191
+ patch("colorama.ansitowin32.os.name", "nt"), \
192
+ patch("colorama.ansitowin32.winapi_test", lambda: True):
193
+ converter = AnsiToWin32(stream)
194
+ self.assertTrue(converter.strip)
195
+ self.assertFalse(converter.convert)
196
+
197
+ def test_wrap_shouldnt_raise_on_missing_closed_attr(self):
198
+ with \
199
+ patch("colorama.ansitowin32.os.name", "nt"), \
200
+ patch("colorama.ansitowin32.winapi_test", lambda: True):
201
+ converter = AnsiToWin32(object())
202
+ self.assertTrue(converter.strip)
203
+ self.assertFalse(converter.convert)
204
+
205
+ def testExtractParams(self):
206
+ stream = AnsiToWin32(Mock())
207
+ data = {
208
+ '': (0,),
209
+ ';;': (0,),
210
+ '2': (2,),
211
+ ';;002;;': (2,),
212
+ '0;1': (0, 1),
213
+ ';;003;;456;;': (3, 456),
214
+ '11;22;33;44;55': (11, 22, 33, 44, 55),
215
+ }
216
+ for datum, expected in data.items():
217
+ self.assertEqual(stream.extract_params('m', datum), expected)
218
+
219
+ def testCallWin32UsesLookup(self):
220
+ listener = Mock()
221
+ stream = AnsiToWin32(listener)
222
+ stream.win32_calls = {
223
+ 1: (lambda *_, **__: listener(11),),
224
+ 2: (lambda *_, **__: listener(22),),
225
+ 3: (lambda *_, **__: listener(33),),
226
+ }
227
+ stream.call_win32('m', (3, 1, 99, 2))
228
+ self.assertEqual(
229
+ [a[0][0] for a in listener.call_args_list],
230
+ [33, 11, 22] )
231
+
232
+ def test_osc_codes(self):
233
+ mockStdout = Mock()
234
+ stream = AnsiToWin32(mockStdout, convert=True)
235
+ with patch('colorama.ansitowin32.winterm') as winterm:
236
+ data = [
237
+ '\033]0\x07', # missing arguments
238
+ '\033]0;foo\x08', # wrong OSC command
239
+ '\033]0;colorama_test_title\x07', # should work
240
+ '\033]1;colorama_test_title\x07', # wrong set command
241
+ '\033]2;colorama_test_title\x07', # should work
242
+ '\033]' + ';' * 64 + '\x08', # see issue #247
243
+ ]
244
+ for code in data:
245
+ stream.write(code)
246
+ self.assertEqual(winterm.set_title.call_count, 2)
247
+
248
+ def test_native_windows_ansi(self):
249
+ with ExitStack() as stack:
250
+ def p(a, b):
251
+ stack.enter_context(patch(a, b, create=True))
252
+ # Pretend to be on Windows
253
+ p("colorama.ansitowin32.os.name", "nt")
254
+ p("colorama.ansitowin32.winapi_test", lambda: True)
255
+ p("colorama.win32.winapi_test", lambda: True)
256
+ p("colorama.winterm.win32.windll", "non-None")
257
+ p("colorama.winterm.get_osfhandle", lambda _: 1234)
258
+
259
+ # Pretend that our mock stream has native ANSI support
260
+ p(
261
+ "colorama.winterm.win32.GetConsoleMode",
262
+ lambda _: ENABLE_VIRTUAL_TERMINAL_PROCESSING,
263
+ )
264
+ SetConsoleMode = Mock()
265
+ p("colorama.winterm.win32.SetConsoleMode", SetConsoleMode)
266
+
267
+ stdout = Mock()
268
+ stdout.closed = False
269
+ stdout.isatty.return_value = True
270
+ stdout.fileno.return_value = 1
271
+
272
+ # Our fake console says it has native vt support, so AnsiToWin32 should
273
+ # enable that support and do nothing else.
274
+ stream = AnsiToWin32(stdout)
275
+ SetConsoleMode.assert_called_with(1234, ENABLE_VIRTUAL_TERMINAL_PROCESSING)
276
+ self.assertFalse(stream.strip)
277
+ self.assertFalse(stream.convert)
278
+ self.assertFalse(stream.should_wrap())
279
+
280
+ # Now let's pretend we're on an old Windows console, that doesn't have
281
+ # native ANSI support.
282
+ p("colorama.winterm.win32.GetConsoleMode", lambda _: 0)
283
+ SetConsoleMode = Mock()
284
+ p("colorama.winterm.win32.SetConsoleMode", SetConsoleMode)
285
+
286
+ stream = AnsiToWin32(stdout)
287
+ SetConsoleMode.assert_called_with(1234, ENABLE_VIRTUAL_TERMINAL_PROCESSING)
288
+ self.assertTrue(stream.strip)
289
+ self.assertTrue(stream.convert)
290
+ self.assertTrue(stream.should_wrap())
291
+
292
+
293
+ if __name__ == '__main__':
294
+ main()
.venv/Lib/site-packages/pip/_vendor/colorama/tests/initialise_test.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ import sys
3
+ from unittest import TestCase, main, skipUnless
4
+
5
+ try:
6
+ from unittest.mock import patch, Mock
7
+ except ImportError:
8
+ from mock import patch, Mock
9
+
10
+ from ..ansitowin32 import StreamWrapper
11
+ from ..initialise import init, just_fix_windows_console, _wipe_internal_state_for_tests
12
+ from .utils import osname, replace_by
13
+
14
+ orig_stdout = sys.stdout
15
+ orig_stderr = sys.stderr
16
+
17
+
18
+ class InitTest(TestCase):
19
+
20
+ @skipUnless(sys.stdout.isatty(), "sys.stdout is not a tty")
21
+ def setUp(self):
22
+ # sanity check
23
+ self.assertNotWrapped()
24
+
25
+ def tearDown(self):
26
+ _wipe_internal_state_for_tests()
27
+ sys.stdout = orig_stdout
28
+ sys.stderr = orig_stderr
29
+
30
+ def assertWrapped(self):
31
+ self.assertIsNot(sys.stdout, orig_stdout, 'stdout should be wrapped')
32
+ self.assertIsNot(sys.stderr, orig_stderr, 'stderr should be wrapped')
33
+ self.assertTrue(isinstance(sys.stdout, StreamWrapper),
34
+ 'bad stdout wrapper')
35
+ self.assertTrue(isinstance(sys.stderr, StreamWrapper),
36
+ 'bad stderr wrapper')
37
+
38
+ def assertNotWrapped(self):
39
+ self.assertIs(sys.stdout, orig_stdout, 'stdout should not be wrapped')
40
+ self.assertIs(sys.stderr, orig_stderr, 'stderr should not be wrapped')
41
+
42
+ @patch('colorama.initialise.reset_all')
43
+ @patch('colorama.ansitowin32.winapi_test', lambda *_: True)
44
+ @patch('colorama.ansitowin32.enable_vt_processing', lambda *_: False)
45
+ def testInitWrapsOnWindows(self, _):
46
+ with osname("nt"):
47
+ init()
48
+ self.assertWrapped()
49
+
50
+ @patch('colorama.initialise.reset_all')
51
+ @patch('colorama.ansitowin32.winapi_test', lambda *_: False)
52
+ def testInitDoesntWrapOnEmulatedWindows(self, _):
53
+ with osname("nt"):
54
+ init()
55
+ self.assertNotWrapped()
56
+
57
+ def testInitDoesntWrapOnNonWindows(self):
58
+ with osname("posix"):
59
+ init()
60
+ self.assertNotWrapped()
61
+
62
+ def testInitDoesntWrapIfNone(self):
63
+ with replace_by(None):
64
+ init()
65
+ # We can't use assertNotWrapped here because replace_by(None)
66
+ # changes stdout/stderr already.
67
+ self.assertIsNone(sys.stdout)
68
+ self.assertIsNone(sys.stderr)
69
+
70
+ def testInitAutoresetOnWrapsOnAllPlatforms(self):
71
+ with osname("posix"):
72
+ init(autoreset=True)
73
+ self.assertWrapped()
74
+
75
+ def testInitWrapOffDoesntWrapOnWindows(self):
76
+ with osname("nt"):
77
+ init(wrap=False)
78
+ self.assertNotWrapped()
79
+
80
+ def testInitWrapOffIncompatibleWithAutoresetOn(self):
81
+ self.assertRaises(ValueError, lambda: init(autoreset=True, wrap=False))
82
+
83
+ @patch('colorama.win32.SetConsoleTextAttribute')
84
+ @patch('colorama.initialise.AnsiToWin32')
85
+ def testAutoResetPassedOn(self, mockATW32, _):
86
+ with osname("nt"):
87
+ init(autoreset=True)
88
+ self.assertEqual(len(mockATW32.call_args_list), 2)
89
+ self.assertEqual(mockATW32.call_args_list[1][1]['autoreset'], True)
90
+ self.assertEqual(mockATW32.call_args_list[0][1]['autoreset'], True)
91
+
92
+ @patch('colorama.initialise.AnsiToWin32')
93
+ def testAutoResetChangeable(self, mockATW32):
94
+ with osname("nt"):
95
+ init()
96
+
97
+ init(autoreset=True)
98
+ self.assertEqual(len(mockATW32.call_args_list), 4)
99
+ self.assertEqual(mockATW32.call_args_list[2][1]['autoreset'], True)
100
+ self.assertEqual(mockATW32.call_args_list[3][1]['autoreset'], True)
101
+
102
+ init()
103
+ self.assertEqual(len(mockATW32.call_args_list), 6)
104
+ self.assertEqual(
105
+ mockATW32.call_args_list[4][1]['autoreset'], False)
106
+ self.assertEqual(
107
+ mockATW32.call_args_list[5][1]['autoreset'], False)
108
+
109
+
110
+ @patch('colorama.initialise.atexit.register')
111
+ def testAtexitRegisteredOnlyOnce(self, mockRegister):
112
+ init()
113
+ self.assertTrue(mockRegister.called)
114
+ mockRegister.reset_mock()
115
+ init()
116
+ self.assertFalse(mockRegister.called)
117
+
118
+
119
+ class JustFixWindowsConsoleTest(TestCase):
120
+ def _reset(self):
121
+ _wipe_internal_state_for_tests()
122
+ sys.stdout = orig_stdout
123
+ sys.stderr = orig_stderr
124
+
125
+ def tearDown(self):
126
+ self._reset()
127
+
128
+ @patch("colorama.ansitowin32.winapi_test", lambda: True)
129
+ def testJustFixWindowsConsole(self):
130
+ if sys.platform != "win32":
131
+ # just_fix_windows_console should be a no-op
132
+ just_fix_windows_console()
133
+ self.assertIs(sys.stdout, orig_stdout)
134
+ self.assertIs(sys.stderr, orig_stderr)
135
+ else:
136
+ def fake_std():
137
+ # Emulate stdout=not a tty, stderr=tty
138
+ # to check that we handle both cases correctly
139
+ stdout = Mock()
140
+ stdout.closed = False
141
+ stdout.isatty.return_value = False
142
+ stdout.fileno.return_value = 1
143
+ sys.stdout = stdout
144
+
145
+ stderr = Mock()
146
+ stderr.closed = False
147
+ stderr.isatty.return_value = True
148
+ stderr.fileno.return_value = 2
149
+ sys.stderr = stderr
150
+
151
+ for native_ansi in [False, True]:
152
+ with patch(
153
+ 'colorama.ansitowin32.enable_vt_processing',
154
+ lambda *_: native_ansi
155
+ ):
156
+ self._reset()
157
+ fake_std()
158
+
159
+ # Regular single-call test
160
+ prev_stdout = sys.stdout
161
+ prev_stderr = sys.stderr
162
+ just_fix_windows_console()
163
+ self.assertIs(sys.stdout, prev_stdout)
164
+ if native_ansi:
165
+ self.assertIs(sys.stderr, prev_stderr)
166
+ else:
167
+ self.assertIsNot(sys.stderr, prev_stderr)
168
+
169
+ # second call without resetting is always a no-op
170
+ prev_stdout = sys.stdout
171
+ prev_stderr = sys.stderr
172
+ just_fix_windows_console()
173
+ self.assertIs(sys.stdout, prev_stdout)
174
+ self.assertIs(sys.stderr, prev_stderr)
175
+
176
+ self._reset()
177
+ fake_std()
178
+
179
+ # If init() runs first, just_fix_windows_console should be a no-op
180
+ init()
181
+ prev_stdout = sys.stdout
182
+ prev_stderr = sys.stderr
183
+ just_fix_windows_console()
184
+ self.assertIs(prev_stdout, sys.stdout)
185
+ self.assertIs(prev_stderr, sys.stderr)
186
+
187
+
188
+ if __name__ == '__main__':
189
+ main()
.venv/Lib/site-packages/pip/_vendor/colorama/tests/isatty_test.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ import sys
3
+ from unittest import TestCase, main
4
+
5
+ from ..ansitowin32 import StreamWrapper, AnsiToWin32
6
+ from .utils import pycharm, replace_by, replace_original_by, StreamTTY, StreamNonTTY
7
+
8
+
9
+ def is_a_tty(stream):
10
+ return StreamWrapper(stream, None).isatty()
11
+
12
+ class IsattyTest(TestCase):
13
+
14
+ def test_TTY(self):
15
+ tty = StreamTTY()
16
+ self.assertTrue(is_a_tty(tty))
17
+ with pycharm():
18
+ self.assertTrue(is_a_tty(tty))
19
+
20
+ def test_nonTTY(self):
21
+ non_tty = StreamNonTTY()
22
+ self.assertFalse(is_a_tty(non_tty))
23
+ with pycharm():
24
+ self.assertFalse(is_a_tty(non_tty))
25
+
26
+ def test_withPycharm(self):
27
+ with pycharm():
28
+ self.assertTrue(is_a_tty(sys.stderr))
29
+ self.assertTrue(is_a_tty(sys.stdout))
30
+
31
+ def test_withPycharmTTYOverride(self):
32
+ tty = StreamTTY()
33
+ with pycharm(), replace_by(tty):
34
+ self.assertTrue(is_a_tty(tty))
35
+
36
+ def test_withPycharmNonTTYOverride(self):
37
+ non_tty = StreamNonTTY()
38
+ with pycharm(), replace_by(non_tty):
39
+ self.assertFalse(is_a_tty(non_tty))
40
+
41
+ def test_withPycharmNoneOverride(self):
42
+ with pycharm():
43
+ with replace_by(None), replace_original_by(None):
44
+ self.assertFalse(is_a_tty(None))
45
+ self.assertFalse(is_a_tty(StreamNonTTY()))
46
+ self.assertTrue(is_a_tty(StreamTTY()))
47
+
48
+ def test_withPycharmStreamWrapped(self):
49
+ with pycharm():
50
+ self.assertTrue(AnsiToWin32(StreamTTY()).stream.isatty())
51
+ self.assertFalse(AnsiToWin32(StreamNonTTY()).stream.isatty())
52
+ self.assertTrue(AnsiToWin32(sys.stdout).stream.isatty())
53
+ self.assertTrue(AnsiToWin32(sys.stderr).stream.isatty())
54
+
55
+
56
+ if __name__ == '__main__':
57
+ main()
.venv/Lib/site-packages/pip/_vendor/colorama/tests/utils.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ from contextlib import contextmanager
3
+ from io import StringIO
4
+ import sys
5
+ import os
6
+
7
+
8
+ class StreamTTY(StringIO):
9
+ def isatty(self):
10
+ return True
11
+
12
+ class StreamNonTTY(StringIO):
13
+ def isatty(self):
14
+ return False
15
+
16
+ @contextmanager
17
+ def osname(name):
18
+ orig = os.name
19
+ os.name = name
20
+ yield
21
+ os.name = orig
22
+
23
+ @contextmanager
24
+ def replace_by(stream):
25
+ orig_stdout = sys.stdout
26
+ orig_stderr = sys.stderr
27
+ sys.stdout = stream
28
+ sys.stderr = stream
29
+ yield
30
+ sys.stdout = orig_stdout
31
+ sys.stderr = orig_stderr
32
+
33
+ @contextmanager
34
+ def replace_original_by(stream):
35
+ orig_stdout = sys.__stdout__
36
+ orig_stderr = sys.__stderr__
37
+ sys.__stdout__ = stream
38
+ sys.__stderr__ = stream
39
+ yield
40
+ sys.__stdout__ = orig_stdout
41
+ sys.__stderr__ = orig_stderr
42
+
43
+ @contextmanager
44
+ def pycharm():
45
+ os.environ["PYCHARM_HOSTED"] = "1"
46
+ non_tty = StreamNonTTY()
47
+ with replace_by(non_tty), replace_original_by(non_tty):
48
+ yield
49
+ del os.environ["PYCHARM_HOSTED"]
.venv/Lib/site-packages/pip/_vendor/colorama/tests/winterm_test.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ import sys
3
+ from unittest import TestCase, main, skipUnless
4
+
5
+ try:
6
+ from unittest.mock import Mock, patch
7
+ except ImportError:
8
+ from mock import Mock, patch
9
+
10
+ from ..winterm import WinColor, WinStyle, WinTerm
11
+
12
+
13
+ class WinTermTest(TestCase):
14
+
15
+ @patch('colorama.winterm.win32')
16
+ def testInit(self, mockWin32):
17
+ mockAttr = Mock()
18
+ mockAttr.wAttributes = 7 + 6 * 16 + 8
19
+ mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
20
+ term = WinTerm()
21
+ self.assertEqual(term._fore, 7)
22
+ self.assertEqual(term._back, 6)
23
+ self.assertEqual(term._style, 8)
24
+
25
+ @skipUnless(sys.platform.startswith("win"), "requires Windows")
26
+ def testGetAttrs(self):
27
+ term = WinTerm()
28
+
29
+ term._fore = 0
30
+ term._back = 0
31
+ term._style = 0
32
+ self.assertEqual(term.get_attrs(), 0)
33
+
34
+ term._fore = WinColor.YELLOW
35
+ self.assertEqual(term.get_attrs(), WinColor.YELLOW)
36
+
37
+ term._back = WinColor.MAGENTA
38
+ self.assertEqual(
39
+ term.get_attrs(),
40
+ WinColor.YELLOW + WinColor.MAGENTA * 16)
41
+
42
+ term._style = WinStyle.BRIGHT
43
+ self.assertEqual(
44
+ term.get_attrs(),
45
+ WinColor.YELLOW + WinColor.MAGENTA * 16 + WinStyle.BRIGHT)
46
+
47
+ @patch('colorama.winterm.win32')
48
+ def testResetAll(self, mockWin32):
49
+ mockAttr = Mock()
50
+ mockAttr.wAttributes = 1 + 2 * 16 + 8
51
+ mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
52
+ term = WinTerm()
53
+
54
+ term.set_console = Mock()
55
+ term._fore = -1
56
+ term._back = -1
57
+ term._style = -1
58
+
59
+ term.reset_all()
60
+
61
+ self.assertEqual(term._fore, 1)
62
+ self.assertEqual(term._back, 2)
63
+ self.assertEqual(term._style, 8)
64
+ self.assertEqual(term.set_console.called, True)
65
+
66
+ @skipUnless(sys.platform.startswith("win"), "requires Windows")
67
+ def testFore(self):
68
+ term = WinTerm()
69
+ term.set_console = Mock()
70
+ term._fore = 0
71
+
72
+ term.fore(5)
73
+
74
+ self.assertEqual(term._fore, 5)
75
+ self.assertEqual(term.set_console.called, True)
76
+
77
+ @skipUnless(sys.platform.startswith("win"), "requires Windows")
78
+ def testBack(self):
79
+ term = WinTerm()
80
+ term.set_console = Mock()
81
+ term._back = 0
82
+
83
+ term.back(5)
84
+
85
+ self.assertEqual(term._back, 5)
86
+ self.assertEqual(term.set_console.called, True)
87
+
88
+ @skipUnless(sys.platform.startswith("win"), "requires Windows")
89
+ def testStyle(self):
90
+ term = WinTerm()
91
+ term.set_console = Mock()
92
+ term._style = 0
93
+
94
+ term.style(22)
95
+
96
+ self.assertEqual(term._style, 22)
97
+ self.assertEqual(term.set_console.called, True)
98
+
99
+ @patch('colorama.winterm.win32')
100
+ def testSetConsole(self, mockWin32):
101
+ mockAttr = Mock()
102
+ mockAttr.wAttributes = 0
103
+ mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
104
+ term = WinTerm()
105
+ term.windll = Mock()
106
+
107
+ term.set_console()
108
+
109
+ self.assertEqual(
110
+ mockWin32.SetConsoleTextAttribute.call_args,
111
+ ((mockWin32.STDOUT, term.get_attrs()), {})
112
+ )
113
+
114
+ @patch('colorama.winterm.win32')
115
+ def testSetConsoleOnStderr(self, mockWin32):
116
+ mockAttr = Mock()
117
+ mockAttr.wAttributes = 0
118
+ mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
119
+ term = WinTerm()
120
+ term.windll = Mock()
121
+
122
+ term.set_console(on_stderr=True)
123
+
124
+ self.assertEqual(
125
+ mockWin32.SetConsoleTextAttribute.call_args,
126
+ ((mockWin32.STDERR, term.get_attrs()), {})
127
+ )
128
+
129
+
130
+ if __name__ == '__main__':
131
+ main()
.venv/Lib/site-packages/pip/_vendor/colorama/win32.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+
3
+ # from winbase.h
4
+ STDOUT = -11
5
+ STDERR = -12
6
+
7
+ ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
8
+
9
+ try:
10
+ import ctypes
11
+ from ctypes import LibraryLoader
12
+ windll = LibraryLoader(ctypes.WinDLL)
13
+ from ctypes import wintypes
14
+ except (AttributeError, ImportError):
15
+ windll = None
16
+ SetConsoleTextAttribute = lambda *_: None
17
+ winapi_test = lambda *_: None
18
+ else:
19
+ from ctypes import byref, Structure, c_char, POINTER
20
+
21
+ COORD = wintypes._COORD
22
+
23
+ class CONSOLE_SCREEN_BUFFER_INFO(Structure):
24
+ """struct in wincon.h."""
25
+ _fields_ = [
26
+ ("dwSize", COORD),
27
+ ("dwCursorPosition", COORD),
28
+ ("wAttributes", wintypes.WORD),
29
+ ("srWindow", wintypes.SMALL_RECT),
30
+ ("dwMaximumWindowSize", COORD),
31
+ ]
32
+ def __str__(self):
33
+ return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % (
34
+ self.dwSize.Y, self.dwSize.X
35
+ , self.dwCursorPosition.Y, self.dwCursorPosition.X
36
+ , self.wAttributes
37
+ , self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right
38
+ , self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X
39
+ )
40
+
41
+ _GetStdHandle = windll.kernel32.GetStdHandle
42
+ _GetStdHandle.argtypes = [
43
+ wintypes.DWORD,
44
+ ]
45
+ _GetStdHandle.restype = wintypes.HANDLE
46
+
47
+ _GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo
48
+ _GetConsoleScreenBufferInfo.argtypes = [
49
+ wintypes.HANDLE,
50
+ POINTER(CONSOLE_SCREEN_BUFFER_INFO),
51
+ ]
52
+ _GetConsoleScreenBufferInfo.restype = wintypes.BOOL
53
+
54
+ _SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute
55
+ _SetConsoleTextAttribute.argtypes = [
56
+ wintypes.HANDLE,
57
+ wintypes.WORD,
58
+ ]
59
+ _SetConsoleTextAttribute.restype = wintypes.BOOL
60
+
61
+ _SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition
62
+ _SetConsoleCursorPosition.argtypes = [
63
+ wintypes.HANDLE,
64
+ COORD,
65
+ ]
66
+ _SetConsoleCursorPosition.restype = wintypes.BOOL
67
+
68
+ _FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA
69
+ _FillConsoleOutputCharacterA.argtypes = [
70
+ wintypes.HANDLE,
71
+ c_char,
72
+ wintypes.DWORD,
73
+ COORD,
74
+ POINTER(wintypes.DWORD),
75
+ ]
76
+ _FillConsoleOutputCharacterA.restype = wintypes.BOOL
77
+
78
+ _FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute
79
+ _FillConsoleOutputAttribute.argtypes = [
80
+ wintypes.HANDLE,
81
+ wintypes.WORD,
82
+ wintypes.DWORD,
83
+ COORD,
84
+ POINTER(wintypes.DWORD),
85
+ ]
86
+ _FillConsoleOutputAttribute.restype = wintypes.BOOL
87
+
88
+ _SetConsoleTitleW = windll.kernel32.SetConsoleTitleW
89
+ _SetConsoleTitleW.argtypes = [
90
+ wintypes.LPCWSTR
91
+ ]
92
+ _SetConsoleTitleW.restype = wintypes.BOOL
93
+
94
+ _GetConsoleMode = windll.kernel32.GetConsoleMode
95
+ _GetConsoleMode.argtypes = [
96
+ wintypes.HANDLE,
97
+ POINTER(wintypes.DWORD)
98
+ ]
99
+ _GetConsoleMode.restype = wintypes.BOOL
100
+
101
+ _SetConsoleMode = windll.kernel32.SetConsoleMode
102
+ _SetConsoleMode.argtypes = [
103
+ wintypes.HANDLE,
104
+ wintypes.DWORD
105
+ ]
106
+ _SetConsoleMode.restype = wintypes.BOOL
107
+
108
+ def _winapi_test(handle):
109
+ csbi = CONSOLE_SCREEN_BUFFER_INFO()
110
+ success = _GetConsoleScreenBufferInfo(
111
+ handle, byref(csbi))
112
+ return bool(success)
113
+
114
+ def winapi_test():
115
+ return any(_winapi_test(h) for h in
116
+ (_GetStdHandle(STDOUT), _GetStdHandle(STDERR)))
117
+
118
+ def GetConsoleScreenBufferInfo(stream_id=STDOUT):
119
+ handle = _GetStdHandle(stream_id)
120
+ csbi = CONSOLE_SCREEN_BUFFER_INFO()
121
+ success = _GetConsoleScreenBufferInfo(
122
+ handle, byref(csbi))
123
+ return csbi
124
+
125
+ def SetConsoleTextAttribute(stream_id, attrs):
126
+ handle = _GetStdHandle(stream_id)
127
+ return _SetConsoleTextAttribute(handle, attrs)
128
+
129
+ def SetConsoleCursorPosition(stream_id, position, adjust=True):
130
+ position = COORD(*position)
131
+ # If the position is out of range, do nothing.
132
+ if position.Y <= 0 or position.X <= 0:
133
+ return
134
+ # Adjust for Windows' SetConsoleCursorPosition:
135
+ # 1. being 0-based, while ANSI is 1-based.
136
+ # 2. expecting (x,y), while ANSI uses (y,x).
137
+ adjusted_position = COORD(position.Y - 1, position.X - 1)
138
+ if adjust:
139
+ # Adjust for viewport's scroll position
140
+ sr = GetConsoleScreenBufferInfo(STDOUT).srWindow
141
+ adjusted_position.Y += sr.Top
142
+ adjusted_position.X += sr.Left
143
+ # Resume normal processing
144
+ handle = _GetStdHandle(stream_id)
145
+ return _SetConsoleCursorPosition(handle, adjusted_position)
146
+
147
+ def FillConsoleOutputCharacter(stream_id, char, length, start):
148
+ handle = _GetStdHandle(stream_id)
149
+ char = c_char(char.encode())
150
+ length = wintypes.DWORD(length)
151
+ num_written = wintypes.DWORD(0)
152
+ # Note that this is hard-coded for ANSI (vs wide) bytes.
153
+ success = _FillConsoleOutputCharacterA(
154
+ handle, char, length, start, byref(num_written))
155
+ return num_written.value
156
+
157
+ def FillConsoleOutputAttribute(stream_id, attr, length, start):
158
+ ''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )'''
159
+ handle = _GetStdHandle(stream_id)
160
+ attribute = wintypes.WORD(attr)
161
+ length = wintypes.DWORD(length)
162
+ num_written = wintypes.DWORD(0)
163
+ # Note that this is hard-coded for ANSI (vs wide) bytes.
164
+ return _FillConsoleOutputAttribute(
165
+ handle, attribute, length, start, byref(num_written))
166
+
167
+ def SetConsoleTitle(title):
168
+ return _SetConsoleTitleW(title)
169
+
170
+ def GetConsoleMode(handle):
171
+ mode = wintypes.DWORD()
172
+ success = _GetConsoleMode(handle, byref(mode))
173
+ if not success:
174
+ raise ctypes.WinError()
175
+ return mode.value
176
+
177
+ def SetConsoleMode(handle, mode):
178
+ success = _SetConsoleMode(handle, mode)
179
+ if not success:
180
+ raise ctypes.WinError()
.venv/Lib/site-packages/pip/_vendor/colorama/winterm.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ try:
3
+ from msvcrt import get_osfhandle
4
+ except ImportError:
5
+ def get_osfhandle(_):
6
+ raise OSError("This isn't windows!")
7
+
8
+
9
+ from . import win32
10
+
11
+ # from wincon.h
12
+ class WinColor(object):
13
+ BLACK = 0
14
+ BLUE = 1
15
+ GREEN = 2
16
+ CYAN = 3
17
+ RED = 4
18
+ MAGENTA = 5
19
+ YELLOW = 6
20
+ GREY = 7
21
+
22
+ # from wincon.h
23
+ class WinStyle(object):
24
+ NORMAL = 0x00 # dim text, dim background
25
+ BRIGHT = 0x08 # bright text, dim background
26
+ BRIGHT_BACKGROUND = 0x80 # dim text, bright background
27
+
28
+ class WinTerm(object):
29
+
30
+ def __init__(self):
31
+ self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes
32
+ self.set_attrs(self._default)
33
+ self._default_fore = self._fore
34
+ self._default_back = self._back
35
+ self._default_style = self._style
36
+ # In order to emulate LIGHT_EX in windows, we borrow the BRIGHT style.
37
+ # So that LIGHT_EX colors and BRIGHT style do not clobber each other,
38
+ # we track them separately, since LIGHT_EX is overwritten by Fore/Back
39
+ # and BRIGHT is overwritten by Style codes.
40
+ self._light = 0
41
+
42
+ def get_attrs(self):
43
+ return self._fore + self._back * 16 + (self._style | self._light)
44
+
45
+ def set_attrs(self, value):
46
+ self._fore = value & 7
47
+ self._back = (value >> 4) & 7
48
+ self._style = value & (WinStyle.BRIGHT | WinStyle.BRIGHT_BACKGROUND)
49
+
50
+ def reset_all(self, on_stderr=None):
51
+ self.set_attrs(self._default)
52
+ self.set_console(attrs=self._default)
53
+ self._light = 0
54
+
55
+ def fore(self, fore=None, light=False, on_stderr=False):
56
+ if fore is None:
57
+ fore = self._default_fore
58
+ self._fore = fore
59
+ # Emulate LIGHT_EX with BRIGHT Style
60
+ if light:
61
+ self._light |= WinStyle.BRIGHT
62
+ else:
63
+ self._light &= ~WinStyle.BRIGHT
64
+ self.set_console(on_stderr=on_stderr)
65
+
66
+ def back(self, back=None, light=False, on_stderr=False):
67
+ if back is None:
68
+ back = self._default_back
69
+ self._back = back
70
+ # Emulate LIGHT_EX with BRIGHT_BACKGROUND Style
71
+ if light:
72
+ self._light |= WinStyle.BRIGHT_BACKGROUND
73
+ else:
74
+ self._light &= ~WinStyle.BRIGHT_BACKGROUND
75
+ self.set_console(on_stderr=on_stderr)
76
+
77
+ def style(self, style=None, on_stderr=False):
78
+ if style is None:
79
+ style = self._default_style
80
+ self._style = style
81
+ self.set_console(on_stderr=on_stderr)
82
+
83
+ def set_console(self, attrs=None, on_stderr=False):
84
+ if attrs is None:
85
+ attrs = self.get_attrs()
86
+ handle = win32.STDOUT
87
+ if on_stderr:
88
+ handle = win32.STDERR
89
+ win32.SetConsoleTextAttribute(handle, attrs)
90
+
91
+ def get_position(self, handle):
92
+ position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition
93
+ # Because Windows coordinates are 0-based,
94
+ # and win32.SetConsoleCursorPosition expects 1-based.
95
+ position.X += 1
96
+ position.Y += 1
97
+ return position
98
+
99
+ def set_cursor_position(self, position=None, on_stderr=False):
100
+ if position is None:
101
+ # I'm not currently tracking the position, so there is no default.
102
+ # position = self.get_position()
103
+ return
104
+ handle = win32.STDOUT
105
+ if on_stderr:
106
+ handle = win32.STDERR
107
+ win32.SetConsoleCursorPosition(handle, position)
108
+
109
+ def cursor_adjust(self, x, y, on_stderr=False):
110
+ handle = win32.STDOUT
111
+ if on_stderr:
112
+ handle = win32.STDERR
113
+ position = self.get_position(handle)
114
+ adjusted_position = (position.Y + y, position.X + x)
115
+ win32.SetConsoleCursorPosition(handle, adjusted_position, adjust=False)
116
+
117
+ def erase_screen(self, mode=0, on_stderr=False):
118
+ # 0 should clear from the cursor to the end of the screen.
119
+ # 1 should clear from the cursor to the beginning of the screen.
120
+ # 2 should clear the entire screen, and move cursor to (1,1)
121
+ handle = win32.STDOUT
122
+ if on_stderr:
123
+ handle = win32.STDERR
124
+ csbi = win32.GetConsoleScreenBufferInfo(handle)
125
+ # get the number of character cells in the current buffer
126
+ cells_in_screen = csbi.dwSize.X * csbi.dwSize.Y
127
+ # get number of character cells before current cursor position
128
+ cells_before_cursor = csbi.dwSize.X * csbi.dwCursorPosition.Y + csbi.dwCursorPosition.X
129
+ if mode == 0:
130
+ from_coord = csbi.dwCursorPosition
131
+ cells_to_erase = cells_in_screen - cells_before_cursor
132
+ elif mode == 1:
133
+ from_coord = win32.COORD(0, 0)
134
+ cells_to_erase = cells_before_cursor
135
+ elif mode == 2:
136
+ from_coord = win32.COORD(0, 0)
137
+ cells_to_erase = cells_in_screen
138
+ else:
139
+ # invalid mode
140
+ return
141
+ # fill the entire screen with blanks
142
+ win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)
143
+ # now set the buffer's attributes accordingly
144
+ win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord)
145
+ if mode == 2:
146
+ # put the cursor where needed
147
+ win32.SetConsoleCursorPosition(handle, (1, 1))
148
+
149
+ def erase_line(self, mode=0, on_stderr=False):
150
+ # 0 should clear from the cursor to the end of the line.
151
+ # 1 should clear from the cursor to the beginning of the line.
152
+ # 2 should clear the entire line.
153
+ handle = win32.STDOUT
154
+ if on_stderr:
155
+ handle = win32.STDERR
156
+ csbi = win32.GetConsoleScreenBufferInfo(handle)
157
+ if mode == 0:
158
+ from_coord = csbi.dwCursorPosition
159
+ cells_to_erase = csbi.dwSize.X - csbi.dwCursorPosition.X
160
+ elif mode == 1:
161
+ from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)
162
+ cells_to_erase = csbi.dwCursorPosition.X
163
+ elif mode == 2:
164
+ from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)
165
+ cells_to_erase = csbi.dwSize.X
166
+ else:
167
+ # invalid mode
168
+ return
169
+ # fill the entire screen with blanks
170
+ win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)
171
+ # now set the buffer's attributes accordingly
172
+ win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord)
173
+
174
+ def set_title(self, title):
175
+ win32.SetConsoleTitle(title)
176
+
177
+
178
+ def enable_vt_processing(fd):
179
+ if win32.windll is None or not win32.winapi_test():
180
+ return False
181
+
182
+ try:
183
+ handle = get_osfhandle(fd)
184
+ mode = win32.GetConsoleMode(handle)
185
+ win32.SetConsoleMode(
186
+ handle,
187
+ mode | win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING,
188
+ )
189
+
190
+ mode = win32.GetConsoleMode(handle)
191
+ if mode & win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING:
192
+ return True
193
+ # Can get TypeError in testsuite where 'fd' is a Mock()
194
+ except (OSError, TypeError):
195
+ return False
.venv/Lib/site-packages/pip/_vendor/distlib/compat.py ADDED
@@ -0,0 +1,1116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 sys
12
+
13
+ try:
14
+ import ssl
15
+ except ImportError: # pragma: no cover
16
+ ssl = None
17
+
18
+ if sys.version_info[0] < 3: # pragma: no cover
19
+ from StringIO import StringIO
20
+ string_types = basestring,
21
+ text_type = unicode
22
+ from types import FileType as file_type
23
+ import __builtin__ as builtins
24
+ import ConfigParser as configparser
25
+ from urlparse import urlparse, urlunparse, urljoin, urlsplit, urlunsplit
26
+ from urllib import (urlretrieve, quote as _quote, unquote, url2pathname,
27
+ pathname2url, ContentTooShortError, splittype)
28
+
29
+ def quote(s):
30
+ if isinstance(s, unicode):
31
+ s = s.encode('utf-8')
32
+ return _quote(s)
33
+
34
+ import urllib2
35
+ from urllib2 import (Request, urlopen, URLError, HTTPError,
36
+ HTTPBasicAuthHandler, HTTPPasswordMgr,
37
+ HTTPHandler, HTTPRedirectHandler,
38
+ 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
+ import shutil
71
+ from urllib.parse import (urlparse, urlunparse, urljoin, quote,
72
+ unquote, urlsplit, urlunsplit, splittype)
73
+ from urllib.request import (urlopen, urlretrieve, Request, url2pathname,
74
+ pathname2url,
75
+ HTTPBasicAuthHandler, HTTPPasswordMgr,
76
+ HTTPHandler, HTTPRedirectHandler,
77
+ build_opener)
78
+ if ssl:
79
+ from urllib.request import HTTPSHandler
80
+ from urllib.error import HTTPError, URLError, ContentTooShortError
81
+ import http.client as httplib
82
+ import urllib.request as urllib2
83
+ import xmlrpc.client as xmlrpclib
84
+ import queue
85
+ from html.parser import HTMLParser
86
+ import html.entities as htmlentitydefs
87
+ raw_input = input
88
+ from itertools import filterfalse
89
+ filter = filter
90
+
91
+
92
+ try:
93
+ from ssl import match_hostname, CertificateError
94
+ except ImportError: # pragma: no cover
95
+ class CertificateError(ValueError):
96
+ pass
97
+
98
+
99
+ def _dnsname_match(dn, hostname, max_wildcards=1):
100
+ """Matching according to RFC 6125, section 6.4.3
101
+
102
+ http://tools.ietf.org/html/rfc6125#section-6.4.3
103
+ """
104
+ pats = []
105
+ if not dn:
106
+ return False
107
+
108
+ parts = dn.split('.')
109
+ leftmost, remainder = parts[0], parts[1:]
110
+
111
+ wildcards = leftmost.count('*')
112
+ if wildcards > max_wildcards:
113
+ # Issue #17980: avoid denials of service by refusing more
114
+ # than one wildcard per fragment. A survey of established
115
+ # policy among SSL implementations showed it to be a
116
+ # reasonable choice.
117
+ raise CertificateError(
118
+ "too many wildcards in certificate DNS name: " + repr(dn))
119
+
120
+ # speed up common case w/o wildcards
121
+ if not wildcards:
122
+ return dn.lower() == hostname.lower()
123
+
124
+ # RFC 6125, section 6.4.3, subitem 1.
125
+ # The client SHOULD NOT attempt to match a presented identifier in which
126
+ # the wildcard character comprises a label other than the left-most label.
127
+ if leftmost == '*':
128
+ # When '*' is a fragment by itself, it matches a non-empty dotless
129
+ # fragment.
130
+ pats.append('[^.]+')
131
+ elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
132
+ # RFC 6125, section 6.4.3, subitem 3.
133
+ # The client SHOULD NOT attempt to match a presented identifier
134
+ # where the wildcard character is embedded within an A-label or
135
+ # U-label of an internationalized domain name.
136
+ pats.append(re.escape(leftmost))
137
+ else:
138
+ # Otherwise, '*' matches any dotless string, e.g. www*
139
+ pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
140
+
141
+ # add the remaining fragments, ignore any wildcards
142
+ for frag in remainder:
143
+ pats.append(re.escape(frag))
144
+
145
+ pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
146
+ return pat.match(hostname)
147
+
148
+
149
+ def match_hostname(cert, hostname):
150
+ """Verify that *cert* (in decoded format as returned by
151
+ SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
152
+ rules are followed, but IP addresses are not accepted for *hostname*.
153
+
154
+ CertificateError is raised on failure. On success, the function
155
+ returns nothing.
156
+ """
157
+ if not cert:
158
+ raise ValueError("empty or no certificate, match_hostname needs a "
159
+ "SSL socket or SSL context with either "
160
+ "CERT_OPTIONAL or CERT_REQUIRED")
161
+ dnsnames = []
162
+ san = cert.get('subjectAltName', ())
163
+ for key, value in san:
164
+ if key == 'DNS':
165
+ if _dnsname_match(value, hostname):
166
+ return
167
+ dnsnames.append(value)
168
+ if not dnsnames:
169
+ # The subject is only checked when there is no dNSName entry
170
+ # in subjectAltName
171
+ for sub in cert.get('subject', ()):
172
+ for key, value in sub:
173
+ # XXX according to RFC 2818, the most specific Common Name
174
+ # must be used.
175
+ if key == 'commonName':
176
+ if _dnsname_match(value, hostname):
177
+ return
178
+ dnsnames.append(value)
179
+ if len(dnsnames) > 1:
180
+ raise CertificateError("hostname %r "
181
+ "doesn't match either of %s"
182
+ % (hostname, ', '.join(map(repr, dnsnames))))
183
+ elif len(dnsnames) == 1:
184
+ raise CertificateError("hostname %r "
185
+ "doesn't match %r"
186
+ % (hostname, dnsnames[0]))
187
+ else:
188
+ raise CertificateError("no appropriate commonName or "
189
+ "subjectAltName fields were found")
190
+
191
+
192
+ try:
193
+ from types import SimpleNamespace as Container
194
+ except ImportError: # pragma: no cover
195
+ class Container(object):
196
+ """
197
+ A generic container for when multiple values need to be returned
198
+ """
199
+ def __init__(self, **kwargs):
200
+ self.__dict__.update(kwargs)
201
+
202
+
203
+ try:
204
+ from shutil import which
205
+ except ImportError: # pragma: no cover
206
+ # Implementation from Python 3.3
207
+ def which(cmd, mode=os.F_OK | os.X_OK, path=None):
208
+ """Given a command, mode, and a PATH string, return the path which
209
+ conforms to the given mode on the PATH, or None if there is no such
210
+ file.
211
+
212
+ `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
213
+ of os.environ.get("PATH"), or can be overridden with a custom search
214
+ path.
215
+
216
+ """
217
+ # Check that a given file can be accessed with the correct mode.
218
+ # Additionally check that `file` is not a directory, as on Windows
219
+ # directories pass the os.access check.
220
+ def _access_check(fn, mode):
221
+ return (os.path.exists(fn) and os.access(fn, mode)
222
+ and not os.path.isdir(fn))
223
+
224
+ # If we're given a path with a directory part, look it up directly rather
225
+ # than referring to PATH directories. This includes checking relative to the
226
+ # current directory, e.g. ./script
227
+ if os.path.dirname(cmd):
228
+ if _access_check(cmd, mode):
229
+ return cmd
230
+ return None
231
+
232
+ if path is None:
233
+ path = os.environ.get("PATH", os.defpath)
234
+ if not path:
235
+ return None
236
+ path = path.split(os.pathsep)
237
+
238
+ if sys.platform == "win32":
239
+ # The current directory takes precedence on Windows.
240
+ if not os.curdir in path:
241
+ path.insert(0, os.curdir)
242
+
243
+ # PATHEXT is necessary to check on Windows.
244
+ pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
245
+ # See if the given file matches any of the expected path extensions.
246
+ # This will allow us to short circuit when given "python.exe".
247
+ # If it does match, only test that one, otherwise we have to try
248
+ # others.
249
+ if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
250
+ files = [cmd]
251
+ else:
252
+ files = [cmd + ext for ext in pathext]
253
+ else:
254
+ # On other platforms you don't have things like PATHEXT to tell you
255
+ # what file suffixes are executable, so just pass on cmd as-is.
256
+ files = [cmd]
257
+
258
+ seen = set()
259
+ for dir in path:
260
+ normdir = os.path.normcase(dir)
261
+ if not normdir in seen:
262
+ seen.add(normdir)
263
+ for thefile in files:
264
+ name = os.path.join(dir, thefile)
265
+ if _access_check(name, mode):
266
+ return name
267
+ return None
268
+
269
+
270
+ # ZipFile is a context manager in 2.7, but not in 2.6
271
+
272
+ from zipfile import ZipFile as BaseZipFile
273
+
274
+ if hasattr(BaseZipFile, '__enter__'): # pragma: no cover
275
+ ZipFile = BaseZipFile
276
+ else: # pragma: no cover
277
+ from zipfile import ZipExtFile as BaseZipExtFile
278
+
279
+ class ZipExtFile(BaseZipExtFile):
280
+ def __init__(self, base):
281
+ self.__dict__.update(base.__dict__)
282
+
283
+ def __enter__(self):
284
+ return self
285
+
286
+ def __exit__(self, *exc_info):
287
+ self.close()
288
+ # return None, so if an exception occurred, it will propagate
289
+
290
+ class ZipFile(BaseZipFile):
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
+ try:
303
+ from platform import python_implementation
304
+ except ImportError: # pragma: no cover
305
+ def python_implementation():
306
+ """Return a string identifying the Python implementation."""
307
+ if 'PyPy' in sys.version:
308
+ return 'PyPy'
309
+ if os.name == 'java':
310
+ return 'Jython'
311
+ if sys.version.startswith('IronPython'):
312
+ return 'IronPython'
313
+ return 'CPython'
314
+
315
+ import shutil
316
+ import sysconfig
317
+
318
+ try:
319
+ callable = callable
320
+ except NameError: # pragma: no cover
321
+ from collections.abc import Callable
322
+
323
+ def callable(obj):
324
+ return isinstance(obj, Callable)
325
+
326
+
327
+ try:
328
+ fsencode = os.fsencode
329
+ fsdecode = os.fsdecode
330
+ except AttributeError: # pragma: no cover
331
+ # Issue #99: on some systems (e.g. containerised),
332
+ # sys.getfilesystemencoding() returns None, and we need a real value,
333
+ # so fall back to utf-8. From the CPython 2.7 docs relating to Unix and
334
+ # sys.getfilesystemencoding(): the return value is "the user’s preference
335
+ # according to the result of nl_langinfo(CODESET), or None if the
336
+ # nl_langinfo(CODESET) failed."
337
+ _fsencoding = sys.getfilesystemencoding() or 'utf-8'
338
+ if _fsencoding == 'mbcs':
339
+ _fserrors = 'strict'
340
+ else:
341
+ _fserrors = 'surrogateescape'
342
+
343
+ def fsencode(filename):
344
+ if isinstance(filename, bytes):
345
+ return filename
346
+ elif isinstance(filename, text_type):
347
+ return filename.encode(_fsencoding, _fserrors)
348
+ else:
349
+ raise TypeError("expect bytes or str, not %s" %
350
+ type(filename).__name__)
351
+
352
+ def fsdecode(filename):
353
+ if isinstance(filename, text_type):
354
+ return filename
355
+ elif isinstance(filename, bytes):
356
+ return filename.decode(_fsencoding, _fserrors)
357
+ else:
358
+ raise TypeError("expect bytes or str, not %s" %
359
+ type(filename).__name__)
360
+
361
+ try:
362
+ from tokenize import detect_encoding
363
+ except ImportError: # pragma: no cover
364
+ from codecs import BOM_UTF8, lookup
365
+ import re
366
+
367
+ cookie_re = re.compile(r"coding[:=]\s*([-\w.]+)")
368
+
369
+ def _get_normal_name(orig_enc):
370
+ """Imitates get_normal_name in tokenizer.c."""
371
+ # Only care about the first 12 characters.
372
+ enc = orig_enc[:12].lower().replace("_", "-")
373
+ if enc == "utf-8" or enc.startswith("utf-8-"):
374
+ return "utf-8"
375
+ if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
376
+ enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
377
+ return "iso-8859-1"
378
+ return orig_enc
379
+
380
+ def detect_encoding(readline):
381
+ """
382
+ The detect_encoding() function is used to detect the encoding that should
383
+ be used to decode a Python source file. It requires one argument, readline,
384
+ in the same way as the tokenize() generator.
385
+
386
+ It will call readline a maximum of twice, and return the encoding used
387
+ (as a string) and a list of any lines (left as bytes) it has read in.
388
+
389
+ It detects the encoding from the presence of a utf-8 bom or an encoding
390
+ cookie as specified in pep-0263. If both a bom and a cookie are present,
391
+ but disagree, a SyntaxError will be raised. If the encoding cookie is an
392
+ invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
393
+ 'utf-8-sig' is returned.
394
+
395
+ If no encoding is specified, then the default of 'utf-8' will be returned.
396
+ """
397
+ try:
398
+ filename = readline.__self__.name
399
+ except AttributeError:
400
+ filename = None
401
+ bom_found = False
402
+ encoding = None
403
+ default = 'utf-8'
404
+ def read_or_stop():
405
+ try:
406
+ return readline()
407
+ except StopIteration:
408
+ return b''
409
+
410
+ def find_cookie(line):
411
+ try:
412
+ # Decode as UTF-8. Either the line is an encoding declaration,
413
+ # in which case it should be pure ASCII, or it must be UTF-8
414
+ # per default encoding.
415
+ line_string = line.decode('utf-8')
416
+ except UnicodeDecodeError:
417
+ msg = "invalid or missing encoding declaration"
418
+ if filename is not None:
419
+ msg = '{} for {!r}'.format(msg, filename)
420
+ raise SyntaxError(msg)
421
+
422
+ matches = cookie_re.findall(line_string)
423
+ if not matches:
424
+ return None
425
+ encoding = _get_normal_name(matches[0])
426
+ try:
427
+ codec = lookup(encoding)
428
+ except LookupError:
429
+ # This behaviour mimics the Python interpreter
430
+ if filename is None:
431
+ msg = "unknown encoding: " + encoding
432
+ else:
433
+ msg = "unknown encoding for {!r}: {}".format(filename,
434
+ encoding)
435
+ raise SyntaxError(msg)
436
+
437
+ if bom_found:
438
+ if codec.name != 'utf-8':
439
+ # This behaviour mimics the Python interpreter
440
+ if filename is None:
441
+ msg = 'encoding problem: utf-8'
442
+ else:
443
+ msg = 'encoding problem for {!r}: utf-8'.format(filename)
444
+ raise SyntaxError(msg)
445
+ encoding += '-sig'
446
+ return encoding
447
+
448
+ first = read_or_stop()
449
+ if first.startswith(BOM_UTF8):
450
+ bom_found = True
451
+ first = first[3:]
452
+ default = 'utf-8-sig'
453
+ if not first:
454
+ return default, []
455
+
456
+ encoding = find_cookie(first)
457
+ if encoding:
458
+ return encoding, [first]
459
+
460
+ second = read_or_stop()
461
+ if not second:
462
+ return default, [first]
463
+
464
+ encoding = find_cookie(second)
465
+ if encoding:
466
+ return encoding, [first, second]
467
+
468
+ return default, [first, second]
469
+
470
+ # For converting & <-> &amp; etc.
471
+ try:
472
+ from html import escape
473
+ except ImportError:
474
+ from cgi import escape
475
+ if sys.version_info[:2] < (3, 4):
476
+ unescape = HTMLParser().unescape
477
+ else:
478
+ from html import unescape
479
+
480
+ try:
481
+ from collections import ChainMap
482
+ except ImportError: # pragma: no cover
483
+ from collections import MutableMapping
484
+
485
+ try:
486
+ from reprlib import recursive_repr as _recursive_repr
487
+ except ImportError:
488
+ def _recursive_repr(fillvalue='...'):
489
+ '''
490
+ Decorator to make a repr function return fillvalue for a recursive
491
+ call
492
+ '''
493
+
494
+ def decorating_function(user_function):
495
+ repr_running = set()
496
+
497
+ def wrapper(self):
498
+ key = id(self), get_ident()
499
+ if key in repr_running:
500
+ return fillvalue
501
+ repr_running.add(key)
502
+ try:
503
+ result = user_function(self)
504
+ finally:
505
+ repr_running.discard(key)
506
+ return result
507
+
508
+ # Can't use functools.wraps() here because of bootstrap issues
509
+ wrapper.__module__ = getattr(user_function, '__module__')
510
+ wrapper.__doc__ = getattr(user_function, '__doc__')
511
+ wrapper.__name__ = getattr(user_function, '__name__')
512
+ wrapper.__annotations__ = getattr(user_function, '__annotations__', {})
513
+ return wrapper
514
+
515
+ return decorating_function
516
+
517
+ class ChainMap(MutableMapping):
518
+ ''' A ChainMap groups multiple dicts (or other mappings) together
519
+ to create a single, updateable view.
520
+
521
+ The underlying mappings are stored in a list. That list is public and can
522
+ accessed or updated using the *maps* attribute. There is no other state.
523
+
524
+ Lookups search the underlying mappings successively until a key is found.
525
+ In contrast, writes, updates, and deletions only operate on the first
526
+ mapping.
527
+
528
+ '''
529
+
530
+ def __init__(self, *maps):
531
+ '''Initialize a ChainMap by setting *maps* to the given mappings.
532
+ If no mappings are provided, a single empty dictionary is used.
533
+
534
+ '''
535
+ self.maps = list(maps) or [{}] # always at least one map
536
+
537
+ def __missing__(self, key):
538
+ raise KeyError(key)
539
+
540
+ def __getitem__(self, key):
541
+ for mapping in self.maps:
542
+ try:
543
+ return mapping[key] # can't use 'key in mapping' with defaultdict
544
+ except KeyError:
545
+ pass
546
+ return self.__missing__(key) # support subclasses that define __missing__
547
+
548
+ def get(self, key, default=None):
549
+ return self[key] if key in self else default
550
+
551
+ def __len__(self):
552
+ return len(set().union(*self.maps)) # reuses stored hash values if possible
553
+
554
+ def __iter__(self):
555
+ return iter(set().union(*self.maps))
556
+
557
+ def __contains__(self, key):
558
+ return any(key in m for m in self.maps)
559
+
560
+ def __bool__(self):
561
+ return any(self.maps)
562
+
563
+ @_recursive_repr()
564
+ def __repr__(self):
565
+ return '{0.__class__.__name__}({1})'.format(
566
+ self, ', '.join(map(repr, self.maps)))
567
+
568
+ @classmethod
569
+ def fromkeys(cls, iterable, *args):
570
+ 'Create a ChainMap with a single dict created from the iterable.'
571
+ return cls(dict.fromkeys(iterable, *args))
572
+
573
+ def copy(self):
574
+ 'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
575
+ return self.__class__(self.maps[0].copy(), *self.maps[1:])
576
+
577
+ __copy__ = copy
578
+
579
+ def new_child(self): # like Django's Context.push()
580
+ 'New ChainMap with a new dict followed by all previous maps.'
581
+ return self.__class__({}, *self.maps)
582
+
583
+ @property
584
+ def parents(self): # like Django's Context.pop()
585
+ 'New ChainMap from maps[1:].'
586
+ return self.__class__(*self.maps[1:])
587
+
588
+ def __setitem__(self, key, value):
589
+ self.maps[0][key] = value
590
+
591
+ def __delitem__(self, key):
592
+ try:
593
+ del self.maps[0][key]
594
+ except KeyError:
595
+ raise KeyError('Key not found in the first mapping: {!r}'.format(key))
596
+
597
+ def popitem(self):
598
+ 'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.'
599
+ try:
600
+ return self.maps[0].popitem()
601
+ except KeyError:
602
+ raise KeyError('No keys found in the first mapping.')
603
+
604
+ def pop(self, key, *args):
605
+ 'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
606
+ try:
607
+ return self.maps[0].pop(key, *args)
608
+ except KeyError:
609
+ raise KeyError('Key not found in the first mapping: {!r}'.format(key))
610
+
611
+ def clear(self):
612
+ 'Clear maps[0], leaving maps[1:] intact.'
613
+ self.maps[0].clear()
614
+
615
+ try:
616
+ from importlib.util import cache_from_source # Python >= 3.4
617
+ except ImportError: # pragma: no cover
618
+ def cache_from_source(path, debug_override=None):
619
+ assert path.endswith('.py')
620
+ if debug_override is None:
621
+ debug_override = __debug__
622
+ if debug_override:
623
+ suffix = 'c'
624
+ else:
625
+ suffix = 'o'
626
+ return path + suffix
627
+
628
+ try:
629
+ from collections import OrderedDict
630
+ except ImportError: # pragma: no cover
631
+ ## {{{ http://code.activestate.com/recipes/576693/ (r9)
632
+ # Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
633
+ # Passes Python2.7's test suite and incorporates all the latest updates.
634
+ try:
635
+ from thread import get_ident as _get_ident
636
+ except ImportError:
637
+ from dummy_thread import get_ident as _get_ident
638
+
639
+ try:
640
+ from _abcoll import KeysView, ValuesView, ItemsView
641
+ except ImportError:
642
+ pass
643
+
644
+
645
+ class OrderedDict(dict):
646
+ 'Dictionary that remembers insertion order'
647
+ # An inherited dict maps keys to values.
648
+ # The inherited dict provides __getitem__, __len__, __contains__, and get.
649
+ # The remaining methods are order-aware.
650
+ # Big-O running times for all methods are the same as for regular dictionaries.
651
+
652
+ # The internal self.__map dictionary maps keys to links in a doubly linked list.
653
+ # The circular doubly linked list starts and ends with a sentinel element.
654
+ # The sentinel element never gets deleted (this simplifies the algorithm).
655
+ # Each link is stored as a list of length three: [PREV, NEXT, KEY].
656
+
657
+ def __init__(self, *args, **kwds):
658
+ '''Initialize an ordered dictionary. Signature is the same as for
659
+ regular dictionaries, but keyword arguments are not recommended
660
+ because their insertion order is arbitrary.
661
+
662
+ '''
663
+ if len(args) > 1:
664
+ raise TypeError('expected at most 1 arguments, got %d' % len(args))
665
+ try:
666
+ self.__root
667
+ except AttributeError:
668
+ self.__root = root = [] # sentinel node
669
+ root[:] = [root, root, None]
670
+ self.__map = {}
671
+ self.__update(*args, **kwds)
672
+
673
+ def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
674
+ 'od.__setitem__(i, y) <==> od[i]=y'
675
+ # Setting a new item creates a new link which goes at the end of the linked
676
+ # list, and the inherited dictionary is updated with the new key/value pair.
677
+ if key not in self:
678
+ root = self.__root
679
+ last = root[0]
680
+ last[1] = root[0] = self.__map[key] = [last, root, key]
681
+ dict_setitem(self, key, value)
682
+
683
+ def __delitem__(self, key, dict_delitem=dict.__delitem__):
684
+ 'od.__delitem__(y) <==> del od[y]'
685
+ # Deleting an existing item uses self.__map to find the link which is
686
+ # then removed by updating the links in the predecessor and successor nodes.
687
+ dict_delitem(self, key)
688
+ link_prev, link_next, key = self.__map.pop(key)
689
+ link_prev[1] = link_next
690
+ link_next[0] = link_prev
691
+
692
+ def __iter__(self):
693
+ 'od.__iter__() <==> iter(od)'
694
+ root = self.__root
695
+ curr = root[1]
696
+ while curr is not root:
697
+ yield curr[2]
698
+ curr = curr[1]
699
+
700
+ def __reversed__(self):
701
+ 'od.__reversed__() <==> reversed(od)'
702
+ root = self.__root
703
+ curr = root[0]
704
+ while curr is not root:
705
+ yield curr[2]
706
+ curr = curr[0]
707
+
708
+ def clear(self):
709
+ 'od.clear() -> None. Remove all items from od.'
710
+ try:
711
+ for node in self.__map.itervalues():
712
+ del node[:]
713
+ root = self.__root
714
+ root[:] = [root, root, None]
715
+ self.__map.clear()
716
+ except AttributeError:
717
+ pass
718
+ dict.clear(self)
719
+
720
+ def popitem(self, last=True):
721
+ '''od.popitem() -> (k, v), return and remove a (key, value) pair.
722
+ Pairs are returned in LIFO order if last is true or FIFO order if false.
723
+
724
+ '''
725
+ if not self:
726
+ raise KeyError('dictionary is empty')
727
+ root = self.__root
728
+ if last:
729
+ link = root[0]
730
+ link_prev = link[0]
731
+ link_prev[1] = root
732
+ root[0] = link_prev
733
+ else:
734
+ link = root[1]
735
+ link_next = link[1]
736
+ root[1] = link_next
737
+ link_next[0] = root
738
+ key = link[2]
739
+ del self.__map[key]
740
+ value = dict.pop(self, key)
741
+ return key, value
742
+
743
+ # -- the following methods do not depend on the internal structure --
744
+
745
+ def keys(self):
746
+ 'od.keys() -> list of keys in od'
747
+ return list(self)
748
+
749
+ def values(self):
750
+ 'od.values() -> list of values in od'
751
+ return [self[key] for key in self]
752
+
753
+ def items(self):
754
+ 'od.items() -> list of (key, value) pairs in od'
755
+ return [(key, self[key]) for key in self]
756
+
757
+ def iterkeys(self):
758
+ 'od.iterkeys() -> an iterator over the keys in od'
759
+ return iter(self)
760
+
761
+ def itervalues(self):
762
+ 'od.itervalues -> an iterator over the values in od'
763
+ for k in self:
764
+ yield self[k]
765
+
766
+ def iteritems(self):
767
+ 'od.iteritems -> an iterator over the (key, value) items in od'
768
+ for k in self:
769
+ yield (k, self[k])
770
+
771
+ def update(*args, **kwds):
772
+ '''od.update(E, **F) -> None. Update od from dict/iterable E and F.
773
+
774
+ If E is a dict instance, does: for k in E: od[k] = E[k]
775
+ If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
776
+ Or if E is an iterable of items, does: for k, v in E: od[k] = v
777
+ In either case, this is followed by: for k, v in F.items(): od[k] = v
778
+
779
+ '''
780
+ if len(args) > 2:
781
+ raise TypeError('update() takes at most 2 positional '
782
+ 'arguments (%d given)' % (len(args),))
783
+ elif not args:
784
+ raise TypeError('update() takes at least 1 argument (0 given)')
785
+ self = args[0]
786
+ # Make progressively weaker assumptions about "other"
787
+ other = ()
788
+ if len(args) == 2:
789
+ other = args[1]
790
+ if isinstance(other, dict):
791
+ for key in other:
792
+ self[key] = other[key]
793
+ elif hasattr(other, 'keys'):
794
+ for key in other.keys():
795
+ self[key] = other[key]
796
+ else:
797
+ for key, value in other:
798
+ self[key] = value
799
+ for key, value in kwds.items():
800
+ self[key] = value
801
+
802
+ __update = update # let subclasses override update without breaking __init__
803
+
804
+ __marker = object()
805
+
806
+ def pop(self, key, default=__marker):
807
+ '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
808
+ If key is not found, d is returned if given, otherwise KeyError is raised.
809
+
810
+ '''
811
+ if key in self:
812
+ result = self[key]
813
+ del self[key]
814
+ return result
815
+ if default is self.__marker:
816
+ raise KeyError(key)
817
+ return default
818
+
819
+ def setdefault(self, key, default=None):
820
+ 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
821
+ if key in self:
822
+ return self[key]
823
+ self[key] = default
824
+ return default
825
+
826
+ def __repr__(self, _repr_running=None):
827
+ 'od.__repr__() <==> repr(od)'
828
+ if not _repr_running: _repr_running = {}
829
+ call_key = id(self), _get_ident()
830
+ if call_key in _repr_running:
831
+ return '...'
832
+ _repr_running[call_key] = 1
833
+ try:
834
+ if not self:
835
+ return '%s()' % (self.__class__.__name__,)
836
+ return '%s(%r)' % (self.__class__.__name__, self.items())
837
+ finally:
838
+ del _repr_running[call_key]
839
+
840
+ def __reduce__(self):
841
+ 'Return state information for pickling'
842
+ items = [[k, self[k]] for k in self]
843
+ inst_dict = vars(self).copy()
844
+ for k in vars(OrderedDict()):
845
+ inst_dict.pop(k, None)
846
+ if inst_dict:
847
+ return (self.__class__, (items,), inst_dict)
848
+ return self.__class__, (items,)
849
+
850
+ def copy(self):
851
+ 'od.copy() -> a shallow copy of od'
852
+ return self.__class__(self)
853
+
854
+ @classmethod
855
+ def fromkeys(cls, iterable, value=None):
856
+ '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
857
+ and values equal to v (which defaults to None).
858
+
859
+ '''
860
+ d = cls()
861
+ for key in iterable:
862
+ d[key] = value
863
+ return d
864
+
865
+ def __eq__(self, other):
866
+ '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
867
+ while comparison to a regular mapping is order-insensitive.
868
+
869
+ '''
870
+ if isinstance(other, OrderedDict):
871
+ return len(self)==len(other) and self.items() == other.items()
872
+ return dict.__eq__(self, other)
873
+
874
+ def __ne__(self, other):
875
+ return not self == other
876
+
877
+ # -- the following methods are only used in Python 2.7 --
878
+
879
+ def viewkeys(self):
880
+ "od.viewkeys() -> a set-like object providing a view on od's keys"
881
+ return KeysView(self)
882
+
883
+ def viewvalues(self):
884
+ "od.viewvalues() -> an object providing a view on od's values"
885
+ return ValuesView(self)
886
+
887
+ def viewitems(self):
888
+ "od.viewitems() -> a set-like object providing a view on od's items"
889
+ return ItemsView(self)
890
+
891
+ try:
892
+ from logging.config import BaseConfigurator, valid_ident
893
+ except ImportError: # pragma: no cover
894
+ IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)
895
+
896
+
897
+ def valid_ident(s):
898
+ m = IDENTIFIER.match(s)
899
+ if not m:
900
+ raise ValueError('Not a valid Python identifier: %r' % s)
901
+ return True
902
+
903
+
904
+ # The ConvertingXXX classes are wrappers around standard Python containers,
905
+ # and they serve to convert any suitable values in the container. The
906
+ # conversion converts base dicts, lists and tuples to their wrapped
907
+ # equivalents, whereas strings which match a conversion format are converted
908
+ # appropriately.
909
+ #
910
+ # Each wrapper should have a configurator attribute holding the actual
911
+ # configurator to use for conversion.
912
+
913
+ class ConvertingDict(dict):
914
+ """A converting dictionary wrapper."""
915
+
916
+ def __getitem__(self, key):
917
+ value = dict.__getitem__(self, key)
918
+ result = self.configurator.convert(value)
919
+ #If the converted value is different, save for next time
920
+ if value is not result:
921
+ self[key] = result
922
+ if type(result) in (ConvertingDict, ConvertingList,
923
+ ConvertingTuple):
924
+ result.parent = self
925
+ result.key = key
926
+ return result
927
+
928
+ def get(self, key, default=None):
929
+ value = dict.get(self, key, default)
930
+ result = self.configurator.convert(value)
931
+ #If the converted value is different, save for next time
932
+ if value is not result:
933
+ self[key] = result
934
+ if type(result) in (ConvertingDict, ConvertingList,
935
+ ConvertingTuple):
936
+ result.parent = self
937
+ result.key = key
938
+ return result
939
+
940
+ def pop(self, key, default=None):
941
+ value = dict.pop(self, key, default)
942
+ result = self.configurator.convert(value)
943
+ if value is not result:
944
+ if type(result) in (ConvertingDict, ConvertingList,
945
+ ConvertingTuple):
946
+ result.parent = self
947
+ result.key = key
948
+ return result
949
+
950
+ class ConvertingList(list):
951
+ """A converting list wrapper."""
952
+ def __getitem__(self, key):
953
+ value = list.__getitem__(self, key)
954
+ result = self.configurator.convert(value)
955
+ #If the converted value is different, save for next time
956
+ if value is not result:
957
+ self[key] = result
958
+ if type(result) in (ConvertingDict, ConvertingList,
959
+ ConvertingTuple):
960
+ result.parent = self
961
+ result.key = key
962
+ return result
963
+
964
+ def pop(self, idx=-1):
965
+ value = list.pop(self, idx)
966
+ result = self.configurator.convert(value)
967
+ if value is not result:
968
+ if type(result) in (ConvertingDict, ConvertingList,
969
+ ConvertingTuple):
970
+ result.parent = self
971
+ return result
972
+
973
+ class ConvertingTuple(tuple):
974
+ """A converting tuple wrapper."""
975
+ def __getitem__(self, key):
976
+ value = tuple.__getitem__(self, key)
977
+ result = self.configurator.convert(value)
978
+ if value is not result:
979
+ if type(result) in (ConvertingDict, ConvertingList,
980
+ ConvertingTuple):
981
+ result.parent = self
982
+ result.key = key
983
+ return result
984
+
985
+ class BaseConfigurator(object):
986
+ """
987
+ The configurator base class which defines some useful defaults.
988
+ """
989
+
990
+ CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$')
991
+
992
+ WORD_PATTERN = re.compile(r'^\s*(\w+)\s*')
993
+ DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*')
994
+ INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*')
995
+ DIGIT_PATTERN = re.compile(r'^\d+$')
996
+
997
+ value_converters = {
998
+ 'ext' : 'ext_convert',
999
+ 'cfg' : 'cfg_convert',
1000
+ }
1001
+
1002
+ # We might want to use a different one, e.g. importlib
1003
+ importer = staticmethod(__import__)
1004
+
1005
+ def __init__(self, config):
1006
+ self.config = ConvertingDict(config)
1007
+ self.config.configurator = self
1008
+
1009
+ def resolve(self, s):
1010
+ """
1011
+ Resolve strings to objects using standard import and attribute
1012
+ syntax.
1013
+ """
1014
+ name = s.split('.')
1015
+ used = name.pop(0)
1016
+ try:
1017
+ found = self.importer(used)
1018
+ for frag in name:
1019
+ used += '.' + frag
1020
+ try:
1021
+ found = getattr(found, frag)
1022
+ except AttributeError:
1023
+ self.importer(used)
1024
+ found = getattr(found, frag)
1025
+ return found
1026
+ except ImportError:
1027
+ e, tb = sys.exc_info()[1:]
1028
+ v = ValueError('Cannot resolve %r: %s' % (s, e))
1029
+ v.__cause__, v.__traceback__ = e, tb
1030
+ raise v
1031
+
1032
+ def ext_convert(self, value):
1033
+ """Default converter for the ext:// protocol."""
1034
+ return self.resolve(value)
1035
+
1036
+ def cfg_convert(self, value):
1037
+ """Default converter for the cfg:// protocol."""
1038
+ rest = value
1039
+ m = self.WORD_PATTERN.match(rest)
1040
+ if m is None:
1041
+ raise ValueError("Unable to convert %r" % value)
1042
+ else:
1043
+ rest = rest[m.end():]
1044
+ d = self.config[m.groups()[0]]
1045
+ #print d, rest
1046
+ while rest:
1047
+ m = self.DOT_PATTERN.match(rest)
1048
+ if m:
1049
+ d = d[m.groups()[0]]
1050
+ else:
1051
+ m = self.INDEX_PATTERN.match(rest)
1052
+ if m:
1053
+ idx = m.groups()[0]
1054
+ if not self.DIGIT_PATTERN.match(idx):
1055
+ d = d[idx]
1056
+ else:
1057
+ try:
1058
+ n = int(idx) # try as number first (most likely)
1059
+ d = d[n]
1060
+ except TypeError:
1061
+ d = d[idx]
1062
+ if m:
1063
+ rest = rest[m.end():]
1064
+ else:
1065
+ raise ValueError('Unable to convert '
1066
+ '%r at %r' % (value, rest))
1067
+ #rest should be empty
1068
+ return d
1069
+
1070
+ def convert(self, value):
1071
+ """
1072
+ Convert values to an appropriate type. dicts, lists and tuples are
1073
+ replaced by their converting alternatives. Strings are checked to
1074
+ see if they have a conversion format and are converted if they do.
1075
+ """
1076
+ if not isinstance(value, ConvertingDict) and isinstance(value, dict):
1077
+ value = ConvertingDict(value)
1078
+ value.configurator = self
1079
+ elif not isinstance(value, ConvertingList) and isinstance(value, list):
1080
+ value = ConvertingList(value)
1081
+ value.configurator = self
1082
+ elif not isinstance(value, ConvertingTuple) and\
1083
+ isinstance(value, tuple):
1084
+ value = ConvertingTuple(value)
1085
+ value.configurator = self
1086
+ elif isinstance(value, string_types):
1087
+ m = self.CONVERT_PATTERN.match(value)
1088
+ if m:
1089
+ d = m.groupdict()
1090
+ prefix = d['prefix']
1091
+ converter = self.value_converters.get(prefix, None)
1092
+ if converter:
1093
+ suffix = d['suffix']
1094
+ converter = getattr(self, converter)
1095
+ value = converter(suffix)
1096
+ return value
1097
+
1098
+ def configure_custom(self, config):
1099
+ """Configure an object with a user-supplied factory."""
1100
+ c = config.pop('()')
1101
+ if not callable(c):
1102
+ c = self.resolve(c)
1103
+ props = config.pop('.', None)
1104
+ # Check for valid identifiers
1105
+ kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
1106
+ result = c(**kwargs)
1107
+ if props:
1108
+ for name, value in props.items():
1109
+ setattr(result, name, value)
1110
+ return result
1111
+
1112
+ def as_tuple(self, value):
1113
+ """Utility function which converts lists to tuples."""
1114
+ if isinstance(value, list):
1115
+ value = tuple(value)
1116
+ return value
.venv/Lib/site-packages/pip/_vendor/distlib/database.py ADDED
@@ -0,0 +1,1350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2012-2017 The Python Software Foundation.
4
+ # See LICENSE.txt and CONTRIBUTORS.txt.
5
+ #
6
+ """PEP 376 implementation."""
7
+
8
+ from __future__ import unicode_literals
9
+
10
+ import base64
11
+ import codecs
12
+ import contextlib
13
+ import hashlib
14
+ import logging
15
+ import os
16
+ import posixpath
17
+ import sys
18
+ import zipimport
19
+
20
+ from . import DistlibException, resources
21
+ from .compat import StringIO
22
+ from .version import get_scheme, UnsupportedVersionError
23
+ from .metadata import (Metadata, METADATA_FILENAME, WHEEL_METADATA_FILENAME,
24
+ LEGACY_METADATA_FILENAME)
25
+ from .util import (parse_requirement, cached_property, parse_name_and_version,
26
+ read_exports, write_exports, CSVReader, CSVWriter)
27
+
28
+
29
+ __all__ = ['Distribution', 'BaseInstalledDistribution',
30
+ 'InstalledDistribution', 'EggInfoDistribution',
31
+ 'DistributionPath']
32
+
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+ EXPORTS_FILENAME = 'pydist-exports.json'
37
+ COMMANDS_FILENAME = 'pydist-commands.json'
38
+
39
+ DIST_FILES = ('INSTALLER', METADATA_FILENAME, 'RECORD', 'REQUESTED',
40
+ 'RESOURCES', EXPORTS_FILENAME, 'SHARED')
41
+
42
+ DISTINFO_EXT = '.dist-info'
43
+
44
+
45
+ class _Cache(object):
46
+ """
47
+ A simple cache mapping names and .dist-info paths to distributions
48
+ """
49
+ def __init__(self):
50
+ """
51
+ Initialise an instance. There is normally one for each DistributionPath.
52
+ """
53
+ self.name = {}
54
+ self.path = {}
55
+ self.generated = False
56
+
57
+ def clear(self):
58
+ """
59
+ Clear the cache, setting it to its initial state.
60
+ """
61
+ self.name.clear()
62
+ self.path.clear()
63
+ self.generated = False
64
+
65
+ def add(self, dist):
66
+ """
67
+ Add a distribution to the cache.
68
+ :param dist: The distribution to add.
69
+ """
70
+ if dist.path not in self.path:
71
+ self.path[dist.path] = dist
72
+ self.name.setdefault(dist.key, []).append(dist)
73
+
74
+
75
+ class DistributionPath(object):
76
+ """
77
+ Represents a set of distributions installed on a path (typically sys.path).
78
+ """
79
+ def __init__(self, path=None, include_egg=False):
80
+ """
81
+ Create an instance from a path, optionally including legacy (distutils/
82
+ setuptools/distribute) distributions.
83
+ :param path: The path to use, as a list of directories. If not specified,
84
+ sys.path is used.
85
+ :param include_egg: If True, this instance will look for and return legacy
86
+ distributions as well as those based on PEP 376.
87
+ """
88
+ if path is None:
89
+ path = sys.path
90
+ self.path = path
91
+ self._include_dist = True
92
+ self._include_egg = include_egg
93
+
94
+ self._cache = _Cache()
95
+ self._cache_egg = _Cache()
96
+ self._cache_enabled = True
97
+ self._scheme = get_scheme('default')
98
+
99
+ def _get_cache_enabled(self):
100
+ return self._cache_enabled
101
+
102
+ def _set_cache_enabled(self, value):
103
+ self._cache_enabled = value
104
+
105
+ cache_enabled = property(_get_cache_enabled, _set_cache_enabled)
106
+
107
+ def clear_cache(self):
108
+ """
109
+ Clears the internal cache.
110
+ """
111
+ self._cache.clear()
112
+ self._cache_egg.clear()
113
+
114
+
115
+ def _yield_distributions(self):
116
+ """
117
+ Yield .dist-info and/or .egg(-info) distributions.
118
+ """
119
+ # We need to check if we've seen some resources already, because on
120
+ # some Linux systems (e.g. some Debian/Ubuntu variants) there are
121
+ # symlinks which alias other files in the environment.
122
+ seen = set()
123
+ for path in self.path:
124
+ finder = resources.finder_for_path(path)
125
+ if finder is None:
126
+ continue
127
+ r = finder.find('')
128
+ if not r or not r.is_container:
129
+ continue
130
+ rset = sorted(r.resources)
131
+ for entry in rset:
132
+ r = finder.find(entry)
133
+ if not r or r.path in seen:
134
+ continue
135
+ try:
136
+ if self._include_dist and entry.endswith(DISTINFO_EXT):
137
+ possible_filenames = [METADATA_FILENAME,
138
+ WHEEL_METADATA_FILENAME,
139
+ LEGACY_METADATA_FILENAME]
140
+ for metadata_filename in possible_filenames:
141
+ metadata_path = posixpath.join(entry, metadata_filename)
142
+ pydist = finder.find(metadata_path)
143
+ if pydist:
144
+ break
145
+ else:
146
+ continue
147
+
148
+ with contextlib.closing(pydist.as_stream()) as stream:
149
+ metadata = Metadata(fileobj=stream, scheme='legacy')
150
+ logger.debug('Found %s', r.path)
151
+ seen.add(r.path)
152
+ yield new_dist_class(r.path, metadata=metadata,
153
+ env=self)
154
+ elif self._include_egg and entry.endswith(('.egg-info',
155
+ '.egg')):
156
+ logger.debug('Found %s', r.path)
157
+ seen.add(r.path)
158
+ yield old_dist_class(r.path, self)
159
+ except Exception as e:
160
+ msg = 'Unable to read distribution at %s, perhaps due to bad metadata: %s'
161
+ logger.warning(msg, r.path, e)
162
+ import warnings
163
+ warnings.warn(msg % (r.path, e), stacklevel=2)
164
+
165
+ def _generate_cache(self):
166
+ """
167
+ Scan the path for distributions and populate the cache with
168
+ those that are found.
169
+ """
170
+ gen_dist = not self._cache.generated
171
+ gen_egg = self._include_egg and not self._cache_egg.generated
172
+ if gen_dist or gen_egg:
173
+ for dist in self._yield_distributions():
174
+ if isinstance(dist, InstalledDistribution):
175
+ self._cache.add(dist)
176
+ else:
177
+ self._cache_egg.add(dist)
178
+
179
+ if gen_dist:
180
+ self._cache.generated = True
181
+ if gen_egg:
182
+ self._cache_egg.generated = True
183
+
184
+ @classmethod
185
+ def distinfo_dirname(cls, name, version):
186
+ """
187
+ The *name* and *version* parameters are converted into their
188
+ filename-escaped form, i.e. any ``'-'`` characters are replaced
189
+ with ``'_'`` other than the one in ``'dist-info'`` and the one
190
+ separating the name from the version number.
191
+
192
+ :parameter name: is converted to a standard distribution name by replacing
193
+ any runs of non- alphanumeric characters with a single
194
+ ``'-'``.
195
+ :type name: string
196
+ :parameter version: is converted to a standard version string. Spaces
197
+ become dots, and all other non-alphanumeric characters
198
+ (except dots) become dashes, with runs of multiple
199
+ dashes condensed to a single dash.
200
+ :type version: string
201
+ :returns: directory name
202
+ :rtype: string"""
203
+ name = name.replace('-', '_')
204
+ return '-'.join([name, version]) + DISTINFO_EXT
205
+
206
+ def get_distributions(self):
207
+ """
208
+ Provides an iterator that looks for distributions and returns
209
+ :class:`InstalledDistribution` or
210
+ :class:`EggInfoDistribution` instances for each one of them.
211
+
212
+ :rtype: iterator of :class:`InstalledDistribution` and
213
+ :class:`EggInfoDistribution` instances
214
+ """
215
+ if not self._cache_enabled:
216
+ for dist in self._yield_distributions():
217
+ yield dist
218
+ else:
219
+ self._generate_cache()
220
+
221
+ for dist in self._cache.path.values():
222
+ yield dist
223
+
224
+ if self._include_egg:
225
+ for dist in self._cache_egg.path.values():
226
+ yield dist
227
+
228
+ def get_distribution(self, name):
229
+ """
230
+ Looks for a named distribution on the path.
231
+
232
+ This function only returns the first result found, as no more than one
233
+ value is expected. If nothing is found, ``None`` is returned.
234
+
235
+ :rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution`
236
+ or ``None``
237
+ """
238
+ result = None
239
+ name = name.lower()
240
+ if not self._cache_enabled:
241
+ for dist in self._yield_distributions():
242
+ if dist.key == name:
243
+ result = dist
244
+ break
245
+ else:
246
+ self._generate_cache()
247
+
248
+ if name in self._cache.name:
249
+ result = self._cache.name[name][0]
250
+ elif self._include_egg and name in self._cache_egg.name:
251
+ result = self._cache_egg.name[name][0]
252
+ return result
253
+
254
+ def provides_distribution(self, name, version=None):
255
+ """
256
+ Iterates over all distributions to find which distributions provide *name*.
257
+ If a *version* is provided, it will be used to filter the results.
258
+
259
+ This function only returns the first result found, since no more than
260
+ one values are expected. If the directory is not found, returns ``None``.
261
+
262
+ :parameter version: a version specifier that indicates the version
263
+ required, conforming to the format in ``PEP-345``
264
+
265
+ :type name: string
266
+ :type version: string
267
+ """
268
+ matcher = None
269
+ if version is not None:
270
+ try:
271
+ matcher = self._scheme.matcher('%s (%s)' % (name, version))
272
+ except ValueError:
273
+ raise DistlibException('invalid name or version: %r, %r' %
274
+ (name, version))
275
+
276
+ for dist in self.get_distributions():
277
+ # We hit a problem on Travis where enum34 was installed and doesn't
278
+ # have a provides attribute ...
279
+ if not hasattr(dist, 'provides'):
280
+ logger.debug('No "provides": %s', dist)
281
+ else:
282
+ provided = dist.provides
283
+
284
+ for p in provided:
285
+ p_name, p_ver = parse_name_and_version(p)
286
+ if matcher is None:
287
+ if p_name == name:
288
+ yield dist
289
+ break
290
+ else:
291
+ if p_name == name and matcher.match(p_ver):
292
+ yield dist
293
+ break
294
+
295
+ def get_file_path(self, name, relative_path):
296
+ """
297
+ Return the path to a resource file.
298
+ """
299
+ dist = self.get_distribution(name)
300
+ if dist is None:
301
+ raise LookupError('no distribution named %r found' % name)
302
+ return dist.get_resource_path(relative_path)
303
+
304
+ def get_exported_entries(self, category, name=None):
305
+ """
306
+ Return all of the exported entries in a particular category.
307
+
308
+ :param category: The category to search for entries.
309
+ :param name: If specified, only entries with that name are returned.
310
+ """
311
+ for dist in self.get_distributions():
312
+ r = dist.exports
313
+ if category in r:
314
+ d = r[category]
315
+ if name is not None:
316
+ if name in d:
317
+ yield d[name]
318
+ else:
319
+ for v in d.values():
320
+ yield v
321
+
322
+
323
+ class Distribution(object):
324
+ """
325
+ A base class for distributions, whether installed or from indexes.
326
+ Either way, it must have some metadata, so that's all that's needed
327
+ for construction.
328
+ """
329
+
330
+ build_time_dependency = False
331
+ """
332
+ Set to True if it's known to be only a build-time dependency (i.e.
333
+ not needed after installation).
334
+ """
335
+
336
+ requested = False
337
+ """A boolean that indicates whether the ``REQUESTED`` metadata file is
338
+ present (in other words, whether the package was installed by user
339
+ request or it was installed as a dependency)."""
340
+
341
+ def __init__(self, metadata):
342
+ """
343
+ Initialise an instance.
344
+ :param metadata: The instance of :class:`Metadata` describing this
345
+ distribution.
346
+ """
347
+ self.metadata = metadata
348
+ self.name = metadata.name
349
+ self.key = self.name.lower() # for case-insensitive comparisons
350
+ self.version = metadata.version
351
+ self.locator = None
352
+ self.digest = None
353
+ self.extras = None # additional features requested
354
+ self.context = None # environment marker overrides
355
+ self.download_urls = set()
356
+ self.digests = {}
357
+
358
+ @property
359
+ def source_url(self):
360
+ """
361
+ The source archive download URL for this distribution.
362
+ """
363
+ return self.metadata.source_url
364
+
365
+ download_url = source_url # Backward compatibility
366
+
367
+ @property
368
+ def name_and_version(self):
369
+ """
370
+ A utility property which displays the name and version in parentheses.
371
+ """
372
+ return '%s (%s)' % (self.name, self.version)
373
+
374
+ @property
375
+ def provides(self):
376
+ """
377
+ A set of distribution names and versions provided by this distribution.
378
+ :return: A set of "name (version)" strings.
379
+ """
380
+ plist = self.metadata.provides
381
+ s = '%s (%s)' % (self.name, self.version)
382
+ if s not in plist:
383
+ plist.append(s)
384
+ return plist
385
+
386
+ def _get_requirements(self, req_attr):
387
+ md = self.metadata
388
+ reqts = getattr(md, req_attr)
389
+ logger.debug('%s: got requirements %r from metadata: %r', self.name, req_attr,
390
+ reqts)
391
+ return set(md.get_requirements(reqts, extras=self.extras,
392
+ env=self.context))
393
+
394
+ @property
395
+ def run_requires(self):
396
+ return self._get_requirements('run_requires')
397
+
398
+ @property
399
+ def meta_requires(self):
400
+ return self._get_requirements('meta_requires')
401
+
402
+ @property
403
+ def build_requires(self):
404
+ return self._get_requirements('build_requires')
405
+
406
+ @property
407
+ def test_requires(self):
408
+ return self._get_requirements('test_requires')
409
+
410
+ @property
411
+ def dev_requires(self):
412
+ return self._get_requirements('dev_requires')
413
+
414
+ def matches_requirement(self, req):
415
+ """
416
+ Say if this instance matches (fulfills) a requirement.
417
+ :param req: The requirement to match.
418
+ :rtype req: str
419
+ :return: True if it matches, else False.
420
+ """
421
+ # Requirement may contain extras - parse to lose those
422
+ # from what's passed to the matcher
423
+ r = parse_requirement(req)
424
+ scheme = get_scheme(self.metadata.scheme)
425
+ try:
426
+ matcher = scheme.matcher(r.requirement)
427
+ except UnsupportedVersionError:
428
+ # XXX compat-mode if cannot read the version
429
+ logger.warning('could not read version %r - using name only',
430
+ req)
431
+ name = req.split()[0]
432
+ matcher = scheme.matcher(name)
433
+
434
+ name = matcher.key # case-insensitive
435
+
436
+ result = False
437
+ for p in self.provides:
438
+ p_name, p_ver = parse_name_and_version(p)
439
+ if p_name != name:
440
+ continue
441
+ try:
442
+ result = matcher.match(p_ver)
443
+ break
444
+ except UnsupportedVersionError:
445
+ pass
446
+ return result
447
+
448
+ def __repr__(self):
449
+ """
450
+ Return a textual representation of this instance,
451
+ """
452
+ if self.source_url:
453
+ suffix = ' [%s]' % self.source_url
454
+ else:
455
+ suffix = ''
456
+ return '<Distribution %s (%s)%s>' % (self.name, self.version, suffix)
457
+
458
+ def __eq__(self, other):
459
+ """
460
+ See if this distribution is the same as another.
461
+ :param other: The distribution to compare with. To be equal to one
462
+ another. distributions must have the same type, name,
463
+ version and source_url.
464
+ :return: True if it is the same, else False.
465
+ """
466
+ if type(other) is not type(self):
467
+ result = False
468
+ else:
469
+ result = (self.name == other.name and
470
+ self.version == other.version and
471
+ self.source_url == other.source_url)
472
+ return result
473
+
474
+ def __hash__(self):
475
+ """
476
+ Compute hash in a way which matches the equality test.
477
+ """
478
+ return hash(self.name) + hash(self.version) + hash(self.source_url)
479
+
480
+
481
+ class BaseInstalledDistribution(Distribution):
482
+ """
483
+ This is the base class for installed distributions (whether PEP 376 or
484
+ legacy).
485
+ """
486
+
487
+ hasher = None
488
+
489
+ def __init__(self, metadata, path, env=None):
490
+ """
491
+ Initialise an instance.
492
+ :param metadata: An instance of :class:`Metadata` which describes the
493
+ distribution. This will normally have been initialised
494
+ from a metadata file in the ``path``.
495
+ :param path: The path of the ``.dist-info`` or ``.egg-info``
496
+ directory for the distribution.
497
+ :param env: This is normally the :class:`DistributionPath`
498
+ instance where this distribution was found.
499
+ """
500
+ super(BaseInstalledDistribution, self).__init__(metadata)
501
+ self.path = path
502
+ self.dist_path = env
503
+
504
+ def get_hash(self, data, hasher=None):
505
+ """
506
+ Get the hash of some data, using a particular hash algorithm, if
507
+ specified.
508
+
509
+ :param data: The data to be hashed.
510
+ :type data: bytes
511
+ :param hasher: The name of a hash implementation, supported by hashlib,
512
+ or ``None``. Examples of valid values are ``'sha1'``,
513
+ ``'sha224'``, ``'sha384'``, '``sha256'``, ``'md5'`` and
514
+ ``'sha512'``. If no hasher is specified, the ``hasher``
515
+ attribute of the :class:`InstalledDistribution` instance
516
+ is used. If the hasher is determined to be ``None``, MD5
517
+ is used as the hashing algorithm.
518
+ :returns: The hash of the data. If a hasher was explicitly specified,
519
+ the returned hash will be prefixed with the specified hasher
520
+ followed by '='.
521
+ :rtype: str
522
+ """
523
+ if hasher is None:
524
+ hasher = self.hasher
525
+ if hasher is None:
526
+ hasher = hashlib.md5
527
+ prefix = ''
528
+ else:
529
+ hasher = getattr(hashlib, hasher)
530
+ prefix = '%s=' % self.hasher
531
+ digest = hasher(data).digest()
532
+ digest = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii')
533
+ return '%s%s' % (prefix, digest)
534
+
535
+
536
+ class InstalledDistribution(BaseInstalledDistribution):
537
+ """
538
+ Created with the *path* of the ``.dist-info`` directory provided to the
539
+ constructor. It reads the metadata contained in ``pydist.json`` when it is
540
+ instantiated., or uses a passed in Metadata instance (useful for when
541
+ dry-run mode is being used).
542
+ """
543
+
544
+ hasher = 'sha256'
545
+
546
+ def __init__(self, path, metadata=None, env=None):
547
+ self.modules = []
548
+ self.finder = finder = resources.finder_for_path(path)
549
+ if finder is None:
550
+ raise ValueError('finder unavailable for %s' % path)
551
+ if env and env._cache_enabled and path in env._cache.path:
552
+ metadata = env._cache.path[path].metadata
553
+ elif metadata is None:
554
+ r = finder.find(METADATA_FILENAME)
555
+ # Temporary - for Wheel 0.23 support
556
+ if r is None:
557
+ r = finder.find(WHEEL_METADATA_FILENAME)
558
+ # Temporary - for legacy support
559
+ if r is None:
560
+ r = finder.find(LEGACY_METADATA_FILENAME)
561
+ if r is None:
562
+ raise ValueError('no %s found in %s' % (METADATA_FILENAME,
563
+ path))
564
+ with contextlib.closing(r.as_stream()) as stream:
565
+ metadata = Metadata(fileobj=stream, scheme='legacy')
566
+
567
+ super(InstalledDistribution, self).__init__(metadata, path, env)
568
+
569
+ if env and env._cache_enabled:
570
+ env._cache.add(self)
571
+
572
+ r = finder.find('REQUESTED')
573
+ self.requested = r is not None
574
+ p = os.path.join(path, 'top_level.txt')
575
+ if os.path.exists(p):
576
+ with open(p, 'rb') as f:
577
+ data = f.read().decode('utf-8')
578
+ self.modules = data.splitlines()
579
+
580
+ def __repr__(self):
581
+ return '<InstalledDistribution %r %s at %r>' % (
582
+ self.name, self.version, self.path)
583
+
584
+ def __str__(self):
585
+ return "%s %s" % (self.name, self.version)
586
+
587
+ def _get_records(self):
588
+ """
589
+ Get the list of installed files for the distribution
590
+ :return: A list of tuples of path, hash and size. Note that hash and
591
+ size might be ``None`` for some entries. The path is exactly
592
+ as stored in the file (which is as in PEP 376).
593
+ """
594
+ results = []
595
+ r = self.get_distinfo_resource('RECORD')
596
+ with contextlib.closing(r.as_stream()) as stream:
597
+ with CSVReader(stream=stream) as record_reader:
598
+ # Base location is parent dir of .dist-info dir
599
+ #base_location = os.path.dirname(self.path)
600
+ #base_location = os.path.abspath(base_location)
601
+ for row in record_reader:
602
+ missing = [None for i in range(len(row), 3)]
603
+ path, checksum, size = row + missing
604
+ #if not os.path.isabs(path):
605
+ # path = path.replace('/', os.sep)
606
+ # path = os.path.join(base_location, path)
607
+ results.append((path, checksum, size))
608
+ return results
609
+
610
+ @cached_property
611
+ def exports(self):
612
+ """
613
+ Return the information exported by this distribution.
614
+ :return: A dictionary of exports, mapping an export category to a dict
615
+ of :class:`ExportEntry` instances describing the individual
616
+ export entries, and keyed by name.
617
+ """
618
+ result = {}
619
+ r = self.get_distinfo_resource(EXPORTS_FILENAME)
620
+ if r:
621
+ result = self.read_exports()
622
+ return result
623
+
624
+ def read_exports(self):
625
+ """
626
+ Read exports data from a file in .ini format.
627
+
628
+ :return: A dictionary of exports, mapping an export category to a list
629
+ of :class:`ExportEntry` instances describing the individual
630
+ export entries.
631
+ """
632
+ result = {}
633
+ r = self.get_distinfo_resource(EXPORTS_FILENAME)
634
+ if r:
635
+ with contextlib.closing(r.as_stream()) as stream:
636
+ result = read_exports(stream)
637
+ return result
638
+
639
+ def write_exports(self, exports):
640
+ """
641
+ Write a dictionary of exports to a file in .ini format.
642
+ :param exports: A dictionary of exports, mapping an export category to
643
+ a list of :class:`ExportEntry` instances describing the
644
+ individual export entries.
645
+ """
646
+ rf = self.get_distinfo_file(EXPORTS_FILENAME)
647
+ with open(rf, 'w') as f:
648
+ write_exports(exports, f)
649
+
650
+ def get_resource_path(self, relative_path):
651
+ """
652
+ NOTE: This API may change in the future.
653
+
654
+ Return the absolute path to a resource file with the given relative
655
+ path.
656
+
657
+ :param relative_path: The path, relative to .dist-info, of the resource
658
+ of interest.
659
+ :return: The absolute path where the resource is to be found.
660
+ """
661
+ r = self.get_distinfo_resource('RESOURCES')
662
+ with contextlib.closing(r.as_stream()) as stream:
663
+ with CSVReader(stream=stream) as resources_reader:
664
+ for relative, destination in resources_reader:
665
+ if relative == relative_path:
666
+ return destination
667
+ raise KeyError('no resource file with relative path %r '
668
+ 'is installed' % relative_path)
669
+
670
+ def list_installed_files(self):
671
+ """
672
+ Iterates over the ``RECORD`` entries and returns a tuple
673
+ ``(path, hash, size)`` for each line.
674
+
675
+ :returns: iterator of (path, hash, size)
676
+ """
677
+ for result in self._get_records():
678
+ yield result
679
+
680
+ def write_installed_files(self, paths, prefix, dry_run=False):
681
+ """
682
+ Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any
683
+ existing ``RECORD`` file is silently overwritten.
684
+
685
+ prefix is used to determine when to write absolute paths.
686
+ """
687
+ prefix = os.path.join(prefix, '')
688
+ base = os.path.dirname(self.path)
689
+ base_under_prefix = base.startswith(prefix)
690
+ base = os.path.join(base, '')
691
+ record_path = self.get_distinfo_file('RECORD')
692
+ logger.info('creating %s', record_path)
693
+ if dry_run:
694
+ return None
695
+ with CSVWriter(record_path) as writer:
696
+ for path in paths:
697
+ if os.path.isdir(path) or path.endswith(('.pyc', '.pyo')):
698
+ # do not put size and hash, as in PEP-376
699
+ hash_value = size = ''
700
+ else:
701
+ size = '%d' % os.path.getsize(path)
702
+ with open(path, 'rb') as fp:
703
+ hash_value = self.get_hash(fp.read())
704
+ if path.startswith(base) or (base_under_prefix and
705
+ path.startswith(prefix)):
706
+ path = os.path.relpath(path, base)
707
+ writer.writerow((path, hash_value, size))
708
+
709
+ # add the RECORD file itself
710
+ if record_path.startswith(base):
711
+ record_path = os.path.relpath(record_path, base)
712
+ writer.writerow((record_path, '', ''))
713
+ return record_path
714
+
715
+ def check_installed_files(self):
716
+ """
717
+ Checks that the hashes and sizes of the files in ``RECORD`` are
718
+ matched by the files themselves. Returns a (possibly empty) list of
719
+ mismatches. Each entry in the mismatch list will be a tuple consisting
720
+ of the path, 'exists', 'size' or 'hash' according to what didn't match
721
+ (existence is checked first, then size, then hash), the expected
722
+ value and the actual value.
723
+ """
724
+ mismatches = []
725
+ base = os.path.dirname(self.path)
726
+ record_path = self.get_distinfo_file('RECORD')
727
+ for path, hash_value, size in self.list_installed_files():
728
+ if not os.path.isabs(path):
729
+ path = os.path.join(base, path)
730
+ if path == record_path:
731
+ continue
732
+ if not os.path.exists(path):
733
+ mismatches.append((path, 'exists', True, False))
734
+ elif os.path.isfile(path):
735
+ actual_size = str(os.path.getsize(path))
736
+ if size and actual_size != size:
737
+ mismatches.append((path, 'size', size, actual_size))
738
+ elif hash_value:
739
+ if '=' in hash_value:
740
+ hasher = hash_value.split('=', 1)[0]
741
+ else:
742
+ hasher = None
743
+
744
+ with open(path, 'rb') as f:
745
+ actual_hash = self.get_hash(f.read(), hasher)
746
+ if actual_hash != hash_value:
747
+ mismatches.append((path, 'hash', hash_value, actual_hash))
748
+ return mismatches
749
+
750
+ @cached_property
751
+ def shared_locations(self):
752
+ """
753
+ A dictionary of shared locations whose keys are in the set 'prefix',
754
+ 'purelib', 'platlib', 'scripts', 'headers', 'data' and 'namespace'.
755
+ The corresponding value is the absolute path of that category for
756
+ this distribution, and takes into account any paths selected by the
757
+ user at installation time (e.g. via command-line arguments). In the
758
+ case of the 'namespace' key, this would be a list of absolute paths
759
+ for the roots of namespace packages in this distribution.
760
+
761
+ The first time this property is accessed, the relevant information is
762
+ read from the SHARED file in the .dist-info directory.
763
+ """
764
+ result = {}
765
+ shared_path = os.path.join(self.path, 'SHARED')
766
+ if os.path.isfile(shared_path):
767
+ with codecs.open(shared_path, 'r', encoding='utf-8') as f:
768
+ lines = f.read().splitlines()
769
+ for line in lines:
770
+ key, value = line.split('=', 1)
771
+ if key == 'namespace':
772
+ result.setdefault(key, []).append(value)
773
+ else:
774
+ result[key] = value
775
+ return result
776
+
777
+ def write_shared_locations(self, paths, dry_run=False):
778
+ """
779
+ Write shared location information to the SHARED file in .dist-info.
780
+ :param paths: A dictionary as described in the documentation for
781
+ :meth:`shared_locations`.
782
+ :param dry_run: If True, the action is logged but no file is actually
783
+ written.
784
+ :return: The path of the file written to.
785
+ """
786
+ shared_path = os.path.join(self.path, 'SHARED')
787
+ logger.info('creating %s', shared_path)
788
+ if dry_run:
789
+ return None
790
+ lines = []
791
+ for key in ('prefix', 'lib', 'headers', 'scripts', 'data'):
792
+ path = paths[key]
793
+ if os.path.isdir(paths[key]):
794
+ lines.append('%s=%s' % (key, path))
795
+ for ns in paths.get('namespace', ()):
796
+ lines.append('namespace=%s' % ns)
797
+
798
+ with codecs.open(shared_path, 'w', encoding='utf-8') as f:
799
+ f.write('\n'.join(lines))
800
+ return shared_path
801
+
802
+ def get_distinfo_resource(self, path):
803
+ if path not in DIST_FILES:
804
+ raise DistlibException('invalid path for a dist-info file: '
805
+ '%r at %r' % (path, self.path))
806
+ finder = resources.finder_for_path(self.path)
807
+ if finder is None:
808
+ raise DistlibException('Unable to get a finder for %s' % self.path)
809
+ return finder.find(path)
810
+
811
+ def get_distinfo_file(self, path):
812
+ """
813
+ Returns a path located under the ``.dist-info`` directory. Returns a
814
+ string representing the path.
815
+
816
+ :parameter path: a ``'/'``-separated path relative to the
817
+ ``.dist-info`` directory or an absolute path;
818
+ If *path* is an absolute path and doesn't start
819
+ with the ``.dist-info`` directory path,
820
+ a :class:`DistlibException` is raised
821
+ :type path: str
822
+ :rtype: str
823
+ """
824
+ # Check if it is an absolute path # XXX use relpath, add tests
825
+ if path.find(os.sep) >= 0:
826
+ # it's an absolute path?
827
+ distinfo_dirname, path = path.split(os.sep)[-2:]
828
+ if distinfo_dirname != self.path.split(os.sep)[-1]:
829
+ raise DistlibException(
830
+ 'dist-info file %r does not belong to the %r %s '
831
+ 'distribution' % (path, self.name, self.version))
832
+
833
+ # The file must be relative
834
+ if path not in DIST_FILES:
835
+ raise DistlibException('invalid path for a dist-info file: '
836
+ '%r at %r' % (path, self.path))
837
+
838
+ return os.path.join(self.path, path)
839
+
840
+ def list_distinfo_files(self):
841
+ """
842
+ Iterates over the ``RECORD`` entries and returns paths for each line if
843
+ the path is pointing to a file located in the ``.dist-info`` directory
844
+ or one of its subdirectories.
845
+
846
+ :returns: iterator of paths
847
+ """
848
+ base = os.path.dirname(self.path)
849
+ for path, checksum, size in self._get_records():
850
+ # XXX add separator or use real relpath algo
851
+ if not os.path.isabs(path):
852
+ path = os.path.join(base, path)
853
+ if path.startswith(self.path):
854
+ yield path
855
+
856
+ def __eq__(self, other):
857
+ return (isinstance(other, InstalledDistribution) and
858
+ self.path == other.path)
859
+
860
+ # See http://docs.python.org/reference/datamodel#object.__hash__
861
+ __hash__ = object.__hash__
862
+
863
+
864
+ class EggInfoDistribution(BaseInstalledDistribution):
865
+ """Created with the *path* of the ``.egg-info`` directory or file provided
866
+ to the constructor. It reads the metadata contained in the file itself, or
867
+ if the given path happens to be a directory, the metadata is read from the
868
+ file ``PKG-INFO`` under that directory."""
869
+
870
+ requested = True # as we have no way of knowing, assume it was
871
+ shared_locations = {}
872
+
873
+ def __init__(self, path, env=None):
874
+ def set_name_and_version(s, n, v):
875
+ s.name = n
876
+ s.key = n.lower() # for case-insensitive comparisons
877
+ s.version = v
878
+
879
+ self.path = path
880
+ self.dist_path = env
881
+ if env and env._cache_enabled and path in env._cache_egg.path:
882
+ metadata = env._cache_egg.path[path].metadata
883
+ set_name_and_version(self, metadata.name, metadata.version)
884
+ else:
885
+ metadata = self._get_metadata(path)
886
+
887
+ # Need to be set before caching
888
+ set_name_and_version(self, metadata.name, metadata.version)
889
+
890
+ if env and env._cache_enabled:
891
+ env._cache_egg.add(self)
892
+ super(EggInfoDistribution, self).__init__(metadata, path, env)
893
+
894
+ def _get_metadata(self, path):
895
+ requires = None
896
+
897
+ def parse_requires_data(data):
898
+ """Create a list of dependencies from a requires.txt file.
899
+
900
+ *data*: the contents of a setuptools-produced requires.txt file.
901
+ """
902
+ reqs = []
903
+ lines = data.splitlines()
904
+ for line in lines:
905
+ line = line.strip()
906
+ if line.startswith('['):
907
+ logger.warning('Unexpected line: quitting requirement scan: %r',
908
+ line)
909
+ break
910
+ r = parse_requirement(line)
911
+ if not r:
912
+ logger.warning('Not recognised as a requirement: %r', line)
913
+ continue
914
+ if r.extras:
915
+ logger.warning('extra requirements in requires.txt are '
916
+ 'not supported')
917
+ if not r.constraints:
918
+ reqs.append(r.name)
919
+ else:
920
+ cons = ', '.join('%s%s' % c for c in r.constraints)
921
+ reqs.append('%s (%s)' % (r.name, cons))
922
+ return reqs
923
+
924
+ def parse_requires_path(req_path):
925
+ """Create a list of dependencies from a requires.txt file.
926
+
927
+ *req_path*: the path to a setuptools-produced requires.txt file.
928
+ """
929
+
930
+ reqs = []
931
+ try:
932
+ with codecs.open(req_path, 'r', 'utf-8') as fp:
933
+ reqs = parse_requires_data(fp.read())
934
+ except IOError:
935
+ pass
936
+ return reqs
937
+
938
+ tl_path = tl_data = None
939
+ if path.endswith('.egg'):
940
+ if os.path.isdir(path):
941
+ p = os.path.join(path, 'EGG-INFO')
942
+ meta_path = os.path.join(p, 'PKG-INFO')
943
+ metadata = Metadata(path=meta_path, scheme='legacy')
944
+ req_path = os.path.join(p, 'requires.txt')
945
+ tl_path = os.path.join(p, 'top_level.txt')
946
+ requires = parse_requires_path(req_path)
947
+ else:
948
+ # FIXME handle the case where zipfile is not available
949
+ zipf = zipimport.zipimporter(path)
950
+ fileobj = StringIO(
951
+ zipf.get_data('EGG-INFO/PKG-INFO').decode('utf8'))
952
+ metadata = Metadata(fileobj=fileobj, scheme='legacy')
953
+ try:
954
+ data = zipf.get_data('EGG-INFO/requires.txt')
955
+ tl_data = zipf.get_data('EGG-INFO/top_level.txt').decode('utf-8')
956
+ requires = parse_requires_data(data.decode('utf-8'))
957
+ except IOError:
958
+ requires = None
959
+ elif path.endswith('.egg-info'):
960
+ if os.path.isdir(path):
961
+ req_path = os.path.join(path, 'requires.txt')
962
+ requires = parse_requires_path(req_path)
963
+ path = os.path.join(path, 'PKG-INFO')
964
+ tl_path = os.path.join(path, 'top_level.txt')
965
+ metadata = Metadata(path=path, scheme='legacy')
966
+ else:
967
+ raise DistlibException('path must end with .egg-info or .egg, '
968
+ 'got %r' % path)
969
+
970
+ if requires:
971
+ metadata.add_requirements(requires)
972
+ # look for top-level modules in top_level.txt, if present
973
+ if tl_data is None:
974
+ if tl_path is not None and os.path.exists(tl_path):
975
+ with open(tl_path, 'rb') as f:
976
+ tl_data = f.read().decode('utf-8')
977
+ if not tl_data:
978
+ tl_data = []
979
+ else:
980
+ tl_data = tl_data.splitlines()
981
+ self.modules = tl_data
982
+ return metadata
983
+
984
+ def __repr__(self):
985
+ return '<EggInfoDistribution %r %s at %r>' % (
986
+ self.name, self.version, self.path)
987
+
988
+ def __str__(self):
989
+ return "%s %s" % (self.name, self.version)
990
+
991
+ def check_installed_files(self):
992
+ """
993
+ Checks that the hashes and sizes of the files in ``RECORD`` are
994
+ matched by the files themselves. Returns a (possibly empty) list of
995
+ mismatches. Each entry in the mismatch list will be a tuple consisting
996
+ of the path, 'exists', 'size' or 'hash' according to what didn't match
997
+ (existence is checked first, then size, then hash), the expected
998
+ value and the actual value.
999
+ """
1000
+ mismatches = []
1001
+ record_path = os.path.join(self.path, 'installed-files.txt')
1002
+ if os.path.exists(record_path):
1003
+ for path, _, _ in self.list_installed_files():
1004
+ if path == record_path:
1005
+ continue
1006
+ if not os.path.exists(path):
1007
+ mismatches.append((path, 'exists', True, False))
1008
+ return mismatches
1009
+
1010
+ def list_installed_files(self):
1011
+ """
1012
+ Iterates over the ``installed-files.txt`` entries and returns a tuple
1013
+ ``(path, hash, size)`` for each line.
1014
+
1015
+ :returns: a list of (path, hash, size)
1016
+ """
1017
+
1018
+ def _md5(path):
1019
+ f = open(path, 'rb')
1020
+ try:
1021
+ content = f.read()
1022
+ finally:
1023
+ f.close()
1024
+ return hashlib.md5(content).hexdigest()
1025
+
1026
+ def _size(path):
1027
+ return os.stat(path).st_size
1028
+
1029
+ record_path = os.path.join(self.path, 'installed-files.txt')
1030
+ result = []
1031
+ if os.path.exists(record_path):
1032
+ with codecs.open(record_path, 'r', encoding='utf-8') as f:
1033
+ for line in f:
1034
+ line = line.strip()
1035
+ p = os.path.normpath(os.path.join(self.path, line))
1036
+ # "./" is present as a marker between installed files
1037
+ # and installation metadata files
1038
+ if not os.path.exists(p):
1039
+ logger.warning('Non-existent file: %s', p)
1040
+ if p.endswith(('.pyc', '.pyo')):
1041
+ continue
1042
+ #otherwise fall through and fail
1043
+ if not os.path.isdir(p):
1044
+ result.append((p, _md5(p), _size(p)))
1045
+ result.append((record_path, None, None))
1046
+ return result
1047
+
1048
+ def list_distinfo_files(self, absolute=False):
1049
+ """
1050
+ Iterates over the ``installed-files.txt`` entries and returns paths for
1051
+ each line if the path is pointing to a file located in the
1052
+ ``.egg-info`` directory or one of its subdirectories.
1053
+
1054
+ :parameter absolute: If *absolute* is ``True``, each returned path is
1055
+ transformed into a local absolute path. Otherwise the
1056
+ raw value from ``installed-files.txt`` is returned.
1057
+ :type absolute: boolean
1058
+ :returns: iterator of paths
1059
+ """
1060
+ record_path = os.path.join(self.path, 'installed-files.txt')
1061
+ if os.path.exists(record_path):
1062
+ skip = True
1063
+ with codecs.open(record_path, 'r', encoding='utf-8') as f:
1064
+ for line in f:
1065
+ line = line.strip()
1066
+ if line == './':
1067
+ skip = False
1068
+ continue
1069
+ if not skip:
1070
+ p = os.path.normpath(os.path.join(self.path, line))
1071
+ if p.startswith(self.path):
1072
+ if absolute:
1073
+ yield p
1074
+ else:
1075
+ yield line
1076
+
1077
+ def __eq__(self, other):
1078
+ return (isinstance(other, EggInfoDistribution) and
1079
+ self.path == other.path)
1080
+
1081
+ # See http://docs.python.org/reference/datamodel#object.__hash__
1082
+ __hash__ = object.__hash__
1083
+
1084
+ new_dist_class = InstalledDistribution
1085
+ old_dist_class = EggInfoDistribution
1086
+
1087
+
1088
+ class DependencyGraph(object):
1089
+ """
1090
+ Represents a dependency graph between distributions.
1091
+
1092
+ The dependency relationships are stored in an ``adjacency_list`` that maps
1093
+ distributions to a list of ``(other, label)`` tuples where ``other``
1094
+ is a distribution and the edge is labeled with ``label`` (i.e. the version
1095
+ specifier, if such was provided). Also, for more efficient traversal, for
1096
+ every distribution ``x``, a list of predecessors is kept in
1097
+ ``reverse_list[x]``. An edge from distribution ``a`` to
1098
+ distribution ``b`` means that ``a`` depends on ``b``. If any missing
1099
+ dependencies are found, they are stored in ``missing``, which is a
1100
+ dictionary that maps distributions to a list of requirements that were not
1101
+ provided by any other distributions.
1102
+ """
1103
+
1104
+ def __init__(self):
1105
+ self.adjacency_list = {}
1106
+ self.reverse_list = {}
1107
+ self.missing = {}
1108
+
1109
+ def add_distribution(self, distribution):
1110
+ """Add the *distribution* to the graph.
1111
+
1112
+ :type distribution: :class:`distutils2.database.InstalledDistribution`
1113
+ or :class:`distutils2.database.EggInfoDistribution`
1114
+ """
1115
+ self.adjacency_list[distribution] = []
1116
+ self.reverse_list[distribution] = []
1117
+ #self.missing[distribution] = []
1118
+
1119
+ def add_edge(self, x, y, label=None):
1120
+ """Add an edge from distribution *x* to distribution *y* with the given
1121
+ *label*.
1122
+
1123
+ :type x: :class:`distutils2.database.InstalledDistribution` or
1124
+ :class:`distutils2.database.EggInfoDistribution`
1125
+ :type y: :class:`distutils2.database.InstalledDistribution` or
1126
+ :class:`distutils2.database.EggInfoDistribution`
1127
+ :type label: ``str`` or ``None``
1128
+ """
1129
+ self.adjacency_list[x].append((y, label))
1130
+ # multiple edges are allowed, so be careful
1131
+ if x not in self.reverse_list[y]:
1132
+ self.reverse_list[y].append(x)
1133
+
1134
+ def add_missing(self, distribution, requirement):
1135
+ """
1136
+ Add a missing *requirement* for the given *distribution*.
1137
+
1138
+ :type distribution: :class:`distutils2.database.InstalledDistribution`
1139
+ or :class:`distutils2.database.EggInfoDistribution`
1140
+ :type requirement: ``str``
1141
+ """
1142
+ logger.debug('%s missing %r', distribution, requirement)
1143
+ self.missing.setdefault(distribution, []).append(requirement)
1144
+
1145
+ def _repr_dist(self, dist):
1146
+ return '%s %s' % (dist.name, dist.version)
1147
+
1148
+ def repr_node(self, dist, level=1):
1149
+ """Prints only a subgraph"""
1150
+ output = [self._repr_dist(dist)]
1151
+ for other, label in self.adjacency_list[dist]:
1152
+ dist = self._repr_dist(other)
1153
+ if label is not None:
1154
+ dist = '%s [%s]' % (dist, label)
1155
+ output.append(' ' * level + str(dist))
1156
+ suboutput = self.repr_node(other, level + 1)
1157
+ subs = suboutput.split('\n')
1158
+ output.extend(subs[1:])
1159
+ return '\n'.join(output)
1160
+
1161
+ def to_dot(self, f, skip_disconnected=True):
1162
+ """Writes a DOT output for the graph to the provided file *f*.
1163
+
1164
+ If *skip_disconnected* is set to ``True``, then all distributions
1165
+ that are not dependent on any other distribution are skipped.
1166
+
1167
+ :type f: has to support ``file``-like operations
1168
+ :type skip_disconnected: ``bool``
1169
+ """
1170
+ disconnected = []
1171
+
1172
+ f.write("digraph dependencies {\n")
1173
+ for dist, adjs in self.adjacency_list.items():
1174
+ if len(adjs) == 0 and not skip_disconnected:
1175
+ disconnected.append(dist)
1176
+ for other, label in adjs:
1177
+ if not label is None:
1178
+ f.write('"%s" -> "%s" [label="%s"]\n' %
1179
+ (dist.name, other.name, label))
1180
+ else:
1181
+ f.write('"%s" -> "%s"\n' % (dist.name, other.name))
1182
+ if not skip_disconnected and len(disconnected) > 0:
1183
+ f.write('subgraph disconnected {\n')
1184
+ f.write('label = "Disconnected"\n')
1185
+ f.write('bgcolor = red\n')
1186
+
1187
+ for dist in disconnected:
1188
+ f.write('"%s"' % dist.name)
1189
+ f.write('\n')
1190
+ f.write('}\n')
1191
+ f.write('}\n')
1192
+
1193
+ def topological_sort(self):
1194
+ """
1195
+ Perform a topological sort of the graph.
1196
+ :return: A tuple, the first element of which is a topologically sorted
1197
+ list of distributions, and the second element of which is a
1198
+ list of distributions that cannot be sorted because they have
1199
+ circular dependencies and so form a cycle.
1200
+ """
1201
+ result = []
1202
+ # Make a shallow copy of the adjacency list
1203
+ alist = {}
1204
+ for k, v in self.adjacency_list.items():
1205
+ alist[k] = v[:]
1206
+ while True:
1207
+ # See what we can remove in this run
1208
+ to_remove = []
1209
+ for k, v in list(alist.items())[:]:
1210
+ if not v:
1211
+ to_remove.append(k)
1212
+ del alist[k]
1213
+ if not to_remove:
1214
+ # What's left in alist (if anything) is a cycle.
1215
+ break
1216
+ # Remove from the adjacency list of others
1217
+ for k, v in alist.items():
1218
+ alist[k] = [(d, r) for d, r in v if d not in to_remove]
1219
+ logger.debug('Moving to result: %s',
1220
+ ['%s (%s)' % (d.name, d.version) for d in to_remove])
1221
+ result.extend(to_remove)
1222
+ return result, list(alist.keys())
1223
+
1224
+ def __repr__(self):
1225
+ """Representation of the graph"""
1226
+ output = []
1227
+ for dist, adjs in self.adjacency_list.items():
1228
+ output.append(self.repr_node(dist))
1229
+ return '\n'.join(output)
1230
+
1231
+
1232
+ def make_graph(dists, scheme='default'):
1233
+ """Makes a dependency graph from the given distributions.
1234
+
1235
+ :parameter dists: a list of distributions
1236
+ :type dists: list of :class:`distutils2.database.InstalledDistribution` and
1237
+ :class:`distutils2.database.EggInfoDistribution` instances
1238
+ :rtype: a :class:`DependencyGraph` instance
1239
+ """
1240
+ scheme = get_scheme(scheme)
1241
+ graph = DependencyGraph()
1242
+ provided = {} # maps names to lists of (version, dist) tuples
1243
+
1244
+ # first, build the graph and find out what's provided
1245
+ for dist in dists:
1246
+ graph.add_distribution(dist)
1247
+
1248
+ for p in dist.provides:
1249
+ name, version = parse_name_and_version(p)
1250
+ logger.debug('Add to provided: %s, %s, %s', name, version, dist)
1251
+ provided.setdefault(name, []).append((version, dist))
1252
+
1253
+ # now make the edges
1254
+ for dist in dists:
1255
+ requires = (dist.run_requires | dist.meta_requires |
1256
+ dist.build_requires | dist.dev_requires)
1257
+ for req in requires:
1258
+ try:
1259
+ matcher = scheme.matcher(req)
1260
+ except UnsupportedVersionError:
1261
+ # XXX compat-mode if cannot read the version
1262
+ logger.warning('could not read version %r - using name only',
1263
+ req)
1264
+ name = req.split()[0]
1265
+ matcher = scheme.matcher(name)
1266
+
1267
+ name = matcher.key # case-insensitive
1268
+
1269
+ matched = False
1270
+ if name in provided:
1271
+ for version, provider in provided[name]:
1272
+ try:
1273
+ match = matcher.match(version)
1274
+ except UnsupportedVersionError:
1275
+ match = False
1276
+
1277
+ if match:
1278
+ graph.add_edge(dist, provider, req)
1279
+ matched = True
1280
+ break
1281
+ if not matched:
1282
+ graph.add_missing(dist, req)
1283
+ return graph
1284
+
1285
+
1286
+ def get_dependent_dists(dists, dist):
1287
+ """Recursively generate a list of distributions from *dists* that are
1288
+ dependent on *dist*.
1289
+
1290
+ :param dists: a list of distributions
1291
+ :param dist: a distribution, member of *dists* for which we are interested
1292
+ """
1293
+ if dist not in dists:
1294
+ raise DistlibException('given distribution %r is not a member '
1295
+ 'of the list' % dist.name)
1296
+ graph = make_graph(dists)
1297
+
1298
+ dep = [dist] # dependent distributions
1299
+ todo = graph.reverse_list[dist] # list of nodes we should inspect
1300
+
1301
+ while todo:
1302
+ d = todo.pop()
1303
+ dep.append(d)
1304
+ for succ in graph.reverse_list[d]:
1305
+ if succ not in dep:
1306
+ todo.append(succ)
1307
+
1308
+ dep.pop(0) # remove dist from dep, was there to prevent infinite loops
1309
+ return dep
1310
+
1311
+
1312
+ def get_required_dists(dists, dist):
1313
+ """Recursively generate a list of distributions from *dists* that are
1314
+ required by *dist*.
1315
+
1316
+ :param dists: a list of distributions
1317
+ :param dist: a distribution, member of *dists* for which we are interested
1318
+ in finding the dependencies.
1319
+ """
1320
+ if dist not in dists:
1321
+ raise DistlibException('given distribution %r is not a member '
1322
+ 'of the list' % dist.name)
1323
+ graph = make_graph(dists)
1324
+
1325
+ req = set() # required distributions
1326
+ todo = graph.adjacency_list[dist] # list of nodes we should inspect
1327
+ seen = set(t[0] for t in todo) # already added to todo
1328
+
1329
+ while todo:
1330
+ d = todo.pop()[0]
1331
+ req.add(d)
1332
+ pred_list = graph.adjacency_list[d]
1333
+ for pred in pred_list:
1334
+ d = pred[0]
1335
+ if d not in req and d not in seen:
1336
+ seen.add(d)
1337
+ todo.append(pred)
1338
+ return req
1339
+
1340
+
1341
+ def make_dist(name, version, **kwargs):
1342
+ """
1343
+ A convenience method for making a dist given just a name and version.
1344
+ """
1345
+ summary = kwargs.pop('summary', 'Placeholder for summary')
1346
+ md = Metadata(**kwargs)
1347
+ md.name = name
1348
+ md.version = version
1349
+ md.summary = summary or 'Placeholder for summary'
1350
+ return Distribution(md)
.venv/Lib/site-packages/pip/_vendor/distlib/index.py ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2013 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
+ class PackageIndex(object):
29
+ """
30
+ This class represents a package index compatible with PyPI, the Python
31
+ Package Index.
32
+ """
33
+
34
+ boundary = b'----------ThIs_Is_tHe_distlib_index_bouNdaRY_$'
35
+
36
+ def __init__(self, url=None):
37
+ """
38
+ Initialise an instance.
39
+
40
+ :param url: The URL of the index. If not specified, the URL for PyPI is
41
+ used.
42
+ """
43
+ self.url = url or DEFAULT_INDEX
44
+ self.read_configuration()
45
+ scheme, netloc, path, params, query, frag = urlparse(self.url)
46
+ if params or query or frag or scheme not in ('http', 'https'):
47
+ raise DistlibException('invalid repository: %s' % self.url)
48
+ self.password_handler = None
49
+ self.ssl_verifier = None
50
+ self.gpg = None
51
+ self.gpg_home = None
52
+ with open(os.devnull, 'w') as sink:
53
+ # Use gpg by default rather than gpg2, as gpg2 insists on
54
+ # prompting for passwords
55
+ for s in ('gpg', 'gpg2'):
56
+ try:
57
+ rc = subprocess.check_call([s, '--version'], stdout=sink,
58
+ stderr=sink)
59
+ if rc == 0:
60
+ self.gpg = s
61
+ break
62
+ except OSError:
63
+ pass
64
+
65
+ def _get_pypirc_command(self):
66
+ """
67
+ Get the distutils command for interacting with PyPI configurations.
68
+ :return: the command.
69
+ """
70
+ from .util import _get_pypirc_command as cmd
71
+ return cmd()
72
+
73
+ def read_configuration(self):
74
+ """
75
+ Read the PyPI access configuration as supported by distutils. This populates
76
+ ``username``, ``password``, ``realm`` and ``url`` attributes from the
77
+ configuration.
78
+ """
79
+ from .util import _load_pypirc
80
+ cfg = _load_pypirc(self)
81
+ self.username = cfg.get('username')
82
+ self.password = cfg.get('password')
83
+ self.realm = cfg.get('realm', 'pypi')
84
+ self.url = cfg.get('repository', self.url)
85
+
86
+ def save_configuration(self):
87
+ """
88
+ Save the PyPI access configuration. You must have set ``username`` and
89
+ ``password`` attributes before calling this method.
90
+ """
91
+ self.check_credentials()
92
+ from .util import _store_pypirc
93
+ _store_pypirc(self)
94
+
95
+ def check_credentials(self):
96
+ """
97
+ Check that ``username`` and ``password`` have been set, and raise an
98
+ exception if not.
99
+ """
100
+ if self.username is None or self.password is None:
101
+ raise DistlibException('username and password must be set')
102
+ pm = HTTPPasswordMgr()
103
+ _, netloc, _, _, _, _ = urlparse(self.url)
104
+ pm.add_password(self.realm, netloc, self.username, self.password)
105
+ self.password_handler = HTTPBasicAuthHandler(pm)
106
+
107
+ def register(self, metadata): # pragma: no cover
108
+ """
109
+ Register a distribution on PyPI, using the provided metadata.
110
+
111
+ :param metadata: A :class:`Metadata` instance defining at least a name
112
+ and version number for the distribution to be
113
+ registered.
114
+ :return: The HTTP response received from PyPI upon submission of the
115
+ request.
116
+ """
117
+ self.check_credentials()
118
+ metadata.validate()
119
+ d = metadata.todict()
120
+ d[':action'] = 'verify'
121
+ request = self.encode_request(d.items(), [])
122
+ response = self.send_request(request)
123
+ d[':action'] = 'submit'
124
+ request = self.encode_request(d.items(), [])
125
+ return self.send_request(request)
126
+
127
+ def _reader(self, name, stream, outbuf):
128
+ """
129
+ Thread runner for reading lines of from a subprocess into a buffer.
130
+
131
+ :param name: The logical name of the stream (used for logging only).
132
+ :param stream: The stream to read from. This will typically a pipe
133
+ connected to the output stream of a subprocess.
134
+ :param outbuf: The list to append the read lines to.
135
+ """
136
+ while True:
137
+ s = stream.readline()
138
+ if not s:
139
+ break
140
+ s = s.decode('utf-8').rstrip()
141
+ outbuf.append(s)
142
+ logger.debug('%s: %s' % (name, s))
143
+ stream.close()
144
+
145
+ def get_sign_command(self, filename, signer, sign_password, keystore=None): # pragma: no cover
146
+ """
147
+ Return a suitable command for signing a file.
148
+
149
+ :param filename: The pathname to the file to be signed.
150
+ :param signer: The identifier of the signer of the file.
151
+ :param sign_password: The passphrase for the signer's
152
+ private key used for signing.
153
+ :param keystore: The path to a directory which contains the keys
154
+ used in verification. If not specified, the
155
+ instance's ``gpg_home`` attribute is used instead.
156
+ :return: The signing command as a list suitable to be
157
+ passed to :class:`subprocess.Popen`.
158
+ """
159
+ cmd = [self.gpg, '--status-fd', '2', '--no-tty']
160
+ if keystore is None:
161
+ keystore = self.gpg_home
162
+ if keystore:
163
+ cmd.extend(['--homedir', keystore])
164
+ if sign_password is not None:
165
+ cmd.extend(['--batch', '--passphrase-fd', '0'])
166
+ td = tempfile.mkdtemp()
167
+ sf = os.path.join(td, os.path.basename(filename) + '.asc')
168
+ cmd.extend(['--detach-sign', '--armor', '--local-user',
169
+ signer, '--output', sf, filename])
170
+ logger.debug('invoking: %s', ' '.join(cmd))
171
+ return cmd, sf
172
+
173
+ def run_command(self, cmd, input_data=None):
174
+ """
175
+ Run a command in a child process , passing it any input data specified.
176
+
177
+ :param cmd: The command to run.
178
+ :param input_data: If specified, this must be a byte string containing
179
+ data to be sent to the child process.
180
+ :return: A tuple consisting of the subprocess' exit code, a list of
181
+ lines read from the subprocess' ``stdout``, and a list of
182
+ lines read from the subprocess' ``stderr``.
183
+ """
184
+ kwargs = {
185
+ 'stdout': subprocess.PIPE,
186
+ 'stderr': subprocess.PIPE,
187
+ }
188
+ if input_data is not None:
189
+ kwargs['stdin'] = subprocess.PIPE
190
+ stdout = []
191
+ stderr = []
192
+ p = subprocess.Popen(cmd, **kwargs)
193
+ # We don't use communicate() here because we may need to
194
+ # get clever with interacting with the command
195
+ t1 = Thread(target=self._reader, args=('stdout', p.stdout, stdout))
196
+ t1.start()
197
+ t2 = Thread(target=self._reader, args=('stderr', p.stderr, stderr))
198
+ t2.start()
199
+ if input_data is not None:
200
+ p.stdin.write(input_data)
201
+ p.stdin.close()
202
+
203
+ p.wait()
204
+ t1.join()
205
+ t2.join()
206
+ return p.returncode, stdout, stderr
207
+
208
+ def sign_file(self, filename, signer, sign_password, keystore=None): # pragma: no cover
209
+ """
210
+ Sign a file.
211
+
212
+ :param filename: The pathname to the file to be signed.
213
+ :param signer: The identifier of the signer of the file.
214
+ :param sign_password: The passphrase for the signer's
215
+ private key used for signing.
216
+ :param keystore: The path to a directory which contains the keys
217
+ used in signing. If not specified, the instance's
218
+ ``gpg_home`` attribute is used instead.
219
+ :return: The absolute pathname of the file where the signature is
220
+ stored.
221
+ """
222
+ cmd, sig_file = self.get_sign_command(filename, signer, sign_password,
223
+ keystore)
224
+ rc, stdout, stderr = self.run_command(cmd,
225
+ sign_password.encode('utf-8'))
226
+ if rc != 0:
227
+ raise DistlibException('sign command failed with error '
228
+ 'code %s' % rc)
229
+ return sig_file
230
+
231
+ def upload_file(self, metadata, filename, signer=None, sign_password=None,
232
+ filetype='sdist', pyversion='source', keystore=None):
233
+ """
234
+ Upload a release file to the index.
235
+
236
+ :param metadata: A :class:`Metadata` instance defining at least a name
237
+ and version number for the file to be uploaded.
238
+ :param filename: The pathname of the file to be uploaded.
239
+ :param signer: The identifier of the signer of the file.
240
+ :param sign_password: The passphrase for the signer's
241
+ private key used for signing.
242
+ :param filetype: The type of the file being uploaded. This is the
243
+ distutils command which produced that file, e.g.
244
+ ``sdist`` or ``bdist_wheel``.
245
+ :param pyversion: The version of Python which the release relates
246
+ to. For code compatible with any Python, this would
247
+ be ``source``, otherwise it would be e.g. ``3.2``.
248
+ :param keystore: The path to a directory which contains the keys
249
+ used in signing. If not specified, the instance's
250
+ ``gpg_home`` attribute is used instead.
251
+ :return: The HTTP response received from PyPI upon submission of the
252
+ request.
253
+ """
254
+ self.check_credentials()
255
+ if not os.path.exists(filename):
256
+ raise DistlibException('not found: %s' % filename)
257
+ metadata.validate()
258
+ d = metadata.todict()
259
+ sig_file = None
260
+ if signer:
261
+ if not self.gpg:
262
+ logger.warning('no signing program available - not signed')
263
+ else:
264
+ sig_file = self.sign_file(filename, signer, sign_password,
265
+ keystore)
266
+ with open(filename, 'rb') as f:
267
+ file_data = f.read()
268
+ md5_digest = hashlib.md5(file_data).hexdigest()
269
+ sha256_digest = hashlib.sha256(file_data).hexdigest()
270
+ d.update({
271
+ ':action': 'file_upload',
272
+ 'protocol_version': '1',
273
+ 'filetype': filetype,
274
+ 'pyversion': pyversion,
275
+ 'md5_digest': md5_digest,
276
+ 'sha256_digest': sha256_digest,
277
+ })
278
+ files = [('content', os.path.basename(filename), file_data)]
279
+ if sig_file:
280
+ with open(sig_file, 'rb') as f:
281
+ sig_data = f.read()
282
+ files.append(('gpg_signature', os.path.basename(sig_file),
283
+ sig_data))
284
+ shutil.rmtree(os.path.dirname(sig_file))
285
+ request = self.encode_request(d.items(), files)
286
+ return self.send_request(request)
287
+
288
+ def upload_documentation(self, metadata, doc_dir): # pragma: no cover
289
+ """
290
+ Upload documentation to the index.
291
+
292
+ :param metadata: A :class:`Metadata` instance defining at least a name
293
+ and version number for the documentation to be
294
+ uploaded.
295
+ :param doc_dir: The pathname of the directory which contains the
296
+ documentation. This should be the directory that
297
+ contains the ``index.html`` for the documentation.
298
+ :return: The HTTP response received from PyPI upon submission of the
299
+ request.
300
+ """
301
+ self.check_credentials()
302
+ if not os.path.isdir(doc_dir):
303
+ raise DistlibException('not a directory: %r' % doc_dir)
304
+ fn = os.path.join(doc_dir, 'index.html')
305
+ if not os.path.exists(fn):
306
+ raise DistlibException('not found: %r' % fn)
307
+ metadata.validate()
308
+ name, version = metadata.name, metadata.version
309
+ zip_data = zip_dir(doc_dir).getvalue()
310
+ fields = [(':action', 'doc_upload'),
311
+ ('name', name), ('version', version)]
312
+ files = [('content', name, zip_data)]
313
+ request = self.encode_request(fields, files)
314
+ return self.send_request(request)
315
+
316
+ def get_verify_command(self, signature_filename, data_filename,
317
+ keystore=None):
318
+ """
319
+ Return a suitable command for verifying a file.
320
+
321
+ :param signature_filename: The pathname to the file containing the
322
+ signature.
323
+ :param data_filename: The pathname to the file containing the
324
+ signed data.
325
+ :param keystore: The path to a directory which contains the keys
326
+ used in verification. If not specified, the
327
+ instance's ``gpg_home`` attribute is used instead.
328
+ :return: The verifying command as a list suitable to be
329
+ passed to :class:`subprocess.Popen`.
330
+ """
331
+ cmd = [self.gpg, '--status-fd', '2', '--no-tty']
332
+ if keystore is None:
333
+ keystore = self.gpg_home
334
+ if keystore:
335
+ cmd.extend(['--homedir', keystore])
336
+ cmd.extend(['--verify', signature_filename, data_filename])
337
+ logger.debug('invoking: %s', ' '.join(cmd))
338
+ return cmd
339
+
340
+ def verify_signature(self, signature_filename, data_filename,
341
+ keystore=None):
342
+ """
343
+ Verify a signature for a file.
344
+
345
+ :param signature_filename: The pathname to the file containing the
346
+ signature.
347
+ :param data_filename: The pathname to the file containing the
348
+ signed data.
349
+ :param keystore: The path to a directory which contains the keys
350
+ used in verification. If not specified, the
351
+ instance's ``gpg_home`` attribute is used instead.
352
+ :return: True if the signature was verified, else False.
353
+ """
354
+ if not self.gpg:
355
+ raise DistlibException('verification unavailable because gpg '
356
+ 'unavailable')
357
+ cmd = self.get_verify_command(signature_filename, data_filename,
358
+ keystore)
359
+ rc, stdout, stderr = self.run_command(cmd)
360
+ if rc not in (0, 1):
361
+ raise DistlibException('verify command failed with error '
362
+ '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')()
.venv/Lib/site-packages/pip/_vendor/distlib/locators.py ADDED
@@ -0,0 +1,1300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2012-2015 Vinay Sajip.
4
+ # Licensed to the Python Software Foundation under a contributor agreement.
5
+ # See LICENSE.txt and CONTRIBUTORS.txt.
6
+ #
7
+
8
+ import gzip
9
+ from io import BytesIO
10
+ import json
11
+ import logging
12
+ import os
13
+ import posixpath
14
+ import re
15
+ try:
16
+ import threading
17
+ except ImportError: # pragma: no cover
18
+ import dummy_threading as threading
19
+ import zlib
20
+
21
+ from . import DistlibException
22
+ from .compat import (urljoin, urlparse, urlunparse, url2pathname, pathname2url,
23
+ queue, quote, unescape, build_opener,
24
+ HTTPRedirectHandler as BaseRedirectHandler, text_type,
25
+ Request, HTTPError, URLError)
26
+ from .database import Distribution, DistributionPath, make_dist
27
+ from .metadata import Metadata, MetadataInvalidError
28
+ from .util import (cached_property, ensure_slash, split_filename, get_project_data,
29
+ parse_requirement, parse_name_and_version, ServerProxy,
30
+ normalize_name)
31
+ from .version import get_scheme, UnsupportedVersionError
32
+ from .wheel import Wheel, is_compatible
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+ HASHER_HASH = re.compile(r'^(\w+)=([a-f0-9]+)')
37
+ CHARSET = re.compile(r';\s*charset\s*=\s*(.*)\s*$', re.I)
38
+ HTML_CONTENT_TYPE = re.compile('text/html|application/x(ht)?ml')
39
+ DEFAULT_INDEX = 'https://pypi.org/pypi'
40
+
41
+ def get_all_distribution_names(url=None):
42
+ """
43
+ Return all distribution names known by an index.
44
+ :param url: The URL of the index.
45
+ :return: A list of all known distribution names.
46
+ """
47
+ if url is None:
48
+ url = DEFAULT_INDEX
49
+ client = ServerProxy(url, timeout=3.0)
50
+ try:
51
+ return client.list_packages()
52
+ finally:
53
+ client('close')()
54
+
55
+ class RedirectHandler(BaseRedirectHandler):
56
+ """
57
+ A class to work around a bug in some Python 3.2.x releases.
58
+ """
59
+ # There's a bug in the base version for some 3.2.x
60
+ # (e.g. 3.2.2 on Ubuntu Oneiric). If a Location header
61
+ # returns e.g. /abc, it bails because it says the scheme ''
62
+ # is bogus, when actually it should use the request's
63
+ # URL for the scheme. See Python issue #13696.
64
+ def http_error_302(self, req, fp, code, msg, headers):
65
+ # Some servers (incorrectly) return multiple Location headers
66
+ # (so probably same goes for URI). Use first header.
67
+ newurl = None
68
+ for key in ('location', 'uri'):
69
+ if key in headers:
70
+ newurl = headers[key]
71
+ break
72
+ if newurl is None: # pragma: no cover
73
+ return
74
+ urlparts = urlparse(newurl)
75
+ if urlparts.scheme == '':
76
+ newurl = urljoin(req.get_full_url(), newurl)
77
+ if hasattr(headers, 'replace_header'):
78
+ headers.replace_header(key, newurl)
79
+ else:
80
+ headers[key] = newurl
81
+ return BaseRedirectHandler.http_error_302(self, req, fp, code, msg,
82
+ headers)
83
+
84
+ http_error_301 = http_error_303 = http_error_307 = http_error_302
85
+
86
+ class Locator(object):
87
+ """
88
+ A base class for locators - things that locate distributions.
89
+ """
90
+ source_extensions = ('.tar.gz', '.tar.bz2', '.tar', '.zip', '.tgz', '.tbz')
91
+ binary_extensions = ('.egg', '.exe', '.whl')
92
+ excluded_extensions = ('.pdf',)
93
+
94
+ # A list of tags indicating which wheels you want to match. The default
95
+ # value of None matches against the tags compatible with the running
96
+ # Python. If you want to match other values, set wheel_tags on a locator
97
+ # instance to a list of tuples (pyver, abi, arch) which you want to match.
98
+ wheel_tags = None
99
+
100
+ downloadable_extensions = source_extensions + ('.whl',)
101
+
102
+ def __init__(self, scheme='default'):
103
+ """
104
+ Initialise an instance.
105
+ :param scheme: Because locators look for most recent versions, they
106
+ need to know the version scheme to use. This specifies
107
+ the current PEP-recommended scheme - use ``'legacy'``
108
+ if you need to support existing distributions on PyPI.
109
+ """
110
+ self._cache = {}
111
+ self.scheme = scheme
112
+ # Because of bugs in some of the handlers on some of the platforms,
113
+ # we use our own opener rather than just using urlopen.
114
+ self.opener = build_opener(RedirectHandler())
115
+ # If get_project() is called from locate(), the matcher instance
116
+ # is set from the requirement passed to locate(). See issue #18 for
117
+ # why this can be useful to know.
118
+ self.matcher = None
119
+ self.errors = queue.Queue()
120
+
121
+ def get_errors(self):
122
+ """
123
+ Return any errors which have occurred.
124
+ """
125
+ result = []
126
+ while not self.errors.empty(): # pragma: no cover
127
+ try:
128
+ e = self.errors.get(False)
129
+ result.append(e)
130
+ except self.errors.Empty:
131
+ continue
132
+ self.errors.task_done()
133
+ return result
134
+
135
+ def clear_errors(self):
136
+ """
137
+ Clear any errors which may have been logged.
138
+ """
139
+ # Just get the errors and throw them away
140
+ self.get_errors()
141
+
142
+ def clear_cache(self):
143
+ self._cache.clear()
144
+
145
+ def _get_scheme(self):
146
+ return self._scheme
147
+
148
+ def _set_scheme(self, value):
149
+ self._scheme = value
150
+
151
+ scheme = property(_get_scheme, _set_scheme)
152
+
153
+ def _get_project(self, name):
154
+ """
155
+ For a given project, get a dictionary mapping available versions to Distribution
156
+ instances.
157
+
158
+ This should be implemented in subclasses.
159
+
160
+ If called from a locate() request, self.matcher will be set to a
161
+ matcher for the requirement to satisfy, otherwise it will be None.
162
+ """
163
+ raise NotImplementedError('Please implement in the subclass')
164
+
165
+ def get_distribution_names(self):
166
+ """
167
+ Return all the distribution names known to this locator.
168
+ """
169
+ raise NotImplementedError('Please implement in the subclass')
170
+
171
+ def get_project(self, name):
172
+ """
173
+ For a given project, get a dictionary mapping available versions to Distribution
174
+ instances.
175
+
176
+ This calls _get_project to do all the work, and just implements a caching layer on top.
177
+ """
178
+ if self._cache is None: # pragma: no cover
179
+ result = self._get_project(name)
180
+ elif name in self._cache:
181
+ result = self._cache[name]
182
+ else:
183
+ self.clear_errors()
184
+ result = self._get_project(name)
185
+ self._cache[name] = result
186
+ return result
187
+
188
+ def score_url(self, url):
189
+ """
190
+ Give an url a score which can be used to choose preferred URLs
191
+ for a given project release.
192
+ """
193
+ t = urlparse(url)
194
+ basename = posixpath.basename(t.path)
195
+ compatible = True
196
+ is_wheel = basename.endswith('.whl')
197
+ is_downloadable = basename.endswith(self.downloadable_extensions)
198
+ if is_wheel:
199
+ compatible = is_compatible(Wheel(basename), self.wheel_tags)
200
+ return (t.scheme == 'https', 'pypi.org' in t.netloc,
201
+ is_downloadable, is_wheel, compatible, basename)
202
+
203
+ def prefer_url(self, url1, url2):
204
+ """
205
+ Choose one of two URLs where both are candidates for distribution
206
+ archives for the same version of a distribution (for example,
207
+ .tar.gz vs. zip).
208
+
209
+ The current implementation favours https:// URLs over http://, archives
210
+ from PyPI over those from other locations, wheel compatibility (if a
211
+ wheel) and then the archive name.
212
+ """
213
+ result = url2
214
+ if url1:
215
+ s1 = self.score_url(url1)
216
+ s2 = self.score_url(url2)
217
+ if s1 > s2:
218
+ result = url1
219
+ if result != url2:
220
+ logger.debug('Not replacing %r with %r', url1, url2)
221
+ else:
222
+ logger.debug('Replacing %r with %r', url1, url2)
223
+ return result
224
+
225
+ def split_filename(self, filename, project_name):
226
+ """
227
+ Attempt to split a filename in project name, version and Python version.
228
+ """
229
+ return split_filename(filename, project_name)
230
+
231
+ def convert_url_to_download_info(self, url, project_name):
232
+ """
233
+ See if a URL is a candidate for a download URL for a project (the URL
234
+ has typically been scraped from an HTML page).
235
+
236
+ If it is, a dictionary is returned with keys "name", "version",
237
+ "filename" and "url"; otherwise, None is returned.
238
+ """
239
+ def same_project(name1, name2):
240
+ return normalize_name(name1) == normalize_name(name2)
241
+
242
+ result = None
243
+ scheme, netloc, path, params, query, frag = urlparse(url)
244
+ if frag.lower().startswith('egg='): # pragma: no cover
245
+ logger.debug('%s: version hint in fragment: %r',
246
+ project_name, frag)
247
+ m = HASHER_HASH.match(frag)
248
+ if m:
249
+ algo, digest = m.groups()
250
+ else:
251
+ algo, digest = None, None
252
+ origpath = path
253
+ if path and path[-1] == '/': # pragma: no cover
254
+ path = path[:-1]
255
+ if path.endswith('.whl'):
256
+ try:
257
+ wheel = Wheel(path)
258
+ if not is_compatible(wheel, self.wheel_tags):
259
+ logger.debug('Wheel not compatible: %s', path)
260
+ else:
261
+ if project_name is None:
262
+ include = True
263
+ else:
264
+ include = same_project(wheel.name, project_name)
265
+ if include:
266
+ result = {
267
+ 'name': wheel.name,
268
+ 'version': wheel.version,
269
+ 'filename': wheel.filename,
270
+ 'url': urlunparse((scheme, netloc, origpath,
271
+ params, query, '')),
272
+ 'python-version': ', '.join(
273
+ ['.'.join(list(v[2:])) for v in wheel.pyver]),
274
+ }
275
+ except Exception as e: # pragma: no cover
276
+ logger.warning('invalid path for wheel: %s', path)
277
+ elif not path.endswith(self.downloadable_extensions): # pragma: no cover
278
+ logger.debug('Not downloadable: %s', path)
279
+ else: # downloadable extension
280
+ path = filename = posixpath.basename(path)
281
+ for ext in self.downloadable_extensions:
282
+ if path.endswith(ext):
283
+ path = path[:-len(ext)]
284
+ t = self.split_filename(path, project_name)
285
+ if not t: # pragma: no cover
286
+ logger.debug('No match for project/version: %s', path)
287
+ else:
288
+ name, version, pyver = t
289
+ if not project_name or same_project(project_name, name):
290
+ result = {
291
+ 'name': name,
292
+ 'version': version,
293
+ 'filename': filename,
294
+ 'url': urlunparse((scheme, netloc, origpath,
295
+ params, query, '')),
296
+ #'packagetype': 'sdist',
297
+ }
298
+ if pyver: # pragma: no cover
299
+ result['python-version'] = pyver
300
+ break
301
+ if result and algo:
302
+ result['%s_digest' % algo] = digest
303
+ return result
304
+
305
+ def _get_digest(self, info):
306
+ """
307
+ Get a digest from a dictionary by looking at a "digests" dictionary
308
+ or keys of the form 'algo_digest'.
309
+
310
+ Returns a 2-tuple (algo, digest) if found, else None. Currently
311
+ looks only for SHA256, then MD5.
312
+ """
313
+ result = None
314
+ if 'digests' in info:
315
+ digests = info['digests']
316
+ for algo in ('sha256', 'md5'):
317
+ if algo in digests:
318
+ result = (algo, digests[algo])
319
+ break
320
+ if not result:
321
+ for algo in ('sha256', 'md5'):
322
+ key = '%s_digest' % algo
323
+ if key in info:
324
+ result = (algo, info[key])
325
+ break
326
+ return result
327
+
328
+ def _update_version_data(self, result, info):
329
+ """
330
+ Update a result dictionary (the final result from _get_project) with a
331
+ dictionary for a specific version, which typically holds information
332
+ gleaned from a filename or URL for an archive for the distribution.
333
+ """
334
+ name = info.pop('name')
335
+ version = info.pop('version')
336
+ if version in result:
337
+ dist = result[version]
338
+ md = dist.metadata
339
+ else:
340
+ dist = make_dist(name, version, scheme=self.scheme)
341
+ md = dist.metadata
342
+ dist.digest = digest = self._get_digest(info)
343
+ url = info['url']
344
+ result['digests'][url] = digest
345
+ if md.source_url != info['url']:
346
+ md.source_url = self.prefer_url(md.source_url, url)
347
+ result['urls'].setdefault(version, set()).add(url)
348
+ dist.locator = self
349
+ result[version] = dist
350
+
351
+ def locate(self, requirement, prereleases=False):
352
+ """
353
+ Find the most recent distribution which matches the given
354
+ requirement.
355
+
356
+ :param requirement: A requirement of the form 'foo (1.0)' or perhaps
357
+ 'foo (>= 1.0, < 2.0, != 1.3)'
358
+ :param prereleases: If ``True``, allow pre-release versions
359
+ to be located. Otherwise, pre-release versions
360
+ are not returned.
361
+ :return: A :class:`Distribution` instance, or ``None`` if no such
362
+ distribution could be located.
363
+ """
364
+ result = None
365
+ r = parse_requirement(requirement)
366
+ if r is None: # pragma: no cover
367
+ raise DistlibException('Not a valid requirement: %r' % requirement)
368
+ scheme = get_scheme(self.scheme)
369
+ self.matcher = matcher = scheme.matcher(r.requirement)
370
+ logger.debug('matcher: %s (%s)', matcher, type(matcher).__name__)
371
+ versions = self.get_project(r.name)
372
+ if len(versions) > 2: # urls and digests keys are present
373
+ # sometimes, versions are invalid
374
+ slist = []
375
+ vcls = matcher.version_class
376
+ for k in versions:
377
+ if k in ('urls', 'digests'):
378
+ continue
379
+ try:
380
+ if not matcher.match(k):
381
+ pass # logger.debug('%s did not match %r', matcher, k)
382
+ else:
383
+ if prereleases or not vcls(k).is_prerelease:
384
+ slist.append(k)
385
+ # else:
386
+ # logger.debug('skipping pre-release '
387
+ # 'version %s of %s', k, matcher.name)
388
+ except Exception: # pragma: no cover
389
+ logger.warning('error matching %s with %r', matcher, k)
390
+ pass # slist.append(k)
391
+ if len(slist) > 1:
392
+ slist = sorted(slist, key=scheme.key)
393
+ if slist:
394
+ logger.debug('sorted list: %s', slist)
395
+ version = slist[-1]
396
+ result = versions[version]
397
+ if result:
398
+ if r.extras:
399
+ result.extras = r.extras
400
+ result.download_urls = versions.get('urls', {}).get(version, set())
401
+ d = {}
402
+ sd = versions.get('digests', {})
403
+ for url in result.download_urls:
404
+ if url in sd: # pragma: no cover
405
+ d[url] = sd[url]
406
+ result.digests = d
407
+ self.matcher = None
408
+ return result
409
+
410
+
411
+ class PyPIRPCLocator(Locator):
412
+ """
413
+ This locator uses XML-RPC to locate distributions. It therefore
414
+ cannot be used with simple mirrors (that only mirror file content).
415
+ """
416
+ def __init__(self, url, **kwargs):
417
+ """
418
+ Initialise an instance.
419
+
420
+ :param url: The URL to use for XML-RPC.
421
+ :param kwargs: Passed to the superclass constructor.
422
+ """
423
+ super(PyPIRPCLocator, self).__init__(**kwargs)
424
+ self.base_url = url
425
+ self.client = ServerProxy(url, timeout=3.0)
426
+
427
+ def get_distribution_names(self):
428
+ """
429
+ Return all the distribution names known to this locator.
430
+ """
431
+ return set(self.client.list_packages())
432
+
433
+ def _get_project(self, name):
434
+ result = {'urls': {}, 'digests': {}}
435
+ versions = self.client.package_releases(name, True)
436
+ for v in versions:
437
+ urls = self.client.release_urls(name, v)
438
+ data = self.client.release_data(name, v)
439
+ metadata = Metadata(scheme=self.scheme)
440
+ metadata.name = data['name']
441
+ metadata.version = data['version']
442
+ metadata.license = data.get('license')
443
+ metadata.keywords = data.get('keywords', [])
444
+ metadata.summary = data.get('summary')
445
+ dist = Distribution(metadata)
446
+ if urls:
447
+ info = urls[0]
448
+ metadata.source_url = info['url']
449
+ dist.digest = self._get_digest(info)
450
+ dist.locator = self
451
+ result[v] = dist
452
+ for info in urls:
453
+ url = info['url']
454
+ digest = self._get_digest(info)
455
+ result['urls'].setdefault(v, set()).add(url)
456
+ result['digests'][url] = digest
457
+ return result
458
+
459
+ class PyPIJSONLocator(Locator):
460
+ """
461
+ This locator uses PyPI's JSON interface. It's very limited in functionality
462
+ and probably not worth using.
463
+ """
464
+ def __init__(self, url, **kwargs):
465
+ super(PyPIJSONLocator, self).__init__(**kwargs)
466
+ self.base_url = ensure_slash(url)
467
+
468
+ def get_distribution_names(self):
469
+ """
470
+ Return all the distribution names known to this locator.
471
+ """
472
+ raise NotImplementedError('Not available from this locator')
473
+
474
+ def _get_project(self, name):
475
+ result = {'urls': {}, 'digests': {}}
476
+ url = urljoin(self.base_url, '%s/json' % quote(name))
477
+ try:
478
+ resp = self.opener.open(url)
479
+ data = resp.read().decode() # for now
480
+ d = json.loads(data)
481
+ md = Metadata(scheme=self.scheme)
482
+ data = d['info']
483
+ md.name = data['name']
484
+ md.version = data['version']
485
+ md.license = data.get('license')
486
+ md.keywords = data.get('keywords', [])
487
+ md.summary = data.get('summary')
488
+ dist = Distribution(md)
489
+ dist.locator = self
490
+ urls = d['urls']
491
+ result[md.version] = dist
492
+ for info in d['urls']:
493
+ url = info['url']
494
+ dist.download_urls.add(url)
495
+ dist.digests[url] = self._get_digest(info)
496
+ result['urls'].setdefault(md.version, set()).add(url)
497
+ result['digests'][url] = self._get_digest(info)
498
+ # Now get other releases
499
+ for version, infos in d['releases'].items():
500
+ if version == md.version:
501
+ continue # already done
502
+ omd = Metadata(scheme=self.scheme)
503
+ omd.name = md.name
504
+ omd.version = version
505
+ odist = Distribution(omd)
506
+ odist.locator = self
507
+ result[version] = odist
508
+ for info in infos:
509
+ url = info['url']
510
+ odist.download_urls.add(url)
511
+ odist.digests[url] = self._get_digest(info)
512
+ result['urls'].setdefault(version, set()).add(url)
513
+ result['digests'][url] = self._get_digest(info)
514
+ # for info in urls:
515
+ # md.source_url = info['url']
516
+ # dist.digest = self._get_digest(info)
517
+ # dist.locator = self
518
+ # for info in urls:
519
+ # url = info['url']
520
+ # result['urls'].setdefault(md.version, set()).add(url)
521
+ # result['digests'][url] = self._get_digest(info)
522
+ except Exception as e:
523
+ self.errors.put(text_type(e))
524
+ logger.exception('JSON fetch failed: %s', e)
525
+ return result
526
+
527
+
528
+ class Page(object):
529
+ """
530
+ This class represents a scraped HTML page.
531
+ """
532
+ # The following slightly hairy-looking regex just looks for the contents of
533
+ # an anchor link, which has an attribute "href" either immediately preceded
534
+ # or immediately followed by a "rel" attribute. The attribute values can be
535
+ # declared with double quotes, single quotes or no quotes - which leads to
536
+ # the length of the expression.
537
+ _href = re.compile("""
538
+ (rel\\s*=\\s*(?:"(?P<rel1>[^"]*)"|'(?P<rel2>[^']*)'|(?P<rel3>[^>\\s\n]*))\\s+)?
539
+ href\\s*=\\s*(?:"(?P<url1>[^"]*)"|'(?P<url2>[^']*)'|(?P<url3>[^>\\s\n]*))
540
+ (\\s+rel\\s*=\\s*(?:"(?P<rel4>[^"]*)"|'(?P<rel5>[^']*)'|(?P<rel6>[^>\\s\n]*)))?
541
+ """, re.I | re.S | re.X)
542
+ _base = re.compile(r"""<base\s+href\s*=\s*['"]?([^'">]+)""", re.I | re.S)
543
+
544
+ def __init__(self, data, url):
545
+ """
546
+ Initialise an instance with the Unicode page contents and the URL they
547
+ came from.
548
+ """
549
+ self.data = data
550
+ self.base_url = self.url = url
551
+ m = self._base.search(self.data)
552
+ if m:
553
+ self.base_url = m.group(1)
554
+
555
+ _clean_re = re.compile(r'[^a-z0-9$&+,/:;=?@.#%_\\|-]', re.I)
556
+
557
+ @cached_property
558
+ def links(self):
559
+ """
560
+ Return the URLs of all the links on a page together with information
561
+ about their "rel" attribute, for determining which ones to treat as
562
+ downloads and which ones to queue for further scraping.
563
+ """
564
+ def clean(url):
565
+ "Tidy up an URL."
566
+ scheme, netloc, path, params, query, frag = urlparse(url)
567
+ return urlunparse((scheme, netloc, quote(path),
568
+ params, query, frag))
569
+
570
+ result = set()
571
+ for match in self._href.finditer(self.data):
572
+ d = match.groupdict('')
573
+ rel = (d['rel1'] or d['rel2'] or d['rel3'] or
574
+ d['rel4'] or d['rel5'] or d['rel6'])
575
+ url = d['url1'] or d['url2'] or d['url3']
576
+ url = urljoin(self.base_url, url)
577
+ url = unescape(url)
578
+ url = self._clean_re.sub(lambda m: '%%%2x' % ord(m.group(0)), url)
579
+ result.add((url, rel))
580
+ # We sort the result, hoping to bring the most recent versions
581
+ # to the front
582
+ result = sorted(result, key=lambda t: t[0], reverse=True)
583
+ return result
584
+
585
+
586
+ class SimpleScrapingLocator(Locator):
587
+ """
588
+ A locator which scrapes HTML pages to locate downloads for a distribution.
589
+ This runs multiple threads to do the I/O; performance is at least as good
590
+ as pip's PackageFinder, which works in an analogous fashion.
591
+ """
592
+
593
+ # These are used to deal with various Content-Encoding schemes.
594
+ decoders = {
595
+ 'deflate': zlib.decompress,
596
+ 'gzip': lambda b: gzip.GzipFile(fileobj=BytesIO(b)).read(),
597
+ 'none': lambda b: b,
598
+ }
599
+
600
+ def __init__(self, url, timeout=None, num_workers=10, **kwargs):
601
+ """
602
+ Initialise an instance.
603
+ :param url: The root URL to use for scraping.
604
+ :param timeout: The timeout, in seconds, to be applied to requests.
605
+ This defaults to ``None`` (no timeout specified).
606
+ :param num_workers: The number of worker threads you want to do I/O,
607
+ This defaults to 10.
608
+ :param kwargs: Passed to the superclass.
609
+ """
610
+ super(SimpleScrapingLocator, self).__init__(**kwargs)
611
+ self.base_url = ensure_slash(url)
612
+ self.timeout = timeout
613
+ self._page_cache = {}
614
+ self._seen = set()
615
+ self._to_fetch = queue.Queue()
616
+ self._bad_hosts = set()
617
+ self.skip_externals = False
618
+ self.num_workers = num_workers
619
+ self._lock = threading.RLock()
620
+ # See issue #45: we need to be resilient when the locator is used
621
+ # in a thread, e.g. with concurrent.futures. We can't use self._lock
622
+ # as it is for coordinating our internal threads - the ones created
623
+ # in _prepare_threads.
624
+ self._gplock = threading.RLock()
625
+ self.platform_check = False # See issue #112
626
+
627
+ def _prepare_threads(self):
628
+ """
629
+ Threads are created only when get_project is called, and terminate
630
+ before it returns. They are there primarily to parallelise I/O (i.e.
631
+ fetching web pages).
632
+ """
633
+ self._threads = []
634
+ for i in range(self.num_workers):
635
+ t = threading.Thread(target=self._fetch)
636
+ t.daemon = True
637
+ t.start()
638
+ self._threads.append(t)
639
+
640
+ def _wait_threads(self):
641
+ """
642
+ Tell all the threads to terminate (by sending a sentinel value) and
643
+ wait for them to do so.
644
+ """
645
+ # Note that you need two loops, since you can't say which
646
+ # thread will get each sentinel
647
+ for t in self._threads:
648
+ self._to_fetch.put(None) # sentinel
649
+ for t in self._threads:
650
+ t.join()
651
+ self._threads = []
652
+
653
+ def _get_project(self, name):
654
+ result = {'urls': {}, 'digests': {}}
655
+ with self._gplock:
656
+ self.result = result
657
+ self.project_name = name
658
+ url = urljoin(self.base_url, '%s/' % quote(name))
659
+ self._seen.clear()
660
+ self._page_cache.clear()
661
+ self._prepare_threads()
662
+ try:
663
+ logger.debug('Queueing %s', url)
664
+ self._to_fetch.put(url)
665
+ self._to_fetch.join()
666
+ finally:
667
+ self._wait_threads()
668
+ del self.result
669
+ return result
670
+
671
+ platform_dependent = re.compile(r'\b(linux_(i\d86|x86_64|arm\w+)|'
672
+ r'win(32|_amd64)|macosx_?\d+)\b', re.I)
673
+
674
+ def _is_platform_dependent(self, url):
675
+ """
676
+ Does an URL refer to a platform-specific download?
677
+ """
678
+ return self.platform_dependent.search(url)
679
+
680
+ def _process_download(self, url):
681
+ """
682
+ See if an URL is a suitable download for a project.
683
+
684
+ If it is, register information in the result dictionary (for
685
+ _get_project) about the specific version it's for.
686
+
687
+ Note that the return value isn't actually used other than as a boolean
688
+ value.
689
+ """
690
+ if self.platform_check and self._is_platform_dependent(url):
691
+ info = None
692
+ else:
693
+ info = self.convert_url_to_download_info(url, self.project_name)
694
+ logger.debug('process_download: %s -> %s', url, info)
695
+ if info:
696
+ with self._lock: # needed because self.result is shared
697
+ self._update_version_data(self.result, info)
698
+ return info
699
+
700
+ def _should_queue(self, link, referrer, rel):
701
+ """
702
+ Determine whether a link URL from a referring page and with a
703
+ particular "rel" attribute should be queued for scraping.
704
+ """
705
+ scheme, netloc, path, _, _, _ = urlparse(link)
706
+ if path.endswith(self.source_extensions + self.binary_extensions +
707
+ self.excluded_extensions):
708
+ result = False
709
+ elif self.skip_externals and not link.startswith(self.base_url):
710
+ result = False
711
+ elif not referrer.startswith(self.base_url):
712
+ result = False
713
+ elif rel not in ('homepage', 'download'):
714
+ result = False
715
+ elif scheme not in ('http', 'https', 'ftp'):
716
+ result = False
717
+ elif self._is_platform_dependent(link):
718
+ result = False
719
+ else:
720
+ host = netloc.split(':', 1)[0]
721
+ if host.lower() == 'localhost':
722
+ result = False
723
+ else:
724
+ result = True
725
+ logger.debug('should_queue: %s (%s) from %s -> %s', link, rel,
726
+ referrer, result)
727
+ return result
728
+
729
+ def _fetch(self):
730
+ """
731
+ Get a URL to fetch from the work queue, get the HTML page, examine its
732
+ links for download candidates and candidates for further scraping.
733
+
734
+ This is a handy method to run in a thread.
735
+ """
736
+ while True:
737
+ url = self._to_fetch.get()
738
+ try:
739
+ if url:
740
+ page = self.get_page(url)
741
+ if page is None: # e.g. after an error
742
+ continue
743
+ for link, rel in page.links:
744
+ if link not in self._seen:
745
+ try:
746
+ self._seen.add(link)
747
+ if (not self._process_download(link) and
748
+ self._should_queue(link, url, rel)):
749
+ logger.debug('Queueing %s from %s', link, url)
750
+ self._to_fetch.put(link)
751
+ except MetadataInvalidError: # e.g. invalid versions
752
+ pass
753
+ except Exception as e: # pragma: no cover
754
+ self.errors.put(text_type(e))
755
+ finally:
756
+ # always do this, to avoid hangs :-)
757
+ self._to_fetch.task_done()
758
+ if not url:
759
+ #logger.debug('Sentinel seen, quitting.')
760
+ break
761
+
762
+ def get_page(self, url):
763
+ """
764
+ Get the HTML for an URL, possibly from an in-memory cache.
765
+
766
+ XXX TODO Note: this cache is never actually cleared. It's assumed that
767
+ the data won't get stale over the lifetime of a locator instance (not
768
+ necessarily true for the default_locator).
769
+ """
770
+ # http://peak.telecommunity.com/DevCenter/EasyInstall#package-index-api
771
+ scheme, netloc, path, _, _, _ = urlparse(url)
772
+ if scheme == 'file' and os.path.isdir(url2pathname(path)):
773
+ url = urljoin(ensure_slash(url), 'index.html')
774
+
775
+ if url in self._page_cache:
776
+ result = self._page_cache[url]
777
+ logger.debug('Returning %s from cache: %s', url, result)
778
+ else:
779
+ host = netloc.split(':', 1)[0]
780
+ result = None
781
+ if host in self._bad_hosts:
782
+ logger.debug('Skipping %s due to bad host %s', url, host)
783
+ else:
784
+ req = Request(url, headers={'Accept-encoding': 'identity'})
785
+ try:
786
+ logger.debug('Fetching %s', url)
787
+ resp = self.opener.open(req, timeout=self.timeout)
788
+ logger.debug('Fetched %s', url)
789
+ headers = resp.info()
790
+ content_type = headers.get('Content-Type', '')
791
+ if HTML_CONTENT_TYPE.match(content_type):
792
+ final_url = resp.geturl()
793
+ data = resp.read()
794
+ encoding = headers.get('Content-Encoding')
795
+ if encoding:
796
+ decoder = self.decoders[encoding] # fail if not found
797
+ data = decoder(data)
798
+ encoding = 'utf-8'
799
+ m = CHARSET.search(content_type)
800
+ if m:
801
+ encoding = m.group(1)
802
+ try:
803
+ data = data.decode(encoding)
804
+ except UnicodeError: # pragma: no cover
805
+ data = data.decode('latin-1') # fallback
806
+ result = Page(data, final_url)
807
+ self._page_cache[final_url] = result
808
+ except HTTPError as e:
809
+ if e.code != 404:
810
+ logger.exception('Fetch failed: %s: %s', url, e)
811
+ except URLError as e: # pragma: no cover
812
+ logger.exception('Fetch failed: %s: %s', url, e)
813
+ with self._lock:
814
+ self._bad_hosts.add(host)
815
+ except Exception as e: # pragma: no cover
816
+ logger.exception('Fetch failed: %s: %s', url, e)
817
+ finally:
818
+ self._page_cache[url] = result # even if None (failure)
819
+ return result
820
+
821
+ _distname_re = re.compile('<a href=[^>]*>([^<]+)<')
822
+
823
+ def get_distribution_names(self):
824
+ """
825
+ Return all the distribution names known to this locator.
826
+ """
827
+ result = set()
828
+ page = self.get_page(self.base_url)
829
+ if not page:
830
+ raise DistlibException('Unable to get %s' % self.base_url)
831
+ for match in self._distname_re.finditer(page.data):
832
+ result.add(match.group(1))
833
+ return result
834
+
835
+ class DirectoryLocator(Locator):
836
+ """
837
+ This class locates distributions in a directory tree.
838
+ """
839
+
840
+ def __init__(self, path, **kwargs):
841
+ """
842
+ Initialise an instance.
843
+ :param path: The root of the directory tree to search.
844
+ :param kwargs: Passed to the superclass constructor,
845
+ except for:
846
+ * recursive - if True (the default), subdirectories are
847
+ recursed into. If False, only the top-level directory
848
+ is searched,
849
+ """
850
+ self.recursive = kwargs.pop('recursive', True)
851
+ super(DirectoryLocator, self).__init__(**kwargs)
852
+ path = os.path.abspath(path)
853
+ if not os.path.isdir(path): # pragma: no cover
854
+ raise DistlibException('Not a directory: %r' % path)
855
+ self.base_dir = path
856
+
857
+ def should_include(self, filename, parent):
858
+ """
859
+ Should a filename be considered as a candidate for a distribution
860
+ archive? As well as the filename, the directory which contains it
861
+ is provided, though not used by the current implementation.
862
+ """
863
+ return filename.endswith(self.downloadable_extensions)
864
+
865
+ def _get_project(self, name):
866
+ result = {'urls': {}, 'digests': {}}
867
+ for root, dirs, files in os.walk(self.base_dir):
868
+ for fn in files:
869
+ if self.should_include(fn, root):
870
+ fn = os.path.join(root, fn)
871
+ url = urlunparse(('file', '',
872
+ pathname2url(os.path.abspath(fn)),
873
+ '', '', ''))
874
+ info = self.convert_url_to_download_info(url, name)
875
+ if info:
876
+ self._update_version_data(result, info)
877
+ if not self.recursive:
878
+ break
879
+ return result
880
+
881
+ def get_distribution_names(self):
882
+ """
883
+ Return all the distribution names known to this locator.
884
+ """
885
+ result = set()
886
+ for root, dirs, files in os.walk(self.base_dir):
887
+ for fn in files:
888
+ if self.should_include(fn, root):
889
+ fn = os.path.join(root, fn)
890
+ url = urlunparse(('file', '',
891
+ pathname2url(os.path.abspath(fn)),
892
+ '', '', ''))
893
+ info = self.convert_url_to_download_info(url, None)
894
+ if info:
895
+ result.add(info['name'])
896
+ if not self.recursive:
897
+ break
898
+ return result
899
+
900
+ class JSONLocator(Locator):
901
+ """
902
+ This locator uses special extended metadata (not available on PyPI) and is
903
+ the basis of performant dependency resolution in distlib. Other locators
904
+ require archive downloads before dependencies can be determined! As you
905
+ might imagine, that can be slow.
906
+ """
907
+ def get_distribution_names(self):
908
+ """
909
+ Return all the distribution names known to this locator.
910
+ """
911
+ raise NotImplementedError('Not available from this locator')
912
+
913
+ def _get_project(self, name):
914
+ result = {'urls': {}, 'digests': {}}
915
+ data = get_project_data(name)
916
+ if data:
917
+ for info in data.get('files', []):
918
+ if info['ptype'] != 'sdist' or info['pyversion'] != 'source':
919
+ continue
920
+ # We don't store summary in project metadata as it makes
921
+ # the data bigger for no benefit during dependency
922
+ # resolution
923
+ dist = make_dist(data['name'], info['version'],
924
+ summary=data.get('summary',
925
+ 'Placeholder for summary'),
926
+ scheme=self.scheme)
927
+ md = dist.metadata
928
+ md.source_url = info['url']
929
+ # TODO SHA256 digest
930
+ if 'digest' in info and info['digest']:
931
+ dist.digest = ('md5', info['digest'])
932
+ md.dependencies = info.get('requirements', {})
933
+ dist.exports = info.get('exports', {})
934
+ result[dist.version] = dist
935
+ result['urls'].setdefault(dist.version, set()).add(info['url'])
936
+ return result
937
+
938
+ class DistPathLocator(Locator):
939
+ """
940
+ This locator finds installed distributions in a path. It can be useful for
941
+ adding to an :class:`AggregatingLocator`.
942
+ """
943
+ def __init__(self, distpath, **kwargs):
944
+ """
945
+ Initialise an instance.
946
+
947
+ :param distpath: A :class:`DistributionPath` instance to search.
948
+ """
949
+ super(DistPathLocator, self).__init__(**kwargs)
950
+ assert isinstance(distpath, DistributionPath)
951
+ self.distpath = distpath
952
+
953
+ def _get_project(self, name):
954
+ dist = self.distpath.get_distribution(name)
955
+ if dist is None:
956
+ result = {'urls': {}, 'digests': {}}
957
+ else:
958
+ result = {
959
+ dist.version: dist,
960
+ 'urls': {dist.version: set([dist.source_url])},
961
+ 'digests': {dist.version: set([None])}
962
+ }
963
+ return result
964
+
965
+
966
+ class AggregatingLocator(Locator):
967
+ """
968
+ This class allows you to chain and/or merge a list of locators.
969
+ """
970
+ def __init__(self, *locators, **kwargs):
971
+ """
972
+ Initialise an instance.
973
+
974
+ :param locators: The list of locators to search.
975
+ :param kwargs: Passed to the superclass constructor,
976
+ except for:
977
+ * merge - if False (the default), the first successful
978
+ search from any of the locators is returned. If True,
979
+ the results from all locators are merged (this can be
980
+ slow).
981
+ """
982
+ self.merge = kwargs.pop('merge', False)
983
+ self.locators = locators
984
+ super(AggregatingLocator, self).__init__(**kwargs)
985
+
986
+ def clear_cache(self):
987
+ super(AggregatingLocator, self).clear_cache()
988
+ for locator in self.locators:
989
+ locator.clear_cache()
990
+
991
+ def _set_scheme(self, value):
992
+ self._scheme = value
993
+ for locator in self.locators:
994
+ locator.scheme = value
995
+
996
+ scheme = property(Locator.scheme.fget, _set_scheme)
997
+
998
+ def _get_project(self, name):
999
+ result = {}
1000
+ for locator in self.locators:
1001
+ d = locator.get_project(name)
1002
+ if d:
1003
+ if self.merge:
1004
+ files = result.get('urls', {})
1005
+ digests = result.get('digests', {})
1006
+ # next line could overwrite result['urls'], result['digests']
1007
+ result.update(d)
1008
+ df = result.get('urls')
1009
+ if files and df:
1010
+ for k, v in files.items():
1011
+ if k in df:
1012
+ df[k] |= v
1013
+ else:
1014
+ df[k] = v
1015
+ dd = result.get('digests')
1016
+ if digests and dd:
1017
+ dd.update(digests)
1018
+ else:
1019
+ # See issue #18. If any dists are found and we're looking
1020
+ # for specific constraints, we only return something if
1021
+ # a match is found. For example, if a DirectoryLocator
1022
+ # returns just foo (1.0) while we're looking for
1023
+ # foo (>= 2.0), we'll pretend there was nothing there so
1024
+ # that subsequent locators can be queried. Otherwise we
1025
+ # would just return foo (1.0) which would then lead to a
1026
+ # failure to find foo (>= 2.0), because other locators
1027
+ # weren't searched. Note that this only matters when
1028
+ # merge=False.
1029
+ if self.matcher is None:
1030
+ found = True
1031
+ else:
1032
+ found = False
1033
+ for k in d:
1034
+ if self.matcher.match(k):
1035
+ found = True
1036
+ break
1037
+ if found:
1038
+ result = d
1039
+ break
1040
+ return result
1041
+
1042
+ def get_distribution_names(self):
1043
+ """
1044
+ Return all the distribution names known to this locator.
1045
+ """
1046
+ result = set()
1047
+ for locator in self.locators:
1048
+ try:
1049
+ result |= locator.get_distribution_names()
1050
+ except NotImplementedError:
1051
+ pass
1052
+ return result
1053
+
1054
+
1055
+ # We use a legacy scheme simply because most of the dists on PyPI use legacy
1056
+ # versions which don't conform to PEP 440.
1057
+ default_locator = AggregatingLocator(
1058
+ # JSONLocator(), # don't use as PEP 426 is withdrawn
1059
+ SimpleScrapingLocator('https://pypi.org/simple/',
1060
+ timeout=3.0),
1061
+ scheme='legacy')
1062
+
1063
+ locate = default_locator.locate
1064
+
1065
+
1066
+ class DependencyFinder(object):
1067
+ """
1068
+ Locate dependencies for distributions.
1069
+ """
1070
+
1071
+ def __init__(self, locator=None):
1072
+ """
1073
+ Initialise an instance, using the specified locator
1074
+ to locate distributions.
1075
+ """
1076
+ self.locator = locator or default_locator
1077
+ self.scheme = get_scheme(self.locator.scheme)
1078
+
1079
+ def add_distribution(self, dist):
1080
+ """
1081
+ Add a distribution to the finder. This will update internal information
1082
+ about who provides what.
1083
+ :param dist: The distribution to add.
1084
+ """
1085
+ logger.debug('adding distribution %s', dist)
1086
+ name = dist.key
1087
+ self.dists_by_name[name] = dist
1088
+ self.dists[(name, dist.version)] = dist
1089
+ for p in dist.provides:
1090
+ name, version = parse_name_and_version(p)
1091
+ logger.debug('Add to provided: %s, %s, %s', name, version, dist)
1092
+ self.provided.setdefault(name, set()).add((version, dist))
1093
+
1094
+ def remove_distribution(self, dist):
1095
+ """
1096
+ Remove a distribution from the finder. This will update internal
1097
+ information about who provides what.
1098
+ :param dist: The distribution to remove.
1099
+ """
1100
+ logger.debug('removing distribution %s', dist)
1101
+ name = dist.key
1102
+ del self.dists_by_name[name]
1103
+ del self.dists[(name, dist.version)]
1104
+ for p in dist.provides:
1105
+ name, version = parse_name_and_version(p)
1106
+ logger.debug('Remove from provided: %s, %s, %s', name, version, dist)
1107
+ s = self.provided[name]
1108
+ s.remove((version, dist))
1109
+ if not s:
1110
+ del self.provided[name]
1111
+
1112
+ def get_matcher(self, reqt):
1113
+ """
1114
+ Get a version matcher for a requirement.
1115
+ :param reqt: The requirement
1116
+ :type reqt: str
1117
+ :return: A version matcher (an instance of
1118
+ :class:`distlib.version.Matcher`).
1119
+ """
1120
+ try:
1121
+ matcher = self.scheme.matcher(reqt)
1122
+ except UnsupportedVersionError: # pragma: no cover
1123
+ # XXX compat-mode if cannot read the version
1124
+ name = reqt.split()[0]
1125
+ matcher = self.scheme.matcher(name)
1126
+ return matcher
1127
+
1128
+ def find_providers(self, reqt):
1129
+ """
1130
+ Find the distributions which can fulfill a requirement.
1131
+
1132
+ :param reqt: The requirement.
1133
+ :type reqt: str
1134
+ :return: A set of distribution which can fulfill the requirement.
1135
+ """
1136
+ matcher = self.get_matcher(reqt)
1137
+ name = matcher.key # case-insensitive
1138
+ result = set()
1139
+ provided = self.provided
1140
+ if name in provided:
1141
+ for version, provider in provided[name]:
1142
+ try:
1143
+ match = matcher.match(version)
1144
+ except UnsupportedVersionError:
1145
+ match = False
1146
+
1147
+ if match:
1148
+ result.add(provider)
1149
+ break
1150
+ return result
1151
+
1152
+ def try_to_replace(self, provider, other, problems):
1153
+ """
1154
+ Attempt to replace one provider with another. This is typically used
1155
+ when resolving dependencies from multiple sources, e.g. A requires
1156
+ (B >= 1.0) while C requires (B >= 1.1).
1157
+
1158
+ For successful replacement, ``provider`` must meet all the requirements
1159
+ which ``other`` fulfills.
1160
+
1161
+ :param provider: The provider we are trying to replace with.
1162
+ :param other: The provider we're trying to replace.
1163
+ :param problems: If False is returned, this will contain what
1164
+ problems prevented replacement. This is currently
1165
+ a tuple of the literal string 'cantreplace',
1166
+ ``provider``, ``other`` and the set of requirements
1167
+ that ``provider`` couldn't fulfill.
1168
+ :return: True if we can replace ``other`` with ``provider``, else
1169
+ False.
1170
+ """
1171
+ rlist = self.reqts[other]
1172
+ unmatched = set()
1173
+ for s in rlist:
1174
+ matcher = self.get_matcher(s)
1175
+ if not matcher.match(provider.version):
1176
+ unmatched.add(s)
1177
+ if unmatched:
1178
+ # can't replace other with provider
1179
+ problems.add(('cantreplace', provider, other,
1180
+ frozenset(unmatched)))
1181
+ result = False
1182
+ else:
1183
+ # can replace other with provider
1184
+ self.remove_distribution(other)
1185
+ del self.reqts[other]
1186
+ for s in rlist:
1187
+ self.reqts.setdefault(provider, set()).add(s)
1188
+ self.add_distribution(provider)
1189
+ result = True
1190
+ return result
1191
+
1192
+ def find(self, requirement, meta_extras=None, prereleases=False):
1193
+ """
1194
+ Find a distribution and all distributions it depends on.
1195
+
1196
+ :param requirement: The requirement specifying the distribution to
1197
+ find, or a Distribution instance.
1198
+ :param meta_extras: A list of meta extras such as :test:, :build: and
1199
+ so on.
1200
+ :param prereleases: If ``True``, allow pre-release versions to be
1201
+ returned - otherwise, don't return prereleases
1202
+ unless they're all that's available.
1203
+
1204
+ Return a set of :class:`Distribution` instances and a set of
1205
+ problems.
1206
+
1207
+ The distributions returned should be such that they have the
1208
+ :attr:`required` attribute set to ``True`` if they were
1209
+ from the ``requirement`` passed to ``find()``, and they have the
1210
+ :attr:`build_time_dependency` attribute set to ``True`` unless they
1211
+ are post-installation dependencies of the ``requirement``.
1212
+
1213
+ The problems should be a tuple consisting of the string
1214
+ ``'unsatisfied'`` and the requirement which couldn't be satisfied
1215
+ by any distribution known to the locator.
1216
+ """
1217
+
1218
+ self.provided = {}
1219
+ self.dists = {}
1220
+ self.dists_by_name = {}
1221
+ self.reqts = {}
1222
+
1223
+ meta_extras = set(meta_extras or [])
1224
+ if ':*:' in meta_extras:
1225
+ meta_extras.remove(':*:')
1226
+ # :meta: and :run: are implicitly included
1227
+ meta_extras |= set([':test:', ':build:', ':dev:'])
1228
+
1229
+ if isinstance(requirement, Distribution):
1230
+ dist = odist = requirement
1231
+ logger.debug('passed %s as requirement', odist)
1232
+ else:
1233
+ dist = odist = self.locator.locate(requirement,
1234
+ prereleases=prereleases)
1235
+ if dist is None:
1236
+ raise DistlibException('Unable to locate %r' % requirement)
1237
+ logger.debug('located %s', odist)
1238
+ dist.requested = True
1239
+ problems = set()
1240
+ todo = set([dist])
1241
+ install_dists = set([odist])
1242
+ while todo:
1243
+ dist = todo.pop()
1244
+ name = dist.key # case-insensitive
1245
+ if name not in self.dists_by_name:
1246
+ self.add_distribution(dist)
1247
+ else:
1248
+ #import pdb; pdb.set_trace()
1249
+ other = self.dists_by_name[name]
1250
+ if other != dist:
1251
+ self.try_to_replace(dist, other, problems)
1252
+
1253
+ ireqts = dist.run_requires | dist.meta_requires
1254
+ sreqts = dist.build_requires
1255
+ ereqts = set()
1256
+ if meta_extras and dist in install_dists:
1257
+ for key in ('test', 'build', 'dev'):
1258
+ e = ':%s:' % key
1259
+ if e in meta_extras:
1260
+ ereqts |= getattr(dist, '%s_requires' % key)
1261
+ all_reqts = ireqts | sreqts | ereqts
1262
+ for r in all_reqts:
1263
+ providers = self.find_providers(r)
1264
+ if not providers:
1265
+ logger.debug('No providers found for %r', r)
1266
+ provider = self.locator.locate(r, prereleases=prereleases)
1267
+ # If no provider is found and we didn't consider
1268
+ # prereleases, consider them now.
1269
+ if provider is None and not prereleases:
1270
+ provider = self.locator.locate(r, prereleases=True)
1271
+ if provider is None:
1272
+ logger.debug('Cannot satisfy %r', r)
1273
+ problems.add(('unsatisfied', r))
1274
+ else:
1275
+ n, v = provider.key, provider.version
1276
+ if (n, v) not in self.dists:
1277
+ todo.add(provider)
1278
+ providers.add(provider)
1279
+ if r in ireqts and dist in install_dists:
1280
+ install_dists.add(provider)
1281
+ logger.debug('Adding %s to install_dists',
1282
+ provider.name_and_version)
1283
+ for p in providers:
1284
+ name = p.key
1285
+ if name not in self.dists_by_name:
1286
+ self.reqts.setdefault(p, set()).add(r)
1287
+ else:
1288
+ other = self.dists_by_name[name]
1289
+ if other != p:
1290
+ # see if other can be replaced by p
1291
+ self.try_to_replace(p, other, problems)
1292
+
1293
+ dists = set(self.dists.values())
1294
+ for dist in dists:
1295
+ dist.build_time_dependency = dist not in install_dists
1296
+ if dist.build_time_dependency:
1297
+ logger.debug('%s is a build-time dependency only.',
1298
+ dist.name_and_version)
1299
+ logger.debug('find done for %s', odist)
1300
+ return dists, problems
.venv/Lib/site-packages/pip/_vendor/distlib/manifest.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2012-2013 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
+ class Manifest(object):
38
+ """A list of files built by on exploring the filesystem and filtered by
39
+ applying various patterns to what we find there.
40
+ """
41
+
42
+ def __init__(self, base=None):
43
+ """
44
+ Initialise an instance.
45
+
46
+ :param base: The base directory to explore under.
47
+ """
48
+ self.base = os.path.abspath(os.path.normpath(base or os.getcwd()))
49
+ self.prefix = self.base + os.sep
50
+ self.allfiles = None
51
+ self.files = set()
52
+
53
+ #
54
+ # Public API
55
+ #
56
+
57
+ def findall(self):
58
+ """Find all files under the base and set ``allfiles`` to the absolute
59
+ pathnames of files found.
60
+ """
61
+ from stat import S_ISREG, S_ISDIR, S_ISLNK
62
+
63
+ self.allfiles = allfiles = []
64
+ root = self.base
65
+ stack = [root]
66
+ pop = stack.pop
67
+ push = stack.append
68
+
69
+ while stack:
70
+ root = pop()
71
+ names = os.listdir(root)
72
+
73
+ for name in names:
74
+ fullname = os.path.join(root, name)
75
+
76
+ # Avoid excess stat calls -- just one will do, thank you!
77
+ stat = os.stat(fullname)
78
+ mode = stat.st_mode
79
+ if S_ISREG(mode):
80
+ allfiles.append(fsdecode(fullname))
81
+ elif S_ISDIR(mode) and not S_ISLNK(mode):
82
+ push(fullname)
83
+
84
+ def add(self, item):
85
+ """
86
+ Add a file to the manifest.
87
+
88
+ :param item: The pathname to add. This can be relative to the base.
89
+ """
90
+ if not item.startswith(self.prefix):
91
+ item = os.path.join(self.base, item)
92
+ self.files.add(os.path.normpath(item))
93
+
94
+ def add_many(self, items):
95
+ """
96
+ Add a list of files to the manifest.
97
+
98
+ :param items: The pathnames to add. These can be relative to the base.
99
+ """
100
+ for item in items:
101
+ self.add(item)
102
+
103
+ def sorted(self, wantdirs=False):
104
+ """
105
+ Return sorted files in directory order
106
+ """
107
+
108
+ def add_dir(dirs, d):
109
+ dirs.add(d)
110
+ logger.debug('add_dir added %s', d)
111
+ if d != self.base:
112
+ parent, _ = os.path.split(d)
113
+ assert parent not in ('', '/')
114
+ add_dir(dirs, parent)
115
+
116
+ result = set(self.files) # make a copy!
117
+ if wantdirs:
118
+ dirs = set()
119
+ for f in result:
120
+ add_dir(dirs, os.path.dirname(f))
121
+ result |= dirs
122
+ return [os.path.join(*path_tuple) for path_tuple in
123
+ sorted(os.path.split(path) for path in result)]
124
+
125
+ def clear(self):
126
+ """Clear all collected files."""
127
+ self.files = set()
128
+ self.allfiles = []
129
+
130
+ def process_directive(self, directive):
131
+ """
132
+ Process a directive which either adds some files from ``allfiles`` to
133
+ ``files``, or removes some files from ``files``.
134
+
135
+ :param directive: The directive to process. This should be in a format
136
+ compatible with distutils ``MANIFEST.in`` files:
137
+
138
+ http://docs.python.org/distutils/sourcedist.html#commands
139
+ """
140
+ # Parse the line: split it up, make sure the right number of words
141
+ # is there, and return the relevant words. 'action' is always
142
+ # defined: it's the first word of the line. Which of the other
143
+ # three are defined depends on the action; it'll be either
144
+ # patterns, (dir and patterns), or (dirpattern).
145
+ action, patterns, thedir, dirpattern = self._parse_directive(directive)
146
+
147
+ # OK, now we know that the action is valid and we have the
148
+ # right number of words on the line for that action -- so we
149
+ # can proceed with minimal error-checking.
150
+ if action == 'include':
151
+ for pattern in patterns:
152
+ if not self._include_pattern(pattern, anchor=True):
153
+ logger.warning('no files found matching %r', pattern)
154
+
155
+ elif action == 'exclude':
156
+ for pattern in patterns:
157
+ found = self._exclude_pattern(pattern, anchor=True)
158
+ #if not found:
159
+ # logger.warning('no previously-included files '
160
+ # 'found matching %r', pattern)
161
+
162
+ elif action == 'global-include':
163
+ for pattern in patterns:
164
+ if not self._include_pattern(pattern, anchor=False):
165
+ logger.warning('no files found matching %r '
166
+ 'anywhere in distribution', pattern)
167
+
168
+ elif action == 'global-exclude':
169
+ for pattern in patterns:
170
+ found = self._exclude_pattern(pattern, anchor=False)
171
+ #if not found:
172
+ # logger.warning('no previously-included files '
173
+ # 'matching %r found anywhere in '
174
+ # 'distribution', pattern)
175
+
176
+ elif action == 'recursive-include':
177
+ for pattern in patterns:
178
+ if not self._include_pattern(pattern, prefix=thedir):
179
+ logger.warning('no files found matching %r '
180
+ 'under directory %r', pattern, thedir)
181
+
182
+ elif action == 'recursive-exclude':
183
+ for pattern in patterns:
184
+ found = self._exclude_pattern(pattern, prefix=thedir)
185
+ #if not found:
186
+ # logger.warning('no previously-included files '
187
+ # 'matching %r found under directory %r',
188
+ # pattern, thedir)
189
+
190
+ elif action == 'graft':
191
+ if not self._include_pattern(None, prefix=dirpattern):
192
+ logger.warning('no directories found matching %r',
193
+ dirpattern)
194
+
195
+ elif action == 'prune':
196
+ if not self._exclude_pattern(None, prefix=dirpattern):
197
+ logger.warning('no previously-included directories found '
198
+ 'matching %r', dirpattern)
199
+ else: # pragma: no cover
200
+ # This should never happen, as it should be caught in
201
+ # _parse_template_line
202
+ raise DistlibException(
203
+ 'invalid action %r' % action)
204
+
205
+ #
206
+ # Private API
207
+ #
208
+
209
+ def _parse_directive(self, directive):
210
+ """
211
+ Validate a directive.
212
+ :param directive: The directive to validate.
213
+ :return: A tuple of action, patterns, thedir, dir_patterns
214
+ """
215
+ words = directive.split()
216
+ if len(words) == 1 and words[0] not in ('include', 'exclude',
217
+ 'global-include',
218
+ 'global-exclude',
219
+ 'recursive-include',
220
+ 'recursive-exclude',
221
+ 'graft', 'prune'):
222
+ # no action given, let's use the default 'include'
223
+ words.insert(0, 'include')
224
+
225
+ action = words[0]
226
+ patterns = thedir = dir_pattern = None
227
+
228
+ if action in ('include', 'exclude',
229
+ 'global-include', 'global-exclude'):
230
+ if len(words) < 2:
231
+ raise DistlibException(
232
+ '%r expects <pattern1> <pattern2> ...' % action)
233
+
234
+ patterns = [convert_path(word) for word in words[1:]]
235
+
236
+ elif action in ('recursive-include', 'recursive-exclude'):
237
+ if len(words) < 3:
238
+ raise DistlibException(
239
+ '%r expects <dir> <pattern1> <pattern2> ...' % action)
240
+
241
+ thedir = convert_path(words[1])
242
+ patterns = [convert_path(word) for word in words[2:]]
243
+
244
+ elif action in ('graft', 'prune'):
245
+ if len(words) != 2:
246
+ raise DistlibException(
247
+ '%r expects a single <dir_pattern>' % action)
248
+
249
+ dir_pattern = convert_path(words[1])
250
+
251
+ else:
252
+ raise DistlibException('unknown action %r' % action)
253
+
254
+ return action, patterns, thedir, dir_pattern
255
+
256
+ def _include_pattern(self, pattern, anchor=True, prefix=None,
257
+ is_regex=False):
258
+ """Select strings (presumably filenames) from 'self.files' that
259
+ match 'pattern', a Unix-style wildcard (glob) pattern.
260
+
261
+ Patterns are not quite the same as implemented by the 'fnmatch'
262
+ module: '*' and '?' match non-special characters, where "special"
263
+ is platform-dependent: slash on Unix; colon, slash, and backslash on
264
+ DOS/Windows; and colon on Mac OS.
265
+
266
+ If 'anchor' is true (the default), then the pattern match is more
267
+ stringent: "*.py" will match "foo.py" but not "foo/bar.py". If
268
+ 'anchor' is false, both of these will match.
269
+
270
+ If 'prefix' is supplied, then only filenames starting with 'prefix'
271
+ (itself a pattern) and ending with 'pattern', with anything in between
272
+ them, will match. 'anchor' is ignored in this case.
273
+
274
+ If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and
275
+ 'pattern' is assumed to be either a string containing a regex or a
276
+ regex object -- no translation is done, the regex is just compiled
277
+ and used as-is.
278
+
279
+ Selected strings will be added to self.files.
280
+
281
+ Return True if files are found.
282
+ """
283
+ # XXX docstring lying about what the special chars are?
284
+ found = False
285
+ pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex)
286
+
287
+ # delayed loading of allfiles list
288
+ if self.allfiles is None:
289
+ self.findall()
290
+
291
+ for name in self.allfiles:
292
+ if pattern_re.search(name):
293
+ self.files.add(name)
294
+ found = True
295
+ return found
296
+
297
+ def _exclude_pattern(self, pattern, anchor=True, prefix=None,
298
+ is_regex=False):
299
+ """Remove strings (presumably filenames) from 'files' that match
300
+ 'pattern'.
301
+
302
+ Other parameters are the same as for 'include_pattern()', above.
303
+ The list 'self.files' is modified in place. Return True if files are
304
+ found.
305
+
306
+ This API is public to allow e.g. exclusion of SCM subdirs, e.g. when
307
+ packaging source distributions
308
+ """
309
+ found = False
310
+ pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex)
311
+ for f in list(self.files):
312
+ if pattern_re.search(f):
313
+ self.files.remove(f)
314
+ found = True
315
+ return found
316
+
317
+ def _translate_pattern(self, pattern, anchor=True, prefix=None,
318
+ is_regex=False):
319
+ """Translate a shell-like wildcard pattern to a compiled regular
320
+ expression.
321
+
322
+ Return the compiled regex. If 'is_regex' true,
323
+ then 'pattern' is directly compiled to a regex (if it's a string)
324
+ or just returned as-is (assumes it's a regex object).
325
+ """
326
+ if is_regex:
327
+ if isinstance(pattern, str):
328
+ return re.compile(pattern)
329
+ else:
330
+ return pattern
331
+
332
+ if _PYTHON_VERSION > (3, 2):
333
+ # ditch start and end characters
334
+ start, _, end = self._glob_to_re('_').partition('_')
335
+
336
+ if pattern:
337
+ pattern_re = self._glob_to_re(pattern)
338
+ if _PYTHON_VERSION > (3, 2):
339
+ assert pattern_re.startswith(start) and pattern_re.endswith(end)
340
+ else:
341
+ pattern_re = ''
342
+
343
+ base = re.escape(os.path.join(self.base, ''))
344
+ if prefix is not None:
345
+ # ditch end of pattern character
346
+ if _PYTHON_VERSION <= (3, 2):
347
+ empty_pattern = self._glob_to_re('')
348
+ prefix_re = self._glob_to_re(prefix)[:-len(empty_pattern)]
349
+ else:
350
+ prefix_re = self._glob_to_re(prefix)
351
+ assert prefix_re.startswith(start) and prefix_re.endswith(end)
352
+ prefix_re = prefix_re[len(start): len(prefix_re) - len(end)]
353
+ sep = os.sep
354
+ if os.sep == '\\':
355
+ sep = r'\\'
356
+ if _PYTHON_VERSION <= (3, 2):
357
+ pattern_re = '^' + base + sep.join((prefix_re,
358
+ '.*' + pattern_re))
359
+ else:
360
+ pattern_re = pattern_re[len(start): len(pattern_re) - len(end)]
361
+ pattern_re = r'%s%s%s%s.*%s%s' % (start, base, prefix_re, sep,
362
+ pattern_re, end)
363
+ else: # no prefix -- respect anchor flag
364
+ if anchor:
365
+ if _PYTHON_VERSION <= (3, 2):
366
+ pattern_re = '^' + base + pattern_re
367
+ else:
368
+ pattern_re = r'%s%s%s' % (start, base, pattern_re[len(start):])
369
+
370
+ return re.compile(pattern_re)
371
+
372
+ def _glob_to_re(self, pattern):
373
+ """Translate a shell-like glob pattern to a regular expression.
374
+
375
+ Return a string containing the regex. Differs from
376
+ 'fnmatch.translate()' in that '*' does not match "special characters"
377
+ (which are platform-specific).
378
+ """
379
+ pattern_re = fnmatch.translate(pattern)
380
+
381
+ # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which
382
+ # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,
383
+ # and by extension they shouldn't match such "special characters" under
384
+ # any OS. So change all non-escaped dots in the RE to match any
385
+ # character except the special characters (currently: just os.sep).
386
+ sep = os.sep
387
+ if os.sep == '\\':
388
+ # we're using a regex to manipulate a regex, so we need
389
+ # to escape the backslash twice
390
+ sep = r'\\\\'
391
+ escaped = r'\1[^%s]' % sep
392
+ pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re)
393
+ return pattern_re
.venv/Lib/site-packages/pip/_vendor/distlib/markers.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2012-2017 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 NormalizedVersion as NV
23
+
24
+ __all__ = ['interpret']
25
+
26
+ _VERSION_PATTERN = re.compile(r'((\d+(\.\d+)*\w*)|\'(\d+(\.\d+)*\w*)\'|\"(\d+(\.\d+)*\w*)\")')
27
+
28
+ def _is_literal(o):
29
+ if not isinstance(o, string_types) or not o:
30
+ return False
31
+ return o[0] in '\'"'
32
+
33
+ def _get_versions(s):
34
+ result = []
35
+ for m in _VERSION_PATTERN.finditer(s):
36
+ result.append(NV(m.groups()[0]))
37
+ return set(result)
38
+
39
+ class Evaluator(object):
40
+ """
41
+ This class is used to evaluate marker expessions.
42
+ """
43
+
44
+ operations = {
45
+ '==': lambda x, y: x == y,
46
+ '===': lambda x, y: x == y,
47
+ '~=': lambda x, y: x == y or x > y,
48
+ '!=': lambda x, y: x != y,
49
+ '<': lambda x, y: x < y,
50
+ '<=': lambda x, y: x == y or x < y,
51
+ '>': lambda x, y: x > y,
52
+ '>=': lambda x, y: x == y or x > y,
53
+ 'and': lambda x, y: x and y,
54
+ 'or': lambda x, y: x or y,
55
+ 'in': lambda x, y: x in y,
56
+ 'not in': lambda x, y: x not in y,
57
+ }
58
+
59
+ def evaluate(self, expr, context):
60
+ """
61
+ Evaluate a marker expression returned by the :func:`parse_requirement`
62
+ function in the specified context.
63
+ """
64
+ if isinstance(expr, string_types):
65
+ if expr[0] in '\'"':
66
+ result = expr[1:-1]
67
+ else:
68
+ if expr not in context:
69
+ raise SyntaxError('unknown variable: %s' % expr)
70
+ result = context[expr]
71
+ else:
72
+ assert isinstance(expr, dict)
73
+ op = expr['op']
74
+ if op not in self.operations:
75
+ raise NotImplementedError('op not implemented: %s' % op)
76
+ elhs = expr['lhs']
77
+ erhs = expr['rhs']
78
+ if _is_literal(expr['lhs']) and _is_literal(expr['rhs']):
79
+ raise SyntaxError('invalid comparison: %s %s %s' % (elhs, op, erhs))
80
+
81
+ lhs = self.evaluate(elhs, context)
82
+ rhs = self.evaluate(erhs, context)
83
+ if ((elhs == 'python_version' or erhs == 'python_version') and
84
+ op in ('<', '<=', '>', '>=', '===', '==', '!=', '~=')):
85
+ lhs = NV(lhs)
86
+ rhs = NV(rhs)
87
+ elif elhs == 'python_version' and op in ('in', 'not in'):
88
+ lhs = NV(lhs)
89
+ rhs = _get_versions(rhs)
90
+ result = self.operations[op](lhs, rhs)
91
+ return result
92
+
93
+ _DIGITS = re.compile(r'\d+\.\d+')
94
+
95
+ def default_context():
96
+ def format_full_version(info):
97
+ version = '%s.%s.%s' % (info.major, info.minor, info.micro)
98
+ kind = info.releaselevel
99
+ if kind != 'final':
100
+ version += kind[0] + str(info.serial)
101
+ return version
102
+
103
+ if hasattr(sys, 'implementation'):
104
+ implementation_version = format_full_version(sys.implementation.version)
105
+ implementation_name = sys.implementation.name
106
+ else:
107
+ implementation_version = '0'
108
+ implementation_name = ''
109
+
110
+ ppv = platform.python_version()
111
+ m = _DIGITS.match(ppv)
112
+ pv = m.group(0)
113
+ result = {
114
+ 'implementation_name': implementation_name,
115
+ 'implementation_version': implementation_version,
116
+ 'os_name': os.name,
117
+ 'platform_machine': platform.machine(),
118
+ 'platform_python_implementation': platform.python_implementation(),
119
+ 'platform_release': platform.release(),
120
+ 'platform_system': platform.system(),
121
+ 'platform_version': platform.version(),
122
+ 'platform_in_venv': str(in_venv()),
123
+ 'python_full_version': ppv,
124
+ 'python_version': pv,
125
+ 'sys_platform': sys.platform,
126
+ }
127
+ return result
128
+
129
+ DEFAULT_CONTEXT = default_context()
130
+ del default_context
131
+
132
+ evaluator = Evaluator()
133
+
134
+ def interpret(marker, execution_context=None):
135
+ """
136
+ Interpret a marker and return a result depending on environment.
137
+
138
+ :param marker: The marker to interpret.
139
+ :type marker: str
140
+ :param execution_context: The context used for name lookup.
141
+ :type execution_context: mapping
142
+ """
143
+ try:
144
+ expr, rest = parse_marker(marker)
145
+ except Exception as e:
146
+ raise SyntaxError('Unable to interpret marker syntax: %s: %s' % (marker, e))
147
+ if rest and rest[0] != '#':
148
+ raise SyntaxError('unexpected trailing data in marker: %s: %s' % (marker, rest))
149
+ context = dict(DEFAULT_CONTEXT)
150
+ if execution_context:
151
+ context.update(execution_context)
152
+ return evaluator.evaluate(expr, context)
.venv/Lib/site-packages/pip/_vendor/distlib/metadata.py ADDED
@@ -0,0 +1,1076 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2012 The Python Software Foundation.
4
+ # See LICENSE.txt and CONTRIBUTORS.txt.
5
+ #
6
+ """Implementation of the Metadata for Python packages PEPs.
7
+
8
+ Supports all metadata formats (1.0, 1.1, 1.2, 1.3/2.1 and 2.2).
9
+ """
10
+ from __future__ import unicode_literals
11
+
12
+ import codecs
13
+ from email import message_from_file
14
+ import json
15
+ import logging
16
+ import re
17
+
18
+
19
+ from . import DistlibException, __version__
20
+ from .compat import StringIO, string_types, text_type
21
+ from .markers import interpret
22
+ from .util import extract_by_key, get_extras
23
+ from .version import get_scheme, PEP440_VERSION_RE
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ class MetadataMissingError(DistlibException):
29
+ """A required metadata is missing"""
30
+
31
+
32
+ class MetadataConflictError(DistlibException):
33
+ """Attempt to read or write metadata fields that are conflictual."""
34
+
35
+
36
+ class MetadataUnrecognizedVersionError(DistlibException):
37
+ """Unknown metadata version number."""
38
+
39
+
40
+ class MetadataInvalidError(DistlibException):
41
+ """A metadata value is invalid"""
42
+
43
+ # public API of this module
44
+ __all__ = ['Metadata', 'PKG_INFO_ENCODING', 'PKG_INFO_PREFERRED_VERSION']
45
+
46
+ # Encoding used for the PKG-INFO files
47
+ PKG_INFO_ENCODING = 'utf-8'
48
+
49
+ # preferred version. Hopefully will be changed
50
+ # to 1.2 once PEP 345 is supported everywhere
51
+ PKG_INFO_PREFERRED_VERSION = '1.1'
52
+
53
+ _LINE_PREFIX_1_2 = re.compile('\n \\|')
54
+ _LINE_PREFIX_PRE_1_2 = re.compile('\n ')
55
+ _241_FIELDS = ('Metadata-Version', 'Name', 'Version', 'Platform',
56
+ 'Summary', 'Description',
57
+ 'Keywords', 'Home-page', 'Author', 'Author-email',
58
+ 'License')
59
+
60
+ _314_FIELDS = ('Metadata-Version', 'Name', 'Version', 'Platform',
61
+ 'Supported-Platform', 'Summary', 'Description',
62
+ 'Keywords', 'Home-page', 'Author', 'Author-email',
63
+ 'License', 'Classifier', 'Download-URL', 'Obsoletes',
64
+ 'Provides', 'Requires')
65
+
66
+ _314_MARKERS = ('Obsoletes', 'Provides', 'Requires', 'Classifier',
67
+ 'Download-URL')
68
+
69
+ _345_FIELDS = ('Metadata-Version', 'Name', 'Version', 'Platform',
70
+ 'Supported-Platform', 'Summary', 'Description',
71
+ 'Keywords', 'Home-page', 'Author', 'Author-email',
72
+ 'Maintainer', 'Maintainer-email', 'License',
73
+ 'Classifier', 'Download-URL', 'Obsoletes-Dist',
74
+ 'Project-URL', 'Provides-Dist', 'Requires-Dist',
75
+ 'Requires-Python', 'Requires-External')
76
+
77
+ _345_MARKERS = ('Provides-Dist', 'Requires-Dist', 'Requires-Python',
78
+ 'Obsoletes-Dist', 'Requires-External', 'Maintainer',
79
+ 'Maintainer-email', 'Project-URL')
80
+
81
+ _426_FIELDS = ('Metadata-Version', 'Name', 'Version', 'Platform',
82
+ 'Supported-Platform', 'Summary', 'Description',
83
+ 'Keywords', 'Home-page', 'Author', 'Author-email',
84
+ 'Maintainer', 'Maintainer-email', 'License',
85
+ 'Classifier', 'Download-URL', 'Obsoletes-Dist',
86
+ 'Project-URL', 'Provides-Dist', 'Requires-Dist',
87
+ 'Requires-Python', 'Requires-External', 'Private-Version',
88
+ 'Obsoleted-By', 'Setup-Requires-Dist', 'Extension',
89
+ 'Provides-Extra')
90
+
91
+ _426_MARKERS = ('Private-Version', 'Provides-Extra', 'Obsoleted-By',
92
+ 'Setup-Requires-Dist', 'Extension')
93
+
94
+ # See issue #106: Sometimes 'Requires' and 'Provides' occur wrongly in
95
+ # the metadata. Include them in the tuple literal below to allow them
96
+ # (for now).
97
+ # Ditto for Obsoletes - see issue #140.
98
+ _566_FIELDS = _426_FIELDS + ('Description-Content-Type',
99
+ 'Requires', 'Provides', 'Obsoletes')
100
+
101
+ _566_MARKERS = ('Description-Content-Type',)
102
+
103
+ _643_MARKERS = ('Dynamic', 'License-File')
104
+
105
+ _643_FIELDS = _566_FIELDS + _643_MARKERS
106
+
107
+ _ALL_FIELDS = set()
108
+ _ALL_FIELDS.update(_241_FIELDS)
109
+ _ALL_FIELDS.update(_314_FIELDS)
110
+ _ALL_FIELDS.update(_345_FIELDS)
111
+ _ALL_FIELDS.update(_426_FIELDS)
112
+ _ALL_FIELDS.update(_566_FIELDS)
113
+ _ALL_FIELDS.update(_643_FIELDS)
114
+
115
+ EXTRA_RE = re.compile(r'''extra\s*==\s*("([^"]+)"|'([^']+)')''')
116
+
117
+
118
+ def _version2fieldlist(version):
119
+ if version == '1.0':
120
+ return _241_FIELDS
121
+ elif version == '1.1':
122
+ return _314_FIELDS
123
+ elif version == '1.2':
124
+ return _345_FIELDS
125
+ elif version in ('1.3', '2.1'):
126
+ # avoid adding field names if already there
127
+ return _345_FIELDS + tuple(f for f in _566_FIELDS if f not in _345_FIELDS)
128
+ elif version == '2.0':
129
+ raise ValueError('Metadata 2.0 is withdrawn and not supported')
130
+ # return _426_FIELDS
131
+ elif version == '2.2':
132
+ return _643_FIELDS
133
+ raise MetadataUnrecognizedVersionError(version)
134
+
135
+
136
+ def _best_version(fields):
137
+ """Detect the best version depending on the fields used."""
138
+ def _has_marker(keys, markers):
139
+ for marker in markers:
140
+ if marker in keys:
141
+ return True
142
+ return False
143
+
144
+ keys = []
145
+ for key, value in fields.items():
146
+ if value in ([], 'UNKNOWN', None):
147
+ continue
148
+ keys.append(key)
149
+
150
+ possible_versions = ['1.0', '1.1', '1.2', '1.3', '2.1', '2.2'] # 2.0 removed
151
+
152
+ # first let's try to see if a field is not part of one of the version
153
+ for key in keys:
154
+ if key not in _241_FIELDS and '1.0' in possible_versions:
155
+ possible_versions.remove('1.0')
156
+ logger.debug('Removed 1.0 due to %s', key)
157
+ if key not in _314_FIELDS and '1.1' in possible_versions:
158
+ possible_versions.remove('1.1')
159
+ logger.debug('Removed 1.1 due to %s', key)
160
+ if key not in _345_FIELDS and '1.2' in possible_versions:
161
+ possible_versions.remove('1.2')
162
+ logger.debug('Removed 1.2 due to %s', key)
163
+ if key not in _566_FIELDS and '1.3' in possible_versions:
164
+ possible_versions.remove('1.3')
165
+ logger.debug('Removed 1.3 due to %s', key)
166
+ if key not in _566_FIELDS and '2.1' in possible_versions:
167
+ if key != 'Description': # In 2.1, description allowed after headers
168
+ possible_versions.remove('2.1')
169
+ logger.debug('Removed 2.1 due to %s', key)
170
+ if key not in _643_FIELDS and '2.2' in possible_versions:
171
+ possible_versions.remove('2.2')
172
+ logger.debug('Removed 2.2 due to %s', key)
173
+ # if key not in _426_FIELDS and '2.0' in possible_versions:
174
+ # possible_versions.remove('2.0')
175
+ # logger.debug('Removed 2.0 due to %s', key)
176
+
177
+ # possible_version contains qualified versions
178
+ if len(possible_versions) == 1:
179
+ return possible_versions[0] # found !
180
+ elif len(possible_versions) == 0:
181
+ logger.debug('Out of options - unknown metadata set: %s', fields)
182
+ raise MetadataConflictError('Unknown metadata set')
183
+
184
+ # let's see if one unique marker is found
185
+ is_1_1 = '1.1' in possible_versions and _has_marker(keys, _314_MARKERS)
186
+ is_1_2 = '1.2' in possible_versions and _has_marker(keys, _345_MARKERS)
187
+ is_2_1 = '2.1' in possible_versions and _has_marker(keys, _566_MARKERS)
188
+ # is_2_0 = '2.0' in possible_versions and _has_marker(keys, _426_MARKERS)
189
+ is_2_2 = '2.2' in possible_versions and _has_marker(keys, _643_MARKERS)
190
+ if int(is_1_1) + int(is_1_2) + int(is_2_1) + int(is_2_2) > 1:
191
+ raise MetadataConflictError('You used incompatible 1.1/1.2/2.1/2.2 fields')
192
+
193
+ # we have the choice, 1.0, or 1.2, 2.1 or 2.2
194
+ # - 1.0 has a broken Summary field but works with all tools
195
+ # - 1.1 is to avoid
196
+ # - 1.2 fixes Summary but has little adoption
197
+ # - 2.1 adds more features
198
+ # - 2.2 is the latest
199
+ if not is_1_1 and not is_1_2 and not is_2_1 and not is_2_2:
200
+ # we couldn't find any specific marker
201
+ if PKG_INFO_PREFERRED_VERSION in possible_versions:
202
+ return PKG_INFO_PREFERRED_VERSION
203
+ if is_1_1:
204
+ return '1.1'
205
+ if is_1_2:
206
+ return '1.2'
207
+ if is_2_1:
208
+ return '2.1'
209
+ # if is_2_2:
210
+ # return '2.2'
211
+
212
+ return '2.2'
213
+
214
+ # This follows the rules about transforming keys as described in
215
+ # https://www.python.org/dev/peps/pep-0566/#id17
216
+ _ATTR2FIELD = {
217
+ name.lower().replace("-", "_"): name for name in _ALL_FIELDS
218
+ }
219
+ _FIELD2ATTR = {field: attr for attr, field in _ATTR2FIELD.items()}
220
+
221
+ _PREDICATE_FIELDS = ('Requires-Dist', 'Obsoletes-Dist', 'Provides-Dist')
222
+ _VERSIONS_FIELDS = ('Requires-Python',)
223
+ _VERSION_FIELDS = ('Version',)
224
+ _LISTFIELDS = ('Platform', 'Classifier', 'Obsoletes',
225
+ 'Requires', 'Provides', 'Obsoletes-Dist',
226
+ 'Provides-Dist', 'Requires-Dist', 'Requires-External',
227
+ 'Project-URL', 'Supported-Platform', 'Setup-Requires-Dist',
228
+ 'Provides-Extra', 'Extension', 'License-File')
229
+ _LISTTUPLEFIELDS = ('Project-URL',)
230
+
231
+ _ELEMENTSFIELD = ('Keywords',)
232
+
233
+ _UNICODEFIELDS = ('Author', 'Maintainer', 'Summary', 'Description')
234
+
235
+ _MISSING = object()
236
+
237
+ _FILESAFE = re.compile('[^A-Za-z0-9.]+')
238
+
239
+
240
+ def _get_name_and_version(name, version, for_filename=False):
241
+ """Return the distribution name with version.
242
+
243
+ If for_filename is true, return a filename-escaped form."""
244
+ if for_filename:
245
+ # For both name and version any runs of non-alphanumeric or '.'
246
+ # characters are replaced with a single '-'. Additionally any
247
+ # spaces in the version string become '.'
248
+ name = _FILESAFE.sub('-', name)
249
+ version = _FILESAFE.sub('-', version.replace(' ', '.'))
250
+ return '%s-%s' % (name, version)
251
+
252
+
253
+ class LegacyMetadata(object):
254
+ """The legacy metadata of a release.
255
+
256
+ Supports versions 1.0, 1.1, 1.2, 2.0 and 1.3/2.1 (auto-detected). You can
257
+ instantiate the class with one of these arguments (or none):
258
+ - *path*, the path to a metadata file
259
+ - *fileobj* give a file-like object with metadata as content
260
+ - *mapping* is a dict-like object
261
+ - *scheme* is a version scheme name
262
+ """
263
+ # TODO document the mapping API and UNKNOWN default key
264
+
265
+ def __init__(self, path=None, fileobj=None, mapping=None,
266
+ scheme='default'):
267
+ if [path, fileobj, mapping].count(None) < 2:
268
+ raise TypeError('path, fileobj and mapping are exclusive')
269
+ self._fields = {}
270
+ self.requires_files = []
271
+ self._dependencies = None
272
+ self.scheme = scheme
273
+ if path is not None:
274
+ self.read(path)
275
+ elif fileobj is not None:
276
+ self.read_file(fileobj)
277
+ elif mapping is not None:
278
+ self.update(mapping)
279
+ self.set_metadata_version()
280
+
281
+ def set_metadata_version(self):
282
+ self._fields['Metadata-Version'] = _best_version(self._fields)
283
+
284
+ def _write_field(self, fileobj, name, value):
285
+ fileobj.write('%s: %s\n' % (name, value))
286
+
287
+ def __getitem__(self, name):
288
+ return self.get(name)
289
+
290
+ def __setitem__(self, name, value):
291
+ return self.set(name, value)
292
+
293
+ def __delitem__(self, name):
294
+ field_name = self._convert_name(name)
295
+ try:
296
+ del self._fields[field_name]
297
+ except KeyError:
298
+ raise KeyError(name)
299
+
300
+ def __contains__(self, name):
301
+ return (name in self._fields or
302
+ self._convert_name(name) in self._fields)
303
+
304
+ def _convert_name(self, name):
305
+ if name in _ALL_FIELDS:
306
+ return name
307
+ name = name.replace('-', '_').lower()
308
+ return _ATTR2FIELD.get(name, name)
309
+
310
+ def _default_value(self, name):
311
+ if name in _LISTFIELDS or name in _ELEMENTSFIELD:
312
+ return []
313
+ return 'UNKNOWN'
314
+
315
+ def _remove_line_prefix(self, value):
316
+ if self.metadata_version in ('1.0', '1.1'):
317
+ return _LINE_PREFIX_PRE_1_2.sub('\n', value)
318
+ else:
319
+ return _LINE_PREFIX_1_2.sub('\n', value)
320
+
321
+ def __getattr__(self, name):
322
+ if name in _ATTR2FIELD:
323
+ return self[name]
324
+ raise AttributeError(name)
325
+
326
+ #
327
+ # Public API
328
+ #
329
+
330
+ # dependencies = property(_get_dependencies, _set_dependencies)
331
+
332
+ def get_fullname(self, filesafe=False):
333
+ """Return the distribution name with version.
334
+
335
+ If filesafe is true, return a filename-escaped form."""
336
+ return _get_name_and_version(self['Name'], self['Version'], filesafe)
337
+
338
+ def is_field(self, name):
339
+ """return True if name is a valid metadata key"""
340
+ name = self._convert_name(name)
341
+ return name in _ALL_FIELDS
342
+
343
+ def is_multi_field(self, name):
344
+ name = self._convert_name(name)
345
+ return name in _LISTFIELDS
346
+
347
+ def read(self, filepath):
348
+ """Read the metadata values from a file path."""
349
+ fp = codecs.open(filepath, 'r', encoding='utf-8')
350
+ try:
351
+ self.read_file(fp)
352
+ finally:
353
+ fp.close()
354
+
355
+ def read_file(self, fileob):
356
+ """Read the metadata values from a file object."""
357
+ msg = message_from_file(fileob)
358
+ self._fields['Metadata-Version'] = msg['metadata-version']
359
+
360
+ # When reading, get all the fields we can
361
+ for field in _ALL_FIELDS:
362
+ if field not in msg:
363
+ continue
364
+ if field in _LISTFIELDS:
365
+ # we can have multiple lines
366
+ values = msg.get_all(field)
367
+ if field in _LISTTUPLEFIELDS and values is not None:
368
+ values = [tuple(value.split(',')) for value in values]
369
+ self.set(field, values)
370
+ else:
371
+ # single line
372
+ value = msg[field]
373
+ if value is not None and value != 'UNKNOWN':
374
+ self.set(field, value)
375
+
376
+ # PEP 566 specifies that the body be used for the description, if
377
+ # available
378
+ body = msg.get_payload()
379
+ self["Description"] = body if body else self["Description"]
380
+ # logger.debug('Attempting to set metadata for %s', self)
381
+ # self.set_metadata_version()
382
+
383
+ def write(self, filepath, skip_unknown=False):
384
+ """Write the metadata fields to filepath."""
385
+ fp = codecs.open(filepath, 'w', encoding='utf-8')
386
+ try:
387
+ self.write_file(fp, skip_unknown)
388
+ finally:
389
+ fp.close()
390
+
391
+ def write_file(self, fileobject, skip_unknown=False):
392
+ """Write the PKG-INFO format data to a file object."""
393
+ self.set_metadata_version()
394
+
395
+ for field in _version2fieldlist(self['Metadata-Version']):
396
+ values = self.get(field)
397
+ if skip_unknown and values in ('UNKNOWN', [], ['UNKNOWN']):
398
+ continue
399
+ if field in _ELEMENTSFIELD:
400
+ self._write_field(fileobject, field, ','.join(values))
401
+ continue
402
+ if field not in _LISTFIELDS:
403
+ if field == 'Description':
404
+ if self.metadata_version in ('1.0', '1.1'):
405
+ values = values.replace('\n', '\n ')
406
+ else:
407
+ values = values.replace('\n', '\n |')
408
+ values = [values]
409
+
410
+ if field in _LISTTUPLEFIELDS:
411
+ values = [','.join(value) for value in values]
412
+
413
+ for value in values:
414
+ self._write_field(fileobject, field, value)
415
+
416
+ def update(self, other=None, **kwargs):
417
+ """Set metadata values from the given iterable `other` and kwargs.
418
+
419
+ Behavior is like `dict.update`: If `other` has a ``keys`` method,
420
+ they are looped over and ``self[key]`` is assigned ``other[key]``.
421
+ Else, ``other`` is an iterable of ``(key, value)`` iterables.
422
+
423
+ Keys that don't match a metadata field or that have an empty value are
424
+ dropped.
425
+ """
426
+ def _set(key, value):
427
+ if key in _ATTR2FIELD and value:
428
+ self.set(self._convert_name(key), value)
429
+
430
+ if not other:
431
+ # other is None or empty container
432
+ pass
433
+ elif hasattr(other, 'keys'):
434
+ for k in other.keys():
435
+ _set(k, other[k])
436
+ else:
437
+ for k, v in other:
438
+ _set(k, v)
439
+
440
+ if kwargs:
441
+ for k, v in kwargs.items():
442
+ _set(k, v)
443
+
444
+ def set(self, name, value):
445
+ """Control then set a metadata field."""
446
+ name = self._convert_name(name)
447
+
448
+ if ((name in _ELEMENTSFIELD or name == 'Platform') and
449
+ not isinstance(value, (list, tuple))):
450
+ if isinstance(value, string_types):
451
+ value = [v.strip() for v in value.split(',')]
452
+ else:
453
+ value = []
454
+ elif (name in _LISTFIELDS and
455
+ not isinstance(value, (list, tuple))):
456
+ if isinstance(value, string_types):
457
+ value = [value]
458
+ else:
459
+ value = []
460
+
461
+ if logger.isEnabledFor(logging.WARNING):
462
+ project_name = self['Name']
463
+
464
+ scheme = get_scheme(self.scheme)
465
+ if name in _PREDICATE_FIELDS and value is not None:
466
+ for v in value:
467
+ # check that the values are valid
468
+ if not scheme.is_valid_matcher(v.split(';')[0]):
469
+ logger.warning(
470
+ "'%s': '%s' is not valid (field '%s')",
471
+ project_name, v, name)
472
+ # FIXME this rejects UNKNOWN, is that right?
473
+ elif name in _VERSIONS_FIELDS and value is not None:
474
+ if not scheme.is_valid_constraint_list(value):
475
+ logger.warning("'%s': '%s' is not a valid version (field '%s')",
476
+ project_name, value, name)
477
+ elif name in _VERSION_FIELDS and value is not None:
478
+ if not scheme.is_valid_version(value):
479
+ logger.warning("'%s': '%s' is not a valid version (field '%s')",
480
+ project_name, value, name)
481
+
482
+ if name in _UNICODEFIELDS:
483
+ if name == 'Description':
484
+ value = self._remove_line_prefix(value)
485
+
486
+ self._fields[name] = value
487
+
488
+ def get(self, name, default=_MISSING):
489
+ """Get a metadata field."""
490
+ name = self._convert_name(name)
491
+ if name not in self._fields:
492
+ if default is _MISSING:
493
+ default = self._default_value(name)
494
+ return default
495
+ if name in _UNICODEFIELDS:
496
+ value = self._fields[name]
497
+ return value
498
+ elif name in _LISTFIELDS:
499
+ value = self._fields[name]
500
+ if value is None:
501
+ return []
502
+ res = []
503
+ for val in value:
504
+ if name not in _LISTTUPLEFIELDS:
505
+ res.append(val)
506
+ else:
507
+ # That's for Project-URL
508
+ res.append((val[0], val[1]))
509
+ return res
510
+
511
+ elif name in _ELEMENTSFIELD:
512
+ value = self._fields[name]
513
+ if isinstance(value, string_types):
514
+ return value.split(',')
515
+ return self._fields[name]
516
+
517
+ def check(self, strict=False):
518
+ """Check if the metadata is compliant. If strict is True then raise if
519
+ no Name or Version are provided"""
520
+ self.set_metadata_version()
521
+
522
+ # XXX should check the versions (if the file was loaded)
523
+ missing, warnings = [], []
524
+
525
+ for attr in ('Name', 'Version'): # required by PEP 345
526
+ if attr not in self:
527
+ missing.append(attr)
528
+
529
+ if strict and missing != []:
530
+ msg = 'missing required metadata: %s' % ', '.join(missing)
531
+ raise MetadataMissingError(msg)
532
+
533
+ for attr in ('Home-page', 'Author'):
534
+ if attr not in self:
535
+ missing.append(attr)
536
+
537
+ # checking metadata 1.2 (XXX needs to check 1.1, 1.0)
538
+ if self['Metadata-Version'] != '1.2':
539
+ return missing, warnings
540
+
541
+ scheme = get_scheme(self.scheme)
542
+
543
+ def are_valid_constraints(value):
544
+ for v in value:
545
+ if not scheme.is_valid_matcher(v.split(';')[0]):
546
+ return False
547
+ return True
548
+
549
+ for fields, controller in ((_PREDICATE_FIELDS, are_valid_constraints),
550
+ (_VERSIONS_FIELDS,
551
+ scheme.is_valid_constraint_list),
552
+ (_VERSION_FIELDS,
553
+ scheme.is_valid_version)):
554
+ for field in fields:
555
+ value = self.get(field, None)
556
+ if value is not None and not controller(value):
557
+ warnings.append("Wrong value for '%s': %s" % (field, value))
558
+
559
+ return missing, warnings
560
+
561
+ def todict(self, skip_missing=False):
562
+ """Return fields as a dict.
563
+
564
+ Field names will be converted to use the underscore-lowercase style
565
+ instead of hyphen-mixed case (i.e. home_page instead of Home-page).
566
+ This is as per https://www.python.org/dev/peps/pep-0566/#id17.
567
+ """
568
+ self.set_metadata_version()
569
+
570
+ fields = _version2fieldlist(self['Metadata-Version'])
571
+
572
+ data = {}
573
+
574
+ for field_name in fields:
575
+ if not skip_missing or field_name in self._fields:
576
+ key = _FIELD2ATTR[field_name]
577
+ if key != 'project_url':
578
+ data[key] = self[field_name]
579
+ else:
580
+ data[key] = [','.join(u) for u in self[field_name]]
581
+
582
+ return data
583
+
584
+ def add_requirements(self, requirements):
585
+ if self['Metadata-Version'] == '1.1':
586
+ # we can't have 1.1 metadata *and* Setuptools requires
587
+ for field in ('Obsoletes', 'Requires', 'Provides'):
588
+ if field in self:
589
+ del self[field]
590
+ self['Requires-Dist'] += requirements
591
+
592
+ # Mapping API
593
+ # TODO could add iter* variants
594
+
595
+ def keys(self):
596
+ return list(_version2fieldlist(self['Metadata-Version']))
597
+
598
+ def __iter__(self):
599
+ for key in self.keys():
600
+ yield key
601
+
602
+ def values(self):
603
+ return [self[key] for key in self.keys()]
604
+
605
+ def items(self):
606
+ return [(key, self[key]) for key in self.keys()]
607
+
608
+ def __repr__(self):
609
+ return '<%s %s %s>' % (self.__class__.__name__, self.name,
610
+ self.version)
611
+
612
+
613
+ METADATA_FILENAME = 'pydist.json'
614
+ WHEEL_METADATA_FILENAME = 'metadata.json'
615
+ LEGACY_METADATA_FILENAME = 'METADATA'
616
+
617
+
618
+ class Metadata(object):
619
+ """
620
+ The metadata of a release. This implementation uses 2.1
621
+ metadata where possible. If not possible, it wraps a LegacyMetadata
622
+ instance which handles the key-value metadata format.
623
+ """
624
+
625
+ METADATA_VERSION_MATCHER = re.compile(r'^\d+(\.\d+)*$')
626
+
627
+ NAME_MATCHER = re.compile('^[0-9A-Z]([0-9A-Z_.-]*[0-9A-Z])?$', re.I)
628
+
629
+ FIELDNAME_MATCHER = re.compile('^[A-Z]([0-9A-Z-]*[0-9A-Z])?$', re.I)
630
+
631
+ VERSION_MATCHER = PEP440_VERSION_RE
632
+
633
+ SUMMARY_MATCHER = re.compile('.{1,2047}')
634
+
635
+ METADATA_VERSION = '2.0'
636
+
637
+ GENERATOR = 'distlib (%s)' % __version__
638
+
639
+ MANDATORY_KEYS = {
640
+ 'name': (),
641
+ 'version': (),
642
+ 'summary': ('legacy',),
643
+ }
644
+
645
+ INDEX_KEYS = ('name version license summary description author '
646
+ 'author_email keywords platform home_page classifiers '
647
+ 'download_url')
648
+
649
+ DEPENDENCY_KEYS = ('extras run_requires test_requires build_requires '
650
+ 'dev_requires provides meta_requires obsoleted_by '
651
+ 'supports_environments')
652
+
653
+ SYNTAX_VALIDATORS = {
654
+ 'metadata_version': (METADATA_VERSION_MATCHER, ()),
655
+ 'name': (NAME_MATCHER, ('legacy',)),
656
+ 'version': (VERSION_MATCHER, ('legacy',)),
657
+ 'summary': (SUMMARY_MATCHER, ('legacy',)),
658
+ 'dynamic': (FIELDNAME_MATCHER, ('legacy',)),
659
+ }
660
+
661
+ __slots__ = ('_legacy', '_data', 'scheme')
662
+
663
+ def __init__(self, path=None, fileobj=None, mapping=None,
664
+ scheme='default'):
665
+ if [path, fileobj, mapping].count(None) < 2:
666
+ raise TypeError('path, fileobj and mapping are exclusive')
667
+ self._legacy = None
668
+ self._data = None
669
+ self.scheme = scheme
670
+ #import pdb; pdb.set_trace()
671
+ if mapping is not None:
672
+ try:
673
+ self._validate_mapping(mapping, scheme)
674
+ self._data = mapping
675
+ except MetadataUnrecognizedVersionError:
676
+ self._legacy = LegacyMetadata(mapping=mapping, scheme=scheme)
677
+ self.validate()
678
+ else:
679
+ data = None
680
+ if path:
681
+ with open(path, 'rb') as f:
682
+ data = f.read()
683
+ elif fileobj:
684
+ data = fileobj.read()
685
+ if data is None:
686
+ # Initialised with no args - to be added
687
+ self._data = {
688
+ 'metadata_version': self.METADATA_VERSION,
689
+ 'generator': self.GENERATOR,
690
+ }
691
+ else:
692
+ if not isinstance(data, text_type):
693
+ data = data.decode('utf-8')
694
+ try:
695
+ self._data = json.loads(data)
696
+ self._validate_mapping(self._data, scheme)
697
+ except ValueError:
698
+ # Note: MetadataUnrecognizedVersionError does not
699
+ # inherit from ValueError (it's a DistlibException,
700
+ # which should not inherit from ValueError).
701
+ # The ValueError comes from the json.load - if that
702
+ # succeeds and we get a validation error, we want
703
+ # that to propagate
704
+ self._legacy = LegacyMetadata(fileobj=StringIO(data),
705
+ scheme=scheme)
706
+ self.validate()
707
+
708
+ common_keys = set(('name', 'version', 'license', 'keywords', 'summary'))
709
+
710
+ none_list = (None, list)
711
+ none_dict = (None, dict)
712
+
713
+ mapped_keys = {
714
+ 'run_requires': ('Requires-Dist', list),
715
+ 'build_requires': ('Setup-Requires-Dist', list),
716
+ 'dev_requires': none_list,
717
+ 'test_requires': none_list,
718
+ 'meta_requires': none_list,
719
+ 'extras': ('Provides-Extra', list),
720
+ 'modules': none_list,
721
+ 'namespaces': none_list,
722
+ 'exports': none_dict,
723
+ 'commands': none_dict,
724
+ 'classifiers': ('Classifier', list),
725
+ 'source_url': ('Download-URL', None),
726
+ 'metadata_version': ('Metadata-Version', None),
727
+ }
728
+
729
+ del none_list, none_dict
730
+
731
+ def __getattribute__(self, key):
732
+ common = object.__getattribute__(self, 'common_keys')
733
+ mapped = object.__getattribute__(self, 'mapped_keys')
734
+ if key in mapped:
735
+ lk, maker = mapped[key]
736
+ if self._legacy:
737
+ if lk is None:
738
+ result = None if maker is None else maker()
739
+ else:
740
+ result = self._legacy.get(lk)
741
+ else:
742
+ value = None if maker is None else maker()
743
+ if key not in ('commands', 'exports', 'modules', 'namespaces',
744
+ 'classifiers'):
745
+ result = self._data.get(key, value)
746
+ else:
747
+ # special cases for PEP 459
748
+ sentinel = object()
749
+ result = sentinel
750
+ d = self._data.get('extensions')
751
+ if d:
752
+ if key == 'commands':
753
+ result = d.get('python.commands', value)
754
+ elif key == 'classifiers':
755
+ d = d.get('python.details')
756
+ if d:
757
+ result = d.get(key, value)
758
+ else:
759
+ d = d.get('python.exports')
760
+ if not d:
761
+ d = self._data.get('python.exports')
762
+ if d:
763
+ result = d.get(key, value)
764
+ if result is sentinel:
765
+ result = value
766
+ elif key not in common:
767
+ result = object.__getattribute__(self, key)
768
+ elif self._legacy:
769
+ result = self._legacy.get(key)
770
+ else:
771
+ result = self._data.get(key)
772
+ return result
773
+
774
+ def _validate_value(self, key, value, scheme=None):
775
+ if key in self.SYNTAX_VALIDATORS:
776
+ pattern, exclusions = self.SYNTAX_VALIDATORS[key]
777
+ if (scheme or self.scheme) not in exclusions:
778
+ m = pattern.match(value)
779
+ if not m:
780
+ raise MetadataInvalidError("'%s' is an invalid value for "
781
+ "the '%s' property" % (value,
782
+ key))
783
+
784
+ def __setattr__(self, key, value):
785
+ self._validate_value(key, value)
786
+ common = object.__getattribute__(self, 'common_keys')
787
+ mapped = object.__getattribute__(self, 'mapped_keys')
788
+ if key in mapped:
789
+ lk, _ = mapped[key]
790
+ if self._legacy:
791
+ if lk is None:
792
+ raise NotImplementedError
793
+ self._legacy[lk] = value
794
+ elif key not in ('commands', 'exports', 'modules', 'namespaces',
795
+ 'classifiers'):
796
+ self._data[key] = value
797
+ else:
798
+ # special cases for PEP 459
799
+ d = self._data.setdefault('extensions', {})
800
+ if key == 'commands':
801
+ d['python.commands'] = value
802
+ elif key == 'classifiers':
803
+ d = d.setdefault('python.details', {})
804
+ d[key] = value
805
+ else:
806
+ d = d.setdefault('python.exports', {})
807
+ d[key] = value
808
+ elif key not in common:
809
+ object.__setattr__(self, key, value)
810
+ else:
811
+ if key == 'keywords':
812
+ if isinstance(value, string_types):
813
+ value = value.strip()
814
+ if value:
815
+ value = value.split()
816
+ else:
817
+ value = []
818
+ if self._legacy:
819
+ self._legacy[key] = value
820
+ else:
821
+ self._data[key] = value
822
+
823
+ @property
824
+ def name_and_version(self):
825
+ return _get_name_and_version(self.name, self.version, True)
826
+
827
+ @property
828
+ def provides(self):
829
+ if self._legacy:
830
+ result = self._legacy['Provides-Dist']
831
+ else:
832
+ result = self._data.setdefault('provides', [])
833
+ s = '%s (%s)' % (self.name, self.version)
834
+ if s not in result:
835
+ result.append(s)
836
+ return result
837
+
838
+ @provides.setter
839
+ def provides(self, value):
840
+ if self._legacy:
841
+ self._legacy['Provides-Dist'] = value
842
+ else:
843
+ self._data['provides'] = value
844
+
845
+ def get_requirements(self, reqts, extras=None, env=None):
846
+ """
847
+ Base method to get dependencies, given a set of extras
848
+ to satisfy and an optional environment context.
849
+ :param reqts: A list of sometimes-wanted dependencies,
850
+ perhaps dependent on extras and environment.
851
+ :param extras: A list of optional components being requested.
852
+ :param env: An optional environment for marker evaluation.
853
+ """
854
+ if self._legacy:
855
+ result = reqts
856
+ else:
857
+ result = []
858
+ extras = get_extras(extras or [], self.extras)
859
+ for d in reqts:
860
+ if 'extra' not in d and 'environment' not in d:
861
+ # unconditional
862
+ include = True
863
+ else:
864
+ if 'extra' not in d:
865
+ # Not extra-dependent - only environment-dependent
866
+ include = True
867
+ else:
868
+ include = d.get('extra') in extras
869
+ if include:
870
+ # Not excluded because of extras, check environment
871
+ marker = d.get('environment')
872
+ if marker:
873
+ include = interpret(marker, env)
874
+ if include:
875
+ result.extend(d['requires'])
876
+ for key in ('build', 'dev', 'test'):
877
+ e = ':%s:' % key
878
+ if e in extras:
879
+ extras.remove(e)
880
+ # A recursive call, but it should terminate since 'test'
881
+ # has been removed from the extras
882
+ reqts = self._data.get('%s_requires' % key, [])
883
+ result.extend(self.get_requirements(reqts, extras=extras,
884
+ env=env))
885
+ return result
886
+
887
+ @property
888
+ def dictionary(self):
889
+ if self._legacy:
890
+ return self._from_legacy()
891
+ return self._data
892
+
893
+ @property
894
+ def dependencies(self):
895
+ if self._legacy:
896
+ raise NotImplementedError
897
+ else:
898
+ return extract_by_key(self._data, self.DEPENDENCY_KEYS)
899
+
900
+ @dependencies.setter
901
+ def dependencies(self, value):
902
+ if self._legacy:
903
+ raise NotImplementedError
904
+ else:
905
+ self._data.update(value)
906
+
907
+ def _validate_mapping(self, mapping, scheme):
908
+ if mapping.get('metadata_version') != self.METADATA_VERSION:
909
+ raise MetadataUnrecognizedVersionError()
910
+ missing = []
911
+ for key, exclusions in self.MANDATORY_KEYS.items():
912
+ if key not in mapping:
913
+ if scheme not in exclusions:
914
+ missing.append(key)
915
+ if missing:
916
+ msg = 'Missing metadata items: %s' % ', '.join(missing)
917
+ raise MetadataMissingError(msg)
918
+ for k, v in mapping.items():
919
+ self._validate_value(k, v, scheme)
920
+
921
+ def validate(self):
922
+ if self._legacy:
923
+ missing, warnings = self._legacy.check(True)
924
+ if missing or warnings:
925
+ logger.warning('Metadata: missing: %s, warnings: %s',
926
+ missing, warnings)
927
+ else:
928
+ self._validate_mapping(self._data, self.scheme)
929
+
930
+ def todict(self):
931
+ if self._legacy:
932
+ return self._legacy.todict(True)
933
+ else:
934
+ result = extract_by_key(self._data, self.INDEX_KEYS)
935
+ return result
936
+
937
+ def _from_legacy(self):
938
+ assert self._legacy and not self._data
939
+ result = {
940
+ 'metadata_version': self.METADATA_VERSION,
941
+ 'generator': self.GENERATOR,
942
+ }
943
+ lmd = self._legacy.todict(True) # skip missing ones
944
+ for k in ('name', 'version', 'license', 'summary', 'description',
945
+ 'classifier'):
946
+ if k in lmd:
947
+ if k == 'classifier':
948
+ nk = 'classifiers'
949
+ else:
950
+ nk = k
951
+ result[nk] = lmd[k]
952
+ kw = lmd.get('Keywords', [])
953
+ if kw == ['']:
954
+ kw = []
955
+ result['keywords'] = kw
956
+ keys = (('requires_dist', 'run_requires'),
957
+ ('setup_requires_dist', 'build_requires'))
958
+ for ok, nk in keys:
959
+ if ok in lmd and lmd[ok]:
960
+ result[nk] = [{'requires': lmd[ok]}]
961
+ result['provides'] = self.provides
962
+ author = {}
963
+ maintainer = {}
964
+ return result
965
+
966
+ LEGACY_MAPPING = {
967
+ 'name': 'Name',
968
+ 'version': 'Version',
969
+ ('extensions', 'python.details', 'license'): 'License',
970
+ 'summary': 'Summary',
971
+ 'description': 'Description',
972
+ ('extensions', 'python.project', 'project_urls', 'Home'): 'Home-page',
973
+ ('extensions', 'python.project', 'contacts', 0, 'name'): 'Author',
974
+ ('extensions', 'python.project', 'contacts', 0, 'email'): 'Author-email',
975
+ 'source_url': 'Download-URL',
976
+ ('extensions', 'python.details', 'classifiers'): 'Classifier',
977
+ }
978
+
979
+ def _to_legacy(self):
980
+ def process_entries(entries):
981
+ reqts = set()
982
+ for e in entries:
983
+ extra = e.get('extra')
984
+ env = e.get('environment')
985
+ rlist = e['requires']
986
+ for r in rlist:
987
+ if not env and not extra:
988
+ reqts.add(r)
989
+ else:
990
+ marker = ''
991
+ if extra:
992
+ marker = 'extra == "%s"' % extra
993
+ if env:
994
+ if marker:
995
+ marker = '(%s) and %s' % (env, marker)
996
+ else:
997
+ marker = env
998
+ reqts.add(';'.join((r, marker)))
999
+ return reqts
1000
+
1001
+ assert self._data and not self._legacy
1002
+ result = LegacyMetadata()
1003
+ nmd = self._data
1004
+ # import pdb; pdb.set_trace()
1005
+ for nk, ok in self.LEGACY_MAPPING.items():
1006
+ if not isinstance(nk, tuple):
1007
+ if nk in nmd:
1008
+ result[ok] = nmd[nk]
1009
+ else:
1010
+ d = nmd
1011
+ found = True
1012
+ for k in nk:
1013
+ try:
1014
+ d = d[k]
1015
+ except (KeyError, IndexError):
1016
+ found = False
1017
+ break
1018
+ if found:
1019
+ result[ok] = d
1020
+ r1 = process_entries(self.run_requires + self.meta_requires)
1021
+ r2 = process_entries(self.build_requires + self.dev_requires)
1022
+ if self.extras:
1023
+ result['Provides-Extra'] = sorted(self.extras)
1024
+ result['Requires-Dist'] = sorted(r1)
1025
+ result['Setup-Requires-Dist'] = sorted(r2)
1026
+ # TODO: any other fields wanted
1027
+ return result
1028
+
1029
+ def write(self, path=None, fileobj=None, legacy=False, skip_unknown=True):
1030
+ if [path, fileobj].count(None) != 1:
1031
+ raise ValueError('Exactly one of path and fileobj is needed')
1032
+ self.validate()
1033
+ if legacy:
1034
+ if self._legacy:
1035
+ legacy_md = self._legacy
1036
+ else:
1037
+ legacy_md = self._to_legacy()
1038
+ if path:
1039
+ legacy_md.write(path, skip_unknown=skip_unknown)
1040
+ else:
1041
+ legacy_md.write_file(fileobj, skip_unknown=skip_unknown)
1042
+ else:
1043
+ if self._legacy:
1044
+ d = self._from_legacy()
1045
+ else:
1046
+ d = self._data
1047
+ if fileobj:
1048
+ json.dump(d, fileobj, ensure_ascii=True, indent=2,
1049
+ sort_keys=True)
1050
+ else:
1051
+ with codecs.open(path, 'w', 'utf-8') as f:
1052
+ json.dump(d, f, ensure_ascii=True, indent=2,
1053
+ sort_keys=True)
1054
+
1055
+ def add_requirements(self, requirements):
1056
+ if self._legacy:
1057
+ self._legacy.add_requirements(requirements)
1058
+ else:
1059
+ run_requires = self._data.setdefault('run_requires', [])
1060
+ always = None
1061
+ for entry in run_requires:
1062
+ if 'environment' not in entry and 'extra' not in entry:
1063
+ always = entry
1064
+ break
1065
+ if always is None:
1066
+ always = { 'requires': requirements }
1067
+ run_requires.insert(0, always)
1068
+ else:
1069
+ rset = set(always['requires']) | set(requirements)
1070
+ always['requires'] = sorted(rset)
1071
+
1072
+ def __repr__(self):
1073
+ name = self.name or '(no name)'
1074
+ version = self.version or 'no version'
1075
+ return '<%s %s %s (%s)>' % (self.__class__.__name__,
1076
+ self.metadata_version, name, version)
.venv/Lib/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
.venv/Lib/site-packages/pip/_vendor/distlib/scripts.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2013-2015 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,
19
+ get_executable, get_platform, in_venv)
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ _DEFAULT_MANIFEST = '''
24
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
25
+ <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
26
+ <assemblyIdentity version="1.0.0.0"
27
+ processorArchitecture="X86"
28
+ name="%s"
29
+ type="win32"/>
30
+
31
+ <!-- Identify the application security requirements. -->
32
+ <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
33
+ <security>
34
+ <requestedPrivileges>
35
+ <requestedExecutionLevel level="asInvoker" uiAccess="false"/>
36
+ </requestedPrivileges>
37
+ </security>
38
+ </trustInfo>
39
+ </assembly>'''.strip()
40
+
41
+ # check if Python is called on the first line with this expression
42
+ FIRST_LINE_RE = re.compile(b'^#!.*pythonw?[0-9.]*([ \t].*)?$')
43
+ SCRIPT_TEMPLATE = r'''# -*- coding: utf-8 -*-
44
+ import re
45
+ import sys
46
+ from %(module)s import %(import_name)s
47
+ if __name__ == '__main__':
48
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
49
+ sys.exit(%(func)s())
50
+ '''
51
+
52
+
53
+ def enquote_executable(executable):
54
+ if ' ' in executable:
55
+ # make sure we quote only the executable in case of env
56
+ # for example /usr/bin/env "/dir with spaces/bin/jython"
57
+ # instead of "/usr/bin/env /dir with spaces/bin/jython"
58
+ # otherwise whole
59
+ if executable.startswith('/usr/bin/env '):
60
+ env, _executable = executable.split(' ', 1)
61
+ if ' ' in _executable and not _executable.startswith('"'):
62
+ executable = '%s "%s"' % (env, _executable)
63
+ else:
64
+ if not executable.startswith('"'):
65
+ executable = '"%s"' % executable
66
+ return executable
67
+
68
+ # Keep the old name around (for now), as there is at least one project using it!
69
+ _enquote_executable = enquote_executable
70
+
71
+ class ScriptMaker(object):
72
+ """
73
+ A class to copy or create scripts from source scripts or callable
74
+ specifications.
75
+ """
76
+ script_template = SCRIPT_TEMPLATE
77
+
78
+ executable = None # for shebangs
79
+
80
+ def __init__(self, source_dir, target_dir, add_launchers=True,
81
+ dry_run=False, fileop=None):
82
+ self.source_dir = source_dir
83
+ self.target_dir = target_dir
84
+ self.add_launchers = add_launchers
85
+ self.force = False
86
+ self.clobber = False
87
+ # It only makes sense to set mode bits on POSIX.
88
+ self.set_mode = (os.name == 'posix') or (os.name == 'java' and
89
+ os._name == 'posix')
90
+ self.variants = set(('', 'X.Y'))
91
+ self._fileop = fileop or FileOperator(dry_run)
92
+
93
+ self._is_nt = os.name == 'nt' or (
94
+ os.name == 'java' and os._name == 'nt')
95
+ self.version_info = sys.version_info
96
+
97
+ def _get_alternate_executable(self, executable, options):
98
+ if options.get('gui', False) and self._is_nt: # pragma: no cover
99
+ dn, fn = os.path.split(executable)
100
+ fn = fn.replace('python', 'pythonw')
101
+ executable = os.path.join(dn, fn)
102
+ return executable
103
+
104
+ if sys.platform.startswith('java'): # pragma: no cover
105
+ def _is_shell(self, executable):
106
+ """
107
+ Determine if the specified executable is a script
108
+ (contains a #! line)
109
+ """
110
+ try:
111
+ with open(executable) as fp:
112
+ return fp.read(2) == '#!'
113
+ except (OSError, IOError):
114
+ logger.warning('Failed to open %s', executable)
115
+ return False
116
+
117
+ def _fix_jython_executable(self, executable):
118
+ if self._is_shell(executable):
119
+ # Workaround for Jython is not needed on Linux systems.
120
+ import java
121
+
122
+ if java.lang.System.getProperty('os.name') == 'Linux':
123
+ return executable
124
+ elif executable.lower().endswith('jython.exe'):
125
+ # Use wrapper exe for Jython on Windows
126
+ return executable
127
+ return '/usr/bin/env %s' % executable
128
+
129
+ def _build_shebang(self, executable, post_interp):
130
+ """
131
+ Build a shebang line. In the simple case (on Windows, or a shebang line
132
+ which is not too long or contains spaces) use a simple formulation for
133
+ the shebang. Otherwise, use /bin/sh as the executable, with a contrived
134
+ shebang which allows the script to run either under Python or sh, using
135
+ suitable quoting. Thanks to Harald Nordgren for his input.
136
+
137
+ See also: http://www.in-ulm.de/~mascheck/various/shebang/#length
138
+ https://hg.mozilla.org/mozilla-central/file/tip/mach
139
+ """
140
+ if os.name != 'posix':
141
+ simple_shebang = True
142
+ else:
143
+ # Add 3 for '#!' prefix and newline suffix.
144
+ shebang_length = len(executable) + len(post_interp) + 3
145
+ if sys.platform == 'darwin':
146
+ max_shebang_length = 512
147
+ else:
148
+ max_shebang_length = 127
149
+ simple_shebang = ((b' ' not in executable) and
150
+ (shebang_length <= max_shebang_length))
151
+
152
+ if simple_shebang:
153
+ result = b'#!' + executable + post_interp + b'\n'
154
+ else:
155
+ result = b'#!/bin/sh\n'
156
+ result += b"'''exec' " + executable + post_interp + b' "$0" "$@"\n'
157
+ result += b"' '''"
158
+ return result
159
+
160
+ def _get_shebang(self, encoding, post_interp=b'', options=None):
161
+ enquote = True
162
+ if self.executable:
163
+ executable = self.executable
164
+ enquote = False # assume this will be taken care of
165
+ elif not sysconfig.is_python_build():
166
+ executable = get_executable()
167
+ elif in_venv(): # pragma: no cover
168
+ executable = os.path.join(sysconfig.get_path('scripts'),
169
+ 'python%s' % sysconfig.get_config_var('EXE'))
170
+ else: # pragma: no cover
171
+ executable = os.path.join(
172
+ sysconfig.get_config_var('BINDIR'),
173
+ 'python%s%s' % (sysconfig.get_config_var('VERSION'),
174
+ sysconfig.get_config_var('EXE')))
175
+ if not os.path.isfile(executable):
176
+ # for Python builds from source on Windows, no Python executables with
177
+ # a version suffix are created, so we use python.exe
178
+ executable = os.path.join(sysconfig.get_config_var('BINDIR'),
179
+ 'python%s' % (sysconfig.get_config_var('EXE')))
180
+ if options:
181
+ executable = self._get_alternate_executable(executable, options)
182
+
183
+ if sys.platform.startswith('java'): # pragma: no cover
184
+ executable = self._fix_jython_executable(executable)
185
+
186
+ # Normalise case for Windows - COMMENTED OUT
187
+ # executable = os.path.normcase(executable)
188
+ # N.B. The normalising operation above has been commented out: See
189
+ # issue #124. Although paths in Windows are generally case-insensitive,
190
+ # they aren't always. For example, a path containing a ẞ (which is a
191
+ # LATIN CAPITAL LETTER SHARP S - U+1E9E) is normcased to ß (which is a
192
+ # LATIN SMALL LETTER SHARP S' - U+00DF). The two are not considered by
193
+ # Windows as equivalent in path names.
194
+
195
+ # If the user didn't specify an executable, it may be necessary to
196
+ # cater for executable paths with spaces (not uncommon on Windows)
197
+ if enquote:
198
+ executable = enquote_executable(executable)
199
+ # Issue #51: don't use fsencode, since we later try to
200
+ # check that the shebang is decodable using utf-8.
201
+ executable = executable.encode('utf-8')
202
+ # in case of IronPython, play safe and enable frames support
203
+ if (sys.platform == 'cli' and '-X:Frames' not in post_interp
204
+ and '-X:FullFrames' not in post_interp): # pragma: no cover
205
+ post_interp += b' -X:Frames'
206
+ shebang = self._build_shebang(executable, post_interp)
207
+ # Python parser starts to read a script using UTF-8 until
208
+ # it gets a #coding:xxx cookie. The shebang has to be the
209
+ # first line of a file, the #coding:xxx cookie cannot be
210
+ # written before. So the shebang has to be decodable from
211
+ # UTF-8.
212
+ try:
213
+ shebang.decode('utf-8')
214
+ except UnicodeDecodeError: # pragma: no cover
215
+ raise ValueError(
216
+ 'The shebang (%r) is not decodable from utf-8' % shebang)
217
+ # If the script is encoded to a custom encoding (use a
218
+ # #coding:xxx cookie), the shebang has to be decodable from
219
+ # the script encoding too.
220
+ if encoding != 'utf-8':
221
+ try:
222
+ shebang.decode(encoding)
223
+ except UnicodeDecodeError: # pragma: no cover
224
+ raise ValueError(
225
+ 'The shebang (%r) is not decodable '
226
+ 'from the script encoding (%r)' % (shebang, encoding))
227
+ return shebang
228
+
229
+ def _get_script_text(self, entry):
230
+ return self.script_template % dict(module=entry.prefix,
231
+ import_name=entry.suffix.split('.')[0],
232
+ func=entry.suffix)
233
+
234
+ manifest = _DEFAULT_MANIFEST
235
+
236
+ def get_manifest(self, exename):
237
+ base = os.path.basename(exename)
238
+ return self.manifest % base
239
+
240
+ def _write_script(self, names, shebang, script_bytes, filenames, ext):
241
+ use_launcher = self.add_launchers and self._is_nt
242
+ linesep = os.linesep.encode('utf-8')
243
+ if not shebang.endswith(linesep):
244
+ shebang += linesep
245
+ if not use_launcher:
246
+ script_bytes = shebang + script_bytes
247
+ else: # pragma: no cover
248
+ if ext == 'py':
249
+ launcher = self._get_launcher('t')
250
+ else:
251
+ launcher = self._get_launcher('w')
252
+ stream = BytesIO()
253
+ with ZipFile(stream, 'w') as zf:
254
+ source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH')
255
+ if source_date_epoch:
256
+ date_time = time.gmtime(int(source_date_epoch))[:6]
257
+ zinfo = ZipInfo(filename='__main__.py', date_time=date_time)
258
+ zf.writestr(zinfo, script_bytes)
259
+ else:
260
+ zf.writestr('__main__.py', script_bytes)
261
+ zip_data = stream.getvalue()
262
+ script_bytes = launcher + shebang + zip_data
263
+ for name in names:
264
+ outname = os.path.join(self.target_dir, name)
265
+ if use_launcher: # pragma: no cover
266
+ n, e = os.path.splitext(outname)
267
+ if e.startswith('.py'):
268
+ outname = n
269
+ outname = '%s.exe' % outname
270
+ try:
271
+ self._fileop.write_binary_file(outname, script_bytes)
272
+ except Exception:
273
+ # Failed writing an executable - it might be in use.
274
+ logger.warning('Failed to write executable - trying to '
275
+ 'use .deleteme logic')
276
+ dfname = '%s.deleteme' % outname
277
+ if os.path.exists(dfname):
278
+ os.remove(dfname) # Not allowed to fail here
279
+ os.rename(outname, dfname) # nor here
280
+ self._fileop.write_binary_file(outname, script_bytes)
281
+ logger.debug('Able to replace executable using '
282
+ '.deleteme logic')
283
+ try:
284
+ os.remove(dfname)
285
+ except Exception:
286
+ pass # still in use - ignore error
287
+ else:
288
+ if self._is_nt and not outname.endswith('.' + ext): # pragma: no cover
289
+ outname = '%s.%s' % (outname, ext)
290
+ if os.path.exists(outname) and not self.clobber:
291
+ logger.warning('Skipping existing file %s', outname)
292
+ continue
293
+ self._fileop.write_binary_file(outname, script_bytes)
294
+ if self.set_mode:
295
+ self._fileop.set_executable_mode([outname])
296
+ filenames.append(outname)
297
+
298
+ variant_separator = '-'
299
+
300
+ def get_script_filenames(self, name):
301
+ result = set()
302
+ if '' in self.variants:
303
+ result.add(name)
304
+ if 'X' in self.variants:
305
+ result.add('%s%s' % (name, self.version_info[0]))
306
+ if 'X.Y' in self.variants:
307
+ result.add('%s%s%s.%s' % (name, self.variant_separator,
308
+ self.version_info[0], self.version_info[1]))
309
+ return result
310
+
311
+ def _make_script(self, entry, filenames, options=None):
312
+ post_interp = b''
313
+ if options:
314
+ args = options.get('interpreter_args', [])
315
+ if args:
316
+ args = ' %s' % ' '.join(args)
317
+ post_interp = args.encode('utf-8')
318
+ shebang = self._get_shebang('utf-8', post_interp, options=options)
319
+ script = self._get_script_text(entry).encode('utf-8')
320
+ scriptnames = self.get_script_filenames(entry.name)
321
+ if options and options.get('gui', False):
322
+ ext = 'pyw'
323
+ else:
324
+ ext = 'py'
325
+ self._write_script(scriptnames, shebang, script, filenames, ext)
326
+
327
+ def _copy_script(self, script, filenames):
328
+ adjust = False
329
+ script = os.path.join(self.source_dir, convert_path(script))
330
+ outname = os.path.join(self.target_dir, os.path.basename(script))
331
+ if not self.force and not self._fileop.newer(script, outname):
332
+ logger.debug('not copying %s (up-to-date)', script)
333
+ return
334
+
335
+ # Always open the file, but ignore failures in dry-run mode --
336
+ # that way, we'll get accurate feedback if we can read the
337
+ # script.
338
+ try:
339
+ f = open(script, 'rb')
340
+ except IOError: # pragma: no cover
341
+ if not self.dry_run:
342
+ raise
343
+ f = None
344
+ else:
345
+ first_line = f.readline()
346
+ if not first_line: # pragma: no cover
347
+ logger.warning('%s is an empty file (skipping)', script)
348
+ return
349
+
350
+ match = FIRST_LINE_RE.match(first_line.replace(b'\r\n', b'\n'))
351
+ if match:
352
+ adjust = True
353
+ post_interp = match.group(1) or b''
354
+
355
+ if not adjust:
356
+ if f:
357
+ f.close()
358
+ self._fileop.copy_file(script, outname)
359
+ if self.set_mode:
360
+ self._fileop.set_executable_mode([outname])
361
+ filenames.append(outname)
362
+ else:
363
+ logger.info('copying and adjusting %s -> %s', script,
364
+ self.target_dir)
365
+ if not self._fileop.dry_run:
366
+ encoding, lines = detect_encoding(f.readline)
367
+ f.seek(0)
368
+ shebang = self._get_shebang(encoding, post_interp)
369
+ if b'pythonw' in first_line: # pragma: no cover
370
+ ext = 'pyw'
371
+ else:
372
+ ext = 'py'
373
+ n = os.path.basename(outname)
374
+ self._write_script([n], shebang, f.read(), filenames, ext)
375
+ if f:
376
+ f.close()
377
+
378
+ @property
379
+ def dry_run(self):
380
+ return self._fileop.dry_run
381
+
382
+ @dry_run.setter
383
+ def dry_run(self, value):
384
+ self._fileop.dry_run = value
385
+
386
+ if os.name == 'nt' or (os.name == 'java' and os._name == 'nt'): # pragma: no cover
387
+ # Executable launcher support.
388
+ # Launchers are from https://bitbucket.org/vinay.sajip/simple_launcher/
389
+
390
+ def _get_launcher(self, kind):
391
+ if struct.calcsize('P') == 8: # 64-bit
392
+ bits = '64'
393
+ else:
394
+ bits = '32'
395
+ platform_suffix = '-arm' if get_platform() == 'win-arm64' else ''
396
+ name = '%s%s%s.exe' % (kind, bits, platform_suffix)
397
+ # Issue 31: don't hardcode an absolute package name, but
398
+ # determine it relative to the current package
399
+ distlib_package = __name__.rsplit('.', 1)[0]
400
+ resource = finder(distlib_package).find(name)
401
+ if not resource:
402
+ msg = ('Unable to find resource %s in package %s' % (name,
403
+ distlib_package))
404
+ raise ValueError(msg)
405
+ return resource.bytes
406
+
407
+ # Public API follows
408
+
409
+ def make(self, specification, options=None):
410
+ """
411
+ Make a script.
412
+
413
+ :param specification: The specification, which is either a valid export
414
+ entry specification (to make a script from a
415
+ callable) or a filename (to make a script by
416
+ copying from a source location).
417
+ :param options: A dictionary of options controlling script generation.
418
+ :return: A list of all absolute pathnames written to.
419
+ """
420
+ filenames = []
421
+ entry = get_export_entry(specification)
422
+ if entry is None:
423
+ self._copy_script(specification, filenames)
424
+ else:
425
+ self._make_script(entry, filenames, options=options)
426
+ return filenames
427
+
428
+ def make_multiple(self, specifications, options=None):
429
+ """
430
+ Take a list of specifications and make scripts from them,
431
+ :param specifications: A list of specifications.
432
+ :return: A list of all absolute pathnames written to,
433
+ """
434
+ filenames = []
435
+ for specification in specifications:
436
+ filenames.extend(self.make(specification, options))
437
+ return filenames
.venv/Lib/site-packages/pip/_vendor/distro/__init__.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .distro import (
2
+ NORMALIZED_DISTRO_ID,
3
+ NORMALIZED_LSB_ID,
4
+ NORMALIZED_OS_ID,
5
+ LinuxDistribution,
6
+ __version__,
7
+ build_number,
8
+ codename,
9
+ distro_release_attr,
10
+ distro_release_info,
11
+ id,
12
+ info,
13
+ like,
14
+ linux_distribution,
15
+ lsb_release_attr,
16
+ lsb_release_info,
17
+ major_version,
18
+ minor_version,
19
+ name,
20
+ os_release_attr,
21
+ os_release_info,
22
+ uname_attr,
23
+ uname_info,
24
+ version,
25
+ version_parts,
26
+ )
27
+
28
+ __all__ = [
29
+ "NORMALIZED_DISTRO_ID",
30
+ "NORMALIZED_LSB_ID",
31
+ "NORMALIZED_OS_ID",
32
+ "LinuxDistribution",
33
+ "build_number",
34
+ "codename",
35
+ "distro_release_attr",
36
+ "distro_release_info",
37
+ "id",
38
+ "info",
39
+ "like",
40
+ "linux_distribution",
41
+ "lsb_release_attr",
42
+ "lsb_release_info",
43
+ "major_version",
44
+ "minor_version",
45
+ "name",
46
+ "os_release_attr",
47
+ "os_release_info",
48
+ "uname_attr",
49
+ "uname_info",
50
+ "version",
51
+ "version_parts",
52
+ ]
53
+
54
+ __version__ = __version__
.venv/Lib/site-packages/pip/_vendor/distro/__main__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .distro import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
.venv/Lib/site-packages/pip/_vendor/distro/distro.py ADDED
@@ -0,0 +1,1399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright 2015,2016,2017 Nir Cohen
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ The ``distro`` package (``distro`` stands for Linux Distribution) provides
18
+ information about the Linux distribution it runs on, such as a reliable
19
+ machine-readable distro ID, or version information.
20
+
21
+ It is the recommended replacement for Python's original
22
+ :py:func:`platform.linux_distribution` function, but it provides much more
23
+ functionality. An alternative implementation became necessary because Python
24
+ 3.5 deprecated this function, and Python 3.8 removed it altogether. Its
25
+ predecessor function :py:func:`platform.dist` was already deprecated since
26
+ Python 2.6 and removed in Python 3.8. Still, there are many cases in which
27
+ access to OS distribution information is needed. See `Python issue 1322
28
+ <https://bugs.python.org/issue1322>`_ for more information.
29
+ """
30
+
31
+ import argparse
32
+ import json
33
+ import logging
34
+ import os
35
+ import re
36
+ import shlex
37
+ import subprocess
38
+ import sys
39
+ import warnings
40
+ from typing import (
41
+ Any,
42
+ Callable,
43
+ Dict,
44
+ Iterable,
45
+ Optional,
46
+ Sequence,
47
+ TextIO,
48
+ Tuple,
49
+ Type,
50
+ )
51
+
52
+ try:
53
+ from typing import TypedDict
54
+ except ImportError:
55
+ # Python 3.7
56
+ TypedDict = dict
57
+
58
+ __version__ = "1.8.0"
59
+
60
+
61
+ class VersionDict(TypedDict):
62
+ major: str
63
+ minor: str
64
+ build_number: str
65
+
66
+
67
+ class InfoDict(TypedDict):
68
+ id: str
69
+ version: str
70
+ version_parts: VersionDict
71
+ like: str
72
+ codename: str
73
+
74
+
75
+ _UNIXCONFDIR = os.environ.get("UNIXCONFDIR", "/etc")
76
+ _UNIXUSRLIBDIR = os.environ.get("UNIXUSRLIBDIR", "/usr/lib")
77
+ _OS_RELEASE_BASENAME = "os-release"
78
+
79
+ #: Translation table for normalizing the "ID" attribute defined in os-release
80
+ #: files, for use by the :func:`distro.id` method.
81
+ #:
82
+ #: * Key: Value as defined in the os-release file, translated to lower case,
83
+ #: with blanks translated to underscores.
84
+ #:
85
+ #: * Value: Normalized value.
86
+ NORMALIZED_OS_ID = {
87
+ "ol": "oracle", # Oracle Linux
88
+ "opensuse-leap": "opensuse", # Newer versions of OpenSuSE report as opensuse-leap
89
+ }
90
+
91
+ #: Translation table for normalizing the "Distributor ID" attribute returned by
92
+ #: the lsb_release command, for use by the :func:`distro.id` method.
93
+ #:
94
+ #: * Key: Value as returned by the lsb_release command, translated to lower
95
+ #: case, with blanks translated to underscores.
96
+ #:
97
+ #: * Value: Normalized value.
98
+ NORMALIZED_LSB_ID = {
99
+ "enterpriseenterpriseas": "oracle", # Oracle Enterprise Linux 4
100
+ "enterpriseenterpriseserver": "oracle", # Oracle Linux 5
101
+ "redhatenterpriseworkstation": "rhel", # RHEL 6, 7 Workstation
102
+ "redhatenterpriseserver": "rhel", # RHEL 6, 7 Server
103
+ "redhatenterprisecomputenode": "rhel", # RHEL 6 ComputeNode
104
+ }
105
+
106
+ #: Translation table for normalizing the distro ID derived from the file name
107
+ #: of distro release files, for use by the :func:`distro.id` method.
108
+ #:
109
+ #: * Key: Value as derived from the file name of a distro release file,
110
+ #: translated to lower case, with blanks translated to underscores.
111
+ #:
112
+ #: * Value: Normalized value.
113
+ NORMALIZED_DISTRO_ID = {
114
+ "redhat": "rhel", # RHEL 6.x, 7.x
115
+ }
116
+
117
+ # Pattern for content of distro release file (reversed)
118
+ _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN = re.compile(
119
+ r"(?:[^)]*\)(.*)\()? *(?:STL )?([\d.+\-a-z]*\d) *(?:esaeler *)?(.+)"
120
+ )
121
+
122
+ # Pattern for base file name of distro release file
123
+ _DISTRO_RELEASE_BASENAME_PATTERN = re.compile(r"(\w+)[-_](release|version)$")
124
+
125
+ # Base file names to be looked up for if _UNIXCONFDIR is not readable.
126
+ _DISTRO_RELEASE_BASENAMES = [
127
+ "SuSE-release",
128
+ "arch-release",
129
+ "base-release",
130
+ "centos-release",
131
+ "fedora-release",
132
+ "gentoo-release",
133
+ "mageia-release",
134
+ "mandrake-release",
135
+ "mandriva-release",
136
+ "mandrivalinux-release",
137
+ "manjaro-release",
138
+ "oracle-release",
139
+ "redhat-release",
140
+ "rocky-release",
141
+ "sl-release",
142
+ "slackware-version",
143
+ ]
144
+
145
+ # Base file names to be ignored when searching for distro release file
146
+ _DISTRO_RELEASE_IGNORE_BASENAMES = (
147
+ "debian_version",
148
+ "lsb-release",
149
+ "oem-release",
150
+ _OS_RELEASE_BASENAME,
151
+ "system-release",
152
+ "plesk-release",
153
+ "iredmail-release",
154
+ )
155
+
156
+
157
+ def linux_distribution(full_distribution_name: bool = True) -> Tuple[str, str, str]:
158
+ """
159
+ .. deprecated:: 1.6.0
160
+
161
+ :func:`distro.linux_distribution()` is deprecated. It should only be
162
+ used as a compatibility shim with Python's
163
+ :py:func:`platform.linux_distribution()`. Please use :func:`distro.id`,
164
+ :func:`distro.version` and :func:`distro.name` instead.
165
+
166
+ Return information about the current OS distribution as a tuple
167
+ ``(id_name, version, codename)`` with items as follows:
168
+
169
+ * ``id_name``: If *full_distribution_name* is false, the result of
170
+ :func:`distro.id`. Otherwise, the result of :func:`distro.name`.
171
+
172
+ * ``version``: The result of :func:`distro.version`.
173
+
174
+ * ``codename``: The extra item (usually in parentheses) after the
175
+ os-release version number, or the result of :func:`distro.codename`.
176
+
177
+ The interface of this function is compatible with the original
178
+ :py:func:`platform.linux_distribution` function, supporting a subset of
179
+ its parameters.
180
+
181
+ The data it returns may not exactly be the same, because it uses more data
182
+ sources than the original function, and that may lead to different data if
183
+ the OS distribution is not consistent across multiple data sources it
184
+ provides (there are indeed such distributions ...).
185
+
186
+ Another reason for differences is the fact that the :func:`distro.id`
187
+ method normalizes the distro ID string to a reliable machine-readable value
188
+ for a number of popular OS distributions.
189
+ """
190
+ warnings.warn(
191
+ "distro.linux_distribution() is deprecated. It should only be used as a "
192
+ "compatibility shim with Python's platform.linux_distribution(). Please use "
193
+ "distro.id(), distro.version() and distro.name() instead.",
194
+ DeprecationWarning,
195
+ stacklevel=2,
196
+ )
197
+ return _distro.linux_distribution(full_distribution_name)
198
+
199
+
200
+ def id() -> str:
201
+ """
202
+ Return the distro ID of the current distribution, as a
203
+ machine-readable string.
204
+
205
+ For a number of OS distributions, the returned distro ID value is
206
+ *reliable*, in the sense that it is documented and that it does not change
207
+ across releases of the distribution.
208
+
209
+ This package maintains the following reliable distro ID values:
210
+
211
+ ============== =========================================
212
+ Distro ID Distribution
213
+ ============== =========================================
214
+ "ubuntu" Ubuntu
215
+ "debian" Debian
216
+ "rhel" RedHat Enterprise Linux
217
+ "centos" CentOS
218
+ "fedora" Fedora
219
+ "sles" SUSE Linux Enterprise Server
220
+ "opensuse" openSUSE
221
+ "amzn" Amazon Linux
222
+ "arch" Arch Linux
223
+ "buildroot" Buildroot
224
+ "cloudlinux" CloudLinux OS
225
+ "exherbo" Exherbo Linux
226
+ "gentoo" GenToo Linux
227
+ "ibm_powerkvm" IBM PowerKVM
228
+ "kvmibm" KVM for IBM z Systems
229
+ "linuxmint" Linux Mint
230
+ "mageia" Mageia
231
+ "mandriva" Mandriva Linux
232
+ "parallels" Parallels
233
+ "pidora" Pidora
234
+ "raspbian" Raspbian
235
+ "oracle" Oracle Linux (and Oracle Enterprise Linux)
236
+ "scientific" Scientific Linux
237
+ "slackware" Slackware
238
+ "xenserver" XenServer
239
+ "openbsd" OpenBSD
240
+ "netbsd" NetBSD
241
+ "freebsd" FreeBSD
242
+ "midnightbsd" MidnightBSD
243
+ "rocky" Rocky Linux
244
+ "aix" AIX
245
+ "guix" Guix System
246
+ ============== =========================================
247
+
248
+ If you have a need to get distros for reliable IDs added into this set,
249
+ or if you find that the :func:`distro.id` function returns a different
250
+ distro ID for one of the listed distros, please create an issue in the
251
+ `distro issue tracker`_.
252
+
253
+ **Lookup hierarchy and transformations:**
254
+
255
+ First, the ID is obtained from the following sources, in the specified
256
+ order. The first available and non-empty value is used:
257
+
258
+ * the value of the "ID" attribute of the os-release file,
259
+
260
+ * the value of the "Distributor ID" attribute returned by the lsb_release
261
+ command,
262
+
263
+ * the first part of the file name of the distro release file,
264
+
265
+ The so determined ID value then passes the following transformations,
266
+ before it is returned by this method:
267
+
268
+ * it is translated to lower case,
269
+
270
+ * blanks (which should not be there anyway) are translated to underscores,
271
+
272
+ * a normalization of the ID is performed, based upon
273
+ `normalization tables`_. The purpose of this normalization is to ensure
274
+ that the ID is as reliable as possible, even across incompatible changes
275
+ in the OS distributions. A common reason for an incompatible change is
276
+ the addition of an os-release file, or the addition of the lsb_release
277
+ command, with ID values that differ from what was previously determined
278
+ from the distro release file name.
279
+ """
280
+ return _distro.id()
281
+
282
+
283
+ def name(pretty: bool = False) -> str:
284
+ """
285
+ Return the name of the current OS distribution, as a human-readable
286
+ string.
287
+
288
+ If *pretty* is false, the name is returned without version or codename.
289
+ (e.g. "CentOS Linux")
290
+
291
+ If *pretty* is true, the version and codename are appended.
292
+ (e.g. "CentOS Linux 7.1.1503 (Core)")
293
+
294
+ **Lookup hierarchy:**
295
+
296
+ The name is obtained from the following sources, in the specified order.
297
+ The first available and non-empty value is used:
298
+
299
+ * If *pretty* is false:
300
+
301
+ - the value of the "NAME" attribute of the os-release file,
302
+
303
+ - the value of the "Distributor ID" attribute returned by the lsb_release
304
+ command,
305
+
306
+ - the value of the "<name>" field of the distro release file.
307
+
308
+ * If *pretty* is true:
309
+
310
+ - the value of the "PRETTY_NAME" attribute of the os-release file,
311
+
312
+ - the value of the "Description" attribute returned by the lsb_release
313
+ command,
314
+
315
+ - the value of the "<name>" field of the distro release file, appended
316
+ with the value of the pretty version ("<version_id>" and "<codename>"
317
+ fields) of the distro release file, if available.
318
+ """
319
+ return _distro.name(pretty)
320
+
321
+
322
+ def version(pretty: bool = False, best: bool = False) -> str:
323
+ """
324
+ Return the version of the current OS distribution, as a human-readable
325
+ string.
326
+
327
+ If *pretty* is false, the version is returned without codename (e.g.
328
+ "7.0").
329
+
330
+ If *pretty* is true, the codename in parenthesis is appended, if the
331
+ codename is non-empty (e.g. "7.0 (Maipo)").
332
+
333
+ Some distributions provide version numbers with different precisions in
334
+ the different sources of distribution information. Examining the different
335
+ sources in a fixed priority order does not always yield the most precise
336
+ version (e.g. for Debian 8.2, or CentOS 7.1).
337
+
338
+ Some other distributions may not provide this kind of information. In these
339
+ cases, an empty string would be returned. This behavior can be observed
340
+ with rolling releases distributions (e.g. Arch Linux).
341
+
342
+ The *best* parameter can be used to control the approach for the returned
343
+ version:
344
+
345
+ If *best* is false, the first non-empty version number in priority order of
346
+ the examined sources is returned.
347
+
348
+ If *best* is true, the most precise version number out of all examined
349
+ sources is returned.
350
+
351
+ **Lookup hierarchy:**
352
+
353
+ In all cases, the version number is obtained from the following sources.
354
+ If *best* is false, this order represents the priority order:
355
+
356
+ * the value of the "VERSION_ID" attribute of the os-release file,
357
+ * the value of the "Release" attribute returned by the lsb_release
358
+ command,
359
+ * the version number parsed from the "<version_id>" field of the first line
360
+ of the distro release file,
361
+ * the version number parsed from the "PRETTY_NAME" attribute of the
362
+ os-release file, if it follows the format of the distro release files.
363
+ * the version number parsed from the "Description" attribute returned by
364
+ the lsb_release command, if it follows the format of the distro release
365
+ files.
366
+ """
367
+ return _distro.version(pretty, best)
368
+
369
+
370
+ def version_parts(best: bool = False) -> Tuple[str, str, str]:
371
+ """
372
+ Return the version of the current OS distribution as a tuple
373
+ ``(major, minor, build_number)`` with items as follows:
374
+
375
+ * ``major``: The result of :func:`distro.major_version`.
376
+
377
+ * ``minor``: The result of :func:`distro.minor_version`.
378
+
379
+ * ``build_number``: The result of :func:`distro.build_number`.
380
+
381
+ For a description of the *best* parameter, see the :func:`distro.version`
382
+ method.
383
+ """
384
+ return _distro.version_parts(best)
385
+
386
+
387
+ def major_version(best: bool = False) -> str:
388
+ """
389
+ Return the major version of the current OS distribution, as a string,
390
+ if provided.
391
+ Otherwise, the empty string is returned. The major version is the first
392
+ part of the dot-separated version string.
393
+
394
+ For a description of the *best* parameter, see the :func:`distro.version`
395
+ method.
396
+ """
397
+ return _distro.major_version(best)
398
+
399
+
400
+ def minor_version(best: bool = False) -> str:
401
+ """
402
+ Return the minor version of the current OS distribution, as a string,
403
+ if provided.
404
+ Otherwise, the empty string is returned. The minor version is the second
405
+ part of the dot-separated version string.
406
+
407
+ For a description of the *best* parameter, see the :func:`distro.version`
408
+ method.
409
+ """
410
+ return _distro.minor_version(best)
411
+
412
+
413
+ def build_number(best: bool = False) -> str:
414
+ """
415
+ Return the build number of the current OS distribution, as a string,
416
+ if provided.
417
+ Otherwise, the empty string is returned. The build number is the third part
418
+ of the dot-separated version string.
419
+
420
+ For a description of the *best* parameter, see the :func:`distro.version`
421
+ method.
422
+ """
423
+ return _distro.build_number(best)
424
+
425
+
426
+ def like() -> str:
427
+ """
428
+ Return a space-separated list of distro IDs of distributions that are
429
+ closely related to the current OS distribution in regards to packaging
430
+ and programming interfaces, for example distributions the current
431
+ distribution is a derivative from.
432
+
433
+ **Lookup hierarchy:**
434
+
435
+ This information item is only provided by the os-release file.
436
+ For details, see the description of the "ID_LIKE" attribute in the
437
+ `os-release man page
438
+ <http://www.freedesktop.org/software/systemd/man/os-release.html>`_.
439
+ """
440
+ return _distro.like()
441
+
442
+
443
+ def codename() -> str:
444
+ """
445
+ Return the codename for the release of the current OS distribution,
446
+ as a string.
447
+
448
+ If the distribution does not have a codename, an empty string is returned.
449
+
450
+ Note that the returned codename is not always really a codename. For
451
+ example, openSUSE returns "x86_64". This function does not handle such
452
+ cases in any special way and just returns the string it finds, if any.
453
+
454
+ **Lookup hierarchy:**
455
+
456
+ * the codename within the "VERSION" attribute of the os-release file, if
457
+ provided,
458
+
459
+ * the value of the "Codename" attribute returned by the lsb_release
460
+ command,
461
+
462
+ * the value of the "<codename>" field of the distro release file.
463
+ """
464
+ return _distro.codename()
465
+
466
+
467
+ def info(pretty: bool = False, best: bool = False) -> InfoDict:
468
+ """
469
+ Return certain machine-readable information items about the current OS
470
+ distribution in a dictionary, as shown in the following example:
471
+
472
+ .. sourcecode:: python
473
+
474
+ {
475
+ 'id': 'rhel',
476
+ 'version': '7.0',
477
+ 'version_parts': {
478
+ 'major': '7',
479
+ 'minor': '0',
480
+ 'build_number': ''
481
+ },
482
+ 'like': 'fedora',
483
+ 'codename': 'Maipo'
484
+ }
485
+
486
+ The dictionary structure and keys are always the same, regardless of which
487
+ information items are available in the underlying data sources. The values
488
+ for the various keys are as follows:
489
+
490
+ * ``id``: The result of :func:`distro.id`.
491
+
492
+ * ``version``: The result of :func:`distro.version`.
493
+
494
+ * ``version_parts -> major``: The result of :func:`distro.major_version`.
495
+
496
+ * ``version_parts -> minor``: The result of :func:`distro.minor_version`.
497
+
498
+ * ``version_parts -> build_number``: The result of
499
+ :func:`distro.build_number`.
500
+
501
+ * ``like``: The result of :func:`distro.like`.
502
+
503
+ * ``codename``: The result of :func:`distro.codename`.
504
+
505
+ For a description of the *pretty* and *best* parameters, see the
506
+ :func:`distro.version` method.
507
+ """
508
+ return _distro.info(pretty, best)
509
+
510
+
511
+ def os_release_info() -> Dict[str, str]:
512
+ """
513
+ Return a dictionary containing key-value pairs for the information items
514
+ from the os-release file data source of the current OS distribution.
515
+
516
+ See `os-release file`_ for details about these information items.
517
+ """
518
+ return _distro.os_release_info()
519
+
520
+
521
+ def lsb_release_info() -> Dict[str, str]:
522
+ """
523
+ Return a dictionary containing key-value pairs for the information items
524
+ from the lsb_release command data source of the current OS distribution.
525
+
526
+ See `lsb_release command output`_ for details about these information
527
+ items.
528
+ """
529
+ return _distro.lsb_release_info()
530
+
531
+
532
+ def distro_release_info() -> Dict[str, str]:
533
+ """
534
+ Return a dictionary containing key-value pairs for the information items
535
+ from the distro release file data source of the current OS distribution.
536
+
537
+ See `distro release file`_ for details about these information items.
538
+ """
539
+ return _distro.distro_release_info()
540
+
541
+
542
+ def uname_info() -> Dict[str, str]:
543
+ """
544
+ Return a dictionary containing key-value pairs for the information items
545
+ from the distro release file data source of the current OS distribution.
546
+ """
547
+ return _distro.uname_info()
548
+
549
+
550
+ def os_release_attr(attribute: str) -> str:
551
+ """
552
+ Return a single named information item from the os-release file data source
553
+ of the current OS distribution.
554
+
555
+ Parameters:
556
+
557
+ * ``attribute`` (string): Key of the information item.
558
+
559
+ Returns:
560
+
561
+ * (string): Value of the information item, if the item exists.
562
+ The empty string, if the item does not exist.
563
+
564
+ See `os-release file`_ for details about these information items.
565
+ """
566
+ return _distro.os_release_attr(attribute)
567
+
568
+
569
+ def lsb_release_attr(attribute: str) -> str:
570
+ """
571
+ Return a single named information item from the lsb_release command output
572
+ data source of the current OS distribution.
573
+
574
+ Parameters:
575
+
576
+ * ``attribute`` (string): Key of the information item.
577
+
578
+ Returns:
579
+
580
+ * (string): Value of the information item, if the item exists.
581
+ The empty string, if the item does not exist.
582
+
583
+ See `lsb_release command output`_ for details about these information
584
+ items.
585
+ """
586
+ return _distro.lsb_release_attr(attribute)
587
+
588
+
589
+ def distro_release_attr(attribute: str) -> str:
590
+ """
591
+ Return a single named information item from the distro release file
592
+ data source of the current OS distribution.
593
+
594
+ Parameters:
595
+
596
+ * ``attribute`` (string): Key of the information item.
597
+
598
+ Returns:
599
+
600
+ * (string): Value of the information item, if the item exists.
601
+ The empty string, if the item does not exist.
602
+
603
+ See `distro release file`_ for details about these information items.
604
+ """
605
+ return _distro.distro_release_attr(attribute)
606
+
607
+
608
+ def uname_attr(attribute: str) -> str:
609
+ """
610
+ Return a single named information item from the distro release file
611
+ data source of the current OS distribution.
612
+
613
+ Parameters:
614
+
615
+ * ``attribute`` (string): Key of the information item.
616
+
617
+ Returns:
618
+
619
+ * (string): Value of the information item, if the item exists.
620
+ The empty string, if the item does not exist.
621
+ """
622
+ return _distro.uname_attr(attribute)
623
+
624
+
625
+ try:
626
+ from functools import cached_property
627
+ except ImportError:
628
+ # Python < 3.8
629
+ class cached_property: # type: ignore
630
+ """A version of @property which caches the value. On access, it calls the
631
+ underlying function and sets the value in `__dict__` so future accesses
632
+ will not re-call the property.
633
+ """
634
+
635
+ def __init__(self, f: Callable[[Any], Any]) -> None:
636
+ self._fname = f.__name__
637
+ self._f = f
638
+
639
+ def __get__(self, obj: Any, owner: Type[Any]) -> Any:
640
+ assert obj is not None, f"call {self._fname} on an instance"
641
+ ret = obj.__dict__[self._fname] = self._f(obj)
642
+ return ret
643
+
644
+
645
+ class LinuxDistribution:
646
+ """
647
+ Provides information about a OS distribution.
648
+
649
+ This package creates a private module-global instance of this class with
650
+ default initialization arguments, that is used by the
651
+ `consolidated accessor functions`_ and `single source accessor functions`_.
652
+ By using default initialization arguments, that module-global instance
653
+ returns data about the current OS distribution (i.e. the distro this
654
+ package runs on).
655
+
656
+ Normally, it is not necessary to create additional instances of this class.
657
+ However, in situations where control is needed over the exact data sources
658
+ that are used, instances of this class can be created with a specific
659
+ distro release file, or a specific os-release file, or without invoking the
660
+ lsb_release command.
661
+ """
662
+
663
+ def __init__(
664
+ self,
665
+ include_lsb: Optional[bool] = None,
666
+ os_release_file: str = "",
667
+ distro_release_file: str = "",
668
+ include_uname: Optional[bool] = None,
669
+ root_dir: Optional[str] = None,
670
+ include_oslevel: Optional[bool] = None,
671
+ ) -> None:
672
+ """
673
+ The initialization method of this class gathers information from the
674
+ available data sources, and stores that in private instance attributes.
675
+ Subsequent access to the information items uses these private instance
676
+ attributes, so that the data sources are read only once.
677
+
678
+ Parameters:
679
+
680
+ * ``include_lsb`` (bool): Controls whether the
681
+ `lsb_release command output`_ is included as a data source.
682
+
683
+ If the lsb_release command is not available in the program execution
684
+ path, the data source for the lsb_release command will be empty.
685
+
686
+ * ``os_release_file`` (string): The path name of the
687
+ `os-release file`_ that is to be used as a data source.
688
+
689
+ An empty string (the default) will cause the default path name to
690
+ be used (see `os-release file`_ for details).
691
+
692
+ If the specified or defaulted os-release file does not exist, the
693
+ data source for the os-release file will be empty.
694
+
695
+ * ``distro_release_file`` (string): The path name of the
696
+ `distro release file`_ that is to be used as a data source.
697
+
698
+ An empty string (the default) will cause a default search algorithm
699
+ to be used (see `distro release file`_ for details).
700
+
701
+ If the specified distro release file does not exist, or if no default
702
+ distro release file can be found, the data source for the distro
703
+ release file will be empty.
704
+
705
+ * ``include_uname`` (bool): Controls whether uname command output is
706
+ included as a data source. If the uname command is not available in
707
+ the program execution path the data source for the uname command will
708
+ be empty.
709
+
710
+ * ``root_dir`` (string): The absolute path to the root directory to use
711
+ to find distro-related information files. Note that ``include_*``
712
+ parameters must not be enabled in combination with ``root_dir``.
713
+
714
+ * ``include_oslevel`` (bool): Controls whether (AIX) oslevel command
715
+ output is included as a data source. If the oslevel command is not
716
+ available in the program execution path the data source will be
717
+ empty.
718
+
719
+ Public instance attributes:
720
+
721
+ * ``os_release_file`` (string): The path name of the
722
+ `os-release file`_ that is actually used as a data source. The
723
+ empty string if no distro release file is used as a data source.
724
+
725
+ * ``distro_release_file`` (string): The path name of the
726
+ `distro release file`_ that is actually used as a data source. The
727
+ empty string if no distro release file is used as a data source.
728
+
729
+ * ``include_lsb`` (bool): The result of the ``include_lsb`` parameter.
730
+ This controls whether the lsb information will be loaded.
731
+
732
+ * ``include_uname`` (bool): The result of the ``include_uname``
733
+ parameter. This controls whether the uname information will
734
+ be loaded.
735
+
736
+ * ``include_oslevel`` (bool): The result of the ``include_oslevel``
737
+ parameter. This controls whether (AIX) oslevel information will be
738
+ loaded.
739
+
740
+ * ``root_dir`` (string): The result of the ``root_dir`` parameter.
741
+ The absolute path to the root directory to use to find distro-related
742
+ information files.
743
+
744
+ Raises:
745
+
746
+ * :py:exc:`ValueError`: Initialization parameters combination is not
747
+ supported.
748
+
749
+ * :py:exc:`OSError`: Some I/O issue with an os-release file or distro
750
+ release file.
751
+
752
+ * :py:exc:`UnicodeError`: A data source has unexpected characters or
753
+ uses an unexpected encoding.
754
+ """
755
+ self.root_dir = root_dir
756
+ self.etc_dir = os.path.join(root_dir, "etc") if root_dir else _UNIXCONFDIR
757
+ self.usr_lib_dir = (
758
+ os.path.join(root_dir, "usr/lib") if root_dir else _UNIXUSRLIBDIR
759
+ )
760
+
761
+ if os_release_file:
762
+ self.os_release_file = os_release_file
763
+ else:
764
+ etc_dir_os_release_file = os.path.join(self.etc_dir, _OS_RELEASE_BASENAME)
765
+ usr_lib_os_release_file = os.path.join(
766
+ self.usr_lib_dir, _OS_RELEASE_BASENAME
767
+ )
768
+
769
+ # NOTE: The idea is to respect order **and** have it set
770
+ # at all times for API backwards compatibility.
771
+ if os.path.isfile(etc_dir_os_release_file) or not os.path.isfile(
772
+ usr_lib_os_release_file
773
+ ):
774
+ self.os_release_file = etc_dir_os_release_file
775
+ else:
776
+ self.os_release_file = usr_lib_os_release_file
777
+
778
+ self.distro_release_file = distro_release_file or "" # updated later
779
+
780
+ is_root_dir_defined = root_dir is not None
781
+ if is_root_dir_defined and (include_lsb or include_uname or include_oslevel):
782
+ raise ValueError(
783
+ "Including subprocess data sources from specific root_dir is disallowed"
784
+ " to prevent false information"
785
+ )
786
+ self.include_lsb = (
787
+ include_lsb if include_lsb is not None else not is_root_dir_defined
788
+ )
789
+ self.include_uname = (
790
+ include_uname if include_uname is not None else not is_root_dir_defined
791
+ )
792
+ self.include_oslevel = (
793
+ include_oslevel if include_oslevel is not None else not is_root_dir_defined
794
+ )
795
+
796
+ def __repr__(self) -> str:
797
+ """Return repr of all info"""
798
+ return (
799
+ "LinuxDistribution("
800
+ "os_release_file={self.os_release_file!r}, "
801
+ "distro_release_file={self.distro_release_file!r}, "
802
+ "include_lsb={self.include_lsb!r}, "
803
+ "include_uname={self.include_uname!r}, "
804
+ "include_oslevel={self.include_oslevel!r}, "
805
+ "root_dir={self.root_dir!r}, "
806
+ "_os_release_info={self._os_release_info!r}, "
807
+ "_lsb_release_info={self._lsb_release_info!r}, "
808
+ "_distro_release_info={self._distro_release_info!r}, "
809
+ "_uname_info={self._uname_info!r}, "
810
+ "_oslevel_info={self._oslevel_info!r})".format(self=self)
811
+ )
812
+
813
+ def linux_distribution(
814
+ self, full_distribution_name: bool = True
815
+ ) -> Tuple[str, str, str]:
816
+ """
817
+ Return information about the OS distribution that is compatible
818
+ with Python's :func:`platform.linux_distribution`, supporting a subset
819
+ of its parameters.
820
+
821
+ For details, see :func:`distro.linux_distribution`.
822
+ """
823
+ return (
824
+ self.name() if full_distribution_name else self.id(),
825
+ self.version(),
826
+ self._os_release_info.get("release_codename") or self.codename(),
827
+ )
828
+
829
+ def id(self) -> str:
830
+ """Return the distro ID of the OS distribution, as a string.
831
+
832
+ For details, see :func:`distro.id`.
833
+ """
834
+
835
+ def normalize(distro_id: str, table: Dict[str, str]) -> str:
836
+ distro_id = distro_id.lower().replace(" ", "_")
837
+ return table.get(distro_id, distro_id)
838
+
839
+ distro_id = self.os_release_attr("id")
840
+ if distro_id:
841
+ return normalize(distro_id, NORMALIZED_OS_ID)
842
+
843
+ distro_id = self.lsb_release_attr("distributor_id")
844
+ if distro_id:
845
+ return normalize(distro_id, NORMALIZED_LSB_ID)
846
+
847
+ distro_id = self.distro_release_attr("id")
848
+ if distro_id:
849
+ return normalize(distro_id, NORMALIZED_DISTRO_ID)
850
+
851
+ distro_id = self.uname_attr("id")
852
+ if distro_id:
853
+ return normalize(distro_id, NORMALIZED_DISTRO_ID)
854
+
855
+ return ""
856
+
857
+ def name(self, pretty: bool = False) -> str:
858
+ """
859
+ Return the name of the OS distribution, as a string.
860
+
861
+ For details, see :func:`distro.name`.
862
+ """
863
+ name = (
864
+ self.os_release_attr("name")
865
+ or self.lsb_release_attr("distributor_id")
866
+ or self.distro_release_attr("name")
867
+ or self.uname_attr("name")
868
+ )
869
+ if pretty:
870
+ name = self.os_release_attr("pretty_name") or self.lsb_release_attr(
871
+ "description"
872
+ )
873
+ if not name:
874
+ name = self.distro_release_attr("name") or self.uname_attr("name")
875
+ version = self.version(pretty=True)
876
+ if version:
877
+ name = f"{name} {version}"
878
+ return name or ""
879
+
880
+ def version(self, pretty: bool = False, best: bool = False) -> str:
881
+ """
882
+ Return the version of the OS distribution, as a string.
883
+
884
+ For details, see :func:`distro.version`.
885
+ """
886
+ versions = [
887
+ self.os_release_attr("version_id"),
888
+ self.lsb_release_attr("release"),
889
+ self.distro_release_attr("version_id"),
890
+ self._parse_distro_release_content(self.os_release_attr("pretty_name")).get(
891
+ "version_id", ""
892
+ ),
893
+ self._parse_distro_release_content(
894
+ self.lsb_release_attr("description")
895
+ ).get("version_id", ""),
896
+ self.uname_attr("release"),
897
+ ]
898
+ if self.uname_attr("id").startswith("aix"):
899
+ # On AIX platforms, prefer oslevel command output.
900
+ versions.insert(0, self.oslevel_info())
901
+ elif self.id() == "debian" or "debian" in self.like().split():
902
+ # On Debian-like, add debian_version file content to candidates list.
903
+ versions.append(self._debian_version)
904
+ version = ""
905
+ if best:
906
+ # This algorithm uses the last version in priority order that has
907
+ # the best precision. If the versions are not in conflict, that
908
+ # does not matter; otherwise, using the last one instead of the
909
+ # first one might be considered a surprise.
910
+ for v in versions:
911
+ if v.count(".") > version.count(".") or version == "":
912
+ version = v
913
+ else:
914
+ for v in versions:
915
+ if v != "":
916
+ version = v
917
+ break
918
+ if pretty and version and self.codename():
919
+ version = f"{version} ({self.codename()})"
920
+ return version
921
+
922
+ def version_parts(self, best: bool = False) -> Tuple[str, str, str]:
923
+ """
924
+ Return the version of the OS distribution, as a tuple of version
925
+ numbers.
926
+
927
+ For details, see :func:`distro.version_parts`.
928
+ """
929
+ version_str = self.version(best=best)
930
+ if version_str:
931
+ version_regex = re.compile(r"(\d+)\.?(\d+)?\.?(\d+)?")
932
+ matches = version_regex.match(version_str)
933
+ if matches:
934
+ major, minor, build_number = matches.groups()
935
+ return major, minor or "", build_number or ""
936
+ return "", "", ""
937
+
938
+ def major_version(self, best: bool = False) -> str:
939
+ """
940
+ Return the major version number of the current distribution.
941
+
942
+ For details, see :func:`distro.major_version`.
943
+ """
944
+ return self.version_parts(best)[0]
945
+
946
+ def minor_version(self, best: bool = False) -> str:
947
+ """
948
+ Return the minor version number of the current distribution.
949
+
950
+ For details, see :func:`distro.minor_version`.
951
+ """
952
+ return self.version_parts(best)[1]
953
+
954
+ def build_number(self, best: bool = False) -> str:
955
+ """
956
+ Return the build number of the current distribution.
957
+
958
+ For details, see :func:`distro.build_number`.
959
+ """
960
+ return self.version_parts(best)[2]
961
+
962
+ def like(self) -> str:
963
+ """
964
+ Return the IDs of distributions that are like the OS distribution.
965
+
966
+ For details, see :func:`distro.like`.
967
+ """
968
+ return self.os_release_attr("id_like") or ""
969
+
970
+ def codename(self) -> str:
971
+ """
972
+ Return the codename of the OS distribution.
973
+
974
+ For details, see :func:`distro.codename`.
975
+ """
976
+ try:
977
+ # Handle os_release specially since distros might purposefully set
978
+ # this to empty string to have no codename
979
+ return self._os_release_info["codename"]
980
+ except KeyError:
981
+ return (
982
+ self.lsb_release_attr("codename")
983
+ or self.distro_release_attr("codename")
984
+ or ""
985
+ )
986
+
987
+ def info(self, pretty: bool = False, best: bool = False) -> InfoDict:
988
+ """
989
+ Return certain machine-readable information about the OS
990
+ distribution.
991
+
992
+ For details, see :func:`distro.info`.
993
+ """
994
+ return dict(
995
+ id=self.id(),
996
+ version=self.version(pretty, best),
997
+ version_parts=dict(
998
+ major=self.major_version(best),
999
+ minor=self.minor_version(best),
1000
+ build_number=self.build_number(best),
1001
+ ),
1002
+ like=self.like(),
1003
+ codename=self.codename(),
1004
+ )
1005
+
1006
+ def os_release_info(self) -> Dict[str, str]:
1007
+ """
1008
+ Return a dictionary containing key-value pairs for the information
1009
+ items from the os-release file data source of the OS distribution.
1010
+
1011
+ For details, see :func:`distro.os_release_info`.
1012
+ """
1013
+ return self._os_release_info
1014
+
1015
+ def lsb_release_info(self) -> Dict[str, str]:
1016
+ """
1017
+ Return a dictionary containing key-value pairs for the information
1018
+ items from the lsb_release command data source of the OS
1019
+ distribution.
1020
+
1021
+ For details, see :func:`distro.lsb_release_info`.
1022
+ """
1023
+ return self._lsb_release_info
1024
+
1025
+ def distro_release_info(self) -> Dict[str, str]:
1026
+ """
1027
+ Return a dictionary containing key-value pairs for the information
1028
+ items from the distro release file data source of the OS
1029
+ distribution.
1030
+
1031
+ For details, see :func:`distro.distro_release_info`.
1032
+ """
1033
+ return self._distro_release_info
1034
+
1035
+ def uname_info(self) -> Dict[str, str]:
1036
+ """
1037
+ Return a dictionary containing key-value pairs for the information
1038
+ items from the uname command data source of the OS distribution.
1039
+
1040
+ For details, see :func:`distro.uname_info`.
1041
+ """
1042
+ return self._uname_info
1043
+
1044
+ def oslevel_info(self) -> str:
1045
+ """
1046
+ Return AIX' oslevel command output.
1047
+ """
1048
+ return self._oslevel_info
1049
+
1050
+ def os_release_attr(self, attribute: str) -> str:
1051
+ """
1052
+ Return a single named information item from the os-release file data
1053
+ source of the OS distribution.
1054
+
1055
+ For details, see :func:`distro.os_release_attr`.
1056
+ """
1057
+ return self._os_release_info.get(attribute, "")
1058
+
1059
+ def lsb_release_attr(self, attribute: str) -> str:
1060
+ """
1061
+ Return a single named information item from the lsb_release command
1062
+ output data source of the OS distribution.
1063
+
1064
+ For details, see :func:`distro.lsb_release_attr`.
1065
+ """
1066
+ return self._lsb_release_info.get(attribute, "")
1067
+
1068
+ def distro_release_attr(self, attribute: str) -> str:
1069
+ """
1070
+ Return a single named information item from the distro release file
1071
+ data source of the OS distribution.
1072
+
1073
+ For details, see :func:`distro.distro_release_attr`.
1074
+ """
1075
+ return self._distro_release_info.get(attribute, "")
1076
+
1077
+ def uname_attr(self, attribute: str) -> str:
1078
+ """
1079
+ Return a single named information item from the uname command
1080
+ output data source of the OS distribution.
1081
+
1082
+ For details, see :func:`distro.uname_attr`.
1083
+ """
1084
+ return self._uname_info.get(attribute, "")
1085
+
1086
+ @cached_property
1087
+ def _os_release_info(self) -> Dict[str, str]:
1088
+ """
1089
+ Get the information items from the specified os-release file.
1090
+
1091
+ Returns:
1092
+ A dictionary containing all information items.
1093
+ """
1094
+ if os.path.isfile(self.os_release_file):
1095
+ with open(self.os_release_file, encoding="utf-8") as release_file:
1096
+ return self._parse_os_release_content(release_file)
1097
+ return {}
1098
+
1099
+ @staticmethod
1100
+ def _parse_os_release_content(lines: TextIO) -> Dict[str, str]:
1101
+ """
1102
+ Parse the lines of an os-release file.
1103
+
1104
+ Parameters:
1105
+
1106
+ * lines: Iterable through the lines in the os-release file.
1107
+ Each line must be a unicode string or a UTF-8 encoded byte
1108
+ string.
1109
+
1110
+ Returns:
1111
+ A dictionary containing all information items.
1112
+ """
1113
+ props = {}
1114
+ lexer = shlex.shlex(lines, posix=True)
1115
+ lexer.whitespace_split = True
1116
+
1117
+ tokens = list(lexer)
1118
+ for token in tokens:
1119
+ # At this point, all shell-like parsing has been done (i.e.
1120
+ # comments processed, quotes and backslash escape sequences
1121
+ # processed, multi-line values assembled, trailing newlines
1122
+ # stripped, etc.), so the tokens are now either:
1123
+ # * variable assignments: var=value
1124
+ # * commands or their arguments (not allowed in os-release)
1125
+ # Ignore any tokens that are not variable assignments
1126
+ if "=" in token:
1127
+ k, v = token.split("=", 1)
1128
+ props[k.lower()] = v
1129
+
1130
+ if "version" in props:
1131
+ # extract release codename (if any) from version attribute
1132
+ match = re.search(r"\((\D+)\)|,\s*(\D+)", props["version"])
1133
+ if match:
1134
+ release_codename = match.group(1) or match.group(2)
1135
+ props["codename"] = props["release_codename"] = release_codename
1136
+
1137
+ if "version_codename" in props:
1138
+ # os-release added a version_codename field. Use that in
1139
+ # preference to anything else Note that some distros purposefully
1140
+ # do not have code names. They should be setting
1141
+ # version_codename=""
1142
+ props["codename"] = props["version_codename"]
1143
+ elif "ubuntu_codename" in props:
1144
+ # Same as above but a non-standard field name used on older Ubuntus
1145
+ props["codename"] = props["ubuntu_codename"]
1146
+
1147
+ return props
1148
+
1149
+ @cached_property
1150
+ def _lsb_release_info(self) -> Dict[str, str]:
1151
+ """
1152
+ Get the information items from the lsb_release command output.
1153
+
1154
+ Returns:
1155
+ A dictionary containing all information items.
1156
+ """
1157
+ if not self.include_lsb:
1158
+ return {}
1159
+ try:
1160
+ cmd = ("lsb_release", "-a")
1161
+ stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
1162
+ # Command not found or lsb_release returned error
1163
+ except (OSError, subprocess.CalledProcessError):
1164
+ return {}
1165
+ content = self._to_str(stdout).splitlines()
1166
+ return self._parse_lsb_release_content(content)
1167
+
1168
+ @staticmethod
1169
+ def _parse_lsb_release_content(lines: Iterable[str]) -> Dict[str, str]:
1170
+ """
1171
+ Parse the output of the lsb_release command.
1172
+
1173
+ Parameters:
1174
+
1175
+ * lines: Iterable through the lines of the lsb_release output.
1176
+ Each line must be a unicode string or a UTF-8 encoded byte
1177
+ string.
1178
+
1179
+ Returns:
1180
+ A dictionary containing all information items.
1181
+ """
1182
+ props = {}
1183
+ for line in lines:
1184
+ kv = line.strip("\n").split(":", 1)
1185
+ if len(kv) != 2:
1186
+ # Ignore lines without colon.
1187
+ continue
1188
+ k, v = kv
1189
+ props.update({k.replace(" ", "_").lower(): v.strip()})
1190
+ return props
1191
+
1192
+ @cached_property
1193
+ def _uname_info(self) -> Dict[str, str]:
1194
+ if not self.include_uname:
1195
+ return {}
1196
+ try:
1197
+ cmd = ("uname", "-rs")
1198
+ stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
1199
+ except OSError:
1200
+ return {}
1201
+ content = self._to_str(stdout).splitlines()
1202
+ return self._parse_uname_content(content)
1203
+
1204
+ @cached_property
1205
+ def _oslevel_info(self) -> str:
1206
+ if not self.include_oslevel:
1207
+ return ""
1208
+ try:
1209
+ stdout = subprocess.check_output("oslevel", stderr=subprocess.DEVNULL)
1210
+ except (OSError, subprocess.CalledProcessError):
1211
+ return ""
1212
+ return self._to_str(stdout).strip()
1213
+
1214
+ @cached_property
1215
+ def _debian_version(self) -> str:
1216
+ try:
1217
+ with open(
1218
+ os.path.join(self.etc_dir, "debian_version"), encoding="ascii"
1219
+ ) as fp:
1220
+ return fp.readline().rstrip()
1221
+ except FileNotFoundError:
1222
+ return ""
1223
+
1224
+ @staticmethod
1225
+ def _parse_uname_content(lines: Sequence[str]) -> Dict[str, str]:
1226
+ if not lines:
1227
+ return {}
1228
+ props = {}
1229
+ match = re.search(r"^([^\s]+)\s+([\d\.]+)", lines[0].strip())
1230
+ if match:
1231
+ name, version = match.groups()
1232
+
1233
+ # This is to prevent the Linux kernel version from
1234
+ # appearing as the 'best' version on otherwise
1235
+ # identifiable distributions.
1236
+ if name == "Linux":
1237
+ return {}
1238
+ props["id"] = name.lower()
1239
+ props["name"] = name
1240
+ props["release"] = version
1241
+ return props
1242
+
1243
+ @staticmethod
1244
+ def _to_str(bytestring: bytes) -> str:
1245
+ encoding = sys.getfilesystemencoding()
1246
+ return bytestring.decode(encoding)
1247
+
1248
+ @cached_property
1249
+ def _distro_release_info(self) -> Dict[str, str]:
1250
+ """
1251
+ Get the information items from the specified distro release file.
1252
+
1253
+ Returns:
1254
+ A dictionary containing all information items.
1255
+ """
1256
+ if self.distro_release_file:
1257
+ # If it was specified, we use it and parse what we can, even if
1258
+ # its file name or content does not match the expected pattern.
1259
+ distro_info = self._parse_distro_release_file(self.distro_release_file)
1260
+ basename = os.path.basename(self.distro_release_file)
1261
+ # The file name pattern for user-specified distro release files
1262
+ # is somewhat more tolerant (compared to when searching for the
1263
+ # file), because we want to use what was specified as best as
1264
+ # possible.
1265
+ match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
1266
+ else:
1267
+ try:
1268
+ basenames = [
1269
+ basename
1270
+ for basename in os.listdir(self.etc_dir)
1271
+ if basename not in _DISTRO_RELEASE_IGNORE_BASENAMES
1272
+ and os.path.isfile(os.path.join(self.etc_dir, basename))
1273
+ ]
1274
+ # We sort for repeatability in cases where there are multiple
1275
+ # distro specific files; e.g. CentOS, Oracle, Enterprise all
1276
+ # containing `redhat-release` on top of their own.
1277
+ basenames.sort()
1278
+ except OSError:
1279
+ # This may occur when /etc is not readable but we can't be
1280
+ # sure about the *-release files. Check common entries of
1281
+ # /etc for information. If they turn out to not be there the
1282
+ # error is handled in `_parse_distro_release_file()`.
1283
+ basenames = _DISTRO_RELEASE_BASENAMES
1284
+ for basename in basenames:
1285
+ match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
1286
+ if match is None:
1287
+ continue
1288
+ filepath = os.path.join(self.etc_dir, basename)
1289
+ distro_info = self._parse_distro_release_file(filepath)
1290
+ # The name is always present if the pattern matches.
1291
+ if "name" not in distro_info:
1292
+ continue
1293
+ self.distro_release_file = filepath
1294
+ break
1295
+ else: # the loop didn't "break": no candidate.
1296
+ return {}
1297
+
1298
+ if match is not None:
1299
+ distro_info["id"] = match.group(1)
1300
+
1301
+ # CloudLinux < 7: manually enrich info with proper id.
1302
+ if "cloudlinux" in distro_info.get("name", "").lower():
1303
+ distro_info["id"] = "cloudlinux"
1304
+
1305
+ return distro_info
1306
+
1307
+ def _parse_distro_release_file(self, filepath: str) -> Dict[str, str]:
1308
+ """
1309
+ Parse a distro release file.
1310
+
1311
+ Parameters:
1312
+
1313
+ * filepath: Path name of the distro release file.
1314
+
1315
+ Returns:
1316
+ A dictionary containing all information items.
1317
+ """
1318
+ try:
1319
+ with open(filepath, encoding="utf-8") as fp:
1320
+ # Only parse the first line. For instance, on SLES there
1321
+ # are multiple lines. We don't want them...
1322
+ return self._parse_distro_release_content(fp.readline())
1323
+ except OSError:
1324
+ # Ignore not being able to read a specific, seemingly version
1325
+ # related file.
1326
+ # See https://github.com/python-distro/distro/issues/162
1327
+ return {}
1328
+
1329
+ @staticmethod
1330
+ def _parse_distro_release_content(line: str) -> Dict[str, str]:
1331
+ """
1332
+ Parse a line from a distro release file.
1333
+
1334
+ Parameters:
1335
+ * line: Line from the distro release file. Must be a unicode string
1336
+ or a UTF-8 encoded byte string.
1337
+
1338
+ Returns:
1339
+ A dictionary containing all information items.
1340
+ """
1341
+ matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match(line.strip()[::-1])
1342
+ distro_info = {}
1343
+ if matches:
1344
+ # regexp ensures non-None
1345
+ distro_info["name"] = matches.group(3)[::-1]
1346
+ if matches.group(2):
1347
+ distro_info["version_id"] = matches.group(2)[::-1]
1348
+ if matches.group(1):
1349
+ distro_info["codename"] = matches.group(1)[::-1]
1350
+ elif line:
1351
+ distro_info["name"] = line.strip()
1352
+ return distro_info
1353
+
1354
+
1355
+ _distro = LinuxDistribution()
1356
+
1357
+
1358
+ def main() -> None:
1359
+ logger = logging.getLogger(__name__)
1360
+ logger.setLevel(logging.DEBUG)
1361
+ logger.addHandler(logging.StreamHandler(sys.stdout))
1362
+
1363
+ parser = argparse.ArgumentParser(description="OS distro info tool")
1364
+ parser.add_argument(
1365
+ "--json", "-j", help="Output in machine readable format", action="store_true"
1366
+ )
1367
+
1368
+ parser.add_argument(
1369
+ "--root-dir",
1370
+ "-r",
1371
+ type=str,
1372
+ dest="root_dir",
1373
+ help="Path to the root filesystem directory (defaults to /)",
1374
+ )
1375
+
1376
+ args = parser.parse_args()
1377
+
1378
+ if args.root_dir:
1379
+ dist = LinuxDistribution(
1380
+ include_lsb=False,
1381
+ include_uname=False,
1382
+ include_oslevel=False,
1383
+ root_dir=args.root_dir,
1384
+ )
1385
+ else:
1386
+ dist = _distro
1387
+
1388
+ if args.json:
1389
+ logger.info(json.dumps(dist.info(), indent=4, sort_keys=True))
1390
+ else:
1391
+ logger.info("Name: %s", dist.name(pretty=True))
1392
+ distribution_version = dist.version(pretty=True)
1393
+ logger.info("Version: %s", distribution_version)
1394
+ distribution_codename = dist.codename()
1395
+ logger.info("Codename: %s", distribution_codename)
1396
+
1397
+
1398
+ if __name__ == "__main__":
1399
+ main()
.venv/Lib/site-packages/pip/_vendor/idna/__init__.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .package_data import __version__
2
+ from .core import (
3
+ IDNABidiError,
4
+ IDNAError,
5
+ InvalidCodepoint,
6
+ InvalidCodepointContext,
7
+ alabel,
8
+ check_bidi,
9
+ check_hyphen_ok,
10
+ check_initial_combiner,
11
+ check_label,
12
+ check_nfc,
13
+ decode,
14
+ encode,
15
+ ulabel,
16
+ uts46_remap,
17
+ valid_contextj,
18
+ valid_contexto,
19
+ valid_label_length,
20
+ valid_string_length,
21
+ )
22
+ from .intranges import intranges_contain
23
+
24
+ __all__ = [
25
+ "IDNABidiError",
26
+ "IDNAError",
27
+ "InvalidCodepoint",
28
+ "InvalidCodepointContext",
29
+ "alabel",
30
+ "check_bidi",
31
+ "check_hyphen_ok",
32
+ "check_initial_combiner",
33
+ "check_label",
34
+ "check_nfc",
35
+ "decode",
36
+ "encode",
37
+ "intranges_contain",
38
+ "ulabel",
39
+ "uts46_remap",
40
+ "valid_contextj",
41
+ "valid_contexto",
42
+ "valid_label_length",
43
+ "valid_string_length",
44
+ ]
.venv/Lib/site-packages/pip/_vendor/idna/codec.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .core import encode, decode, alabel, ulabel, IDNAError
2
+ import codecs
3
+ import re
4
+ from typing import Tuple, Optional
5
+
6
+ _unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]')
7
+
8
+ class Codec(codecs.Codec):
9
+
10
+ def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]:
11
+ if errors != 'strict':
12
+ raise IDNAError('Unsupported error handling \"{}\"'.format(errors))
13
+
14
+ if not data:
15
+ return b"", 0
16
+
17
+ return encode(data), len(data)
18
+
19
+ def decode(self, data: bytes, errors: str = 'strict') -> Tuple[str, int]:
20
+ if errors != 'strict':
21
+ raise IDNAError('Unsupported error handling \"{}\"'.format(errors))
22
+
23
+ if not data:
24
+ return '', 0
25
+
26
+ return decode(data), len(data)
27
+
28
+ class IncrementalEncoder(codecs.BufferedIncrementalEncoder):
29
+ def _buffer_encode(self, data: str, errors: str, final: bool) -> Tuple[str, int]: # type: ignore
30
+ if errors != 'strict':
31
+ raise IDNAError('Unsupported error handling \"{}\"'.format(errors))
32
+
33
+ if not data:
34
+ return "", 0
35
+
36
+ labels = _unicode_dots_re.split(data)
37
+ trailing_dot = ''
38
+ if labels:
39
+ if not labels[-1]:
40
+ trailing_dot = '.'
41
+ del labels[-1]
42
+ elif not final:
43
+ # Keep potentially unfinished label until the next call
44
+ del labels[-1]
45
+ if labels:
46
+ trailing_dot = '.'
47
+
48
+ result = []
49
+ size = 0
50
+ for label in labels:
51
+ result.append(alabel(label))
52
+ if size:
53
+ size += 1
54
+ size += len(label)
55
+
56
+ # Join with U+002E
57
+ result_str = '.'.join(result) + trailing_dot # type: ignore
58
+ size += len(trailing_dot)
59
+ return result_str, size
60
+
61
+ class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
62
+ def _buffer_decode(self, data: str, errors: str, final: bool) -> Tuple[str, int]: # type: ignore
63
+ if errors != 'strict':
64
+ raise IDNAError('Unsupported error handling \"{}\"'.format(errors))
65
+
66
+ if not data:
67
+ return ('', 0)
68
+
69
+ labels = _unicode_dots_re.split(data)
70
+ trailing_dot = ''
71
+ if labels:
72
+ if not labels[-1]:
73
+ trailing_dot = '.'
74
+ del labels[-1]
75
+ elif not final:
76
+ # Keep potentially unfinished label until the next call
77
+ del labels[-1]
78
+ if labels:
79
+ trailing_dot = '.'
80
+
81
+ result = []
82
+ size = 0
83
+ for label in labels:
84
+ result.append(ulabel(label))
85
+ if size:
86
+ size += 1
87
+ size += len(label)
88
+
89
+ result_str = '.'.join(result) + trailing_dot
90
+ size += len(trailing_dot)
91
+ return (result_str, size)
92
+
93
+
94
+ class StreamWriter(Codec, codecs.StreamWriter):
95
+ pass
96
+
97
+
98
+ class StreamReader(Codec, codecs.StreamReader):
99
+ pass
100
+
101
+
102
+ def getregentry() -> codecs.CodecInfo:
103
+ # Compatibility as a search_function for codecs.register()
104
+ return codecs.CodecInfo(
105
+ name='idna',
106
+ encode=Codec().encode, # type: ignore
107
+ decode=Codec().decode, # type: ignore
108
+ incrementalencoder=IncrementalEncoder,
109
+ incrementaldecoder=IncrementalDecoder,
110
+ streamwriter=StreamWriter,
111
+ streamreader=StreamReader,
112
+ )
.venv/Lib/site-packages/pip/_vendor/idna/compat.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .core import *
2
+ from .codec import *
3
+ from typing import Any, Union
4
+
5
+ def ToASCII(label: str) -> bytes:
6
+ return encode(label)
7
+
8
+ def ToUnicode(label: Union[bytes, bytearray]) -> str:
9
+ return decode(label)
10
+
11
+ def nameprep(s: Any) -> None:
12
+ raise NotImplementedError('IDNA 2008 does not utilise nameprep protocol')
13
+
.venv/Lib/site-packages/pip/_vendor/idna/core.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import idnadata
2
+ import bisect
3
+ import unicodedata
4
+ import re
5
+ from typing import Union, Optional
6
+ from .intranges import intranges_contain
7
+
8
+ _virama_combining_class = 9
9
+ _alabel_prefix = b'xn--'
10
+ _unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]')
11
+
12
+ class IDNAError(UnicodeError):
13
+ """ Base exception for all IDNA-encoding related problems """
14
+ pass
15
+
16
+
17
+ class IDNABidiError(IDNAError):
18
+ """ Exception when bidirectional requirements are not satisfied """
19
+ pass
20
+
21
+
22
+ class InvalidCodepoint(IDNAError):
23
+ """ Exception when a disallowed or unallocated codepoint is used """
24
+ pass
25
+
26
+
27
+ class InvalidCodepointContext(IDNAError):
28
+ """ Exception when the codepoint is not valid in the context it is used """
29
+ pass
30
+
31
+
32
+ def _combining_class(cp: int) -> int:
33
+ v = unicodedata.combining(chr(cp))
34
+ if v == 0:
35
+ if not unicodedata.name(chr(cp)):
36
+ raise ValueError('Unknown character in unicodedata')
37
+ return v
38
+
39
+ def _is_script(cp: str, script: str) -> bool:
40
+ return intranges_contain(ord(cp), idnadata.scripts[script])
41
+
42
+ def _punycode(s: str) -> bytes:
43
+ return s.encode('punycode')
44
+
45
+ def _unot(s: int) -> str:
46
+ return 'U+{:04X}'.format(s)
47
+
48
+
49
+ def valid_label_length(label: Union[bytes, str]) -> bool:
50
+ if len(label) > 63:
51
+ return False
52
+ return True
53
+
54
+
55
+ def valid_string_length(label: Union[bytes, str], trailing_dot: bool) -> bool:
56
+ if len(label) > (254 if trailing_dot else 253):
57
+ return False
58
+ return True
59
+
60
+
61
+ def check_bidi(label: str, check_ltr: bool = False) -> bool:
62
+ # Bidi rules should only be applied if string contains RTL characters
63
+ bidi_label = False
64
+ for (idx, cp) in enumerate(label, 1):
65
+ direction = unicodedata.bidirectional(cp)
66
+ if direction == '':
67
+ # String likely comes from a newer version of Unicode
68
+ raise IDNABidiError('Unknown directionality in label {} at position {}'.format(repr(label), idx))
69
+ if direction in ['R', 'AL', 'AN']:
70
+ bidi_label = True
71
+ if not bidi_label and not check_ltr:
72
+ return True
73
+
74
+ # Bidi rule 1
75
+ direction = unicodedata.bidirectional(label[0])
76
+ if direction in ['R', 'AL']:
77
+ rtl = True
78
+ elif direction == 'L':
79
+ rtl = False
80
+ else:
81
+ raise IDNABidiError('First codepoint in label {} must be directionality L, R or AL'.format(repr(label)))
82
+
83
+ valid_ending = False
84
+ number_type = None # type: Optional[str]
85
+ for (idx, cp) in enumerate(label, 1):
86
+ direction = unicodedata.bidirectional(cp)
87
+
88
+ if rtl:
89
+ # Bidi rule 2
90
+ if not direction in ['R', 'AL', 'AN', 'EN', 'ES', 'CS', 'ET', 'ON', 'BN', 'NSM']:
91
+ raise IDNABidiError('Invalid direction for codepoint at position {} in a right-to-left label'.format(idx))
92
+ # Bidi rule 3
93
+ if direction in ['R', 'AL', 'EN', 'AN']:
94
+ valid_ending = True
95
+ elif direction != 'NSM':
96
+ valid_ending = False
97
+ # Bidi rule 4
98
+ if direction in ['AN', 'EN']:
99
+ if not number_type:
100
+ number_type = direction
101
+ else:
102
+ if number_type != direction:
103
+ raise IDNABidiError('Can not mix numeral types in a right-to-left label')
104
+ else:
105
+ # Bidi rule 5
106
+ if not direction in ['L', 'EN', 'ES', 'CS', 'ET', 'ON', 'BN', 'NSM']:
107
+ raise IDNABidiError('Invalid direction for codepoint at position {} in a left-to-right label'.format(idx))
108
+ # Bidi rule 6
109
+ if direction in ['L', 'EN']:
110
+ valid_ending = True
111
+ elif direction != 'NSM':
112
+ valid_ending = False
113
+
114
+ if not valid_ending:
115
+ raise IDNABidiError('Label ends with illegal codepoint directionality')
116
+
117
+ return True
118
+
119
+
120
+ def check_initial_combiner(label: str) -> bool:
121
+ if unicodedata.category(label[0])[0] == 'M':
122
+ raise IDNAError('Label begins with an illegal combining character')
123
+ return True
124
+
125
+
126
+ def check_hyphen_ok(label: str) -> bool:
127
+ if label[2:4] == '--':
128
+ raise IDNAError('Label has disallowed hyphens in 3rd and 4th position')
129
+ if label[0] == '-' or label[-1] == '-':
130
+ raise IDNAError('Label must not start or end with a hyphen')
131
+ return True
132
+
133
+
134
+ def check_nfc(label: str) -> None:
135
+ if unicodedata.normalize('NFC', label) != label:
136
+ raise IDNAError('Label must be in Normalization Form C')
137
+
138
+
139
+ def valid_contextj(label: str, pos: int) -> bool:
140
+ cp_value = ord(label[pos])
141
+
142
+ if cp_value == 0x200c:
143
+
144
+ if pos > 0:
145
+ if _combining_class(ord(label[pos - 1])) == _virama_combining_class:
146
+ return True
147
+
148
+ ok = False
149
+ for i in range(pos-1, -1, -1):
150
+ joining_type = idnadata.joining_types.get(ord(label[i]))
151
+ if joining_type == ord('T'):
152
+ continue
153
+ if joining_type in [ord('L'), ord('D')]:
154
+ ok = True
155
+ break
156
+
157
+ if not ok:
158
+ return False
159
+
160
+ ok = False
161
+ for i in range(pos+1, len(label)):
162
+ joining_type = idnadata.joining_types.get(ord(label[i]))
163
+ if joining_type == ord('T'):
164
+ continue
165
+ if joining_type in [ord('R'), ord('D')]:
166
+ ok = True
167
+ break
168
+ return ok
169
+
170
+ if cp_value == 0x200d:
171
+
172
+ if pos > 0:
173
+ if _combining_class(ord(label[pos - 1])) == _virama_combining_class:
174
+ return True
175
+ return False
176
+
177
+ else:
178
+
179
+ return False
180
+
181
+
182
+ def valid_contexto(label: str, pos: int, exception: bool = False) -> bool:
183
+ cp_value = ord(label[pos])
184
+
185
+ if cp_value == 0x00b7:
186
+ if 0 < pos < len(label)-1:
187
+ if ord(label[pos - 1]) == 0x006c and ord(label[pos + 1]) == 0x006c:
188
+ return True
189
+ return False
190
+
191
+ elif cp_value == 0x0375:
192
+ if pos < len(label)-1 and len(label) > 1:
193
+ return _is_script(label[pos + 1], 'Greek')
194
+ return False
195
+
196
+ elif cp_value == 0x05f3 or cp_value == 0x05f4:
197
+ if pos > 0:
198
+ return _is_script(label[pos - 1], 'Hebrew')
199
+ return False
200
+
201
+ elif cp_value == 0x30fb:
202
+ for cp in label:
203
+ if cp == '\u30fb':
204
+ continue
205
+ if _is_script(cp, 'Hiragana') or _is_script(cp, 'Katakana') or _is_script(cp, 'Han'):
206
+ return True
207
+ return False
208
+
209
+ elif 0x660 <= cp_value <= 0x669:
210
+ for cp in label:
211
+ if 0x6f0 <= ord(cp) <= 0x06f9:
212
+ return False
213
+ return True
214
+
215
+ elif 0x6f0 <= cp_value <= 0x6f9:
216
+ for cp in label:
217
+ if 0x660 <= ord(cp) <= 0x0669:
218
+ return False
219
+ return True
220
+
221
+ return False
222
+
223
+
224
+ def check_label(label: Union[str, bytes, bytearray]) -> None:
225
+ if isinstance(label, (bytes, bytearray)):
226
+ label = label.decode('utf-8')
227
+ if len(label) == 0:
228
+ raise IDNAError('Empty Label')
229
+
230
+ check_nfc(label)
231
+ check_hyphen_ok(label)
232
+ check_initial_combiner(label)
233
+
234
+ for (pos, cp) in enumerate(label):
235
+ cp_value = ord(cp)
236
+ if intranges_contain(cp_value, idnadata.codepoint_classes['PVALID']):
237
+ continue
238
+ elif intranges_contain(cp_value, idnadata.codepoint_classes['CONTEXTJ']):
239
+ try:
240
+ if not valid_contextj(label, pos):
241
+ raise InvalidCodepointContext('Joiner {} not allowed at position {} in {}'.format(
242
+ _unot(cp_value), pos+1, repr(label)))
243
+ except ValueError:
244
+ raise IDNAError('Unknown codepoint adjacent to joiner {} at position {} in {}'.format(
245
+ _unot(cp_value), pos+1, repr(label)))
246
+ elif intranges_contain(cp_value, idnadata.codepoint_classes['CONTEXTO']):
247
+ if not valid_contexto(label, pos):
248
+ raise InvalidCodepointContext('Codepoint {} not allowed at position {} in {}'.format(_unot(cp_value), pos+1, repr(label)))
249
+ else:
250
+ raise InvalidCodepoint('Codepoint {} at position {} of {} not allowed'.format(_unot(cp_value), pos+1, repr(label)))
251
+
252
+ check_bidi(label)
253
+
254
+
255
+ def alabel(label: str) -> bytes:
256
+ try:
257
+ label_bytes = label.encode('ascii')
258
+ ulabel(label_bytes)
259
+ if not valid_label_length(label_bytes):
260
+ raise IDNAError('Label too long')
261
+ return label_bytes
262
+ except UnicodeEncodeError:
263
+ pass
264
+
265
+ if not label:
266
+ raise IDNAError('No Input')
267
+
268
+ label = str(label)
269
+ check_label(label)
270
+ label_bytes = _punycode(label)
271
+ label_bytes = _alabel_prefix + label_bytes
272
+
273
+ if not valid_label_length(label_bytes):
274
+ raise IDNAError('Label too long')
275
+
276
+ return label_bytes
277
+
278
+
279
+ def ulabel(label: Union[str, bytes, bytearray]) -> str:
280
+ if not isinstance(label, (bytes, bytearray)):
281
+ try:
282
+ label_bytes = label.encode('ascii')
283
+ except UnicodeEncodeError:
284
+ check_label(label)
285
+ return label
286
+ else:
287
+ label_bytes = label
288
+
289
+ label_bytes = label_bytes.lower()
290
+ if label_bytes.startswith(_alabel_prefix):
291
+ label_bytes = label_bytes[len(_alabel_prefix):]
292
+ if not label_bytes:
293
+ raise IDNAError('Malformed A-label, no Punycode eligible content found')
294
+ if label_bytes.decode('ascii')[-1] == '-':
295
+ raise IDNAError('A-label must not end with a hyphen')
296
+ else:
297
+ check_label(label_bytes)
298
+ return label_bytes.decode('ascii')
299
+
300
+ try:
301
+ label = label_bytes.decode('punycode')
302
+ except UnicodeError:
303
+ raise IDNAError('Invalid A-label')
304
+ check_label(label)
305
+ return label
306
+
307
+
308
+ def uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str:
309
+ """Re-map the characters in the string according to UTS46 processing."""
310
+ from .uts46data import uts46data
311
+ output = ''
312
+
313
+ for pos, char in enumerate(domain):
314
+ code_point = ord(char)
315
+ try:
316
+ uts46row = uts46data[code_point if code_point < 256 else
317
+ bisect.bisect_left(uts46data, (code_point, 'Z')) - 1]
318
+ status = uts46row[1]
319
+ replacement = None # type: Optional[str]
320
+ if len(uts46row) == 3:
321
+ replacement = uts46row[2] # type: ignore
322
+ if (status == 'V' or
323
+ (status == 'D' and not transitional) or
324
+ (status == '3' and not std3_rules and replacement is None)):
325
+ output += char
326
+ elif replacement is not None and (status == 'M' or
327
+ (status == '3' and not std3_rules) or
328
+ (status == 'D' and transitional)):
329
+ output += replacement
330
+ elif status != 'I':
331
+ raise IndexError()
332
+ except IndexError:
333
+ raise InvalidCodepoint(
334
+ 'Codepoint {} not allowed at position {} in {}'.format(
335
+ _unot(code_point), pos + 1, repr(domain)))
336
+
337
+ return unicodedata.normalize('NFC', output)
338
+
339
+
340
+ def encode(s: Union[str, bytes, bytearray], strict: bool = False, uts46: bool = False, std3_rules: bool = False, transitional: bool = False) -> bytes:
341
+ if isinstance(s, (bytes, bytearray)):
342
+ try:
343
+ s = s.decode('ascii')
344
+ except UnicodeDecodeError:
345
+ raise IDNAError('should pass a unicode string to the function rather than a byte string.')
346
+ if uts46:
347
+ s = uts46_remap(s, std3_rules, transitional)
348
+ trailing_dot = False
349
+ result = []
350
+ if strict:
351
+ labels = s.split('.')
352
+ else:
353
+ labels = _unicode_dots_re.split(s)
354
+ if not labels or labels == ['']:
355
+ raise IDNAError('Empty domain')
356
+ if labels[-1] == '':
357
+ del labels[-1]
358
+ trailing_dot = True
359
+ for label in labels:
360
+ s = alabel(label)
361
+ if s:
362
+ result.append(s)
363
+ else:
364
+ raise IDNAError('Empty label')
365
+ if trailing_dot:
366
+ result.append(b'')
367
+ s = b'.'.join(result)
368
+ if not valid_string_length(s, trailing_dot):
369
+ raise IDNAError('Domain too long')
370
+ return s
371
+
372
+
373
+ def decode(s: Union[str, bytes, bytearray], strict: bool = False, uts46: bool = False, std3_rules: bool = False) -> str:
374
+ try:
375
+ if isinstance(s, (bytes, bytearray)):
376
+ s = s.decode('ascii')
377
+ except UnicodeDecodeError:
378
+ raise IDNAError('Invalid ASCII in A-label')
379
+ if uts46:
380
+ s = uts46_remap(s, std3_rules, False)
381
+ trailing_dot = False
382
+ result = []
383
+ if not strict:
384
+ labels = _unicode_dots_re.split(s)
385
+ else:
386
+ labels = s.split('.')
387
+ if not labels or labels == ['']:
388
+ raise IDNAError('Empty domain')
389
+ if not labels[-1]:
390
+ del labels[-1]
391
+ trailing_dot = True
392
+ for label in labels:
393
+ s = ulabel(label)
394
+ if s:
395
+ result.append(s)
396
+ else:
397
+ raise IDNAError('Empty label')
398
+ if trailing_dot:
399
+ result.append('')
400
+ return '.'.join(result)
.venv/Lib/site-packages/pip/_vendor/idna/idnadata.py ADDED
@@ -0,0 +1,2151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is automatically generated by tools/idna-data
2
+
3
+ __version__ = '15.0.0'
4
+ scripts = {
5
+ 'Greek': (
6
+ 0x37000000374,
7
+ 0x37500000378,
8
+ 0x37a0000037e,
9
+ 0x37f00000380,
10
+ 0x38400000385,
11
+ 0x38600000387,
12
+ 0x3880000038b,
13
+ 0x38c0000038d,
14
+ 0x38e000003a2,
15
+ 0x3a3000003e2,
16
+ 0x3f000000400,
17
+ 0x1d2600001d2b,
18
+ 0x1d5d00001d62,
19
+ 0x1d6600001d6b,
20
+ 0x1dbf00001dc0,
21
+ 0x1f0000001f16,
22
+ 0x1f1800001f1e,
23
+ 0x1f2000001f46,
24
+ 0x1f4800001f4e,
25
+ 0x1f5000001f58,
26
+ 0x1f5900001f5a,
27
+ 0x1f5b00001f5c,
28
+ 0x1f5d00001f5e,
29
+ 0x1f5f00001f7e,
30
+ 0x1f8000001fb5,
31
+ 0x1fb600001fc5,
32
+ 0x1fc600001fd4,
33
+ 0x1fd600001fdc,
34
+ 0x1fdd00001ff0,
35
+ 0x1ff200001ff5,
36
+ 0x1ff600001fff,
37
+ 0x212600002127,
38
+ 0xab650000ab66,
39
+ 0x101400001018f,
40
+ 0x101a0000101a1,
41
+ 0x1d2000001d246,
42
+ ),
43
+ 'Han': (
44
+ 0x2e8000002e9a,
45
+ 0x2e9b00002ef4,
46
+ 0x2f0000002fd6,
47
+ 0x300500003006,
48
+ 0x300700003008,
49
+ 0x30210000302a,
50
+ 0x30380000303c,
51
+ 0x340000004dc0,
52
+ 0x4e000000a000,
53
+ 0xf9000000fa6e,
54
+ 0xfa700000fada,
55
+ 0x16fe200016fe4,
56
+ 0x16ff000016ff2,
57
+ 0x200000002a6e0,
58
+ 0x2a7000002b73a,
59
+ 0x2b7400002b81e,
60
+ 0x2b8200002cea2,
61
+ 0x2ceb00002ebe1,
62
+ 0x2f8000002fa1e,
63
+ 0x300000003134b,
64
+ 0x31350000323b0,
65
+ ),
66
+ 'Hebrew': (
67
+ 0x591000005c8,
68
+ 0x5d0000005eb,
69
+ 0x5ef000005f5,
70
+ 0xfb1d0000fb37,
71
+ 0xfb380000fb3d,
72
+ 0xfb3e0000fb3f,
73
+ 0xfb400000fb42,
74
+ 0xfb430000fb45,
75
+ 0xfb460000fb50,
76
+ ),
77
+ 'Hiragana': (
78
+ 0x304100003097,
79
+ 0x309d000030a0,
80
+ 0x1b0010001b120,
81
+ 0x1b1320001b133,
82
+ 0x1b1500001b153,
83
+ 0x1f2000001f201,
84
+ ),
85
+ 'Katakana': (
86
+ 0x30a1000030fb,
87
+ 0x30fd00003100,
88
+ 0x31f000003200,
89
+ 0x32d0000032ff,
90
+ 0x330000003358,
91
+ 0xff660000ff70,
92
+ 0xff710000ff9e,
93
+ 0x1aff00001aff4,
94
+ 0x1aff50001affc,
95
+ 0x1affd0001afff,
96
+ 0x1b0000001b001,
97
+ 0x1b1200001b123,
98
+ 0x1b1550001b156,
99
+ 0x1b1640001b168,
100
+ ),
101
+ }
102
+ joining_types = {
103
+ 0x600: 85,
104
+ 0x601: 85,
105
+ 0x602: 85,
106
+ 0x603: 85,
107
+ 0x604: 85,
108
+ 0x605: 85,
109
+ 0x608: 85,
110
+ 0x60b: 85,
111
+ 0x620: 68,
112
+ 0x621: 85,
113
+ 0x622: 82,
114
+ 0x623: 82,
115
+ 0x624: 82,
116
+ 0x625: 82,
117
+ 0x626: 68,
118
+ 0x627: 82,
119
+ 0x628: 68,
120
+ 0x629: 82,
121
+ 0x62a: 68,
122
+ 0x62b: 68,
123
+ 0x62c: 68,
124
+ 0x62d: 68,
125
+ 0x62e: 68,
126
+ 0x62f: 82,
127
+ 0x630: 82,
128
+ 0x631: 82,
129
+ 0x632: 82,
130
+ 0x633: 68,
131
+ 0x634: 68,
132
+ 0x635: 68,
133
+ 0x636: 68,
134
+ 0x637: 68,
135
+ 0x638: 68,
136
+ 0x639: 68,
137
+ 0x63a: 68,
138
+ 0x63b: 68,
139
+ 0x63c: 68,
140
+ 0x63d: 68,
141
+ 0x63e: 68,
142
+ 0x63f: 68,
143
+ 0x640: 67,
144
+ 0x641: 68,
145
+ 0x642: 68,
146
+ 0x643: 68,
147
+ 0x644: 68,
148
+ 0x645: 68,
149
+ 0x646: 68,
150
+ 0x647: 68,
151
+ 0x648: 82,
152
+ 0x649: 68,
153
+ 0x64a: 68,
154
+ 0x66e: 68,
155
+ 0x66f: 68,
156
+ 0x671: 82,
157
+ 0x672: 82,
158
+ 0x673: 82,
159
+ 0x674: 85,
160
+ 0x675: 82,
161
+ 0x676: 82,
162
+ 0x677: 82,
163
+ 0x678: 68,
164
+ 0x679: 68,
165
+ 0x67a: 68,
166
+ 0x67b: 68,
167
+ 0x67c: 68,
168
+ 0x67d: 68,
169
+ 0x67e: 68,
170
+ 0x67f: 68,
171
+ 0x680: 68,
172
+ 0x681: 68,
173
+ 0x682: 68,
174
+ 0x683: 68,
175
+ 0x684: 68,
176
+ 0x685: 68,
177
+ 0x686: 68,
178
+ 0x687: 68,
179
+ 0x688: 82,
180
+ 0x689: 82,
181
+ 0x68a: 82,
182
+ 0x68b: 82,
183
+ 0x68c: 82,
184
+ 0x68d: 82,
185
+ 0x68e: 82,
186
+ 0x68f: 82,
187
+ 0x690: 82,
188
+ 0x691: 82,
189
+ 0x692: 82,
190
+ 0x693: 82,
191
+ 0x694: 82,
192
+ 0x695: 82,
193
+ 0x696: 82,
194
+ 0x697: 82,
195
+ 0x698: 82,
196
+ 0x699: 82,
197
+ 0x69a: 68,
198
+ 0x69b: 68,
199
+ 0x69c: 68,
200
+ 0x69d: 68,
201
+ 0x69e: 68,
202
+ 0x69f: 68,
203
+ 0x6a0: 68,
204
+ 0x6a1: 68,
205
+ 0x6a2: 68,
206
+ 0x6a3: 68,
207
+ 0x6a4: 68,
208
+ 0x6a5: 68,
209
+ 0x6a6: 68,
210
+ 0x6a7: 68,
211
+ 0x6a8: 68,
212
+ 0x6a9: 68,
213
+ 0x6aa: 68,
214
+ 0x6ab: 68,
215
+ 0x6ac: 68,
216
+ 0x6ad: 68,
217
+ 0x6ae: 68,
218
+ 0x6af: 68,
219
+ 0x6b0: 68,
220
+ 0x6b1: 68,
221
+ 0x6b2: 68,
222
+ 0x6b3: 68,
223
+ 0x6b4: 68,
224
+ 0x6b5: 68,
225
+ 0x6b6: 68,
226
+ 0x6b7: 68,
227
+ 0x6b8: 68,
228
+ 0x6b9: 68,
229
+ 0x6ba: 68,
230
+ 0x6bb: 68,
231
+ 0x6bc: 68,
232
+ 0x6bd: 68,
233
+ 0x6be: 68,
234
+ 0x6bf: 68,
235
+ 0x6c0: 82,
236
+ 0x6c1: 68,
237
+ 0x6c2: 68,
238
+ 0x6c3: 82,
239
+ 0x6c4: 82,
240
+ 0x6c5: 82,
241
+ 0x6c6: 82,
242
+ 0x6c7: 82,
243
+ 0x6c8: 82,
244
+ 0x6c9: 82,
245
+ 0x6ca: 82,
246
+ 0x6cb: 82,
247
+ 0x6cc: 68,
248
+ 0x6cd: 82,
249
+ 0x6ce: 68,
250
+ 0x6cf: 82,
251
+ 0x6d0: 68,
252
+ 0x6d1: 68,
253
+ 0x6d2: 82,
254
+ 0x6d3: 82,
255
+ 0x6d5: 82,
256
+ 0x6dd: 85,
257
+ 0x6ee: 82,
258
+ 0x6ef: 82,
259
+ 0x6fa: 68,
260
+ 0x6fb: 68,
261
+ 0x6fc: 68,
262
+ 0x6ff: 68,
263
+ 0x70f: 84,
264
+ 0x710: 82,
265
+ 0x712: 68,
266
+ 0x713: 68,
267
+ 0x714: 68,
268
+ 0x715: 82,
269
+ 0x716: 82,
270
+ 0x717: 82,
271
+ 0x718: 82,
272
+ 0x719: 82,
273
+ 0x71a: 68,
274
+ 0x71b: 68,
275
+ 0x71c: 68,
276
+ 0x71d: 68,
277
+ 0x71e: 82,
278
+ 0x71f: 68,
279
+ 0x720: 68,
280
+ 0x721: 68,
281
+ 0x722: 68,
282
+ 0x723: 68,
283
+ 0x724: 68,
284
+ 0x725: 68,
285
+ 0x726: 68,
286
+ 0x727: 68,
287
+ 0x728: 82,
288
+ 0x729: 68,
289
+ 0x72a: 82,
290
+ 0x72b: 68,
291
+ 0x72c: 82,
292
+ 0x72d: 68,
293
+ 0x72e: 68,
294
+ 0x72f: 82,
295
+ 0x74d: 82,
296
+ 0x74e: 68,
297
+ 0x74f: 68,
298
+ 0x750: 68,
299
+ 0x751: 68,
300
+ 0x752: 68,
301
+ 0x753: 68,
302
+ 0x754: 68,
303
+ 0x755: 68,
304
+ 0x756: 68,
305
+ 0x757: 68,
306
+ 0x758: 68,
307
+ 0x759: 82,
308
+ 0x75a: 82,
309
+ 0x75b: 82,
310
+ 0x75c: 68,
311
+ 0x75d: 68,
312
+ 0x75e: 68,
313
+ 0x75f: 68,
314
+ 0x760: 68,
315
+ 0x761: 68,
316
+ 0x762: 68,
317
+ 0x763: 68,
318
+ 0x764: 68,
319
+ 0x765: 68,
320
+ 0x766: 68,
321
+ 0x767: 68,
322
+ 0x768: 68,
323
+ 0x769: 68,
324
+ 0x76a: 68,
325
+ 0x76b: 82,
326
+ 0x76c: 82,
327
+ 0x76d: 68,
328
+ 0x76e: 68,
329
+ 0x76f: 68,
330
+ 0x770: 68,
331
+ 0x771: 82,
332
+ 0x772: 68,
333
+ 0x773: 82,
334
+ 0x774: 82,
335
+ 0x775: 68,
336
+ 0x776: 68,
337
+ 0x777: 68,
338
+ 0x778: 82,
339
+ 0x779: 82,
340
+ 0x77a: 68,
341
+ 0x77b: 68,
342
+ 0x77c: 68,
343
+ 0x77d: 68,
344
+ 0x77e: 68,
345
+ 0x77f: 68,
346
+ 0x7ca: 68,
347
+ 0x7cb: 68,
348
+ 0x7cc: 68,
349
+ 0x7cd: 68,
350
+ 0x7ce: 68,
351
+ 0x7cf: 68,
352
+ 0x7d0: 68,
353
+ 0x7d1: 68,
354
+ 0x7d2: 68,
355
+ 0x7d3: 68,
356
+ 0x7d4: 68,
357
+ 0x7d5: 68,
358
+ 0x7d6: 68,
359
+ 0x7d7: 68,
360
+ 0x7d8: 68,
361
+ 0x7d9: 68,
362
+ 0x7da: 68,
363
+ 0x7db: 68,
364
+ 0x7dc: 68,
365
+ 0x7dd: 68,
366
+ 0x7de: 68,
367
+ 0x7df: 68,
368
+ 0x7e0: 68,
369
+ 0x7e1: 68,
370
+ 0x7e2: 68,
371
+ 0x7e3: 68,
372
+ 0x7e4: 68,
373
+ 0x7e5: 68,
374
+ 0x7e6: 68,
375
+ 0x7e7: 68,
376
+ 0x7e8: 68,
377
+ 0x7e9: 68,
378
+ 0x7ea: 68,
379
+ 0x7fa: 67,
380
+ 0x840: 82,
381
+ 0x841: 68,
382
+ 0x842: 68,
383
+ 0x843: 68,
384
+ 0x844: 68,
385
+ 0x845: 68,
386
+ 0x846: 82,
387
+ 0x847: 82,
388
+ 0x848: 68,
389
+ 0x849: 82,
390
+ 0x84a: 68,
391
+ 0x84b: 68,
392
+ 0x84c: 68,
393
+ 0x84d: 68,
394
+ 0x84e: 68,
395
+ 0x84f: 68,
396
+ 0x850: 68,
397
+ 0x851: 68,
398
+ 0x852: 68,
399
+ 0x853: 68,
400
+ 0x854: 82,
401
+ 0x855: 68,
402
+ 0x856: 82,
403
+ 0x857: 82,
404
+ 0x858: 82,
405
+ 0x860: 68,
406
+ 0x861: 85,
407
+ 0x862: 68,
408
+ 0x863: 68,
409
+ 0x864: 68,
410
+ 0x865: 68,
411
+ 0x866: 85,
412
+ 0x867: 82,
413
+ 0x868: 68,
414
+ 0x869: 82,
415
+ 0x86a: 82,
416
+ 0x870: 82,
417
+ 0x871: 82,
418
+ 0x872: 82,
419
+ 0x873: 82,
420
+ 0x874: 82,
421
+ 0x875: 82,
422
+ 0x876: 82,
423
+ 0x877: 82,
424
+ 0x878: 82,
425
+ 0x879: 82,
426
+ 0x87a: 82,
427
+ 0x87b: 82,
428
+ 0x87c: 82,
429
+ 0x87d: 82,
430
+ 0x87e: 82,
431
+ 0x87f: 82,
432
+ 0x880: 82,
433
+ 0x881: 82,
434
+ 0x882: 82,
435
+ 0x883: 67,
436
+ 0x884: 67,
437
+ 0x885: 67,
438
+ 0x886: 68,
439
+ 0x887: 85,
440
+ 0x888: 85,
441
+ 0x889: 68,
442
+ 0x88a: 68,
443
+ 0x88b: 68,
444
+ 0x88c: 68,
445
+ 0x88d: 68,
446
+ 0x88e: 82,
447
+ 0x890: 85,
448
+ 0x891: 85,
449
+ 0x8a0: 68,
450
+ 0x8a1: 68,
451
+ 0x8a2: 68,
452
+ 0x8a3: 68,
453
+ 0x8a4: 68,
454
+ 0x8a5: 68,
455
+ 0x8a6: 68,
456
+ 0x8a7: 68,
457
+ 0x8a8: 68,
458
+ 0x8a9: 68,
459
+ 0x8aa: 82,
460
+ 0x8ab: 82,
461
+ 0x8ac: 82,
462
+ 0x8ad: 85,
463
+ 0x8ae: 82,
464
+ 0x8af: 68,
465
+ 0x8b0: 68,
466
+ 0x8b1: 82,
467
+ 0x8b2: 82,
468
+ 0x8b3: 68,
469
+ 0x8b4: 68,
470
+ 0x8b5: 68,
471
+ 0x8b6: 68,
472
+ 0x8b7: 68,
473
+ 0x8b8: 68,
474
+ 0x8b9: 82,
475
+ 0x8ba: 68,
476
+ 0x8bb: 68,
477
+ 0x8bc: 68,
478
+ 0x8bd: 68,
479
+ 0x8be: 68,
480
+ 0x8bf: 68,
481
+ 0x8c0: 68,
482
+ 0x8c1: 68,
483
+ 0x8c2: 68,
484
+ 0x8c3: 68,
485
+ 0x8c4: 68,
486
+ 0x8c5: 68,
487
+ 0x8c6: 68,
488
+ 0x8c7: 68,
489
+ 0x8c8: 68,
490
+ 0x8e2: 85,
491
+ 0x1806: 85,
492
+ 0x1807: 68,
493
+ 0x180a: 67,
494
+ 0x180e: 85,
495
+ 0x1820: 68,
496
+ 0x1821: 68,
497
+ 0x1822: 68,
498
+ 0x1823: 68,
499
+ 0x1824: 68,
500
+ 0x1825: 68,
501
+ 0x1826: 68,
502
+ 0x1827: 68,
503
+ 0x1828: 68,
504
+ 0x1829: 68,
505
+ 0x182a: 68,
506
+ 0x182b: 68,
507
+ 0x182c: 68,
508
+ 0x182d: 68,
509
+ 0x182e: 68,
510
+ 0x182f: 68,
511
+ 0x1830: 68,
512
+ 0x1831: 68,
513
+ 0x1832: 68,
514
+ 0x1833: 68,
515
+ 0x1834: 68,
516
+ 0x1835: 68,
517
+ 0x1836: 68,
518
+ 0x1837: 68,
519
+ 0x1838: 68,
520
+ 0x1839: 68,
521
+ 0x183a: 68,
522
+ 0x183b: 68,
523
+ 0x183c: 68,
524
+ 0x183d: 68,
525
+ 0x183e: 68,
526
+ 0x183f: 68,
527
+ 0x1840: 68,
528
+ 0x1841: 68,
529
+ 0x1842: 68,
530
+ 0x1843: 68,
531
+ 0x1844: 68,
532
+ 0x1845: 68,
533
+ 0x1846: 68,
534
+ 0x1847: 68,
535
+ 0x1848: 68,
536
+ 0x1849: 68,
537
+ 0x184a: 68,
538
+ 0x184b: 68,
539
+ 0x184c: 68,
540
+ 0x184d: 68,
541
+ 0x184e: 68,
542
+ 0x184f: 68,
543
+ 0x1850: 68,
544
+ 0x1851: 68,
545
+ 0x1852: 68,
546
+ 0x1853: 68,
547
+ 0x1854: 68,
548
+ 0x1855: 68,
549
+ 0x1856: 68,
550
+ 0x1857: 68,
551
+ 0x1858: 68,
552
+ 0x1859: 68,
553
+ 0x185a: 68,
554
+ 0x185b: 68,
555
+ 0x185c: 68,
556
+ 0x185d: 68,
557
+ 0x185e: 68,
558
+ 0x185f: 68,
559
+ 0x1860: 68,
560
+ 0x1861: 68,
561
+ 0x1862: 68,
562
+ 0x1863: 68,
563
+ 0x1864: 68,
564
+ 0x1865: 68,
565
+ 0x1866: 68,
566
+ 0x1867: 68,
567
+ 0x1868: 68,
568
+ 0x1869: 68,
569
+ 0x186a: 68,
570
+ 0x186b: 68,
571
+ 0x186c: 68,
572
+ 0x186d: 68,
573
+ 0x186e: 68,
574
+ 0x186f: 68,
575
+ 0x1870: 68,
576
+ 0x1871: 68,
577
+ 0x1872: 68,
578
+ 0x1873: 68,
579
+ 0x1874: 68,
580
+ 0x1875: 68,
581
+ 0x1876: 68,
582
+ 0x1877: 68,
583
+ 0x1878: 68,
584
+ 0x1880: 85,
585
+ 0x1881: 85,
586
+ 0x1882: 85,
587
+ 0x1883: 85,
588
+ 0x1884: 85,
589
+ 0x1885: 84,
590
+ 0x1886: 84,
591
+ 0x1887: 68,
592
+ 0x1888: 68,
593
+ 0x1889: 68,
594
+ 0x188a: 68,
595
+ 0x188b: 68,
596
+ 0x188c: 68,
597
+ 0x188d: 68,
598
+ 0x188e: 68,
599
+ 0x188f: 68,
600
+ 0x1890: 68,
601
+ 0x1891: 68,
602
+ 0x1892: 68,
603
+ 0x1893: 68,
604
+ 0x1894: 68,
605
+ 0x1895: 68,
606
+ 0x1896: 68,
607
+ 0x1897: 68,
608
+ 0x1898: 68,
609
+ 0x1899: 68,
610
+ 0x189a: 68,
611
+ 0x189b: 68,
612
+ 0x189c: 68,
613
+ 0x189d: 68,
614
+ 0x189e: 68,
615
+ 0x189f: 68,
616
+ 0x18a0: 68,
617
+ 0x18a1: 68,
618
+ 0x18a2: 68,
619
+ 0x18a3: 68,
620
+ 0x18a4: 68,
621
+ 0x18a5: 68,
622
+ 0x18a6: 68,
623
+ 0x18a7: 68,
624
+ 0x18a8: 68,
625
+ 0x18aa: 68,
626
+ 0x200c: 85,
627
+ 0x200d: 67,
628
+ 0x202f: 85,
629
+ 0x2066: 85,
630
+ 0x2067: 85,
631
+ 0x2068: 85,
632
+ 0x2069: 85,
633
+ 0xa840: 68,
634
+ 0xa841: 68,
635
+ 0xa842: 68,
636
+ 0xa843: 68,
637
+ 0xa844: 68,
638
+ 0xa845: 68,
639
+ 0xa846: 68,
640
+ 0xa847: 68,
641
+ 0xa848: 68,
642
+ 0xa849: 68,
643
+ 0xa84a: 68,
644
+ 0xa84b: 68,
645
+ 0xa84c: 68,
646
+ 0xa84d: 68,
647
+ 0xa84e: 68,
648
+ 0xa84f: 68,
649
+ 0xa850: 68,
650
+ 0xa851: 68,
651
+ 0xa852: 68,
652
+ 0xa853: 68,
653
+ 0xa854: 68,
654
+ 0xa855: 68,
655
+ 0xa856: 68,
656
+ 0xa857: 68,
657
+ 0xa858: 68,
658
+ 0xa859: 68,
659
+ 0xa85a: 68,
660
+ 0xa85b: 68,
661
+ 0xa85c: 68,
662
+ 0xa85d: 68,
663
+ 0xa85e: 68,
664
+ 0xa85f: 68,
665
+ 0xa860: 68,
666
+ 0xa861: 68,
667
+ 0xa862: 68,
668
+ 0xa863: 68,
669
+ 0xa864: 68,
670
+ 0xa865: 68,
671
+ 0xa866: 68,
672
+ 0xa867: 68,
673
+ 0xa868: 68,
674
+ 0xa869: 68,
675
+ 0xa86a: 68,
676
+ 0xa86b: 68,
677
+ 0xa86c: 68,
678
+ 0xa86d: 68,
679
+ 0xa86e: 68,
680
+ 0xa86f: 68,
681
+ 0xa870: 68,
682
+ 0xa871: 68,
683
+ 0xa872: 76,
684
+ 0xa873: 85,
685
+ 0x10ac0: 68,
686
+ 0x10ac1: 68,
687
+ 0x10ac2: 68,
688
+ 0x10ac3: 68,
689
+ 0x10ac4: 68,
690
+ 0x10ac5: 82,
691
+ 0x10ac6: 85,
692
+ 0x10ac7: 82,
693
+ 0x10ac8: 85,
694
+ 0x10ac9: 82,
695
+ 0x10aca: 82,
696
+ 0x10acb: 85,
697
+ 0x10acc: 85,
698
+ 0x10acd: 76,
699
+ 0x10ace: 82,
700
+ 0x10acf: 82,
701
+ 0x10ad0: 82,
702
+ 0x10ad1: 82,
703
+ 0x10ad2: 82,
704
+ 0x10ad3: 68,
705
+ 0x10ad4: 68,
706
+ 0x10ad5: 68,
707
+ 0x10ad6: 68,
708
+ 0x10ad7: 76,
709
+ 0x10ad8: 68,
710
+ 0x10ad9: 68,
711
+ 0x10ada: 68,
712
+ 0x10adb: 68,
713
+ 0x10adc: 68,
714
+ 0x10add: 82,
715
+ 0x10ade: 68,
716
+ 0x10adf: 68,
717
+ 0x10ae0: 68,
718
+ 0x10ae1: 82,
719
+ 0x10ae2: 85,
720
+ 0x10ae3: 85,
721
+ 0x10ae4: 82,
722
+ 0x10aeb: 68,
723
+ 0x10aec: 68,
724
+ 0x10aed: 68,
725
+ 0x10aee: 68,
726
+ 0x10aef: 82,
727
+ 0x10b80: 68,
728
+ 0x10b81: 82,
729
+ 0x10b82: 68,
730
+ 0x10b83: 82,
731
+ 0x10b84: 82,
732
+ 0x10b85: 82,
733
+ 0x10b86: 68,
734
+ 0x10b87: 68,
735
+ 0x10b88: 68,
736
+ 0x10b89: 82,
737
+ 0x10b8a: 68,
738
+ 0x10b8b: 68,
739
+ 0x10b8c: 82,
740
+ 0x10b8d: 68,
741
+ 0x10b8e: 82,
742
+ 0x10b8f: 82,
743
+ 0x10b90: 68,
744
+ 0x10b91: 82,
745
+ 0x10ba9: 82,
746
+ 0x10baa: 82,
747
+ 0x10bab: 82,
748
+ 0x10bac: 82,
749
+ 0x10bad: 68,
750
+ 0x10bae: 68,
751
+ 0x10baf: 85,
752
+ 0x10d00: 76,
753
+ 0x10d01: 68,
754
+ 0x10d02: 68,
755
+ 0x10d03: 68,
756
+ 0x10d04: 68,
757
+ 0x10d05: 68,
758
+ 0x10d06: 68,
759
+ 0x10d07: 68,
760
+ 0x10d08: 68,
761
+ 0x10d09: 68,
762
+ 0x10d0a: 68,
763
+ 0x10d0b: 68,
764
+ 0x10d0c: 68,
765
+ 0x10d0d: 68,
766
+ 0x10d0e: 68,
767
+ 0x10d0f: 68,
768
+ 0x10d10: 68,
769
+ 0x10d11: 68,
770
+ 0x10d12: 68,
771
+ 0x10d13: 68,
772
+ 0x10d14: 68,
773
+ 0x10d15: 68,
774
+ 0x10d16: 68,
775
+ 0x10d17: 68,
776
+ 0x10d18: 68,
777
+ 0x10d19: 68,
778
+ 0x10d1a: 68,
779
+ 0x10d1b: 68,
780
+ 0x10d1c: 68,
781
+ 0x10d1d: 68,
782
+ 0x10d1e: 68,
783
+ 0x10d1f: 68,
784
+ 0x10d20: 68,
785
+ 0x10d21: 68,
786
+ 0x10d22: 82,
787
+ 0x10d23: 68,
788
+ 0x10f30: 68,
789
+ 0x10f31: 68,
790
+ 0x10f32: 68,
791
+ 0x10f33: 82,
792
+ 0x10f34: 68,
793
+ 0x10f35: 68,
794
+ 0x10f36: 68,
795
+ 0x10f37: 68,
796
+ 0x10f38: 68,
797
+ 0x10f39: 68,
798
+ 0x10f3a: 68,
799
+ 0x10f3b: 68,
800
+ 0x10f3c: 68,
801
+ 0x10f3d: 68,
802
+ 0x10f3e: 68,
803
+ 0x10f3f: 68,
804
+ 0x10f40: 68,
805
+ 0x10f41: 68,
806
+ 0x10f42: 68,
807
+ 0x10f43: 68,
808
+ 0x10f44: 68,
809
+ 0x10f45: 85,
810
+ 0x10f51: 68,
811
+ 0x10f52: 68,
812
+ 0x10f53: 68,
813
+ 0x10f54: 82,
814
+ 0x10f70: 68,
815
+ 0x10f71: 68,
816
+ 0x10f72: 68,
817
+ 0x10f73: 68,
818
+ 0x10f74: 82,
819
+ 0x10f75: 82,
820
+ 0x10f76: 68,
821
+ 0x10f77: 68,
822
+ 0x10f78: 68,
823
+ 0x10f79: 68,
824
+ 0x10f7a: 68,
825
+ 0x10f7b: 68,
826
+ 0x10f7c: 68,
827
+ 0x10f7d: 68,
828
+ 0x10f7e: 68,
829
+ 0x10f7f: 68,
830
+ 0x10f80: 68,
831
+ 0x10f81: 68,
832
+ 0x10fb0: 68,
833
+ 0x10fb1: 85,
834
+ 0x10fb2: 68,
835
+ 0x10fb3: 68,
836
+ 0x10fb4: 82,
837
+ 0x10fb5: 82,
838
+ 0x10fb6: 82,
839
+ 0x10fb7: 85,
840
+ 0x10fb8: 68,
841
+ 0x10fb9: 82,
842
+ 0x10fba: 82,
843
+ 0x10fbb: 68,
844
+ 0x10fbc: 68,
845
+ 0x10fbd: 82,
846
+ 0x10fbe: 68,
847
+ 0x10fbf: 68,
848
+ 0x10fc0: 85,
849
+ 0x10fc1: 68,
850
+ 0x10fc2: 82,
851
+ 0x10fc3: 82,
852
+ 0x10fc4: 68,
853
+ 0x10fc5: 85,
854
+ 0x10fc6: 85,
855
+ 0x10fc7: 85,
856
+ 0x10fc8: 85,
857
+ 0x10fc9: 82,
858
+ 0x10fca: 68,
859
+ 0x10fcb: 76,
860
+ 0x110bd: 85,
861
+ 0x110cd: 85,
862
+ 0x1e900: 68,
863
+ 0x1e901: 68,
864
+ 0x1e902: 68,
865
+ 0x1e903: 68,
866
+ 0x1e904: 68,
867
+ 0x1e905: 68,
868
+ 0x1e906: 68,
869
+ 0x1e907: 68,
870
+ 0x1e908: 68,
871
+ 0x1e909: 68,
872
+ 0x1e90a: 68,
873
+ 0x1e90b: 68,
874
+ 0x1e90c: 68,
875
+ 0x1e90d: 68,
876
+ 0x1e90e: 68,
877
+ 0x1e90f: 68,
878
+ 0x1e910: 68,
879
+ 0x1e911: 68,
880
+ 0x1e912: 68,
881
+ 0x1e913: 68,
882
+ 0x1e914: 68,
883
+ 0x1e915: 68,
884
+ 0x1e916: 68,
885
+ 0x1e917: 68,
886
+ 0x1e918: 68,
887
+ 0x1e919: 68,
888
+ 0x1e91a: 68,
889
+ 0x1e91b: 68,
890
+ 0x1e91c: 68,
891
+ 0x1e91d: 68,
892
+ 0x1e91e: 68,
893
+ 0x1e91f: 68,
894
+ 0x1e920: 68,
895
+ 0x1e921: 68,
896
+ 0x1e922: 68,
897
+ 0x1e923: 68,
898
+ 0x1e924: 68,
899
+ 0x1e925: 68,
900
+ 0x1e926: 68,
901
+ 0x1e927: 68,
902
+ 0x1e928: 68,
903
+ 0x1e929: 68,
904
+ 0x1e92a: 68,
905
+ 0x1e92b: 68,
906
+ 0x1e92c: 68,
907
+ 0x1e92d: 68,
908
+ 0x1e92e: 68,
909
+ 0x1e92f: 68,
910
+ 0x1e930: 68,
911
+ 0x1e931: 68,
912
+ 0x1e932: 68,
913
+ 0x1e933: 68,
914
+ 0x1e934: 68,
915
+ 0x1e935: 68,
916
+ 0x1e936: 68,
917
+ 0x1e937: 68,
918
+ 0x1e938: 68,
919
+ 0x1e939: 68,
920
+ 0x1e93a: 68,
921
+ 0x1e93b: 68,
922
+ 0x1e93c: 68,
923
+ 0x1e93d: 68,
924
+ 0x1e93e: 68,
925
+ 0x1e93f: 68,
926
+ 0x1e940: 68,
927
+ 0x1e941: 68,
928
+ 0x1e942: 68,
929
+ 0x1e943: 68,
930
+ 0x1e94b: 84,
931
+ }
932
+ codepoint_classes = {
933
+ 'PVALID': (
934
+ 0x2d0000002e,
935
+ 0x300000003a,
936
+ 0x610000007b,
937
+ 0xdf000000f7,
938
+ 0xf800000100,
939
+ 0x10100000102,
940
+ 0x10300000104,
941
+ 0x10500000106,
942
+ 0x10700000108,
943
+ 0x1090000010a,
944
+ 0x10b0000010c,
945
+ 0x10d0000010e,
946
+ 0x10f00000110,
947
+ 0x11100000112,
948
+ 0x11300000114,
949
+ 0x11500000116,
950
+ 0x11700000118,
951
+ 0x1190000011a,
952
+ 0x11b0000011c,
953
+ 0x11d0000011e,
954
+ 0x11f00000120,
955
+ 0x12100000122,
956
+ 0x12300000124,
957
+ 0x12500000126,
958
+ 0x12700000128,
959
+ 0x1290000012a,
960
+ 0x12b0000012c,
961
+ 0x12d0000012e,
962
+ 0x12f00000130,
963
+ 0x13100000132,
964
+ 0x13500000136,
965
+ 0x13700000139,
966
+ 0x13a0000013b,
967
+ 0x13c0000013d,
968
+ 0x13e0000013f,
969
+ 0x14200000143,
970
+ 0x14400000145,
971
+ 0x14600000147,
972
+ 0x14800000149,
973
+ 0x14b0000014c,
974
+ 0x14d0000014e,
975
+ 0x14f00000150,
976
+ 0x15100000152,
977
+ 0x15300000154,
978
+ 0x15500000156,
979
+ 0x15700000158,
980
+ 0x1590000015a,
981
+ 0x15b0000015c,
982
+ 0x15d0000015e,
983
+ 0x15f00000160,
984
+ 0x16100000162,
985
+ 0x16300000164,
986
+ 0x16500000166,
987
+ 0x16700000168,
988
+ 0x1690000016a,
989
+ 0x16b0000016c,
990
+ 0x16d0000016e,
991
+ 0x16f00000170,
992
+ 0x17100000172,
993
+ 0x17300000174,
994
+ 0x17500000176,
995
+ 0x17700000178,
996
+ 0x17a0000017b,
997
+ 0x17c0000017d,
998
+ 0x17e0000017f,
999
+ 0x18000000181,
1000
+ 0x18300000184,
1001
+ 0x18500000186,
1002
+ 0x18800000189,
1003
+ 0x18c0000018e,
1004
+ 0x19200000193,
1005
+ 0x19500000196,
1006
+ 0x1990000019c,
1007
+ 0x19e0000019f,
1008
+ 0x1a1000001a2,
1009
+ 0x1a3000001a4,
1010
+ 0x1a5000001a6,
1011
+ 0x1a8000001a9,
1012
+ 0x1aa000001ac,
1013
+ 0x1ad000001ae,
1014
+ 0x1b0000001b1,
1015
+ 0x1b4000001b5,
1016
+ 0x1b6000001b7,
1017
+ 0x1b9000001bc,
1018
+ 0x1bd000001c4,
1019
+ 0x1ce000001cf,
1020
+ 0x1d0000001d1,
1021
+ 0x1d2000001d3,
1022
+ 0x1d4000001d5,
1023
+ 0x1d6000001d7,
1024
+ 0x1d8000001d9,
1025
+ 0x1da000001db,
1026
+ 0x1dc000001de,
1027
+ 0x1df000001e0,
1028
+ 0x1e1000001e2,
1029
+ 0x1e3000001e4,
1030
+ 0x1e5000001e6,
1031
+ 0x1e7000001e8,
1032
+ 0x1e9000001ea,
1033
+ 0x1eb000001ec,
1034
+ 0x1ed000001ee,
1035
+ 0x1ef000001f1,
1036
+ 0x1f5000001f6,
1037
+ 0x1f9000001fa,
1038
+ 0x1fb000001fc,
1039
+ 0x1fd000001fe,
1040
+ 0x1ff00000200,
1041
+ 0x20100000202,
1042
+ 0x20300000204,
1043
+ 0x20500000206,
1044
+ 0x20700000208,
1045
+ 0x2090000020a,
1046
+ 0x20b0000020c,
1047
+ 0x20d0000020e,
1048
+ 0x20f00000210,
1049
+ 0x21100000212,
1050
+ 0x21300000214,
1051
+ 0x21500000216,
1052
+ 0x21700000218,
1053
+ 0x2190000021a,
1054
+ 0x21b0000021c,
1055
+ 0x21d0000021e,
1056
+ 0x21f00000220,
1057
+ 0x22100000222,
1058
+ 0x22300000224,
1059
+ 0x22500000226,
1060
+ 0x22700000228,
1061
+ 0x2290000022a,
1062
+ 0x22b0000022c,
1063
+ 0x22d0000022e,
1064
+ 0x22f00000230,
1065
+ 0x23100000232,
1066
+ 0x2330000023a,
1067
+ 0x23c0000023d,
1068
+ 0x23f00000241,
1069
+ 0x24200000243,
1070
+ 0x24700000248,
1071
+ 0x2490000024a,
1072
+ 0x24b0000024c,
1073
+ 0x24d0000024e,
1074
+ 0x24f000002b0,
1075
+ 0x2b9000002c2,
1076
+ 0x2c6000002d2,
1077
+ 0x2ec000002ed,
1078
+ 0x2ee000002ef,
1079
+ 0x30000000340,
1080
+ 0x34200000343,
1081
+ 0x3460000034f,
1082
+ 0x35000000370,
1083
+ 0x37100000372,
1084
+ 0x37300000374,
1085
+ 0x37700000378,
1086
+ 0x37b0000037e,
1087
+ 0x39000000391,
1088
+ 0x3ac000003cf,
1089
+ 0x3d7000003d8,
1090
+ 0x3d9000003da,
1091
+ 0x3db000003dc,
1092
+ 0x3dd000003de,
1093
+ 0x3df000003e0,
1094
+ 0x3e1000003e2,
1095
+ 0x3e3000003e4,
1096
+ 0x3e5000003e6,
1097
+ 0x3e7000003e8,
1098
+ 0x3e9000003ea,
1099
+ 0x3eb000003ec,
1100
+ 0x3ed000003ee,
1101
+ 0x3ef000003f0,
1102
+ 0x3f3000003f4,
1103
+ 0x3f8000003f9,
1104
+ 0x3fb000003fd,
1105
+ 0x43000000460,
1106
+ 0x46100000462,
1107
+ 0x46300000464,
1108
+ 0x46500000466,
1109
+ 0x46700000468,
1110
+ 0x4690000046a,
1111
+ 0x46b0000046c,
1112
+ 0x46d0000046e,
1113
+ 0x46f00000470,
1114
+ 0x47100000472,
1115
+ 0x47300000474,
1116
+ 0x47500000476,
1117
+ 0x47700000478,
1118
+ 0x4790000047a,
1119
+ 0x47b0000047c,
1120
+ 0x47d0000047e,
1121
+ 0x47f00000480,
1122
+ 0x48100000482,
1123
+ 0x48300000488,
1124
+ 0x48b0000048c,
1125
+ 0x48d0000048e,
1126
+ 0x48f00000490,
1127
+ 0x49100000492,
1128
+ 0x49300000494,
1129
+ 0x49500000496,
1130
+ 0x49700000498,
1131
+ 0x4990000049a,
1132
+ 0x49b0000049c,
1133
+ 0x49d0000049e,
1134
+ 0x49f000004a0,
1135
+ 0x4a1000004a2,
1136
+ 0x4a3000004a4,
1137
+ 0x4a5000004a6,
1138
+ 0x4a7000004a8,
1139
+ 0x4a9000004aa,
1140
+ 0x4ab000004ac,
1141
+ 0x4ad000004ae,
1142
+ 0x4af000004b0,
1143
+ 0x4b1000004b2,
1144
+ 0x4b3000004b4,
1145
+ 0x4b5000004b6,
1146
+ 0x4b7000004b8,
1147
+ 0x4b9000004ba,
1148
+ 0x4bb000004bc,
1149
+ 0x4bd000004be,
1150
+ 0x4bf000004c0,
1151
+ 0x4c2000004c3,
1152
+ 0x4c4000004c5,
1153
+ 0x4c6000004c7,
1154
+ 0x4c8000004c9,
1155
+ 0x4ca000004cb,
1156
+ 0x4cc000004cd,
1157
+ 0x4ce000004d0,
1158
+ 0x4d1000004d2,
1159
+ 0x4d3000004d4,
1160
+ 0x4d5000004d6,
1161
+ 0x4d7000004d8,
1162
+ 0x4d9000004da,
1163
+ 0x4db000004dc,
1164
+ 0x4dd000004de,
1165
+ 0x4df000004e0,
1166
+ 0x4e1000004e2,
1167
+ 0x4e3000004e4,
1168
+ 0x4e5000004e6,
1169
+ 0x4e7000004e8,
1170
+ 0x4e9000004ea,
1171
+ 0x4eb000004ec,
1172
+ 0x4ed000004ee,
1173
+ 0x4ef000004f0,
1174
+ 0x4f1000004f2,
1175
+ 0x4f3000004f4,
1176
+ 0x4f5000004f6,
1177
+ 0x4f7000004f8,
1178
+ 0x4f9000004fa,
1179
+ 0x4fb000004fc,
1180
+ 0x4fd000004fe,
1181
+ 0x4ff00000500,
1182
+ 0x50100000502,
1183
+ 0x50300000504,
1184
+ 0x50500000506,
1185
+ 0x50700000508,
1186
+ 0x5090000050a,
1187
+ 0x50b0000050c,
1188
+ 0x50d0000050e,
1189
+ 0x50f00000510,
1190
+ 0x51100000512,
1191
+ 0x51300000514,
1192
+ 0x51500000516,
1193
+ 0x51700000518,
1194
+ 0x5190000051a,
1195
+ 0x51b0000051c,
1196
+ 0x51d0000051e,
1197
+ 0x51f00000520,
1198
+ 0x52100000522,
1199
+ 0x52300000524,
1200
+ 0x52500000526,
1201
+ 0x52700000528,
1202
+ 0x5290000052a,
1203
+ 0x52b0000052c,
1204
+ 0x52d0000052e,
1205
+ 0x52f00000530,
1206
+ 0x5590000055a,
1207
+ 0x56000000587,
1208
+ 0x58800000589,
1209
+ 0x591000005be,
1210
+ 0x5bf000005c0,
1211
+ 0x5c1000005c3,
1212
+ 0x5c4000005c6,
1213
+ 0x5c7000005c8,
1214
+ 0x5d0000005eb,
1215
+ 0x5ef000005f3,
1216
+ 0x6100000061b,
1217
+ 0x62000000640,
1218
+ 0x64100000660,
1219
+ 0x66e00000675,
1220
+ 0x679000006d4,
1221
+ 0x6d5000006dd,
1222
+ 0x6df000006e9,
1223
+ 0x6ea000006f0,
1224
+ 0x6fa00000700,
1225
+ 0x7100000074b,
1226
+ 0x74d000007b2,
1227
+ 0x7c0000007f6,
1228
+ 0x7fd000007fe,
1229
+ 0x8000000082e,
1230
+ 0x8400000085c,
1231
+ 0x8600000086b,
1232
+ 0x87000000888,
1233
+ 0x8890000088f,
1234
+ 0x898000008e2,
1235
+ 0x8e300000958,
1236
+ 0x96000000964,
1237
+ 0x96600000970,
1238
+ 0x97100000984,
1239
+ 0x9850000098d,
1240
+ 0x98f00000991,
1241
+ 0x993000009a9,
1242
+ 0x9aa000009b1,
1243
+ 0x9b2000009b3,
1244
+ 0x9b6000009ba,
1245
+ 0x9bc000009c5,
1246
+ 0x9c7000009c9,
1247
+ 0x9cb000009cf,
1248
+ 0x9d7000009d8,
1249
+ 0x9e0000009e4,
1250
+ 0x9e6000009f2,
1251
+ 0x9fc000009fd,
1252
+ 0x9fe000009ff,
1253
+ 0xa0100000a04,
1254
+ 0xa0500000a0b,
1255
+ 0xa0f00000a11,
1256
+ 0xa1300000a29,
1257
+ 0xa2a00000a31,
1258
+ 0xa3200000a33,
1259
+ 0xa3500000a36,
1260
+ 0xa3800000a3a,
1261
+ 0xa3c00000a3d,
1262
+ 0xa3e00000a43,
1263
+ 0xa4700000a49,
1264
+ 0xa4b00000a4e,
1265
+ 0xa5100000a52,
1266
+ 0xa5c00000a5d,
1267
+ 0xa6600000a76,
1268
+ 0xa8100000a84,
1269
+ 0xa8500000a8e,
1270
+ 0xa8f00000a92,
1271
+ 0xa9300000aa9,
1272
+ 0xaaa00000ab1,
1273
+ 0xab200000ab4,
1274
+ 0xab500000aba,
1275
+ 0xabc00000ac6,
1276
+ 0xac700000aca,
1277
+ 0xacb00000ace,
1278
+ 0xad000000ad1,
1279
+ 0xae000000ae4,
1280
+ 0xae600000af0,
1281
+ 0xaf900000b00,
1282
+ 0xb0100000b04,
1283
+ 0xb0500000b0d,
1284
+ 0xb0f00000b11,
1285
+ 0xb1300000b29,
1286
+ 0xb2a00000b31,
1287
+ 0xb3200000b34,
1288
+ 0xb3500000b3a,
1289
+ 0xb3c00000b45,
1290
+ 0xb4700000b49,
1291
+ 0xb4b00000b4e,
1292
+ 0xb5500000b58,
1293
+ 0xb5f00000b64,
1294
+ 0xb6600000b70,
1295
+ 0xb7100000b72,
1296
+ 0xb8200000b84,
1297
+ 0xb8500000b8b,
1298
+ 0xb8e00000b91,
1299
+ 0xb9200000b96,
1300
+ 0xb9900000b9b,
1301
+ 0xb9c00000b9d,
1302
+ 0xb9e00000ba0,
1303
+ 0xba300000ba5,
1304
+ 0xba800000bab,
1305
+ 0xbae00000bba,
1306
+ 0xbbe00000bc3,
1307
+ 0xbc600000bc9,
1308
+ 0xbca00000bce,
1309
+ 0xbd000000bd1,
1310
+ 0xbd700000bd8,
1311
+ 0xbe600000bf0,
1312
+ 0xc0000000c0d,
1313
+ 0xc0e00000c11,
1314
+ 0xc1200000c29,
1315
+ 0xc2a00000c3a,
1316
+ 0xc3c00000c45,
1317
+ 0xc4600000c49,
1318
+ 0xc4a00000c4e,
1319
+ 0xc5500000c57,
1320
+ 0xc5800000c5b,
1321
+ 0xc5d00000c5e,
1322
+ 0xc6000000c64,
1323
+ 0xc6600000c70,
1324
+ 0xc8000000c84,
1325
+ 0xc8500000c8d,
1326
+ 0xc8e00000c91,
1327
+ 0xc9200000ca9,
1328
+ 0xcaa00000cb4,
1329
+ 0xcb500000cba,
1330
+ 0xcbc00000cc5,
1331
+ 0xcc600000cc9,
1332
+ 0xcca00000cce,
1333
+ 0xcd500000cd7,
1334
+ 0xcdd00000cdf,
1335
+ 0xce000000ce4,
1336
+ 0xce600000cf0,
1337
+ 0xcf100000cf4,
1338
+ 0xd0000000d0d,
1339
+ 0xd0e00000d11,
1340
+ 0xd1200000d45,
1341
+ 0xd4600000d49,
1342
+ 0xd4a00000d4f,
1343
+ 0xd5400000d58,
1344
+ 0xd5f00000d64,
1345
+ 0xd6600000d70,
1346
+ 0xd7a00000d80,
1347
+ 0xd8100000d84,
1348
+ 0xd8500000d97,
1349
+ 0xd9a00000db2,
1350
+ 0xdb300000dbc,
1351
+ 0xdbd00000dbe,
1352
+ 0xdc000000dc7,
1353
+ 0xdca00000dcb,
1354
+ 0xdcf00000dd5,
1355
+ 0xdd600000dd7,
1356
+ 0xdd800000de0,
1357
+ 0xde600000df0,
1358
+ 0xdf200000df4,
1359
+ 0xe0100000e33,
1360
+ 0xe3400000e3b,
1361
+ 0xe4000000e4f,
1362
+ 0xe5000000e5a,
1363
+ 0xe8100000e83,
1364
+ 0xe8400000e85,
1365
+ 0xe8600000e8b,
1366
+ 0xe8c00000ea4,
1367
+ 0xea500000ea6,
1368
+ 0xea700000eb3,
1369
+ 0xeb400000ebe,
1370
+ 0xec000000ec5,
1371
+ 0xec600000ec7,
1372
+ 0xec800000ecf,
1373
+ 0xed000000eda,
1374
+ 0xede00000ee0,
1375
+ 0xf0000000f01,
1376
+ 0xf0b00000f0c,
1377
+ 0xf1800000f1a,
1378
+ 0xf2000000f2a,
1379
+ 0xf3500000f36,
1380
+ 0xf3700000f38,
1381
+ 0xf3900000f3a,
1382
+ 0xf3e00000f43,
1383
+ 0xf4400000f48,
1384
+ 0xf4900000f4d,
1385
+ 0xf4e00000f52,
1386
+ 0xf5300000f57,
1387
+ 0xf5800000f5c,
1388
+ 0xf5d00000f69,
1389
+ 0xf6a00000f6d,
1390
+ 0xf7100000f73,
1391
+ 0xf7400000f75,
1392
+ 0xf7a00000f81,
1393
+ 0xf8200000f85,
1394
+ 0xf8600000f93,
1395
+ 0xf9400000f98,
1396
+ 0xf9900000f9d,
1397
+ 0xf9e00000fa2,
1398
+ 0xfa300000fa7,
1399
+ 0xfa800000fac,
1400
+ 0xfad00000fb9,
1401
+ 0xfba00000fbd,
1402
+ 0xfc600000fc7,
1403
+ 0x10000000104a,
1404
+ 0x10500000109e,
1405
+ 0x10d0000010fb,
1406
+ 0x10fd00001100,
1407
+ 0x120000001249,
1408
+ 0x124a0000124e,
1409
+ 0x125000001257,
1410
+ 0x125800001259,
1411
+ 0x125a0000125e,
1412
+ 0x126000001289,
1413
+ 0x128a0000128e,
1414
+ 0x1290000012b1,
1415
+ 0x12b2000012b6,
1416
+ 0x12b8000012bf,
1417
+ 0x12c0000012c1,
1418
+ 0x12c2000012c6,
1419
+ 0x12c8000012d7,
1420
+ 0x12d800001311,
1421
+ 0x131200001316,
1422
+ 0x13180000135b,
1423
+ 0x135d00001360,
1424
+ 0x138000001390,
1425
+ 0x13a0000013f6,
1426
+ 0x14010000166d,
1427
+ 0x166f00001680,
1428
+ 0x16810000169b,
1429
+ 0x16a0000016eb,
1430
+ 0x16f1000016f9,
1431
+ 0x170000001716,
1432
+ 0x171f00001735,
1433
+ 0x174000001754,
1434
+ 0x17600000176d,
1435
+ 0x176e00001771,
1436
+ 0x177200001774,
1437
+ 0x1780000017b4,
1438
+ 0x17b6000017d4,
1439
+ 0x17d7000017d8,
1440
+ 0x17dc000017de,
1441
+ 0x17e0000017ea,
1442
+ 0x18100000181a,
1443
+ 0x182000001879,
1444
+ 0x1880000018ab,
1445
+ 0x18b0000018f6,
1446
+ 0x19000000191f,
1447
+ 0x19200000192c,
1448
+ 0x19300000193c,
1449
+ 0x19460000196e,
1450
+ 0x197000001975,
1451
+ 0x1980000019ac,
1452
+ 0x19b0000019ca,
1453
+ 0x19d0000019da,
1454
+ 0x1a0000001a1c,
1455
+ 0x1a2000001a5f,
1456
+ 0x1a6000001a7d,
1457
+ 0x1a7f00001a8a,
1458
+ 0x1a9000001a9a,
1459
+ 0x1aa700001aa8,
1460
+ 0x1ab000001abe,
1461
+ 0x1abf00001acf,
1462
+ 0x1b0000001b4d,
1463
+ 0x1b5000001b5a,
1464
+ 0x1b6b00001b74,
1465
+ 0x1b8000001bf4,
1466
+ 0x1c0000001c38,
1467
+ 0x1c4000001c4a,
1468
+ 0x1c4d00001c7e,
1469
+ 0x1cd000001cd3,
1470
+ 0x1cd400001cfb,
1471
+ 0x1d0000001d2c,
1472
+ 0x1d2f00001d30,
1473
+ 0x1d3b00001d3c,
1474
+ 0x1d4e00001d4f,
1475
+ 0x1d6b00001d78,
1476
+ 0x1d7900001d9b,
1477
+ 0x1dc000001e00,
1478
+ 0x1e0100001e02,
1479
+ 0x1e0300001e04,
1480
+ 0x1e0500001e06,
1481
+ 0x1e0700001e08,
1482
+ 0x1e0900001e0a,
1483
+ 0x1e0b00001e0c,
1484
+ 0x1e0d00001e0e,
1485
+ 0x1e0f00001e10,
1486
+ 0x1e1100001e12,
1487
+ 0x1e1300001e14,
1488
+ 0x1e1500001e16,
1489
+ 0x1e1700001e18,
1490
+ 0x1e1900001e1a,
1491
+ 0x1e1b00001e1c,
1492
+ 0x1e1d00001e1e,
1493
+ 0x1e1f00001e20,
1494
+ 0x1e2100001e22,
1495
+ 0x1e2300001e24,
1496
+ 0x1e2500001e26,
1497
+ 0x1e2700001e28,
1498
+ 0x1e2900001e2a,
1499
+ 0x1e2b00001e2c,
1500
+ 0x1e2d00001e2e,
1501
+ 0x1e2f00001e30,
1502
+ 0x1e3100001e32,
1503
+ 0x1e3300001e34,
1504
+ 0x1e3500001e36,
1505
+ 0x1e3700001e38,
1506
+ 0x1e3900001e3a,
1507
+ 0x1e3b00001e3c,
1508
+ 0x1e3d00001e3e,
1509
+ 0x1e3f00001e40,
1510
+ 0x1e4100001e42,
1511
+ 0x1e4300001e44,
1512
+ 0x1e4500001e46,
1513
+ 0x1e4700001e48,
1514
+ 0x1e4900001e4a,
1515
+ 0x1e4b00001e4c,
1516
+ 0x1e4d00001e4e,
1517
+ 0x1e4f00001e50,
1518
+ 0x1e5100001e52,
1519
+ 0x1e5300001e54,
1520
+ 0x1e5500001e56,
1521
+ 0x1e5700001e58,
1522
+ 0x1e5900001e5a,
1523
+ 0x1e5b00001e5c,
1524
+ 0x1e5d00001e5e,
1525
+ 0x1e5f00001e60,
1526
+ 0x1e6100001e62,
1527
+ 0x1e6300001e64,
1528
+ 0x1e6500001e66,
1529
+ 0x1e6700001e68,
1530
+ 0x1e6900001e6a,
1531
+ 0x1e6b00001e6c,
1532
+ 0x1e6d00001e6e,
1533
+ 0x1e6f00001e70,
1534
+ 0x1e7100001e72,
1535
+ 0x1e7300001e74,
1536
+ 0x1e7500001e76,
1537
+ 0x1e7700001e78,
1538
+ 0x1e7900001e7a,
1539
+ 0x1e7b00001e7c,
1540
+ 0x1e7d00001e7e,
1541
+ 0x1e7f00001e80,
1542
+ 0x1e8100001e82,
1543
+ 0x1e8300001e84,
1544
+ 0x1e8500001e86,
1545
+ 0x1e8700001e88,
1546
+ 0x1e8900001e8a,
1547
+ 0x1e8b00001e8c,
1548
+ 0x1e8d00001e8e,
1549
+ 0x1e8f00001e90,
1550
+ 0x1e9100001e92,
1551
+ 0x1e9300001e94,
1552
+ 0x1e9500001e9a,
1553
+ 0x1e9c00001e9e,
1554
+ 0x1e9f00001ea0,
1555
+ 0x1ea100001ea2,
1556
+ 0x1ea300001ea4,
1557
+ 0x1ea500001ea6,
1558
+ 0x1ea700001ea8,
1559
+ 0x1ea900001eaa,
1560
+ 0x1eab00001eac,
1561
+ 0x1ead00001eae,
1562
+ 0x1eaf00001eb0,
1563
+ 0x1eb100001eb2,
1564
+ 0x1eb300001eb4,
1565
+ 0x1eb500001eb6,
1566
+ 0x1eb700001eb8,
1567
+ 0x1eb900001eba,
1568
+ 0x1ebb00001ebc,
1569
+ 0x1ebd00001ebe,
1570
+ 0x1ebf00001ec0,
1571
+ 0x1ec100001ec2,
1572
+ 0x1ec300001ec4,
1573
+ 0x1ec500001ec6,
1574
+ 0x1ec700001ec8,
1575
+ 0x1ec900001eca,
1576
+ 0x1ecb00001ecc,
1577
+ 0x1ecd00001ece,
1578
+ 0x1ecf00001ed0,
1579
+ 0x1ed100001ed2,
1580
+ 0x1ed300001ed4,
1581
+ 0x1ed500001ed6,
1582
+ 0x1ed700001ed8,
1583
+ 0x1ed900001eda,
1584
+ 0x1edb00001edc,
1585
+ 0x1edd00001ede,
1586
+ 0x1edf00001ee0,
1587
+ 0x1ee100001ee2,
1588
+ 0x1ee300001ee4,
1589
+ 0x1ee500001ee6,
1590
+ 0x1ee700001ee8,
1591
+ 0x1ee900001eea,
1592
+ 0x1eeb00001eec,
1593
+ 0x1eed00001eee,
1594
+ 0x1eef00001ef0,
1595
+ 0x1ef100001ef2,
1596
+ 0x1ef300001ef4,
1597
+ 0x1ef500001ef6,
1598
+ 0x1ef700001ef8,
1599
+ 0x1ef900001efa,
1600
+ 0x1efb00001efc,
1601
+ 0x1efd00001efe,
1602
+ 0x1eff00001f08,
1603
+ 0x1f1000001f16,
1604
+ 0x1f2000001f28,
1605
+ 0x1f3000001f38,
1606
+ 0x1f4000001f46,
1607
+ 0x1f5000001f58,
1608
+ 0x1f6000001f68,
1609
+ 0x1f7000001f71,
1610
+ 0x1f7200001f73,
1611
+ 0x1f7400001f75,
1612
+ 0x1f7600001f77,
1613
+ 0x1f7800001f79,
1614
+ 0x1f7a00001f7b,
1615
+ 0x1f7c00001f7d,
1616
+ 0x1fb000001fb2,
1617
+ 0x1fb600001fb7,
1618
+ 0x1fc600001fc7,
1619
+ 0x1fd000001fd3,
1620
+ 0x1fd600001fd8,
1621
+ 0x1fe000001fe3,
1622
+ 0x1fe400001fe8,
1623
+ 0x1ff600001ff7,
1624
+ 0x214e0000214f,
1625
+ 0x218400002185,
1626
+ 0x2c3000002c60,
1627
+ 0x2c6100002c62,
1628
+ 0x2c6500002c67,
1629
+ 0x2c6800002c69,
1630
+ 0x2c6a00002c6b,
1631
+ 0x2c6c00002c6d,
1632
+ 0x2c7100002c72,
1633
+ 0x2c7300002c75,
1634
+ 0x2c7600002c7c,
1635
+ 0x2c8100002c82,
1636
+ 0x2c8300002c84,
1637
+ 0x2c8500002c86,
1638
+ 0x2c8700002c88,
1639
+ 0x2c8900002c8a,
1640
+ 0x2c8b00002c8c,
1641
+ 0x2c8d00002c8e,
1642
+ 0x2c8f00002c90,
1643
+ 0x2c9100002c92,
1644
+ 0x2c9300002c94,
1645
+ 0x2c9500002c96,
1646
+ 0x2c9700002c98,
1647
+ 0x2c9900002c9a,
1648
+ 0x2c9b00002c9c,
1649
+ 0x2c9d00002c9e,
1650
+ 0x2c9f00002ca0,
1651
+ 0x2ca100002ca2,
1652
+ 0x2ca300002ca4,
1653
+ 0x2ca500002ca6,
1654
+ 0x2ca700002ca8,
1655
+ 0x2ca900002caa,
1656
+ 0x2cab00002cac,
1657
+ 0x2cad00002cae,
1658
+ 0x2caf00002cb0,
1659
+ 0x2cb100002cb2,
1660
+ 0x2cb300002cb4,
1661
+ 0x2cb500002cb6,
1662
+ 0x2cb700002cb8,
1663
+ 0x2cb900002cba,
1664
+ 0x2cbb00002cbc,
1665
+ 0x2cbd00002cbe,
1666
+ 0x2cbf00002cc0,
1667
+ 0x2cc100002cc2,
1668
+ 0x2cc300002cc4,
1669
+ 0x2cc500002cc6,
1670
+ 0x2cc700002cc8,
1671
+ 0x2cc900002cca,
1672
+ 0x2ccb00002ccc,
1673
+ 0x2ccd00002cce,
1674
+ 0x2ccf00002cd0,
1675
+ 0x2cd100002cd2,
1676
+ 0x2cd300002cd4,
1677
+ 0x2cd500002cd6,
1678
+ 0x2cd700002cd8,
1679
+ 0x2cd900002cda,
1680
+ 0x2cdb00002cdc,
1681
+ 0x2cdd00002cde,
1682
+ 0x2cdf00002ce0,
1683
+ 0x2ce100002ce2,
1684
+ 0x2ce300002ce5,
1685
+ 0x2cec00002ced,
1686
+ 0x2cee00002cf2,
1687
+ 0x2cf300002cf4,
1688
+ 0x2d0000002d26,
1689
+ 0x2d2700002d28,
1690
+ 0x2d2d00002d2e,
1691
+ 0x2d3000002d68,
1692
+ 0x2d7f00002d97,
1693
+ 0x2da000002da7,
1694
+ 0x2da800002daf,
1695
+ 0x2db000002db7,
1696
+ 0x2db800002dbf,
1697
+ 0x2dc000002dc7,
1698
+ 0x2dc800002dcf,
1699
+ 0x2dd000002dd7,
1700
+ 0x2dd800002ddf,
1701
+ 0x2de000002e00,
1702
+ 0x2e2f00002e30,
1703
+ 0x300500003008,
1704
+ 0x302a0000302e,
1705
+ 0x303c0000303d,
1706
+ 0x304100003097,
1707
+ 0x30990000309b,
1708
+ 0x309d0000309f,
1709
+ 0x30a1000030fb,
1710
+ 0x30fc000030ff,
1711
+ 0x310500003130,
1712
+ 0x31a0000031c0,
1713
+ 0x31f000003200,
1714
+ 0x340000004dc0,
1715
+ 0x4e000000a48d,
1716
+ 0xa4d00000a4fe,
1717
+ 0xa5000000a60d,
1718
+ 0xa6100000a62c,
1719
+ 0xa6410000a642,
1720
+ 0xa6430000a644,
1721
+ 0xa6450000a646,
1722
+ 0xa6470000a648,
1723
+ 0xa6490000a64a,
1724
+ 0xa64b0000a64c,
1725
+ 0xa64d0000a64e,
1726
+ 0xa64f0000a650,
1727
+ 0xa6510000a652,
1728
+ 0xa6530000a654,
1729
+ 0xa6550000a656,
1730
+ 0xa6570000a658,
1731
+ 0xa6590000a65a,
1732
+ 0xa65b0000a65c,
1733
+ 0xa65d0000a65e,
1734
+ 0xa65f0000a660,
1735
+ 0xa6610000a662,
1736
+ 0xa6630000a664,
1737
+ 0xa6650000a666,
1738
+ 0xa6670000a668,
1739
+ 0xa6690000a66a,
1740
+ 0xa66b0000a66c,
1741
+ 0xa66d0000a670,
1742
+ 0xa6740000a67e,
1743
+ 0xa67f0000a680,
1744
+ 0xa6810000a682,
1745
+ 0xa6830000a684,
1746
+ 0xa6850000a686,
1747
+ 0xa6870000a688,
1748
+ 0xa6890000a68a,
1749
+ 0xa68b0000a68c,
1750
+ 0xa68d0000a68e,
1751
+ 0xa68f0000a690,
1752
+ 0xa6910000a692,
1753
+ 0xa6930000a694,
1754
+ 0xa6950000a696,
1755
+ 0xa6970000a698,
1756
+ 0xa6990000a69a,
1757
+ 0xa69b0000a69c,
1758
+ 0xa69e0000a6e6,
1759
+ 0xa6f00000a6f2,
1760
+ 0xa7170000a720,
1761
+ 0xa7230000a724,
1762
+ 0xa7250000a726,
1763
+ 0xa7270000a728,
1764
+ 0xa7290000a72a,
1765
+ 0xa72b0000a72c,
1766
+ 0xa72d0000a72e,
1767
+ 0xa72f0000a732,
1768
+ 0xa7330000a734,
1769
+ 0xa7350000a736,
1770
+ 0xa7370000a738,
1771
+ 0xa7390000a73a,
1772
+ 0xa73b0000a73c,
1773
+ 0xa73d0000a73e,
1774
+ 0xa73f0000a740,
1775
+ 0xa7410000a742,
1776
+ 0xa7430000a744,
1777
+ 0xa7450000a746,
1778
+ 0xa7470000a748,
1779
+ 0xa7490000a74a,
1780
+ 0xa74b0000a74c,
1781
+ 0xa74d0000a74e,
1782
+ 0xa74f0000a750,
1783
+ 0xa7510000a752,
1784
+ 0xa7530000a754,
1785
+ 0xa7550000a756,
1786
+ 0xa7570000a758,
1787
+ 0xa7590000a75a,
1788
+ 0xa75b0000a75c,
1789
+ 0xa75d0000a75e,
1790
+ 0xa75f0000a760,
1791
+ 0xa7610000a762,
1792
+ 0xa7630000a764,
1793
+ 0xa7650000a766,
1794
+ 0xa7670000a768,
1795
+ 0xa7690000a76a,
1796
+ 0xa76b0000a76c,
1797
+ 0xa76d0000a76e,
1798
+ 0xa76f0000a770,
1799
+ 0xa7710000a779,
1800
+ 0xa77a0000a77b,
1801
+ 0xa77c0000a77d,
1802
+ 0xa77f0000a780,
1803
+ 0xa7810000a782,
1804
+ 0xa7830000a784,
1805
+ 0xa7850000a786,
1806
+ 0xa7870000a789,
1807
+ 0xa78c0000a78d,
1808
+ 0xa78e0000a790,
1809
+ 0xa7910000a792,
1810
+ 0xa7930000a796,
1811
+ 0xa7970000a798,
1812
+ 0xa7990000a79a,
1813
+ 0xa79b0000a79c,
1814
+ 0xa79d0000a79e,
1815
+ 0xa79f0000a7a0,
1816
+ 0xa7a10000a7a2,
1817
+ 0xa7a30000a7a4,
1818
+ 0xa7a50000a7a6,
1819
+ 0xa7a70000a7a8,
1820
+ 0xa7a90000a7aa,
1821
+ 0xa7af0000a7b0,
1822
+ 0xa7b50000a7b6,
1823
+ 0xa7b70000a7b8,
1824
+ 0xa7b90000a7ba,
1825
+ 0xa7bb0000a7bc,
1826
+ 0xa7bd0000a7be,
1827
+ 0xa7bf0000a7c0,
1828
+ 0xa7c10000a7c2,
1829
+ 0xa7c30000a7c4,
1830
+ 0xa7c80000a7c9,
1831
+ 0xa7ca0000a7cb,
1832
+ 0xa7d10000a7d2,
1833
+ 0xa7d30000a7d4,
1834
+ 0xa7d50000a7d6,
1835
+ 0xa7d70000a7d8,
1836
+ 0xa7d90000a7da,
1837
+ 0xa7f20000a7f5,
1838
+ 0xa7f60000a7f8,
1839
+ 0xa7fa0000a828,
1840
+ 0xa82c0000a82d,
1841
+ 0xa8400000a874,
1842
+ 0xa8800000a8c6,
1843
+ 0xa8d00000a8da,
1844
+ 0xa8e00000a8f8,
1845
+ 0xa8fb0000a8fc,
1846
+ 0xa8fd0000a92e,
1847
+ 0xa9300000a954,
1848
+ 0xa9800000a9c1,
1849
+ 0xa9cf0000a9da,
1850
+ 0xa9e00000a9ff,
1851
+ 0xaa000000aa37,
1852
+ 0xaa400000aa4e,
1853
+ 0xaa500000aa5a,
1854
+ 0xaa600000aa77,
1855
+ 0xaa7a0000aac3,
1856
+ 0xaadb0000aade,
1857
+ 0xaae00000aaf0,
1858
+ 0xaaf20000aaf7,
1859
+ 0xab010000ab07,
1860
+ 0xab090000ab0f,
1861
+ 0xab110000ab17,
1862
+ 0xab200000ab27,
1863
+ 0xab280000ab2f,
1864
+ 0xab300000ab5b,
1865
+ 0xab600000ab69,
1866
+ 0xabc00000abeb,
1867
+ 0xabec0000abee,
1868
+ 0xabf00000abfa,
1869
+ 0xac000000d7a4,
1870
+ 0xfa0e0000fa10,
1871
+ 0xfa110000fa12,
1872
+ 0xfa130000fa15,
1873
+ 0xfa1f0000fa20,
1874
+ 0xfa210000fa22,
1875
+ 0xfa230000fa25,
1876
+ 0xfa270000fa2a,
1877
+ 0xfb1e0000fb1f,
1878
+ 0xfe200000fe30,
1879
+ 0xfe730000fe74,
1880
+ 0x100000001000c,
1881
+ 0x1000d00010027,
1882
+ 0x100280001003b,
1883
+ 0x1003c0001003e,
1884
+ 0x1003f0001004e,
1885
+ 0x100500001005e,
1886
+ 0x10080000100fb,
1887
+ 0x101fd000101fe,
1888
+ 0x102800001029d,
1889
+ 0x102a0000102d1,
1890
+ 0x102e0000102e1,
1891
+ 0x1030000010320,
1892
+ 0x1032d00010341,
1893
+ 0x103420001034a,
1894
+ 0x103500001037b,
1895
+ 0x103800001039e,
1896
+ 0x103a0000103c4,
1897
+ 0x103c8000103d0,
1898
+ 0x104280001049e,
1899
+ 0x104a0000104aa,
1900
+ 0x104d8000104fc,
1901
+ 0x1050000010528,
1902
+ 0x1053000010564,
1903
+ 0x10597000105a2,
1904
+ 0x105a3000105b2,
1905
+ 0x105b3000105ba,
1906
+ 0x105bb000105bd,
1907
+ 0x1060000010737,
1908
+ 0x1074000010756,
1909
+ 0x1076000010768,
1910
+ 0x1078000010786,
1911
+ 0x10787000107b1,
1912
+ 0x107b2000107bb,
1913
+ 0x1080000010806,
1914
+ 0x1080800010809,
1915
+ 0x1080a00010836,
1916
+ 0x1083700010839,
1917
+ 0x1083c0001083d,
1918
+ 0x1083f00010856,
1919
+ 0x1086000010877,
1920
+ 0x108800001089f,
1921
+ 0x108e0000108f3,
1922
+ 0x108f4000108f6,
1923
+ 0x1090000010916,
1924
+ 0x109200001093a,
1925
+ 0x10980000109b8,
1926
+ 0x109be000109c0,
1927
+ 0x10a0000010a04,
1928
+ 0x10a0500010a07,
1929
+ 0x10a0c00010a14,
1930
+ 0x10a1500010a18,
1931
+ 0x10a1900010a36,
1932
+ 0x10a3800010a3b,
1933
+ 0x10a3f00010a40,
1934
+ 0x10a6000010a7d,
1935
+ 0x10a8000010a9d,
1936
+ 0x10ac000010ac8,
1937
+ 0x10ac900010ae7,
1938
+ 0x10b0000010b36,
1939
+ 0x10b4000010b56,
1940
+ 0x10b6000010b73,
1941
+ 0x10b8000010b92,
1942
+ 0x10c0000010c49,
1943
+ 0x10cc000010cf3,
1944
+ 0x10d0000010d28,
1945
+ 0x10d3000010d3a,
1946
+ 0x10e8000010eaa,
1947
+ 0x10eab00010ead,
1948
+ 0x10eb000010eb2,
1949
+ 0x10efd00010f1d,
1950
+ 0x10f2700010f28,
1951
+ 0x10f3000010f51,
1952
+ 0x10f7000010f86,
1953
+ 0x10fb000010fc5,
1954
+ 0x10fe000010ff7,
1955
+ 0x1100000011047,
1956
+ 0x1106600011076,
1957
+ 0x1107f000110bb,
1958
+ 0x110c2000110c3,
1959
+ 0x110d0000110e9,
1960
+ 0x110f0000110fa,
1961
+ 0x1110000011135,
1962
+ 0x1113600011140,
1963
+ 0x1114400011148,
1964
+ 0x1115000011174,
1965
+ 0x1117600011177,
1966
+ 0x11180000111c5,
1967
+ 0x111c9000111cd,
1968
+ 0x111ce000111db,
1969
+ 0x111dc000111dd,
1970
+ 0x1120000011212,
1971
+ 0x1121300011238,
1972
+ 0x1123e00011242,
1973
+ 0x1128000011287,
1974
+ 0x1128800011289,
1975
+ 0x1128a0001128e,
1976
+ 0x1128f0001129e,
1977
+ 0x1129f000112a9,
1978
+ 0x112b0000112eb,
1979
+ 0x112f0000112fa,
1980
+ 0x1130000011304,
1981
+ 0x113050001130d,
1982
+ 0x1130f00011311,
1983
+ 0x1131300011329,
1984
+ 0x1132a00011331,
1985
+ 0x1133200011334,
1986
+ 0x113350001133a,
1987
+ 0x1133b00011345,
1988
+ 0x1134700011349,
1989
+ 0x1134b0001134e,
1990
+ 0x1135000011351,
1991
+ 0x1135700011358,
1992
+ 0x1135d00011364,
1993
+ 0x113660001136d,
1994
+ 0x1137000011375,
1995
+ 0x114000001144b,
1996
+ 0x114500001145a,
1997
+ 0x1145e00011462,
1998
+ 0x11480000114c6,
1999
+ 0x114c7000114c8,
2000
+ 0x114d0000114da,
2001
+ 0x11580000115b6,
2002
+ 0x115b8000115c1,
2003
+ 0x115d8000115de,
2004
+ 0x1160000011641,
2005
+ 0x1164400011645,
2006
+ 0x116500001165a,
2007
+ 0x11680000116b9,
2008
+ 0x116c0000116ca,
2009
+ 0x117000001171b,
2010
+ 0x1171d0001172c,
2011
+ 0x117300001173a,
2012
+ 0x1174000011747,
2013
+ 0x118000001183b,
2014
+ 0x118c0000118ea,
2015
+ 0x118ff00011907,
2016
+ 0x119090001190a,
2017
+ 0x1190c00011914,
2018
+ 0x1191500011917,
2019
+ 0x1191800011936,
2020
+ 0x1193700011939,
2021
+ 0x1193b00011944,
2022
+ 0x119500001195a,
2023
+ 0x119a0000119a8,
2024
+ 0x119aa000119d8,
2025
+ 0x119da000119e2,
2026
+ 0x119e3000119e5,
2027
+ 0x11a0000011a3f,
2028
+ 0x11a4700011a48,
2029
+ 0x11a5000011a9a,
2030
+ 0x11a9d00011a9e,
2031
+ 0x11ab000011af9,
2032
+ 0x11c0000011c09,
2033
+ 0x11c0a00011c37,
2034
+ 0x11c3800011c41,
2035
+ 0x11c5000011c5a,
2036
+ 0x11c7200011c90,
2037
+ 0x11c9200011ca8,
2038
+ 0x11ca900011cb7,
2039
+ 0x11d0000011d07,
2040
+ 0x11d0800011d0a,
2041
+ 0x11d0b00011d37,
2042
+ 0x11d3a00011d3b,
2043
+ 0x11d3c00011d3e,
2044
+ 0x11d3f00011d48,
2045
+ 0x11d5000011d5a,
2046
+ 0x11d6000011d66,
2047
+ 0x11d6700011d69,
2048
+ 0x11d6a00011d8f,
2049
+ 0x11d9000011d92,
2050
+ 0x11d9300011d99,
2051
+ 0x11da000011daa,
2052
+ 0x11ee000011ef7,
2053
+ 0x11f0000011f11,
2054
+ 0x11f1200011f3b,
2055
+ 0x11f3e00011f43,
2056
+ 0x11f5000011f5a,
2057
+ 0x11fb000011fb1,
2058
+ 0x120000001239a,
2059
+ 0x1248000012544,
2060
+ 0x12f9000012ff1,
2061
+ 0x1300000013430,
2062
+ 0x1344000013456,
2063
+ 0x1440000014647,
2064
+ 0x1680000016a39,
2065
+ 0x16a4000016a5f,
2066
+ 0x16a6000016a6a,
2067
+ 0x16a7000016abf,
2068
+ 0x16ac000016aca,
2069
+ 0x16ad000016aee,
2070
+ 0x16af000016af5,
2071
+ 0x16b0000016b37,
2072
+ 0x16b4000016b44,
2073
+ 0x16b5000016b5a,
2074
+ 0x16b6300016b78,
2075
+ 0x16b7d00016b90,
2076
+ 0x16e6000016e80,
2077
+ 0x16f0000016f4b,
2078
+ 0x16f4f00016f88,
2079
+ 0x16f8f00016fa0,
2080
+ 0x16fe000016fe2,
2081
+ 0x16fe300016fe5,
2082
+ 0x16ff000016ff2,
2083
+ 0x17000000187f8,
2084
+ 0x1880000018cd6,
2085
+ 0x18d0000018d09,
2086
+ 0x1aff00001aff4,
2087
+ 0x1aff50001affc,
2088
+ 0x1affd0001afff,
2089
+ 0x1b0000001b123,
2090
+ 0x1b1320001b133,
2091
+ 0x1b1500001b153,
2092
+ 0x1b1550001b156,
2093
+ 0x1b1640001b168,
2094
+ 0x1b1700001b2fc,
2095
+ 0x1bc000001bc6b,
2096
+ 0x1bc700001bc7d,
2097
+ 0x1bc800001bc89,
2098
+ 0x1bc900001bc9a,
2099
+ 0x1bc9d0001bc9f,
2100
+ 0x1cf000001cf2e,
2101
+ 0x1cf300001cf47,
2102
+ 0x1da000001da37,
2103
+ 0x1da3b0001da6d,
2104
+ 0x1da750001da76,
2105
+ 0x1da840001da85,
2106
+ 0x1da9b0001daa0,
2107
+ 0x1daa10001dab0,
2108
+ 0x1df000001df1f,
2109
+ 0x1df250001df2b,
2110
+ 0x1e0000001e007,
2111
+ 0x1e0080001e019,
2112
+ 0x1e01b0001e022,
2113
+ 0x1e0230001e025,
2114
+ 0x1e0260001e02b,
2115
+ 0x1e0300001e06e,
2116
+ 0x1e08f0001e090,
2117
+ 0x1e1000001e12d,
2118
+ 0x1e1300001e13e,
2119
+ 0x1e1400001e14a,
2120
+ 0x1e14e0001e14f,
2121
+ 0x1e2900001e2af,
2122
+ 0x1e2c00001e2fa,
2123
+ 0x1e4d00001e4fa,
2124
+ 0x1e7e00001e7e7,
2125
+ 0x1e7e80001e7ec,
2126
+ 0x1e7ed0001e7ef,
2127
+ 0x1e7f00001e7ff,
2128
+ 0x1e8000001e8c5,
2129
+ 0x1e8d00001e8d7,
2130
+ 0x1e9220001e94c,
2131
+ 0x1e9500001e95a,
2132
+ 0x200000002a6e0,
2133
+ 0x2a7000002b73a,
2134
+ 0x2b7400002b81e,
2135
+ 0x2b8200002cea2,
2136
+ 0x2ceb00002ebe1,
2137
+ 0x300000003134b,
2138
+ 0x31350000323b0,
2139
+ ),
2140
+ 'CONTEXTJ': (
2141
+ 0x200c0000200e,
2142
+ ),
2143
+ 'CONTEXTO': (
2144
+ 0xb7000000b8,
2145
+ 0x37500000376,
2146
+ 0x5f3000005f5,
2147
+ 0x6600000066a,
2148
+ 0x6f0000006fa,
2149
+ 0x30fb000030fc,
2150
+ ),
2151
+ }
.venv/Lib/site-packages/pip/_vendor/idna/intranges.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def intranges_from_list(list_: List[int]) -> Tuple[int, ...]:
12
+ """Represent a list of integers as a sequence of ranges:
13
+ ((start_0, end_0), (start_1, end_1), ...), such that the original
14
+ integers are exactly those x such that start_i <= x < end_i for some i.
15
+
16
+ Ranges are encoded as single integers (start << 32 | end), not as tuples.
17
+ """
18
+
19
+ sorted_list = sorted(list_)
20
+ ranges = []
21
+ last_write = -1
22
+ for i in range(len(sorted_list)):
23
+ if i+1 < len(sorted_list):
24
+ if sorted_list[i] == sorted_list[i+1]-1:
25
+ continue
26
+ current_range = sorted_list[last_write+1:i+1]
27
+ ranges.append(_encode_range(current_range[0], current_range[-1] + 1))
28
+ last_write = i
29
+
30
+ return tuple(ranges)
31
+
32
+ def _encode_range(start: int, end: int) -> int:
33
+ return (start << 32) | end
34
+
35
+ def _decode_range(r: int) -> Tuple[int, int]:
36
+ return (r >> 32), (r & ((1 << 32) - 1))
37
+
38
+
39
+ def intranges_contain(int_: int, ranges: Tuple[int, ...]) -> bool:
40
+ """Determine if `int_` falls into one of the ranges in `ranges`."""
41
+ tuple_ = _encode_range(int_, 0)
42
+ pos = bisect.bisect_left(ranges, tuple_)
43
+ # we could be immediately ahead of a tuple (start, end)
44
+ # with start < int_ <= end
45
+ if pos > 0:
46
+ left, right = _decode_range(ranges[pos-1])
47
+ if left <= int_ < right:
48
+ return True
49
+ # or we could be immediately behind a tuple (int_, end)
50
+ if pos < len(ranges):
51
+ left, _ = _decode_range(ranges[pos])
52
+ if left == int_:
53
+ return True
54
+ return False
.venv/Lib/site-packages/pip/_vendor/idna/package_data.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ __version__ = '3.4'
2
+
.venv/Lib/site-packages/pip/_vendor/idna/uts46data.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/Lib/site-packages/pip/_vendor/msgpack/__init__.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+ from .exceptions import *
3
+ from .ext import ExtType, Timestamp
4
+
5
+ import os
6
+ import sys
7
+
8
+
9
+ version = (1, 0, 5)
10
+ __version__ = "1.0.5"
11
+
12
+
13
+ if os.environ.get("MSGPACK_PUREPYTHON") or sys.version_info[0] == 2:
14
+ from .fallback import Packer, unpackb, Unpacker
15
+ else:
16
+ try:
17
+ from ._cmsgpack import Packer, unpackb, Unpacker
18
+ except ImportError:
19
+ from .fallback import Packer, unpackb, Unpacker
20
+
21
+
22
+ def pack(o, stream, **kwargs):
23
+ """
24
+ Pack object `o` and write it to `stream`
25
+
26
+ See :class:`Packer` for options.
27
+ """
28
+ packer = Packer(**kwargs)
29
+ stream.write(packer.pack(o))
30
+
31
+
32
+ def packb(o, **kwargs):
33
+ """
34
+ Pack object `o` and return packed bytes
35
+
36
+ See :class:`Packer` for options.
37
+ """
38
+ return Packer(**kwargs).pack(o)
39
+
40
+
41
+ def unpack(stream, **kwargs):
42
+ """
43
+ Unpack an object from `stream`.
44
+
45
+ Raises `ExtraData` when `stream` contains extra bytes.
46
+ See :class:`Unpacker` for options.
47
+ """
48
+ data = stream.read()
49
+ return unpackb(data, **kwargs)
50
+
51
+
52
+ # alias for compatibility to simplejson/marshal/pickle.
53
+ load = unpack
54
+ loads = unpackb
55
+
56
+ dump = pack
57
+ dumps = packb
.venv/Lib/site-packages/pip/_vendor/msgpack/exceptions.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class UnpackException(Exception):
2
+ """Base class for some exceptions raised while unpacking.
3
+
4
+ NOTE: unpack may raise exception other than subclass of
5
+ UnpackException. If you want to catch all error, catch
6
+ Exception instead.
7
+ """
8
+
9
+
10
+ class BufferFull(UnpackException):
11
+ pass
12
+
13
+
14
+ class OutOfData(UnpackException):
15
+ pass
16
+
17
+
18
+ class FormatError(ValueError, UnpackException):
19
+ """Invalid msgpack format"""
20
+
21
+
22
+ class StackError(ValueError, UnpackException):
23
+ """Too nested"""
24
+
25
+
26
+ # Deprecated. Use ValueError instead
27
+ UnpackValueError = ValueError
28
+
29
+
30
+ class ExtraData(UnpackValueError):
31
+ """ExtraData is raised when there is trailing data.
32
+
33
+ This exception is raised while only one-shot (not streaming)
34
+ unpack.
35
+ """
36
+
37
+ def __init__(self, unpacked, extra):
38
+ self.unpacked = unpacked
39
+ self.extra = extra
40
+
41
+ def __str__(self):
42
+ return "unpack(b) received extra data."
43
+
44
+
45
+ # Deprecated. Use Exception instead to catch all exception during packing.
46
+ PackException = Exception
47
+ PackValueError = ValueError
48
+ PackOverflowError = OverflowError
.venv/Lib/site-packages/pip/_vendor/msgpack/ext.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+ from collections import namedtuple
3
+ import datetime
4
+ import sys
5
+ import struct
6
+
7
+
8
+ PY2 = sys.version_info[0] == 2
9
+
10
+ if PY2:
11
+ int_types = (int, long)
12
+ _utc = None
13
+ else:
14
+ int_types = int
15
+ try:
16
+ _utc = datetime.timezone.utc
17
+ except AttributeError:
18
+ _utc = datetime.timezone(datetime.timedelta(0))
19
+
20
+
21
+ class ExtType(namedtuple("ExtType", "code data")):
22
+ """ExtType represents ext type in msgpack."""
23
+
24
+ def __new__(cls, code, data):
25
+ if not isinstance(code, int):
26
+ raise TypeError("code must be int")
27
+ if not isinstance(data, bytes):
28
+ raise TypeError("data must be bytes")
29
+ if not 0 <= code <= 127:
30
+ raise ValueError("code must be 0~127")
31
+ return super(ExtType, cls).__new__(cls, code, data)
32
+
33
+
34
+ class Timestamp(object):
35
+ """Timestamp represents the Timestamp extension type in msgpack.
36
+
37
+ When built with Cython, msgpack uses C methods to pack and unpack `Timestamp`. When using pure-Python
38
+ msgpack, :func:`to_bytes` and :func:`from_bytes` are used to pack and unpack `Timestamp`.
39
+
40
+ This class is immutable: Do not override seconds and nanoseconds.
41
+ """
42
+
43
+ __slots__ = ["seconds", "nanoseconds"]
44
+
45
+ def __init__(self, seconds, nanoseconds=0):
46
+ """Initialize a Timestamp object.
47
+
48
+ :param int seconds:
49
+ Number of seconds since the UNIX epoch (00:00:00 UTC Jan 1 1970, minus leap seconds).
50
+ May be negative.
51
+
52
+ :param int nanoseconds:
53
+ Number of nanoseconds to add to `seconds` to get fractional time.
54
+ Maximum is 999_999_999. Default is 0.
55
+
56
+ Note: Negative times (before the UNIX epoch) are represented as negative seconds + positive ns.
57
+ """
58
+ if not isinstance(seconds, int_types):
59
+ raise TypeError("seconds must be an integer")
60
+ if not isinstance(nanoseconds, int_types):
61
+ raise TypeError("nanoseconds must be an integer")
62
+ if not (0 <= nanoseconds < 10**9):
63
+ raise ValueError(
64
+ "nanoseconds must be a non-negative integer less than 999999999."
65
+ )
66
+ self.seconds = seconds
67
+ self.nanoseconds = nanoseconds
68
+
69
+ def __repr__(self):
70
+ """String representation of Timestamp."""
71
+ return "Timestamp(seconds={0}, nanoseconds={1})".format(
72
+ self.seconds, self.nanoseconds
73
+ )
74
+
75
+ def __eq__(self, other):
76
+ """Check for equality with another Timestamp object"""
77
+ if type(other) is self.__class__:
78
+ return (
79
+ self.seconds == other.seconds and self.nanoseconds == other.nanoseconds
80
+ )
81
+ return False
82
+
83
+ def __ne__(self, other):
84
+ """not-equals method (see :func:`__eq__()`)"""
85
+ return not self.__eq__(other)
86
+
87
+ def __hash__(self):
88
+ return hash((self.seconds, self.nanoseconds))
89
+
90
+ @staticmethod
91
+ def from_bytes(b):
92
+ """Unpack bytes into a `Timestamp` object.
93
+
94
+ Used for pure-Python msgpack unpacking.
95
+
96
+ :param b: Payload from msgpack ext message with code -1
97
+ :type b: bytes
98
+
99
+ :returns: Timestamp object unpacked from msgpack ext payload
100
+ :rtype: Timestamp
101
+ """
102
+ if len(b) == 4:
103
+ seconds = struct.unpack("!L", b)[0]
104
+ nanoseconds = 0
105
+ elif len(b) == 8:
106
+ data64 = struct.unpack("!Q", b)[0]
107
+ seconds = data64 & 0x00000003FFFFFFFF
108
+ nanoseconds = data64 >> 34
109
+ elif len(b) == 12:
110
+ nanoseconds, seconds = struct.unpack("!Iq", b)
111
+ else:
112
+ raise ValueError(
113
+ "Timestamp type can only be created from 32, 64, or 96-bit byte objects"
114
+ )
115
+ return Timestamp(seconds, nanoseconds)
116
+
117
+ def to_bytes(self):
118
+ """Pack this Timestamp object into bytes.
119
+
120
+ Used for pure-Python msgpack packing.
121
+
122
+ :returns data: Payload for EXT message with code -1 (timestamp type)
123
+ :rtype: bytes
124
+ """
125
+ if (self.seconds >> 34) == 0: # seconds is non-negative and fits in 34 bits
126
+ data64 = self.nanoseconds << 34 | self.seconds
127
+ if data64 & 0xFFFFFFFF00000000 == 0:
128
+ # nanoseconds is zero and seconds < 2**32, so timestamp 32
129
+ data = struct.pack("!L", data64)
130
+ else:
131
+ # timestamp 64
132
+ data = struct.pack("!Q", data64)
133
+ else:
134
+ # timestamp 96
135
+ data = struct.pack("!Iq", self.nanoseconds, self.seconds)
136
+ return data
137
+
138
+ @staticmethod
139
+ def from_unix(unix_sec):
140
+ """Create a Timestamp from posix timestamp in seconds.
141
+
142
+ :param unix_float: Posix timestamp in seconds.
143
+ :type unix_float: int or float.
144
+ """
145
+ seconds = int(unix_sec // 1)
146
+ nanoseconds = int((unix_sec % 1) * 10**9)
147
+ return Timestamp(seconds, nanoseconds)
148
+
149
+ def to_unix(self):
150
+ """Get the timestamp as a floating-point value.
151
+
152
+ :returns: posix timestamp
153
+ :rtype: float
154
+ """
155
+ return self.seconds + self.nanoseconds / 1e9
156
+
157
+ @staticmethod
158
+ def from_unix_nano(unix_ns):
159
+ """Create a Timestamp from posix timestamp in nanoseconds.
160
+
161
+ :param int unix_ns: Posix timestamp in nanoseconds.
162
+ :rtype: Timestamp
163
+ """
164
+ return Timestamp(*divmod(unix_ns, 10**9))
165
+
166
+ def to_unix_nano(self):
167
+ """Get the timestamp as a unixtime in nanoseconds.
168
+
169
+ :returns: posix timestamp in nanoseconds
170
+ :rtype: int
171
+ """
172
+ return self.seconds * 10**9 + self.nanoseconds
173
+
174
+ def to_datetime(self):
175
+ """Get the timestamp as a UTC datetime.
176
+
177
+ Python 2 is not supported.
178
+
179
+ :rtype: datetime.
180
+ """
181
+ return datetime.datetime.fromtimestamp(0, _utc) + datetime.timedelta(
182
+ seconds=self.to_unix()
183
+ )
184
+
185
+ @staticmethod
186
+ def from_datetime(dt):
187
+ """Create a Timestamp from datetime with tzinfo.
188
+
189
+ Python 2 is not supported.
190
+
191
+ :rtype: Timestamp
192
+ """
193
+ return Timestamp.from_unix(dt.timestamp())
.venv/Lib/site-packages/pip/_vendor/msgpack/fallback.py ADDED
@@ -0,0 +1,1010 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fallback pure Python implementation of msgpack"""
2
+ from datetime import datetime as _DateTime
3
+ import sys
4
+ import struct
5
+
6
+
7
+ PY2 = sys.version_info[0] == 2
8
+ if PY2:
9
+ int_types = (int, long)
10
+
11
+ def dict_iteritems(d):
12
+ return d.iteritems()
13
+
14
+ else:
15
+ int_types = int
16
+ unicode = str
17
+ xrange = range
18
+
19
+ def dict_iteritems(d):
20
+ return d.items()
21
+
22
+
23
+ if sys.version_info < (3, 5):
24
+ # Ugly hack...
25
+ RecursionError = RuntimeError
26
+
27
+ def _is_recursionerror(e):
28
+ return (
29
+ len(e.args) == 1
30
+ and isinstance(e.args[0], str)
31
+ and e.args[0].startswith("maximum recursion depth exceeded")
32
+ )
33
+
34
+ else:
35
+
36
+ def _is_recursionerror(e):
37
+ return True
38
+
39
+
40
+ if hasattr(sys, "pypy_version_info"):
41
+ # StringIO is slow on PyPy, StringIO is faster. However: PyPy's own
42
+ # StringBuilder is fastest.
43
+ from __pypy__ import newlist_hint
44
+
45
+ try:
46
+ from __pypy__.builders import BytesBuilder as StringBuilder
47
+ except ImportError:
48
+ from __pypy__.builders import StringBuilder
49
+ USING_STRINGBUILDER = True
50
+
51
+ class StringIO(object):
52
+ def __init__(self, s=b""):
53
+ if s:
54
+ self.builder = StringBuilder(len(s))
55
+ self.builder.append(s)
56
+ else:
57
+ self.builder = StringBuilder()
58
+
59
+ def write(self, s):
60
+ if isinstance(s, memoryview):
61
+ s = s.tobytes()
62
+ elif isinstance(s, bytearray):
63
+ s = bytes(s)
64
+ self.builder.append(s)
65
+
66
+ def getvalue(self):
67
+ return self.builder.build()
68
+
69
+ else:
70
+ USING_STRINGBUILDER = False
71
+ from io import BytesIO as StringIO
72
+
73
+ newlist_hint = lambda size: []
74
+
75
+
76
+ from .exceptions import BufferFull, OutOfData, ExtraData, FormatError, StackError
77
+
78
+ from .ext import ExtType, Timestamp
79
+
80
+
81
+ EX_SKIP = 0
82
+ EX_CONSTRUCT = 1
83
+ EX_READ_ARRAY_HEADER = 2
84
+ EX_READ_MAP_HEADER = 3
85
+
86
+ TYPE_IMMEDIATE = 0
87
+ TYPE_ARRAY = 1
88
+ TYPE_MAP = 2
89
+ TYPE_RAW = 3
90
+ TYPE_BIN = 4
91
+ TYPE_EXT = 5
92
+
93
+ DEFAULT_RECURSE_LIMIT = 511
94
+
95
+
96
+ def _check_type_strict(obj, t, type=type, tuple=tuple):
97
+ if type(t) is tuple:
98
+ return type(obj) in t
99
+ else:
100
+ return type(obj) is t
101
+
102
+
103
+ def _get_data_from_buffer(obj):
104
+ view = memoryview(obj)
105
+ if view.itemsize != 1:
106
+ raise ValueError("cannot unpack from multi-byte object")
107
+ return view
108
+
109
+
110
+ def unpackb(packed, **kwargs):
111
+ """
112
+ Unpack an object from `packed`.
113
+
114
+ Raises ``ExtraData`` when *packed* contains extra bytes.
115
+ Raises ``ValueError`` when *packed* is incomplete.
116
+ Raises ``FormatError`` when *packed* is not valid msgpack.
117
+ Raises ``StackError`` when *packed* contains too nested.
118
+ Other exceptions can be raised during unpacking.
119
+
120
+ See :class:`Unpacker` for options.
121
+ """
122
+ unpacker = Unpacker(None, max_buffer_size=len(packed), **kwargs)
123
+ unpacker.feed(packed)
124
+ try:
125
+ ret = unpacker._unpack()
126
+ except OutOfData:
127
+ raise ValueError("Unpack failed: incomplete input")
128
+ except RecursionError as e:
129
+ if _is_recursionerror(e):
130
+ raise StackError
131
+ raise
132
+ if unpacker._got_extradata():
133
+ raise ExtraData(ret, unpacker._get_extradata())
134
+ return ret
135
+
136
+
137
+ if sys.version_info < (2, 7, 6):
138
+
139
+ def _unpack_from(f, b, o=0):
140
+ """Explicit type cast for legacy struct.unpack_from"""
141
+ return struct.unpack_from(f, bytes(b), o)
142
+
143
+ else:
144
+ _unpack_from = struct.unpack_from
145
+
146
+ _NO_FORMAT_USED = ""
147
+ _MSGPACK_HEADERS = {
148
+ 0xC4: (1, _NO_FORMAT_USED, TYPE_BIN),
149
+ 0xC5: (2, ">H", TYPE_BIN),
150
+ 0xC6: (4, ">I", TYPE_BIN),
151
+ 0xC7: (2, "Bb", TYPE_EXT),
152
+ 0xC8: (3, ">Hb", TYPE_EXT),
153
+ 0xC9: (5, ">Ib", TYPE_EXT),
154
+ 0xCA: (4, ">f"),
155
+ 0xCB: (8, ">d"),
156
+ 0xCC: (1, _NO_FORMAT_USED),
157
+ 0xCD: (2, ">H"),
158
+ 0xCE: (4, ">I"),
159
+ 0xCF: (8, ">Q"),
160
+ 0xD0: (1, "b"),
161
+ 0xD1: (2, ">h"),
162
+ 0xD2: (4, ">i"),
163
+ 0xD3: (8, ">q"),
164
+ 0xD4: (1, "b1s", TYPE_EXT),
165
+ 0xD5: (2, "b2s", TYPE_EXT),
166
+ 0xD6: (4, "b4s", TYPE_EXT),
167
+ 0xD7: (8, "b8s", TYPE_EXT),
168
+ 0xD8: (16, "b16s", TYPE_EXT),
169
+ 0xD9: (1, _NO_FORMAT_USED, TYPE_RAW),
170
+ 0xDA: (2, ">H", TYPE_RAW),
171
+ 0xDB: (4, ">I", TYPE_RAW),
172
+ 0xDC: (2, ">H", TYPE_ARRAY),
173
+ 0xDD: (4, ">I", TYPE_ARRAY),
174
+ 0xDE: (2, ">H", TYPE_MAP),
175
+ 0xDF: (4, ">I", TYPE_MAP),
176
+ }
177
+
178
+
179
+ class Unpacker(object):
180
+ """Streaming unpacker.
181
+
182
+ Arguments:
183
+
184
+ :param file_like:
185
+ File-like object having `.read(n)` method.
186
+ If specified, unpacker reads serialized data from it and :meth:`feed()` is not usable.
187
+
188
+ :param int read_size:
189
+ Used as `file_like.read(read_size)`. (default: `min(16*1024, max_buffer_size)`)
190
+
191
+ :param bool use_list:
192
+ If true, unpack msgpack array to Python list.
193
+ Otherwise, unpack to Python tuple. (default: True)
194
+
195
+ :param bool raw:
196
+ If true, unpack msgpack raw to Python bytes.
197
+ Otherwise, unpack to Python str by decoding with UTF-8 encoding (default).
198
+
199
+ :param int timestamp:
200
+ Control how timestamp type is unpacked:
201
+
202
+ 0 - Timestamp
203
+ 1 - float (Seconds from the EPOCH)
204
+ 2 - int (Nanoseconds from the EPOCH)
205
+ 3 - datetime.datetime (UTC). Python 2 is not supported.
206
+
207
+ :param bool strict_map_key:
208
+ If true (default), only str or bytes are accepted for map (dict) keys.
209
+
210
+ :param callable object_hook:
211
+ When specified, it should be callable.
212
+ Unpacker calls it with a dict argument after unpacking msgpack map.
213
+ (See also simplejson)
214
+
215
+ :param callable object_pairs_hook:
216
+ When specified, it should be callable.
217
+ Unpacker calls it with a list of key-value pairs after unpacking msgpack map.
218
+ (See also simplejson)
219
+
220
+ :param str unicode_errors:
221
+ The error handler for decoding unicode. (default: 'strict')
222
+ This option should be used only when you have msgpack data which
223
+ contains invalid UTF-8 string.
224
+
225
+ :param int max_buffer_size:
226
+ Limits size of data waiting unpacked. 0 means 2**32-1.
227
+ The default value is 100*1024*1024 (100MiB).
228
+ Raises `BufferFull` exception when it is insufficient.
229
+ You should set this parameter when unpacking data from untrusted source.
230
+
231
+ :param int max_str_len:
232
+ Deprecated, use *max_buffer_size* instead.
233
+ Limits max length of str. (default: max_buffer_size)
234
+
235
+ :param int max_bin_len:
236
+ Deprecated, use *max_buffer_size* instead.
237
+ Limits max length of bin. (default: max_buffer_size)
238
+
239
+ :param int max_array_len:
240
+ Limits max length of array.
241
+ (default: max_buffer_size)
242
+
243
+ :param int max_map_len:
244
+ Limits max length of map.
245
+ (default: max_buffer_size//2)
246
+
247
+ :param int max_ext_len:
248
+ Deprecated, use *max_buffer_size* instead.
249
+ Limits max size of ext type. (default: max_buffer_size)
250
+
251
+ Example of streaming deserialize from file-like object::
252
+
253
+ unpacker = Unpacker(file_like)
254
+ for o in unpacker:
255
+ process(o)
256
+
257
+ Example of streaming deserialize from socket::
258
+
259
+ unpacker = Unpacker()
260
+ while True:
261
+ buf = sock.recv(1024**2)
262
+ if not buf:
263
+ break
264
+ unpacker.feed(buf)
265
+ for o in unpacker:
266
+ process(o)
267
+
268
+ Raises ``ExtraData`` when *packed* contains extra bytes.
269
+ Raises ``OutOfData`` when *packed* is incomplete.
270
+ Raises ``FormatError`` when *packed* is not valid msgpack.
271
+ Raises ``StackError`` when *packed* contains too nested.
272
+ Other exceptions can be raised during unpacking.
273
+ """
274
+
275
+ def __init__(
276
+ self,
277
+ file_like=None,
278
+ read_size=0,
279
+ use_list=True,
280
+ raw=False,
281
+ timestamp=0,
282
+ strict_map_key=True,
283
+ object_hook=None,
284
+ object_pairs_hook=None,
285
+ list_hook=None,
286
+ unicode_errors=None,
287
+ max_buffer_size=100 * 1024 * 1024,
288
+ ext_hook=ExtType,
289
+ max_str_len=-1,
290
+ max_bin_len=-1,
291
+ max_array_len=-1,
292
+ max_map_len=-1,
293
+ max_ext_len=-1,
294
+ ):
295
+ if unicode_errors is None:
296
+ unicode_errors = "strict"
297
+
298
+ if file_like is None:
299
+ self._feeding = True
300
+ else:
301
+ if not callable(file_like.read):
302
+ raise TypeError("`file_like.read` must be callable")
303
+ self.file_like = file_like
304
+ self._feeding = False
305
+
306
+ #: array of bytes fed.
307
+ self._buffer = bytearray()
308
+ #: Which position we currently reads
309
+ self._buff_i = 0
310
+
311
+ # When Unpacker is used as an iterable, between the calls to next(),
312
+ # the buffer is not "consumed" completely, for efficiency sake.
313
+ # Instead, it is done sloppily. To make sure we raise BufferFull at
314
+ # the correct moments, we have to keep track of how sloppy we were.
315
+ # Furthermore, when the buffer is incomplete (that is: in the case
316
+ # we raise an OutOfData) we need to rollback the buffer to the correct
317
+ # state, which _buf_checkpoint records.
318
+ self._buf_checkpoint = 0
319
+
320
+ if not max_buffer_size:
321
+ max_buffer_size = 2**31 - 1
322
+ if max_str_len == -1:
323
+ max_str_len = max_buffer_size
324
+ if max_bin_len == -1:
325
+ max_bin_len = max_buffer_size
326
+ if max_array_len == -1:
327
+ max_array_len = max_buffer_size
328
+ if max_map_len == -1:
329
+ max_map_len = max_buffer_size // 2
330
+ if max_ext_len == -1:
331
+ max_ext_len = max_buffer_size
332
+
333
+ self._max_buffer_size = max_buffer_size
334
+ if read_size > self._max_buffer_size:
335
+ raise ValueError("read_size must be smaller than max_buffer_size")
336
+ self._read_size = read_size or min(self._max_buffer_size, 16 * 1024)
337
+ self._raw = bool(raw)
338
+ self._strict_map_key = bool(strict_map_key)
339
+ self._unicode_errors = unicode_errors
340
+ self._use_list = use_list
341
+ if not (0 <= timestamp <= 3):
342
+ raise ValueError("timestamp must be 0..3")
343
+ self._timestamp = timestamp
344
+ self._list_hook = list_hook
345
+ self._object_hook = object_hook
346
+ self._object_pairs_hook = object_pairs_hook
347
+ self._ext_hook = ext_hook
348
+ self._max_str_len = max_str_len
349
+ self._max_bin_len = max_bin_len
350
+ self._max_array_len = max_array_len
351
+ self._max_map_len = max_map_len
352
+ self._max_ext_len = max_ext_len
353
+ self._stream_offset = 0
354
+
355
+ if list_hook is not None and not callable(list_hook):
356
+ raise TypeError("`list_hook` is not callable")
357
+ if object_hook is not None and not callable(object_hook):
358
+ raise TypeError("`object_hook` is not callable")
359
+ if object_pairs_hook is not None and not callable(object_pairs_hook):
360
+ raise TypeError("`object_pairs_hook` is not callable")
361
+ if object_hook is not None and object_pairs_hook is not None:
362
+ raise TypeError(
363
+ "object_pairs_hook and object_hook are mutually " "exclusive"
364
+ )
365
+ if not callable(ext_hook):
366
+ raise TypeError("`ext_hook` is not callable")
367
+
368
+ def feed(self, next_bytes):
369
+ assert self._feeding
370
+ view = _get_data_from_buffer(next_bytes)
371
+ if len(self._buffer) - self._buff_i + len(view) > self._max_buffer_size:
372
+ raise BufferFull
373
+
374
+ # Strip buffer before checkpoint before reading file.
375
+ if self._buf_checkpoint > 0:
376
+ del self._buffer[: self._buf_checkpoint]
377
+ self._buff_i -= self._buf_checkpoint
378
+ self._buf_checkpoint = 0
379
+
380
+ # Use extend here: INPLACE_ADD += doesn't reliably typecast memoryview in jython
381
+ self._buffer.extend(view)
382
+
383
+ def _consume(self):
384
+ """Gets rid of the used parts of the buffer."""
385
+ self._stream_offset += self._buff_i - self._buf_checkpoint
386
+ self._buf_checkpoint = self._buff_i
387
+
388
+ def _got_extradata(self):
389
+ return self._buff_i < len(self._buffer)
390
+
391
+ def _get_extradata(self):
392
+ return self._buffer[self._buff_i :]
393
+
394
+ def read_bytes(self, n):
395
+ ret = self._read(n, raise_outofdata=False)
396
+ self._consume()
397
+ return ret
398
+
399
+ def _read(self, n, raise_outofdata=True):
400
+ # (int) -> bytearray
401
+ self._reserve(n, raise_outofdata=raise_outofdata)
402
+ i = self._buff_i
403
+ ret = self._buffer[i : i + n]
404
+ self._buff_i = i + len(ret)
405
+ return ret
406
+
407
+ def _reserve(self, n, raise_outofdata=True):
408
+ remain_bytes = len(self._buffer) - self._buff_i - n
409
+
410
+ # Fast path: buffer has n bytes already
411
+ if remain_bytes >= 0:
412
+ return
413
+
414
+ if self._feeding:
415
+ self._buff_i = self._buf_checkpoint
416
+ raise OutOfData
417
+
418
+ # Strip buffer before checkpoint before reading file.
419
+ if self._buf_checkpoint > 0:
420
+ del self._buffer[: self._buf_checkpoint]
421
+ self._buff_i -= self._buf_checkpoint
422
+ self._buf_checkpoint = 0
423
+
424
+ # Read from file
425
+ remain_bytes = -remain_bytes
426
+ if remain_bytes + len(self._buffer) > self._max_buffer_size:
427
+ raise BufferFull
428
+ while remain_bytes > 0:
429
+ to_read_bytes = max(self._read_size, remain_bytes)
430
+ read_data = self.file_like.read(to_read_bytes)
431
+ if not read_data:
432
+ break
433
+ assert isinstance(read_data, bytes)
434
+ self._buffer += read_data
435
+ remain_bytes -= len(read_data)
436
+
437
+ if len(self._buffer) < n + self._buff_i and raise_outofdata:
438
+ self._buff_i = 0 # rollback
439
+ raise OutOfData
440
+
441
+ def _read_header(self):
442
+ typ = TYPE_IMMEDIATE
443
+ n = 0
444
+ obj = None
445
+ self._reserve(1)
446
+ b = self._buffer[self._buff_i]
447
+ self._buff_i += 1
448
+ if b & 0b10000000 == 0:
449
+ obj = b
450
+ elif b & 0b11100000 == 0b11100000:
451
+ obj = -1 - (b ^ 0xFF)
452
+ elif b & 0b11100000 == 0b10100000:
453
+ n = b & 0b00011111
454
+ typ = TYPE_RAW
455
+ if n > self._max_str_len:
456
+ raise ValueError("%s exceeds max_str_len(%s)" % (n, self._max_str_len))
457
+ obj = self._read(n)
458
+ elif b & 0b11110000 == 0b10010000:
459
+ n = b & 0b00001111
460
+ typ = TYPE_ARRAY
461
+ if n > self._max_array_len:
462
+ raise ValueError(
463
+ "%s exceeds max_array_len(%s)" % (n, self._max_array_len)
464
+ )
465
+ elif b & 0b11110000 == 0b10000000:
466
+ n = b & 0b00001111
467
+ typ = TYPE_MAP
468
+ if n > self._max_map_len:
469
+ raise ValueError("%s exceeds max_map_len(%s)" % (n, self._max_map_len))
470
+ elif b == 0xC0:
471
+ obj = None
472
+ elif b == 0xC2:
473
+ obj = False
474
+ elif b == 0xC3:
475
+ obj = True
476
+ elif 0xC4 <= b <= 0xC6:
477
+ size, fmt, typ = _MSGPACK_HEADERS[b]
478
+ self._reserve(size)
479
+ if len(fmt) > 0:
480
+ n = _unpack_from(fmt, self._buffer, self._buff_i)[0]
481
+ else:
482
+ n = self._buffer[self._buff_i]
483
+ self._buff_i += size
484
+ if n > self._max_bin_len:
485
+ raise ValueError("%s exceeds max_bin_len(%s)" % (n, self._max_bin_len))
486
+ obj = self._read(n)
487
+ elif 0xC7 <= b <= 0xC9:
488
+ size, fmt, typ = _MSGPACK_HEADERS[b]
489
+ self._reserve(size)
490
+ L, n = _unpack_from(fmt, self._buffer, self._buff_i)
491
+ self._buff_i += size
492
+ if L > self._max_ext_len:
493
+ raise ValueError("%s exceeds max_ext_len(%s)" % (L, self._max_ext_len))
494
+ obj = self._read(L)
495
+ elif 0xCA <= b <= 0xD3:
496
+ size, fmt = _MSGPACK_HEADERS[b]
497
+ self._reserve(size)
498
+ if len(fmt) > 0:
499
+ obj = _unpack_from(fmt, self._buffer, self._buff_i)[0]
500
+ else:
501
+ obj = self._buffer[self._buff_i]
502
+ self._buff_i += size
503
+ elif 0xD4 <= b <= 0xD8:
504
+ size, fmt, typ = _MSGPACK_HEADERS[b]
505
+ if self._max_ext_len < size:
506
+ raise ValueError(
507
+ "%s exceeds max_ext_len(%s)" % (size, self._max_ext_len)
508
+ )
509
+ self._reserve(size + 1)
510
+ n, obj = _unpack_from(fmt, self._buffer, self._buff_i)
511
+ self._buff_i += size + 1
512
+ elif 0xD9 <= b <= 0xDB:
513
+ size, fmt, typ = _MSGPACK_HEADERS[b]
514
+ self._reserve(size)
515
+ if len(fmt) > 0:
516
+ (n,) = _unpack_from(fmt, self._buffer, self._buff_i)
517
+ else:
518
+ n = self._buffer[self._buff_i]
519
+ self._buff_i += size
520
+ if n > self._max_str_len:
521
+ raise ValueError("%s exceeds max_str_len(%s)" % (n, self._max_str_len))
522
+ obj = self._read(n)
523
+ elif 0xDC <= b <= 0xDD:
524
+ size, fmt, typ = _MSGPACK_HEADERS[b]
525
+ self._reserve(size)
526
+ (n,) = _unpack_from(fmt, self._buffer, self._buff_i)
527
+ self._buff_i += size
528
+ if n > self._max_array_len:
529
+ raise ValueError(
530
+ "%s exceeds max_array_len(%s)" % (n, self._max_array_len)
531
+ )
532
+ elif 0xDE <= b <= 0xDF:
533
+ size, fmt, typ = _MSGPACK_HEADERS[b]
534
+ self._reserve(size)
535
+ (n,) = _unpack_from(fmt, self._buffer, self._buff_i)
536
+ self._buff_i += size
537
+ if n > self._max_map_len:
538
+ raise ValueError("%s exceeds max_map_len(%s)" % (n, self._max_map_len))
539
+ else:
540
+ raise FormatError("Unknown header: 0x%x" % b)
541
+ return typ, n, obj
542
+
543
+ def _unpack(self, execute=EX_CONSTRUCT):
544
+ typ, n, obj = self._read_header()
545
+
546
+ if execute == EX_READ_ARRAY_HEADER:
547
+ if typ != TYPE_ARRAY:
548
+ raise ValueError("Expected array")
549
+ return n
550
+ if execute == EX_READ_MAP_HEADER:
551
+ if typ != TYPE_MAP:
552
+ raise ValueError("Expected map")
553
+ return n
554
+ # TODO should we eliminate the recursion?
555
+ if typ == TYPE_ARRAY:
556
+ if execute == EX_SKIP:
557
+ for i in xrange(n):
558
+ # TODO check whether we need to call `list_hook`
559
+ self._unpack(EX_SKIP)
560
+ return
561
+ ret = newlist_hint(n)
562
+ for i in xrange(n):
563
+ ret.append(self._unpack(EX_CONSTRUCT))
564
+ if self._list_hook is not None:
565
+ ret = self._list_hook(ret)
566
+ # TODO is the interaction between `list_hook` and `use_list` ok?
567
+ return ret if self._use_list else tuple(ret)
568
+ if typ == TYPE_MAP:
569
+ if execute == EX_SKIP:
570
+ for i in xrange(n):
571
+ # TODO check whether we need to call hooks
572
+ self._unpack(EX_SKIP)
573
+ self._unpack(EX_SKIP)
574
+ return
575
+ if self._object_pairs_hook is not None:
576
+ ret = self._object_pairs_hook(
577
+ (self._unpack(EX_CONSTRUCT), self._unpack(EX_CONSTRUCT))
578
+ for _ in xrange(n)
579
+ )
580
+ else:
581
+ ret = {}
582
+ for _ in xrange(n):
583
+ key = self._unpack(EX_CONSTRUCT)
584
+ if self._strict_map_key and type(key) not in (unicode, bytes):
585
+ raise ValueError(
586
+ "%s is not allowed for map key" % str(type(key))
587
+ )
588
+ if not PY2 and type(key) is str:
589
+ key = sys.intern(key)
590
+ ret[key] = self._unpack(EX_CONSTRUCT)
591
+ if self._object_hook is not None:
592
+ ret = self._object_hook(ret)
593
+ return ret
594
+ if execute == EX_SKIP:
595
+ return
596
+ if typ == TYPE_RAW:
597
+ if self._raw:
598
+ obj = bytes(obj)
599
+ else:
600
+ obj = obj.decode("utf_8", self._unicode_errors)
601
+ return obj
602
+ if typ == TYPE_BIN:
603
+ return bytes(obj)
604
+ if typ == TYPE_EXT:
605
+ if n == -1: # timestamp
606
+ ts = Timestamp.from_bytes(bytes(obj))
607
+ if self._timestamp == 1:
608
+ return ts.to_unix()
609
+ elif self._timestamp == 2:
610
+ return ts.to_unix_nano()
611
+ elif self._timestamp == 3:
612
+ return ts.to_datetime()
613
+ else:
614
+ return ts
615
+ else:
616
+ return self._ext_hook(n, bytes(obj))
617
+ assert typ == TYPE_IMMEDIATE
618
+ return obj
619
+
620
+ def __iter__(self):
621
+ return self
622
+
623
+ def __next__(self):
624
+ try:
625
+ ret = self._unpack(EX_CONSTRUCT)
626
+ self._consume()
627
+ return ret
628
+ except OutOfData:
629
+ self._consume()
630
+ raise StopIteration
631
+ except RecursionError:
632
+ raise StackError
633
+
634
+ next = __next__
635
+
636
+ def skip(self):
637
+ self._unpack(EX_SKIP)
638
+ self._consume()
639
+
640
+ def unpack(self):
641
+ try:
642
+ ret = self._unpack(EX_CONSTRUCT)
643
+ except RecursionError:
644
+ raise StackError
645
+ self._consume()
646
+ return ret
647
+
648
+ def read_array_header(self):
649
+ ret = self._unpack(EX_READ_ARRAY_HEADER)
650
+ self._consume()
651
+ return ret
652
+
653
+ def read_map_header(self):
654
+ ret = self._unpack(EX_READ_MAP_HEADER)
655
+ self._consume()
656
+ return ret
657
+
658
+ def tell(self):
659
+ return self._stream_offset
660
+
661
+
662
+ class Packer(object):
663
+ """
664
+ MessagePack Packer
665
+
666
+ Usage::
667
+
668
+ packer = Packer()
669
+ astream.write(packer.pack(a))
670
+ astream.write(packer.pack(b))
671
+
672
+ Packer's constructor has some keyword arguments:
673
+
674
+ :param callable default:
675
+ Convert user type to builtin type that Packer supports.
676
+ See also simplejson's document.
677
+
678
+ :param bool use_single_float:
679
+ Use single precision float type for float. (default: False)
680
+
681
+ :param bool autoreset:
682
+ Reset buffer after each pack and return its content as `bytes`. (default: True).
683
+ If set this to false, use `bytes()` to get content and `.reset()` to clear buffer.
684
+
685
+ :param bool use_bin_type:
686
+ Use bin type introduced in msgpack spec 2.0 for bytes.
687
+ It also enables str8 type for unicode. (default: True)
688
+
689
+ :param bool strict_types:
690
+ If set to true, types will be checked to be exact. Derived classes
691
+ from serializable types will not be serialized and will be
692
+ treated as unsupported type and forwarded to default.
693
+ Additionally tuples will not be serialized as lists.
694
+ This is useful when trying to implement accurate serialization
695
+ for python types.
696
+
697
+ :param bool datetime:
698
+ If set to true, datetime with tzinfo is packed into Timestamp type.
699
+ Note that the tzinfo is stripped in the timestamp.
700
+ You can get UTC datetime with `timestamp=3` option of the Unpacker.
701
+ (Python 2 is not supported).
702
+
703
+ :param str unicode_errors:
704
+ The error handler for encoding unicode. (default: 'strict')
705
+ DO NOT USE THIS!! This option is kept for very specific usage.
706
+
707
+ Example of streaming deserialize from file-like object::
708
+
709
+ unpacker = Unpacker(file_like)
710
+ for o in unpacker:
711
+ process(o)
712
+
713
+ Example of streaming deserialize from socket::
714
+
715
+ unpacker = Unpacker()
716
+ while True:
717
+ buf = sock.recv(1024**2)
718
+ if not buf:
719
+ break
720
+ unpacker.feed(buf)
721
+ for o in unpacker:
722
+ process(o)
723
+
724
+ Raises ``ExtraData`` when *packed* contains extra bytes.
725
+ Raises ``OutOfData`` when *packed* is incomplete.
726
+ Raises ``FormatError`` when *packed* is not valid msgpack.
727
+ Raises ``StackError`` when *packed* contains too nested.
728
+ Other exceptions can be raised during unpacking.
729
+ """
730
+
731
+ def __init__(
732
+ self,
733
+ default=None,
734
+ use_single_float=False,
735
+ autoreset=True,
736
+ use_bin_type=True,
737
+ strict_types=False,
738
+ datetime=False,
739
+ unicode_errors=None,
740
+ ):
741
+ self._strict_types = strict_types
742
+ self._use_float = use_single_float
743
+ self._autoreset = autoreset
744
+ self._use_bin_type = use_bin_type
745
+ self._buffer = StringIO()
746
+ if PY2 and datetime:
747
+ raise ValueError("datetime is not supported in Python 2")
748
+ self._datetime = bool(datetime)
749
+ self._unicode_errors = unicode_errors or "strict"
750
+ if default is not None:
751
+ if not callable(default):
752
+ raise TypeError("default must be callable")
753
+ self._default = default
754
+
755
+ def _pack(
756
+ self,
757
+ obj,
758
+ nest_limit=DEFAULT_RECURSE_LIMIT,
759
+ check=isinstance,
760
+ check_type_strict=_check_type_strict,
761
+ ):
762
+ default_used = False
763
+ if self._strict_types:
764
+ check = check_type_strict
765
+ list_types = list
766
+ else:
767
+ list_types = (list, tuple)
768
+ while True:
769
+ if nest_limit < 0:
770
+ raise ValueError("recursion limit exceeded")
771
+ if obj is None:
772
+ return self._buffer.write(b"\xc0")
773
+ if check(obj, bool):
774
+ if obj:
775
+ return self._buffer.write(b"\xc3")
776
+ return self._buffer.write(b"\xc2")
777
+ if check(obj, int_types):
778
+ if 0 <= obj < 0x80:
779
+ return self._buffer.write(struct.pack("B", obj))
780
+ if -0x20 <= obj < 0:
781
+ return self._buffer.write(struct.pack("b", obj))
782
+ if 0x80 <= obj <= 0xFF:
783
+ return self._buffer.write(struct.pack("BB", 0xCC, obj))
784
+ if -0x80 <= obj < 0:
785
+ return self._buffer.write(struct.pack(">Bb", 0xD0, obj))
786
+ if 0xFF < obj <= 0xFFFF:
787
+ return self._buffer.write(struct.pack(">BH", 0xCD, obj))
788
+ if -0x8000 <= obj < -0x80:
789
+ return self._buffer.write(struct.pack(">Bh", 0xD1, obj))
790
+ if 0xFFFF < obj <= 0xFFFFFFFF:
791
+ return self._buffer.write(struct.pack(">BI", 0xCE, obj))
792
+ if -0x80000000 <= obj < -0x8000:
793
+ return self._buffer.write(struct.pack(">Bi", 0xD2, obj))
794
+ if 0xFFFFFFFF < obj <= 0xFFFFFFFFFFFFFFFF:
795
+ return self._buffer.write(struct.pack(">BQ", 0xCF, obj))
796
+ if -0x8000000000000000 <= obj < -0x80000000:
797
+ return self._buffer.write(struct.pack(">Bq", 0xD3, obj))
798
+ if not default_used and self._default is not None:
799
+ obj = self._default(obj)
800
+ default_used = True
801
+ continue
802
+ raise OverflowError("Integer value out of range")
803
+ if check(obj, (bytes, bytearray)):
804
+ n = len(obj)
805
+ if n >= 2**32:
806
+ raise ValueError("%s is too large" % type(obj).__name__)
807
+ self._pack_bin_header(n)
808
+ return self._buffer.write(obj)
809
+ if check(obj, unicode):
810
+ obj = obj.encode("utf-8", self._unicode_errors)
811
+ n = len(obj)
812
+ if n >= 2**32:
813
+ raise ValueError("String is too large")
814
+ self._pack_raw_header(n)
815
+ return self._buffer.write(obj)
816
+ if check(obj, memoryview):
817
+ n = obj.nbytes
818
+ if n >= 2**32:
819
+ raise ValueError("Memoryview is too large")
820
+ self._pack_bin_header(n)
821
+ return self._buffer.write(obj)
822
+ if check(obj, float):
823
+ if self._use_float:
824
+ return self._buffer.write(struct.pack(">Bf", 0xCA, obj))
825
+ return self._buffer.write(struct.pack(">Bd", 0xCB, obj))
826
+ if check(obj, (ExtType, Timestamp)):
827
+ if check(obj, Timestamp):
828
+ code = -1
829
+ data = obj.to_bytes()
830
+ else:
831
+ code = obj.code
832
+ data = obj.data
833
+ assert isinstance(code, int)
834
+ assert isinstance(data, bytes)
835
+ L = len(data)
836
+ if L == 1:
837
+ self._buffer.write(b"\xd4")
838
+ elif L == 2:
839
+ self._buffer.write(b"\xd5")
840
+ elif L == 4:
841
+ self._buffer.write(b"\xd6")
842
+ elif L == 8:
843
+ self._buffer.write(b"\xd7")
844
+ elif L == 16:
845
+ self._buffer.write(b"\xd8")
846
+ elif L <= 0xFF:
847
+ self._buffer.write(struct.pack(">BB", 0xC7, L))
848
+ elif L <= 0xFFFF:
849
+ self._buffer.write(struct.pack(">BH", 0xC8, L))
850
+ else:
851
+ self._buffer.write(struct.pack(">BI", 0xC9, L))
852
+ self._buffer.write(struct.pack("b", code))
853
+ self._buffer.write(data)
854
+ return
855
+ if check(obj, list_types):
856
+ n = len(obj)
857
+ self._pack_array_header(n)
858
+ for i in xrange(n):
859
+ self._pack(obj[i], nest_limit - 1)
860
+ return
861
+ if check(obj, dict):
862
+ return self._pack_map_pairs(
863
+ len(obj), dict_iteritems(obj), nest_limit - 1
864
+ )
865
+
866
+ if self._datetime and check(obj, _DateTime) and obj.tzinfo is not None:
867
+ obj = Timestamp.from_datetime(obj)
868
+ default_used = 1
869
+ continue
870
+
871
+ if not default_used and self._default is not None:
872
+ obj = self._default(obj)
873
+ default_used = 1
874
+ continue
875
+
876
+ if self._datetime and check(obj, _DateTime):
877
+ raise ValueError("Cannot serialize %r where tzinfo=None" % (obj,))
878
+
879
+ raise TypeError("Cannot serialize %r" % (obj,))
880
+
881
+ def pack(self, obj):
882
+ try:
883
+ self._pack(obj)
884
+ except:
885
+ self._buffer = StringIO() # force reset
886
+ raise
887
+ if self._autoreset:
888
+ ret = self._buffer.getvalue()
889
+ self._buffer = StringIO()
890
+ return ret
891
+
892
+ def pack_map_pairs(self, pairs):
893
+ self._pack_map_pairs(len(pairs), pairs)
894
+ if self._autoreset:
895
+ ret = self._buffer.getvalue()
896
+ self._buffer = StringIO()
897
+ return ret
898
+
899
+ def pack_array_header(self, n):
900
+ if n >= 2**32:
901
+ raise ValueError
902
+ self._pack_array_header(n)
903
+ if self._autoreset:
904
+ ret = self._buffer.getvalue()
905
+ self._buffer = StringIO()
906
+ return ret
907
+
908
+ def pack_map_header(self, n):
909
+ if n >= 2**32:
910
+ raise ValueError
911
+ self._pack_map_header(n)
912
+ if self._autoreset:
913
+ ret = self._buffer.getvalue()
914
+ self._buffer = StringIO()
915
+ return ret
916
+
917
+ def pack_ext_type(self, typecode, data):
918
+ if not isinstance(typecode, int):
919
+ raise TypeError("typecode must have int type.")
920
+ if not 0 <= typecode <= 127:
921
+ raise ValueError("typecode should be 0-127")
922
+ if not isinstance(data, bytes):
923
+ raise TypeError("data must have bytes type")
924
+ L = len(data)
925
+ if L > 0xFFFFFFFF:
926
+ raise ValueError("Too large data")
927
+ if L == 1:
928
+ self._buffer.write(b"\xd4")
929
+ elif L == 2:
930
+ self._buffer.write(b"\xd5")
931
+ elif L == 4:
932
+ self._buffer.write(b"\xd6")
933
+ elif L == 8:
934
+ self._buffer.write(b"\xd7")
935
+ elif L == 16:
936
+ self._buffer.write(b"\xd8")
937
+ elif L <= 0xFF:
938
+ self._buffer.write(b"\xc7" + struct.pack("B", L))
939
+ elif L <= 0xFFFF:
940
+ self._buffer.write(b"\xc8" + struct.pack(">H", L))
941
+ else:
942
+ self._buffer.write(b"\xc9" + struct.pack(">I", L))
943
+ self._buffer.write(struct.pack("B", typecode))
944
+ self._buffer.write(data)
945
+
946
+ def _pack_array_header(self, n):
947
+ if n <= 0x0F:
948
+ return self._buffer.write(struct.pack("B", 0x90 + n))
949
+ if n <= 0xFFFF:
950
+ return self._buffer.write(struct.pack(">BH", 0xDC, n))
951
+ if n <= 0xFFFFFFFF:
952
+ return self._buffer.write(struct.pack(">BI", 0xDD, n))
953
+ raise ValueError("Array is too large")
954
+
955
+ def _pack_map_header(self, n):
956
+ if n <= 0x0F:
957
+ return self._buffer.write(struct.pack("B", 0x80 + n))
958
+ if n <= 0xFFFF:
959
+ return self._buffer.write(struct.pack(">BH", 0xDE, n))
960
+ if n <= 0xFFFFFFFF:
961
+ return self._buffer.write(struct.pack(">BI", 0xDF, n))
962
+ raise ValueError("Dict is too large")
963
+
964
+ def _pack_map_pairs(self, n, pairs, nest_limit=DEFAULT_RECURSE_LIMIT):
965
+ self._pack_map_header(n)
966
+ for (k, v) in pairs:
967
+ self._pack(k, nest_limit - 1)
968
+ self._pack(v, nest_limit - 1)
969
+
970
+ def _pack_raw_header(self, n):
971
+ if n <= 0x1F:
972
+ self._buffer.write(struct.pack("B", 0xA0 + n))
973
+ elif self._use_bin_type and n <= 0xFF:
974
+ self._buffer.write(struct.pack(">BB", 0xD9, n))
975
+ elif n <= 0xFFFF:
976
+ self._buffer.write(struct.pack(">BH", 0xDA, n))
977
+ elif n <= 0xFFFFFFFF:
978
+ self._buffer.write(struct.pack(">BI", 0xDB, n))
979
+ else:
980
+ raise ValueError("Raw is too large")
981
+
982
+ def _pack_bin_header(self, n):
983
+ if not self._use_bin_type:
984
+ return self._pack_raw_header(n)
985
+ elif n <= 0xFF:
986
+ return self._buffer.write(struct.pack(">BB", 0xC4, n))
987
+ elif n <= 0xFFFF:
988
+ return self._buffer.write(struct.pack(">BH", 0xC5, n))
989
+ elif n <= 0xFFFFFFFF:
990
+ return self._buffer.write(struct.pack(">BI", 0xC6, n))
991
+ else:
992
+ raise ValueError("Bin is too large")
993
+
994
+ def bytes(self):
995
+ """Return internal buffer contents as bytes object"""
996
+ return self._buffer.getvalue()
997
+
998
+ def reset(self):
999
+ """Reset internal buffer.
1000
+
1001
+ This method is useful only when autoreset=False.
1002
+ """
1003
+ self._buffer = StringIO()
1004
+
1005
+ def getbuffer(self):
1006
+ """Return view of internal buffer."""
1007
+ if USING_STRINGBUILDER or PY2:
1008
+ return memoryview(self.bytes())
1009
+ else:
1010
+ return self._buffer.getbuffer()
.venv/Lib/site-packages/pip/_vendor/packaging/__about__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ __all__ = [
6
+ "__title__",
7
+ "__summary__",
8
+ "__uri__",
9
+ "__version__",
10
+ "__author__",
11
+ "__email__",
12
+ "__license__",
13
+ "__copyright__",
14
+ ]
15
+
16
+ __title__ = "packaging"
17
+ __summary__ = "Core utilities for Python packages"
18
+ __uri__ = "https://github.com/pypa/packaging"
19
+
20
+ __version__ = "21.3"
21
+
22
+ __author__ = "Donald Stufft and individual contributors"
23
+ __email__ = "donald@stufft.io"
24
+
25
+ __license__ = "BSD-2-Clause or Apache-2.0"
26
+ __copyright__ = "2014-2019 %s" % __author__