Let us walk on the 3-isogeny graph
Loading...
Searching...
No Matches
pip._vendor.distlib.compat Namespace Reference

Data Structures

class  BaseConfigurator
 
class  CertificateError
 
class  ChainMap
 
class  Container
 
class  ConvertingDict
 
class  ConvertingList
 
class  ConvertingTuple
 
class  OrderedDict
 
class  ZipExtFile
 
class  ZipFile
 

Functions

 quote (s)
 
 _dnsname_match (dn, hostname, max_wildcards=1)
 
 match_hostname (cert, hostname)
 
 which (cmd, mode=os.F_OK|os.X_OK, path=None)
 
 python_implementation ()
 
 callable (obj)
 
 fsencode (filename)
 
 fsdecode (filename)
 
 _get_normal_name (orig_enc)
 
 detect_encoding (readline)
 
 _recursive_repr (fillvalue='...')
 
 cache_from_source (path, debug_override=None)
 
 valid_ident (s)
 
 pop (self, key, default=None)
 

Variables

 ssl = None
 
 string_types = basestring,
 
 text_type = unicode
 
 raw_input = raw_input
 
 filter = filter
 
 ZipFile = BaseZipFile
 
 callable = callable
 
 fsencode = os.fsencode
 
 fsdecode = os.fsdecode
 
str _fsencoding = sys.getfilesystemencoding() or 'utf-8'
 
str _fserrors = 'strict'
 
 cookie_re = re.compile(r"coding[:=]\s*([-\w.]+)")
 
 unescape = HTMLParser().unescape
 
 IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)
 

Function Documentation

◆ _dnsname_match()

_dnsname_match (   dn,
  hostname,
  max_wildcards = 1 
)
protected
Matching according to RFC 6125, section 6.4.3

http://tools.ietf.org/html/rfc6125#section-6.4.3

Definition at line 99 of file compat.py.

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:
144
145 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
146 return pat.match(hostname)
147
148
for i

Referenced by pip._vendor.distlib.compat.match_hostname().

Here is the caller graph for this function:

◆ _get_normal_name()

_get_normal_name (   orig_enc)
protected
Imitates get_normal_name in tokenizer.c.

Definition at line 369 of file compat.py.

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

References i.

Referenced by pip._vendor.distlib.compat.detect_encoding().

Here is the caller graph for this function:

◆ _recursive_repr()

_recursive_repr (   fillvalue = '...')
protected
Decorator to make a repr function return fillvalue for a recursive
call

Definition at line 488 of file compat.py.

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
502 try:
503 result = user_function(self)
504 finally:
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

References i.

◆ cache_from_source()

cache_from_source (   path,
  debug_override = None 
)

Definition at line 618 of file compat.py.

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

References i.

◆ callable()

callable (   obj)

Definition at line 323 of file compat.py.

323 def callable(obj):
324 return isinstance(obj, Callable)
325
326

References i.

◆ detect_encoding()

detect_encoding (   readline)
The detect_encoding() function is used to detect the encoding that should
be used to decode a Python source file.  It requires one argument, readline,
in the same way as the tokenize() generator.

It will call readline a maximum of twice, and return the encoding used
(as a string) and a list of any lines (left as bytes) it has read in.

It detects the encoding from the presence of a utf-8 bom or an encoding
cookie as specified in pep-0263.  If both a bom and a cookie are present,
but disagree, a SyntaxError will be raised.  If the encoding cookie is an
invalid charset, raise a SyntaxError.  Note that if a utf-8 bom is found,
'utf-8-sig' is returned.

If no encoding is specified, then the default of 'utf-8' will be returned.

Definition at line 380 of file compat.py.

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.

References pip._vendor.distlib.compat._get_normal_name(), and i.

Here is the call graph for this function:

◆ fsdecode()

fsdecode (   filename)

Definition at line 352 of file compat.py.

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

References i.

◆ fsencode()

fsencode (   filename)

Definition at line 343 of file compat.py.

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

References i.

◆ match_hostname()

match_hostname (   cert,
  hostname 
)
Verify that *cert* (in decoded format as returned by
SSLSocket.getpeercert()) matches the *hostname*.  RFC 2818 and RFC 6125
rules are followed, but IP addresses are not accepted for *hostname*.

CertificateError is raised on failure. On success, the function
returns nothing.

Definition at line 149 of file compat.py.

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

References pip._vendor.distlib.compat._dnsname_match(), and i.

Here is the call graph for this function:

◆ pop()

pop (   self,
  key,
  default = None 
)

Definition at line 940 of file compat.py.

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

References i.

◆ python_implementation()

python_implementation ( )
Return a string identifying the Python implementation.

Definition at line 305 of file compat.py.

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

References i.

◆ quote()

quote (   s)

Definition at line 29 of file compat.py.

29 def quote(s):
30 if isinstance(s, unicode):
31 s = s.encode('utf-8')
32 return _quote(s)
33

References i.

◆ valid_ident()

valid_ident (   s)

Definition at line 897 of file compat.py.

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

References i.

◆ which()

which (   cmd,
  mode = os.F_OK | os.X_OK,
  path = None 
)
Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such
file.

`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
of os.environ.get("PATH"), or can be overridden with a custom search
path.

Definition at line 207 of file compat.py.

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:
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

References i.

Variable Documentation

◆ _fsencoding

str _fsencoding = sys.getfilesystemencoding() or 'utf-8'
protected

Definition at line 337 of file compat.py.

◆ _fserrors

str _fserrors = 'strict'
protected

Definition at line 339 of file compat.py.

◆ callable

callable = callable

Definition at line 319 of file compat.py.

Referenced by BaseConfigurator.configure_custom().

◆ cookie_re

cookie_re = re.compile(r"coding[:=]\s*([-\w.]+)")

Definition at line 367 of file compat.py.

◆ filter

filter = filter

Definition at line 89 of file compat.py.

◆ fsdecode

fsdecode = os.fsdecode

Definition at line 329 of file compat.py.

◆ fsencode

fsencode = os.fsencode

Definition at line 328 of file compat.py.

◆ IDENTIFIER

IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)

Definition at line 894 of file compat.py.

◆ raw_input

raw_input = raw_input

Definition at line 46 of file compat.py.

◆ ssl

ssl = None

Definition at line 16 of file compat.py.

◆ string_types

string_types = basestring,

Definition at line 20 of file compat.py.

◆ text_type

text_type = unicode

Definition at line 21 of file compat.py.

◆ unescape

unescape = HTMLParser().unescape

Definition at line 476 of file compat.py.

◆ ZipFile

ZipFile = BaseZipFile

Definition at line 275 of file compat.py.