repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/webencodings/__init__.py
|
iter_encode
|
def iter_encode(input, encoding=UTF8, errors='strict'):
"""
“Pull”-based encoder.
:param input: An iterable of Unicode strings.
:param encoding: An :class:`Encoding` object or a label string.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
:returns: An iterable of byte strings.
"""
# Fail early if `encoding` is an invalid label.
encode = IncrementalEncoder(encoding, errors).encode
return _iter_encode_generator(input, encode)
|
python
|
def iter_encode(input, encoding=UTF8, errors='strict'):
"""
“Pull”-based encoder.
:param input: An iterable of Unicode strings.
:param encoding: An :class:`Encoding` object or a label string.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
:returns: An iterable of byte strings.
"""
# Fail early if `encoding` is an invalid label.
encode = IncrementalEncoder(encoding, errors).encode
return _iter_encode_generator(input, encode)
|
[
"def",
"iter_encode",
"(",
"input",
",",
"encoding",
"=",
"UTF8",
",",
"errors",
"=",
"'strict'",
")",
":",
"# Fail early if `encoding` is an invalid label.",
"encode",
"=",
"IncrementalEncoder",
"(",
"encoding",
",",
"errors",
")",
".",
"encode",
"return",
"_iter_encode_generator",
"(",
"input",
",",
"encode",
")"
] |
“Pull”-based encoder.
:param input: An iterable of Unicode strings.
:param encoding: An :class:`Encoding` object or a label string.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
:returns: An iterable of byte strings.
|
[
"“Pull”",
"-",
"based",
"encoder",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L246-L259
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/webencodings/__init__.py
|
IncrementalDecoder.decode
|
def decode(self, input, final=False):
"""Decode one chunk of the input.
:param input: A byte string.
:param final:
Indicate that no more input is available.
Must be :obj:`True` if this is the last call.
:returns: An Unicode string.
"""
decoder = self._decoder
if decoder is not None:
return decoder(input, final)
input = self._buffer + input
encoding, input = _detect_bom(input)
if encoding is None:
if len(input) < 3 and not final: # Not enough data yet.
self._buffer = input
return ''
else: # No BOM
encoding = self._fallback_encoding
decoder = encoding.codec_info.incrementaldecoder(self._errors).decode
self._decoder = decoder
self.encoding = encoding
return decoder(input, final)
|
python
|
def decode(self, input, final=False):
"""Decode one chunk of the input.
:param input: A byte string.
:param final:
Indicate that no more input is available.
Must be :obj:`True` if this is the last call.
:returns: An Unicode string.
"""
decoder = self._decoder
if decoder is not None:
return decoder(input, final)
input = self._buffer + input
encoding, input = _detect_bom(input)
if encoding is None:
if len(input) < 3 and not final: # Not enough data yet.
self._buffer = input
return ''
else: # No BOM
encoding = self._fallback_encoding
decoder = encoding.codec_info.incrementaldecoder(self._errors).decode
self._decoder = decoder
self.encoding = encoding
return decoder(input, final)
|
[
"def",
"decode",
"(",
"self",
",",
"input",
",",
"final",
"=",
"False",
")",
":",
"decoder",
"=",
"self",
".",
"_decoder",
"if",
"decoder",
"is",
"not",
"None",
":",
"return",
"decoder",
"(",
"input",
",",
"final",
")",
"input",
"=",
"self",
".",
"_buffer",
"+",
"input",
"encoding",
",",
"input",
"=",
"_detect_bom",
"(",
"input",
")",
"if",
"encoding",
"is",
"None",
":",
"if",
"len",
"(",
"input",
")",
"<",
"3",
"and",
"not",
"final",
":",
"# Not enough data yet.",
"self",
".",
"_buffer",
"=",
"input",
"return",
"''",
"else",
":",
"# No BOM",
"encoding",
"=",
"self",
".",
"_fallback_encoding",
"decoder",
"=",
"encoding",
".",
"codec_info",
".",
"incrementaldecoder",
"(",
"self",
".",
"_errors",
")",
".",
"decode",
"self",
".",
"_decoder",
"=",
"decoder",
"self",
".",
"encoding",
"=",
"encoding",
"return",
"decoder",
"(",
"input",
",",
"final",
")"
] |
Decode one chunk of the input.
:param input: A byte string.
:param final:
Indicate that no more input is available.
Must be :obj:`True` if this is the last call.
:returns: An Unicode string.
|
[
"Decode",
"one",
"chunk",
"of",
"the",
"input",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L295-L320
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
|
_cf_dictionary_from_tuples
|
def _cf_dictionary_from_tuples(tuples):
"""
Given a list of Python tuples, create an associated CFDictionary.
"""
dictionary_size = len(tuples)
# We need to get the dictionary keys and values out in the same order.
keys = (t[0] for t in tuples)
values = (t[1] for t in tuples)
cf_keys = (CoreFoundation.CFTypeRef * dictionary_size)(*keys)
cf_values = (CoreFoundation.CFTypeRef * dictionary_size)(*values)
return CoreFoundation.CFDictionaryCreate(
CoreFoundation.kCFAllocatorDefault,
cf_keys,
cf_values,
dictionary_size,
CoreFoundation.kCFTypeDictionaryKeyCallBacks,
CoreFoundation.kCFTypeDictionaryValueCallBacks,
)
|
python
|
def _cf_dictionary_from_tuples(tuples):
"""
Given a list of Python tuples, create an associated CFDictionary.
"""
dictionary_size = len(tuples)
# We need to get the dictionary keys and values out in the same order.
keys = (t[0] for t in tuples)
values = (t[1] for t in tuples)
cf_keys = (CoreFoundation.CFTypeRef * dictionary_size)(*keys)
cf_values = (CoreFoundation.CFTypeRef * dictionary_size)(*values)
return CoreFoundation.CFDictionaryCreate(
CoreFoundation.kCFAllocatorDefault,
cf_keys,
cf_values,
dictionary_size,
CoreFoundation.kCFTypeDictionaryKeyCallBacks,
CoreFoundation.kCFTypeDictionaryValueCallBacks,
)
|
[
"def",
"_cf_dictionary_from_tuples",
"(",
"tuples",
")",
":",
"dictionary_size",
"=",
"len",
"(",
"tuples",
")",
"# We need to get the dictionary keys and values out in the same order.",
"keys",
"=",
"(",
"t",
"[",
"0",
"]",
"for",
"t",
"in",
"tuples",
")",
"values",
"=",
"(",
"t",
"[",
"1",
"]",
"for",
"t",
"in",
"tuples",
")",
"cf_keys",
"=",
"(",
"CoreFoundation",
".",
"CFTypeRef",
"*",
"dictionary_size",
")",
"(",
"*",
"keys",
")",
"cf_values",
"=",
"(",
"CoreFoundation",
".",
"CFTypeRef",
"*",
"dictionary_size",
")",
"(",
"*",
"values",
")",
"return",
"CoreFoundation",
".",
"CFDictionaryCreate",
"(",
"CoreFoundation",
".",
"kCFAllocatorDefault",
",",
"cf_keys",
",",
"cf_values",
",",
"dictionary_size",
",",
"CoreFoundation",
".",
"kCFTypeDictionaryKeyCallBacks",
",",
"CoreFoundation",
".",
"kCFTypeDictionaryValueCallBacks",
",",
")"
] |
Given a list of Python tuples, create an associated CFDictionary.
|
[
"Given",
"a",
"list",
"of",
"Python",
"tuples",
"create",
"an",
"associated",
"CFDictionary",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L37-L56
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
|
_cf_string_to_unicode
|
def _cf_string_to_unicode(value):
"""
Creates a Unicode string from a CFString object. Used entirely for error
reporting.
Yes, it annoys me quite a lot that this function is this complex.
"""
value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p))
string = CoreFoundation.CFStringGetCStringPtr(
value_as_void_p,
CFConst.kCFStringEncodingUTF8
)
if string is None:
buffer = ctypes.create_string_buffer(1024)
result = CoreFoundation.CFStringGetCString(
value_as_void_p,
buffer,
1024,
CFConst.kCFStringEncodingUTF8
)
if not result:
raise OSError('Error copying C string from CFStringRef')
string = buffer.value
if string is not None:
string = string.decode('utf-8')
return string
|
python
|
def _cf_string_to_unicode(value):
"""
Creates a Unicode string from a CFString object. Used entirely for error
reporting.
Yes, it annoys me quite a lot that this function is this complex.
"""
value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p))
string = CoreFoundation.CFStringGetCStringPtr(
value_as_void_p,
CFConst.kCFStringEncodingUTF8
)
if string is None:
buffer = ctypes.create_string_buffer(1024)
result = CoreFoundation.CFStringGetCString(
value_as_void_p,
buffer,
1024,
CFConst.kCFStringEncodingUTF8
)
if not result:
raise OSError('Error copying C string from CFStringRef')
string = buffer.value
if string is not None:
string = string.decode('utf-8')
return string
|
[
"def",
"_cf_string_to_unicode",
"(",
"value",
")",
":",
"value_as_void_p",
"=",
"ctypes",
".",
"cast",
"(",
"value",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_void_p",
")",
")",
"string",
"=",
"CoreFoundation",
".",
"CFStringGetCStringPtr",
"(",
"value_as_void_p",
",",
"CFConst",
".",
"kCFStringEncodingUTF8",
")",
"if",
"string",
"is",
"None",
":",
"buffer",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"1024",
")",
"result",
"=",
"CoreFoundation",
".",
"CFStringGetCString",
"(",
"value_as_void_p",
",",
"buffer",
",",
"1024",
",",
"CFConst",
".",
"kCFStringEncodingUTF8",
")",
"if",
"not",
"result",
":",
"raise",
"OSError",
"(",
"'Error copying C string from CFStringRef'",
")",
"string",
"=",
"buffer",
".",
"value",
"if",
"string",
"is",
"not",
"None",
":",
"string",
"=",
"string",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"string"
] |
Creates a Unicode string from a CFString object. Used entirely for error
reporting.
Yes, it annoys me quite a lot that this function is this complex.
|
[
"Creates",
"a",
"Unicode",
"string",
"from",
"a",
"CFString",
"object",
".",
"Used",
"entirely",
"for",
"error",
"reporting",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L59-L85
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
|
_assert_no_error
|
def _assert_no_error(error, exception_class=None):
"""
Checks the return code and throws an exception if there is an error to
report
"""
if error == 0:
return
cf_error_string = Security.SecCopyErrorMessageString(error, None)
output = _cf_string_to_unicode(cf_error_string)
CoreFoundation.CFRelease(cf_error_string)
if output is None or output == u'':
output = u'OSStatus %s' % error
if exception_class is None:
exception_class = ssl.SSLError
raise exception_class(output)
|
python
|
def _assert_no_error(error, exception_class=None):
"""
Checks the return code and throws an exception if there is an error to
report
"""
if error == 0:
return
cf_error_string = Security.SecCopyErrorMessageString(error, None)
output = _cf_string_to_unicode(cf_error_string)
CoreFoundation.CFRelease(cf_error_string)
if output is None or output == u'':
output = u'OSStatus %s' % error
if exception_class is None:
exception_class = ssl.SSLError
raise exception_class(output)
|
[
"def",
"_assert_no_error",
"(",
"error",
",",
"exception_class",
"=",
"None",
")",
":",
"if",
"error",
"==",
"0",
":",
"return",
"cf_error_string",
"=",
"Security",
".",
"SecCopyErrorMessageString",
"(",
"error",
",",
"None",
")",
"output",
"=",
"_cf_string_to_unicode",
"(",
"cf_error_string",
")",
"CoreFoundation",
".",
"CFRelease",
"(",
"cf_error_string",
")",
"if",
"output",
"is",
"None",
"or",
"output",
"==",
"u''",
":",
"output",
"=",
"u'OSStatus %s'",
"%",
"error",
"if",
"exception_class",
"is",
"None",
":",
"exception_class",
"=",
"ssl",
".",
"SSLError",
"raise",
"exception_class",
"(",
"output",
")"
] |
Checks the return code and throws an exception if there is an error to
report
|
[
"Checks",
"the",
"return",
"code",
"and",
"throws",
"an",
"exception",
"if",
"there",
"is",
"an",
"error",
"to",
"report"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L88-L106
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
|
_cert_array_from_pem
|
def _cert_array_from_pem(pem_bundle):
"""
Given a bundle of certs in PEM format, turns them into a CFArray of certs
that can be used to validate a cert chain.
"""
# Normalize the PEM bundle's line endings.
pem_bundle = pem_bundle.replace(b"\r\n", b"\n")
der_certs = [
base64.b64decode(match.group(1))
for match in _PEM_CERTS_RE.finditer(pem_bundle)
]
if not der_certs:
raise ssl.SSLError("No root certificates specified")
cert_array = CoreFoundation.CFArrayCreateMutable(
CoreFoundation.kCFAllocatorDefault,
0,
ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks)
)
if not cert_array:
raise ssl.SSLError("Unable to allocate memory!")
try:
for der_bytes in der_certs:
certdata = _cf_data_from_bytes(der_bytes)
if not certdata:
raise ssl.SSLError("Unable to allocate memory!")
cert = Security.SecCertificateCreateWithData(
CoreFoundation.kCFAllocatorDefault, certdata
)
CoreFoundation.CFRelease(certdata)
if not cert:
raise ssl.SSLError("Unable to build cert object!")
CoreFoundation.CFArrayAppendValue(cert_array, cert)
CoreFoundation.CFRelease(cert)
except Exception:
# We need to free the array before the exception bubbles further.
# We only want to do that if an error occurs: otherwise, the caller
# should free.
CoreFoundation.CFRelease(cert_array)
return cert_array
|
python
|
def _cert_array_from_pem(pem_bundle):
"""
Given a bundle of certs in PEM format, turns them into a CFArray of certs
that can be used to validate a cert chain.
"""
# Normalize the PEM bundle's line endings.
pem_bundle = pem_bundle.replace(b"\r\n", b"\n")
der_certs = [
base64.b64decode(match.group(1))
for match in _PEM_CERTS_RE.finditer(pem_bundle)
]
if not der_certs:
raise ssl.SSLError("No root certificates specified")
cert_array = CoreFoundation.CFArrayCreateMutable(
CoreFoundation.kCFAllocatorDefault,
0,
ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks)
)
if not cert_array:
raise ssl.SSLError("Unable to allocate memory!")
try:
for der_bytes in der_certs:
certdata = _cf_data_from_bytes(der_bytes)
if not certdata:
raise ssl.SSLError("Unable to allocate memory!")
cert = Security.SecCertificateCreateWithData(
CoreFoundation.kCFAllocatorDefault, certdata
)
CoreFoundation.CFRelease(certdata)
if not cert:
raise ssl.SSLError("Unable to build cert object!")
CoreFoundation.CFArrayAppendValue(cert_array, cert)
CoreFoundation.CFRelease(cert)
except Exception:
# We need to free the array before the exception bubbles further.
# We only want to do that if an error occurs: otherwise, the caller
# should free.
CoreFoundation.CFRelease(cert_array)
return cert_array
|
[
"def",
"_cert_array_from_pem",
"(",
"pem_bundle",
")",
":",
"# Normalize the PEM bundle's line endings.",
"pem_bundle",
"=",
"pem_bundle",
".",
"replace",
"(",
"b\"\\r\\n\"",
",",
"b\"\\n\"",
")",
"der_certs",
"=",
"[",
"base64",
".",
"b64decode",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
"for",
"match",
"in",
"_PEM_CERTS_RE",
".",
"finditer",
"(",
"pem_bundle",
")",
"]",
"if",
"not",
"der_certs",
":",
"raise",
"ssl",
".",
"SSLError",
"(",
"\"No root certificates specified\"",
")",
"cert_array",
"=",
"CoreFoundation",
".",
"CFArrayCreateMutable",
"(",
"CoreFoundation",
".",
"kCFAllocatorDefault",
",",
"0",
",",
"ctypes",
".",
"byref",
"(",
"CoreFoundation",
".",
"kCFTypeArrayCallBacks",
")",
")",
"if",
"not",
"cert_array",
":",
"raise",
"ssl",
".",
"SSLError",
"(",
"\"Unable to allocate memory!\"",
")",
"try",
":",
"for",
"der_bytes",
"in",
"der_certs",
":",
"certdata",
"=",
"_cf_data_from_bytes",
"(",
"der_bytes",
")",
"if",
"not",
"certdata",
":",
"raise",
"ssl",
".",
"SSLError",
"(",
"\"Unable to allocate memory!\"",
")",
"cert",
"=",
"Security",
".",
"SecCertificateCreateWithData",
"(",
"CoreFoundation",
".",
"kCFAllocatorDefault",
",",
"certdata",
")",
"CoreFoundation",
".",
"CFRelease",
"(",
"certdata",
")",
"if",
"not",
"cert",
":",
"raise",
"ssl",
".",
"SSLError",
"(",
"\"Unable to build cert object!\"",
")",
"CoreFoundation",
".",
"CFArrayAppendValue",
"(",
"cert_array",
",",
"cert",
")",
"CoreFoundation",
".",
"CFRelease",
"(",
"cert",
")",
"except",
"Exception",
":",
"# We need to free the array before the exception bubbles further.",
"# We only want to do that if an error occurs: otherwise, the caller",
"# should free.",
"CoreFoundation",
".",
"CFRelease",
"(",
"cert_array",
")",
"return",
"cert_array"
] |
Given a bundle of certs in PEM format, turns them into a CFArray of certs
that can be used to validate a cert chain.
|
[
"Given",
"a",
"bundle",
"of",
"certs",
"in",
"PEM",
"format",
"turns",
"them",
"into",
"a",
"CFArray",
"of",
"certs",
"that",
"can",
"be",
"used",
"to",
"validate",
"a",
"cert",
"chain",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L109-L152
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
|
_temporary_keychain
|
def _temporary_keychain():
"""
This function creates a temporary Mac keychain that we can use to work with
credentials. This keychain uses a one-time password and a temporary file to
store the data. We expect to have one keychain per socket. The returned
SecKeychainRef must be freed by the caller, including calling
SecKeychainDelete.
Returns a tuple of the SecKeychainRef and the path to the temporary
directory that contains it.
"""
# Unfortunately, SecKeychainCreate requires a path to a keychain. This
# means we cannot use mkstemp to use a generic temporary file. Instead,
# we're going to create a temporary directory and a filename to use there.
# This filename will be 8 random bytes expanded into base64. We also need
# some random bytes to password-protect the keychain we're creating, so we
# ask for 40 random bytes.
random_bytes = os.urandom(40)
filename = base64.b16encode(random_bytes[:8]).decode('utf-8')
password = base64.b16encode(random_bytes[8:]) # Must be valid UTF-8
tempdirectory = tempfile.mkdtemp()
keychain_path = os.path.join(tempdirectory, filename).encode('utf-8')
# We now want to create the keychain itself.
keychain = Security.SecKeychainRef()
status = Security.SecKeychainCreate(
keychain_path,
len(password),
password,
False,
None,
ctypes.byref(keychain)
)
_assert_no_error(status)
# Having created the keychain, we want to pass it off to the caller.
return keychain, tempdirectory
|
python
|
def _temporary_keychain():
"""
This function creates a temporary Mac keychain that we can use to work with
credentials. This keychain uses a one-time password and a temporary file to
store the data. We expect to have one keychain per socket. The returned
SecKeychainRef must be freed by the caller, including calling
SecKeychainDelete.
Returns a tuple of the SecKeychainRef and the path to the temporary
directory that contains it.
"""
# Unfortunately, SecKeychainCreate requires a path to a keychain. This
# means we cannot use mkstemp to use a generic temporary file. Instead,
# we're going to create a temporary directory and a filename to use there.
# This filename will be 8 random bytes expanded into base64. We also need
# some random bytes to password-protect the keychain we're creating, so we
# ask for 40 random bytes.
random_bytes = os.urandom(40)
filename = base64.b16encode(random_bytes[:8]).decode('utf-8')
password = base64.b16encode(random_bytes[8:]) # Must be valid UTF-8
tempdirectory = tempfile.mkdtemp()
keychain_path = os.path.join(tempdirectory, filename).encode('utf-8')
# We now want to create the keychain itself.
keychain = Security.SecKeychainRef()
status = Security.SecKeychainCreate(
keychain_path,
len(password),
password,
False,
None,
ctypes.byref(keychain)
)
_assert_no_error(status)
# Having created the keychain, we want to pass it off to the caller.
return keychain, tempdirectory
|
[
"def",
"_temporary_keychain",
"(",
")",
":",
"# Unfortunately, SecKeychainCreate requires a path to a keychain. This",
"# means we cannot use mkstemp to use a generic temporary file. Instead,",
"# we're going to create a temporary directory and a filename to use there.",
"# This filename will be 8 random bytes expanded into base64. We also need",
"# some random bytes to password-protect the keychain we're creating, so we",
"# ask for 40 random bytes.",
"random_bytes",
"=",
"os",
".",
"urandom",
"(",
"40",
")",
"filename",
"=",
"base64",
".",
"b16encode",
"(",
"random_bytes",
"[",
":",
"8",
"]",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"password",
"=",
"base64",
".",
"b16encode",
"(",
"random_bytes",
"[",
"8",
":",
"]",
")",
"# Must be valid UTF-8",
"tempdirectory",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"keychain_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempdirectory",
",",
"filename",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"# We now want to create the keychain itself.",
"keychain",
"=",
"Security",
".",
"SecKeychainRef",
"(",
")",
"status",
"=",
"Security",
".",
"SecKeychainCreate",
"(",
"keychain_path",
",",
"len",
"(",
"password",
")",
",",
"password",
",",
"False",
",",
"None",
",",
"ctypes",
".",
"byref",
"(",
"keychain",
")",
")",
"_assert_no_error",
"(",
"status",
")",
"# Having created the keychain, we want to pass it off to the caller.",
"return",
"keychain",
",",
"tempdirectory"
] |
This function creates a temporary Mac keychain that we can use to work with
credentials. This keychain uses a one-time password and a temporary file to
store the data. We expect to have one keychain per socket. The returned
SecKeychainRef must be freed by the caller, including calling
SecKeychainDelete.
Returns a tuple of the SecKeychainRef and the path to the temporary
directory that contains it.
|
[
"This",
"function",
"creates",
"a",
"temporary",
"Mac",
"keychain",
"that",
"we",
"can",
"use",
"to",
"work",
"with",
"credentials",
".",
"This",
"keychain",
"uses",
"a",
"one",
"-",
"time",
"password",
"and",
"a",
"temporary",
"file",
"to",
"store",
"the",
"data",
".",
"We",
"expect",
"to",
"have",
"one",
"keychain",
"per",
"socket",
".",
"The",
"returned",
"SecKeychainRef",
"must",
"be",
"freed",
"by",
"the",
"caller",
"including",
"calling",
"SecKeychainDelete",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L171-L208
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
|
_load_items_from_file
|
def _load_items_from_file(keychain, path):
"""
Given a single file, loads all the trust objects from it into arrays and
the keychain.
Returns a tuple of lists: the first list is a list of identities, the
second a list of certs.
"""
certificates = []
identities = []
result_array = None
with open(path, 'rb') as f:
raw_filedata = f.read()
try:
filedata = CoreFoundation.CFDataCreate(
CoreFoundation.kCFAllocatorDefault,
raw_filedata,
len(raw_filedata)
)
result_array = CoreFoundation.CFArrayRef()
result = Security.SecItemImport(
filedata, # cert data
None, # Filename, leaving it out for now
None, # What the type of the file is, we don't care
None, # what's in the file, we don't care
0, # import flags
None, # key params, can include passphrase in the future
keychain, # The keychain to insert into
ctypes.byref(result_array) # Results
)
_assert_no_error(result)
# A CFArray is not very useful to us as an intermediary
# representation, so we are going to extract the objects we want
# and then free the array. We don't need to keep hold of keys: the
# keychain already has them!
result_count = CoreFoundation.CFArrayGetCount(result_array)
for index in range(result_count):
item = CoreFoundation.CFArrayGetValueAtIndex(
result_array, index
)
item = ctypes.cast(item, CoreFoundation.CFTypeRef)
if _is_cert(item):
CoreFoundation.CFRetain(item)
certificates.append(item)
elif _is_identity(item):
CoreFoundation.CFRetain(item)
identities.append(item)
finally:
if result_array:
CoreFoundation.CFRelease(result_array)
CoreFoundation.CFRelease(filedata)
return (identities, certificates)
|
python
|
def _load_items_from_file(keychain, path):
"""
Given a single file, loads all the trust objects from it into arrays and
the keychain.
Returns a tuple of lists: the first list is a list of identities, the
second a list of certs.
"""
certificates = []
identities = []
result_array = None
with open(path, 'rb') as f:
raw_filedata = f.read()
try:
filedata = CoreFoundation.CFDataCreate(
CoreFoundation.kCFAllocatorDefault,
raw_filedata,
len(raw_filedata)
)
result_array = CoreFoundation.CFArrayRef()
result = Security.SecItemImport(
filedata, # cert data
None, # Filename, leaving it out for now
None, # What the type of the file is, we don't care
None, # what's in the file, we don't care
0, # import flags
None, # key params, can include passphrase in the future
keychain, # The keychain to insert into
ctypes.byref(result_array) # Results
)
_assert_no_error(result)
# A CFArray is not very useful to us as an intermediary
# representation, so we are going to extract the objects we want
# and then free the array. We don't need to keep hold of keys: the
# keychain already has them!
result_count = CoreFoundation.CFArrayGetCount(result_array)
for index in range(result_count):
item = CoreFoundation.CFArrayGetValueAtIndex(
result_array, index
)
item = ctypes.cast(item, CoreFoundation.CFTypeRef)
if _is_cert(item):
CoreFoundation.CFRetain(item)
certificates.append(item)
elif _is_identity(item):
CoreFoundation.CFRetain(item)
identities.append(item)
finally:
if result_array:
CoreFoundation.CFRelease(result_array)
CoreFoundation.CFRelease(filedata)
return (identities, certificates)
|
[
"def",
"_load_items_from_file",
"(",
"keychain",
",",
"path",
")",
":",
"certificates",
"=",
"[",
"]",
"identities",
"=",
"[",
"]",
"result_array",
"=",
"None",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
"raw_filedata",
"=",
"f",
".",
"read",
"(",
")",
"try",
":",
"filedata",
"=",
"CoreFoundation",
".",
"CFDataCreate",
"(",
"CoreFoundation",
".",
"kCFAllocatorDefault",
",",
"raw_filedata",
",",
"len",
"(",
"raw_filedata",
")",
")",
"result_array",
"=",
"CoreFoundation",
".",
"CFArrayRef",
"(",
")",
"result",
"=",
"Security",
".",
"SecItemImport",
"(",
"filedata",
",",
"# cert data",
"None",
",",
"# Filename, leaving it out for now",
"None",
",",
"# What the type of the file is, we don't care",
"None",
",",
"# what's in the file, we don't care",
"0",
",",
"# import flags",
"None",
",",
"# key params, can include passphrase in the future",
"keychain",
",",
"# The keychain to insert into",
"ctypes",
".",
"byref",
"(",
"result_array",
")",
"# Results",
")",
"_assert_no_error",
"(",
"result",
")",
"# A CFArray is not very useful to us as an intermediary",
"# representation, so we are going to extract the objects we want",
"# and then free the array. We don't need to keep hold of keys: the",
"# keychain already has them!",
"result_count",
"=",
"CoreFoundation",
".",
"CFArrayGetCount",
"(",
"result_array",
")",
"for",
"index",
"in",
"range",
"(",
"result_count",
")",
":",
"item",
"=",
"CoreFoundation",
".",
"CFArrayGetValueAtIndex",
"(",
"result_array",
",",
"index",
")",
"item",
"=",
"ctypes",
".",
"cast",
"(",
"item",
",",
"CoreFoundation",
".",
"CFTypeRef",
")",
"if",
"_is_cert",
"(",
"item",
")",
":",
"CoreFoundation",
".",
"CFRetain",
"(",
"item",
")",
"certificates",
".",
"append",
"(",
"item",
")",
"elif",
"_is_identity",
"(",
"item",
")",
":",
"CoreFoundation",
".",
"CFRetain",
"(",
"item",
")",
"identities",
".",
"append",
"(",
"item",
")",
"finally",
":",
"if",
"result_array",
":",
"CoreFoundation",
".",
"CFRelease",
"(",
"result_array",
")",
"CoreFoundation",
".",
"CFRelease",
"(",
"filedata",
")",
"return",
"(",
"identities",
",",
"certificates",
")"
] |
Given a single file, loads all the trust objects from it into arrays and
the keychain.
Returns a tuple of lists: the first list is a list of identities, the
second a list of certs.
|
[
"Given",
"a",
"single",
"file",
"loads",
"all",
"the",
"trust",
"objects",
"from",
"it",
"into",
"arrays",
"and",
"the",
"keychain",
".",
"Returns",
"a",
"tuple",
"of",
"lists",
":",
"the",
"first",
"list",
"is",
"a",
"list",
"of",
"identities",
"the",
"second",
"a",
"list",
"of",
"certs",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L211-L267
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
|
_load_client_cert_chain
|
def _load_client_cert_chain(keychain, *paths):
"""
Load certificates and maybe keys from a number of files. Has the end goal
of returning a CFArray containing one SecIdentityRef, and then zero or more
SecCertificateRef objects, suitable for use as a client certificate trust
chain.
"""
# Ok, the strategy.
#
# This relies on knowing that macOS will not give you a SecIdentityRef
# unless you have imported a key into a keychain. This is a somewhat
# artificial limitation of macOS (for example, it doesn't necessarily
# affect iOS), but there is nothing inside Security.framework that lets you
# get a SecIdentityRef without having a key in a keychain.
#
# So the policy here is we take all the files and iterate them in order.
# Each one will use SecItemImport to have one or more objects loaded from
# it. We will also point at a keychain that macOS can use to work with the
# private key.
#
# Once we have all the objects, we'll check what we actually have. If we
# already have a SecIdentityRef in hand, fab: we'll use that. Otherwise,
# we'll take the first certificate (which we assume to be our leaf) and
# ask the keychain to give us a SecIdentityRef with that cert's associated
# key.
#
# We'll then return a CFArray containing the trust chain: one
# SecIdentityRef and then zero-or-more SecCertificateRef objects. The
# responsibility for freeing this CFArray will be with the caller. This
# CFArray must remain alive for the entire connection, so in practice it
# will be stored with a single SSLSocket, along with the reference to the
# keychain.
certificates = []
identities = []
# Filter out bad paths.
paths = (path for path in paths if path)
try:
for file_path in paths:
new_identities, new_certs = _load_items_from_file(
keychain, file_path
)
identities.extend(new_identities)
certificates.extend(new_certs)
# Ok, we have everything. The question is: do we have an identity? If
# not, we want to grab one from the first cert we have.
if not identities:
new_identity = Security.SecIdentityRef()
status = Security.SecIdentityCreateWithCertificate(
keychain,
certificates[0],
ctypes.byref(new_identity)
)
_assert_no_error(status)
identities.append(new_identity)
# We now want to release the original certificate, as we no longer
# need it.
CoreFoundation.CFRelease(certificates.pop(0))
# We now need to build a new CFArray that holds the trust chain.
trust_chain = CoreFoundation.CFArrayCreateMutable(
CoreFoundation.kCFAllocatorDefault,
0,
ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),
)
for item in itertools.chain(identities, certificates):
# ArrayAppendValue does a CFRetain on the item. That's fine,
# because the finally block will release our other refs to them.
CoreFoundation.CFArrayAppendValue(trust_chain, item)
return trust_chain
finally:
for obj in itertools.chain(identities, certificates):
CoreFoundation.CFRelease(obj)
|
python
|
def _load_client_cert_chain(keychain, *paths):
"""
Load certificates and maybe keys from a number of files. Has the end goal
of returning a CFArray containing one SecIdentityRef, and then zero or more
SecCertificateRef objects, suitable for use as a client certificate trust
chain.
"""
# Ok, the strategy.
#
# This relies on knowing that macOS will not give you a SecIdentityRef
# unless you have imported a key into a keychain. This is a somewhat
# artificial limitation of macOS (for example, it doesn't necessarily
# affect iOS), but there is nothing inside Security.framework that lets you
# get a SecIdentityRef without having a key in a keychain.
#
# So the policy here is we take all the files and iterate them in order.
# Each one will use SecItemImport to have one or more objects loaded from
# it. We will also point at a keychain that macOS can use to work with the
# private key.
#
# Once we have all the objects, we'll check what we actually have. If we
# already have a SecIdentityRef in hand, fab: we'll use that. Otherwise,
# we'll take the first certificate (which we assume to be our leaf) and
# ask the keychain to give us a SecIdentityRef with that cert's associated
# key.
#
# We'll then return a CFArray containing the trust chain: one
# SecIdentityRef and then zero-or-more SecCertificateRef objects. The
# responsibility for freeing this CFArray will be with the caller. This
# CFArray must remain alive for the entire connection, so in practice it
# will be stored with a single SSLSocket, along with the reference to the
# keychain.
certificates = []
identities = []
# Filter out bad paths.
paths = (path for path in paths if path)
try:
for file_path in paths:
new_identities, new_certs = _load_items_from_file(
keychain, file_path
)
identities.extend(new_identities)
certificates.extend(new_certs)
# Ok, we have everything. The question is: do we have an identity? If
# not, we want to grab one from the first cert we have.
if not identities:
new_identity = Security.SecIdentityRef()
status = Security.SecIdentityCreateWithCertificate(
keychain,
certificates[0],
ctypes.byref(new_identity)
)
_assert_no_error(status)
identities.append(new_identity)
# We now want to release the original certificate, as we no longer
# need it.
CoreFoundation.CFRelease(certificates.pop(0))
# We now need to build a new CFArray that holds the trust chain.
trust_chain = CoreFoundation.CFArrayCreateMutable(
CoreFoundation.kCFAllocatorDefault,
0,
ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),
)
for item in itertools.chain(identities, certificates):
# ArrayAppendValue does a CFRetain on the item. That's fine,
# because the finally block will release our other refs to them.
CoreFoundation.CFArrayAppendValue(trust_chain, item)
return trust_chain
finally:
for obj in itertools.chain(identities, certificates):
CoreFoundation.CFRelease(obj)
|
[
"def",
"_load_client_cert_chain",
"(",
"keychain",
",",
"*",
"paths",
")",
":",
"# Ok, the strategy.",
"#",
"# This relies on knowing that macOS will not give you a SecIdentityRef",
"# unless you have imported a key into a keychain. This is a somewhat",
"# artificial limitation of macOS (for example, it doesn't necessarily",
"# affect iOS), but there is nothing inside Security.framework that lets you",
"# get a SecIdentityRef without having a key in a keychain.",
"#",
"# So the policy here is we take all the files and iterate them in order.",
"# Each one will use SecItemImport to have one or more objects loaded from",
"# it. We will also point at a keychain that macOS can use to work with the",
"# private key.",
"#",
"# Once we have all the objects, we'll check what we actually have. If we",
"# already have a SecIdentityRef in hand, fab: we'll use that. Otherwise,",
"# we'll take the first certificate (which we assume to be our leaf) and",
"# ask the keychain to give us a SecIdentityRef with that cert's associated",
"# key.",
"#",
"# We'll then return a CFArray containing the trust chain: one",
"# SecIdentityRef and then zero-or-more SecCertificateRef objects. The",
"# responsibility for freeing this CFArray will be with the caller. This",
"# CFArray must remain alive for the entire connection, so in practice it",
"# will be stored with a single SSLSocket, along with the reference to the",
"# keychain.",
"certificates",
"=",
"[",
"]",
"identities",
"=",
"[",
"]",
"# Filter out bad paths.",
"paths",
"=",
"(",
"path",
"for",
"path",
"in",
"paths",
"if",
"path",
")",
"try",
":",
"for",
"file_path",
"in",
"paths",
":",
"new_identities",
",",
"new_certs",
"=",
"_load_items_from_file",
"(",
"keychain",
",",
"file_path",
")",
"identities",
".",
"extend",
"(",
"new_identities",
")",
"certificates",
".",
"extend",
"(",
"new_certs",
")",
"# Ok, we have everything. The question is: do we have an identity? If",
"# not, we want to grab one from the first cert we have.",
"if",
"not",
"identities",
":",
"new_identity",
"=",
"Security",
".",
"SecIdentityRef",
"(",
")",
"status",
"=",
"Security",
".",
"SecIdentityCreateWithCertificate",
"(",
"keychain",
",",
"certificates",
"[",
"0",
"]",
",",
"ctypes",
".",
"byref",
"(",
"new_identity",
")",
")",
"_assert_no_error",
"(",
"status",
")",
"identities",
".",
"append",
"(",
"new_identity",
")",
"# We now want to release the original certificate, as we no longer",
"# need it.",
"CoreFoundation",
".",
"CFRelease",
"(",
"certificates",
".",
"pop",
"(",
"0",
")",
")",
"# We now need to build a new CFArray that holds the trust chain.",
"trust_chain",
"=",
"CoreFoundation",
".",
"CFArrayCreateMutable",
"(",
"CoreFoundation",
".",
"kCFAllocatorDefault",
",",
"0",
",",
"ctypes",
".",
"byref",
"(",
"CoreFoundation",
".",
"kCFTypeArrayCallBacks",
")",
",",
")",
"for",
"item",
"in",
"itertools",
".",
"chain",
"(",
"identities",
",",
"certificates",
")",
":",
"# ArrayAppendValue does a CFRetain on the item. That's fine,",
"# because the finally block will release our other refs to them.",
"CoreFoundation",
".",
"CFArrayAppendValue",
"(",
"trust_chain",
",",
"item",
")",
"return",
"trust_chain",
"finally",
":",
"for",
"obj",
"in",
"itertools",
".",
"chain",
"(",
"identities",
",",
"certificates",
")",
":",
"CoreFoundation",
".",
"CFRelease",
"(",
"obj",
")"
] |
Load certificates and maybe keys from a number of files. Has the end goal
of returning a CFArray containing one SecIdentityRef, and then zero or more
SecCertificateRef objects, suitable for use as a client certificate trust
chain.
|
[
"Load",
"certificates",
"and",
"maybe",
"keys",
"from",
"a",
"number",
"of",
"files",
".",
"Has",
"the",
"end",
"goal",
"of",
"returning",
"a",
"CFArray",
"containing",
"one",
"SecIdentityRef",
"and",
"then",
"zero",
"or",
"more",
"SecCertificateRef",
"objects",
"suitable",
"for",
"use",
"as",
"a",
"client",
"certificate",
"trust",
"chain",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L270-L346
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/response.py
|
HTTPResponse.get_redirect_location
|
def get_redirect_location(self):
"""
Should we redirect and where to?
:returns: Truthy redirect location string if we got a redirect status
code and valid location. ``None`` if redirect status and no
location. ``False`` if not a redirect status code.
"""
if self.status in self.REDIRECT_STATUSES:
return self.headers.get('location')
return False
|
python
|
def get_redirect_location(self):
"""
Should we redirect and where to?
:returns: Truthy redirect location string if we got a redirect status
code and valid location. ``None`` if redirect status and no
location. ``False`` if not a redirect status code.
"""
if self.status in self.REDIRECT_STATUSES:
return self.headers.get('location')
return False
|
[
"def",
"get_redirect_location",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"in",
"self",
".",
"REDIRECT_STATUSES",
":",
"return",
"self",
".",
"headers",
".",
"get",
"(",
"'location'",
")",
"return",
"False"
] |
Should we redirect and where to?
:returns: Truthy redirect location string if we got a redirect status
code and valid location. ``None`` if redirect status and no
location. ``False`` if not a redirect status code.
|
[
"Should",
"we",
"redirect",
"and",
"where",
"to?"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L211-L222
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/response.py
|
HTTPResponse._init_length
|
def _init_length(self, request_method):
"""
Set initial length value for Response content if available.
"""
length = self.headers.get('content-length')
if length is not None:
if self.chunked:
# This Response will fail with an IncompleteRead if it can't be
# received as chunked. This method falls back to attempt reading
# the response before raising an exception.
log.warning("Received response with both Content-Length and "
"Transfer-Encoding set. This is expressly forbidden "
"by RFC 7230 sec 3.3.2. Ignoring Content-Length and "
"attempting to process response as Transfer-Encoding: "
"chunked.")
return None
try:
# RFC 7230 section 3.3.2 specifies multiple content lengths can
# be sent in a single Content-Length header
# (e.g. Content-Length: 42, 42). This line ensures the values
# are all valid ints and that as long as the `set` length is 1,
# all values are the same. Otherwise, the header is invalid.
lengths = set([int(val) for val in length.split(',')])
if len(lengths) > 1:
raise InvalidHeader("Content-Length contained multiple "
"unmatching values (%s)" % length)
length = lengths.pop()
except ValueError:
length = None
else:
if length < 0:
length = None
# Convert status to int for comparison
# In some cases, httplib returns a status of "_UNKNOWN"
try:
status = int(self.status)
except ValueError:
status = 0
# Check for responses that shouldn't include a body
if status in (204, 304) or 100 <= status < 200 or request_method == 'HEAD':
length = 0
return length
|
python
|
def _init_length(self, request_method):
"""
Set initial length value for Response content if available.
"""
length = self.headers.get('content-length')
if length is not None:
if self.chunked:
# This Response will fail with an IncompleteRead if it can't be
# received as chunked. This method falls back to attempt reading
# the response before raising an exception.
log.warning("Received response with both Content-Length and "
"Transfer-Encoding set. This is expressly forbidden "
"by RFC 7230 sec 3.3.2. Ignoring Content-Length and "
"attempting to process response as Transfer-Encoding: "
"chunked.")
return None
try:
# RFC 7230 section 3.3.2 specifies multiple content lengths can
# be sent in a single Content-Length header
# (e.g. Content-Length: 42, 42). This line ensures the values
# are all valid ints and that as long as the `set` length is 1,
# all values are the same. Otherwise, the header is invalid.
lengths = set([int(val) for val in length.split(',')])
if len(lengths) > 1:
raise InvalidHeader("Content-Length contained multiple "
"unmatching values (%s)" % length)
length = lengths.pop()
except ValueError:
length = None
else:
if length < 0:
length = None
# Convert status to int for comparison
# In some cases, httplib returns a status of "_UNKNOWN"
try:
status = int(self.status)
except ValueError:
status = 0
# Check for responses that shouldn't include a body
if status in (204, 304) or 100 <= status < 200 or request_method == 'HEAD':
length = 0
return length
|
[
"def",
"_init_length",
"(",
"self",
",",
"request_method",
")",
":",
"length",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'content-length'",
")",
"if",
"length",
"is",
"not",
"None",
":",
"if",
"self",
".",
"chunked",
":",
"# This Response will fail with an IncompleteRead if it can't be",
"# received as chunked. This method falls back to attempt reading",
"# the response before raising an exception.",
"log",
".",
"warning",
"(",
"\"Received response with both Content-Length and \"",
"\"Transfer-Encoding set. This is expressly forbidden \"",
"\"by RFC 7230 sec 3.3.2. Ignoring Content-Length and \"",
"\"attempting to process response as Transfer-Encoding: \"",
"\"chunked.\"",
")",
"return",
"None",
"try",
":",
"# RFC 7230 section 3.3.2 specifies multiple content lengths can",
"# be sent in a single Content-Length header",
"# (e.g. Content-Length: 42, 42). This line ensures the values",
"# are all valid ints and that as long as the `set` length is 1,",
"# all values are the same. Otherwise, the header is invalid.",
"lengths",
"=",
"set",
"(",
"[",
"int",
"(",
"val",
")",
"for",
"val",
"in",
"length",
".",
"split",
"(",
"','",
")",
"]",
")",
"if",
"len",
"(",
"lengths",
")",
">",
"1",
":",
"raise",
"InvalidHeader",
"(",
"\"Content-Length contained multiple \"",
"\"unmatching values (%s)\"",
"%",
"length",
")",
"length",
"=",
"lengths",
".",
"pop",
"(",
")",
"except",
"ValueError",
":",
"length",
"=",
"None",
"else",
":",
"if",
"length",
"<",
"0",
":",
"length",
"=",
"None",
"# Convert status to int for comparison",
"# In some cases, httplib returns a status of \"_UNKNOWN\"",
"try",
":",
"status",
"=",
"int",
"(",
"self",
".",
"status",
")",
"except",
"ValueError",
":",
"status",
"=",
"0",
"# Check for responses that shouldn't include a body",
"if",
"status",
"in",
"(",
"204",
",",
"304",
")",
"or",
"100",
"<=",
"status",
"<",
"200",
"or",
"request_method",
"==",
"'HEAD'",
":",
"length",
"=",
"0",
"return",
"length"
] |
Set initial length value for Response content if available.
|
[
"Set",
"initial",
"length",
"value",
"for",
"Response",
"content",
"if",
"available",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L255-L301
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/response.py
|
HTTPResponse._init_decoder
|
def _init_decoder(self):
"""
Set-up the _decoder attribute if necessary.
"""
# Note: content-encoding value should be case-insensitive, per RFC 7230
# Section 3.2
content_encoding = self.headers.get('content-encoding', '').lower()
if self._decoder is None:
if content_encoding in self.CONTENT_DECODERS:
self._decoder = _get_decoder(content_encoding)
elif ',' in content_encoding:
encodings = [e.strip() for e in content_encoding.split(',') if e.strip() in self.CONTENT_DECODERS]
if len(encodings):
self._decoder = _get_decoder(content_encoding)
|
python
|
def _init_decoder(self):
"""
Set-up the _decoder attribute if necessary.
"""
# Note: content-encoding value should be case-insensitive, per RFC 7230
# Section 3.2
content_encoding = self.headers.get('content-encoding', '').lower()
if self._decoder is None:
if content_encoding in self.CONTENT_DECODERS:
self._decoder = _get_decoder(content_encoding)
elif ',' in content_encoding:
encodings = [e.strip() for e in content_encoding.split(',') if e.strip() in self.CONTENT_DECODERS]
if len(encodings):
self._decoder = _get_decoder(content_encoding)
|
[
"def",
"_init_decoder",
"(",
"self",
")",
":",
"# Note: content-encoding value should be case-insensitive, per RFC 7230",
"# Section 3.2",
"content_encoding",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'content-encoding'",
",",
"''",
")",
".",
"lower",
"(",
")",
"if",
"self",
".",
"_decoder",
"is",
"None",
":",
"if",
"content_encoding",
"in",
"self",
".",
"CONTENT_DECODERS",
":",
"self",
".",
"_decoder",
"=",
"_get_decoder",
"(",
"content_encoding",
")",
"elif",
"','",
"in",
"content_encoding",
":",
"encodings",
"=",
"[",
"e",
".",
"strip",
"(",
")",
"for",
"e",
"in",
"content_encoding",
".",
"split",
"(",
"','",
")",
"if",
"e",
".",
"strip",
"(",
")",
"in",
"self",
".",
"CONTENT_DECODERS",
"]",
"if",
"len",
"(",
"encodings",
")",
":",
"self",
".",
"_decoder",
"=",
"_get_decoder",
"(",
"content_encoding",
")"
] |
Set-up the _decoder attribute if necessary.
|
[
"Set",
"-",
"up",
"the",
"_decoder",
"attribute",
"if",
"necessary",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L303-L316
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/response.py
|
HTTPResponse._flush_decoder
|
def _flush_decoder(self):
"""
Flushes the decoder. Should only be called if the decoder is actually
being used.
"""
if self._decoder:
buf = self._decoder.decompress(b'')
return buf + self._decoder.flush()
return b''
|
python
|
def _flush_decoder(self):
"""
Flushes the decoder. Should only be called if the decoder is actually
being used.
"""
if self._decoder:
buf = self._decoder.decompress(b'')
return buf + self._decoder.flush()
return b''
|
[
"def",
"_flush_decoder",
"(",
"self",
")",
":",
"if",
"self",
".",
"_decoder",
":",
"buf",
"=",
"self",
".",
"_decoder",
".",
"decompress",
"(",
"b''",
")",
"return",
"buf",
"+",
"self",
".",
"_decoder",
".",
"flush",
"(",
")",
"return",
"b''"
] |
Flushes the decoder. Should only be called if the decoder is actually
being used.
|
[
"Flushes",
"the",
"decoder",
".",
"Should",
"only",
"be",
"called",
"if",
"the",
"decoder",
"is",
"actually",
"being",
"used",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L336-L345
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/response.py
|
HTTPResponse._error_catcher
|
def _error_catcher(self):
"""
Catch low-level python exceptions, instead re-raising urllib3
variants, so that low-level exceptions are not leaked in the
high-level api.
On exit, release the connection back to the pool.
"""
clean_exit = False
try:
try:
yield
except SocketTimeout:
# FIXME: Ideally we'd like to include the url in the ReadTimeoutError but
# there is yet no clean way to get at it from this context.
raise ReadTimeoutError(self._pool, None, 'Read timed out.')
except BaseSSLError as e:
# FIXME: Is there a better way to differentiate between SSLErrors?
if 'read operation timed out' not in str(e): # Defensive:
# This shouldn't happen but just in case we're missing an edge
# case, let's avoid swallowing SSL errors.
raise
raise ReadTimeoutError(self._pool, None, 'Read timed out.')
except (HTTPException, SocketError) as e:
# This includes IncompleteRead.
raise ProtocolError('Connection broken: %r' % e, e)
# If no exception is thrown, we should avoid cleaning up
# unnecessarily.
clean_exit = True
finally:
# If we didn't terminate cleanly, we need to throw away our
# connection.
if not clean_exit:
# The response may not be closed but we're not going to use it
# anymore so close it now to ensure that the connection is
# released back to the pool.
if self._original_response:
self._original_response.close()
# Closing the response may not actually be sufficient to close
# everything, so if we have a hold of the connection close that
# too.
if self._connection:
self._connection.close()
# If we hold the original response but it's closed now, we should
# return the connection back to the pool.
if self._original_response and self._original_response.isclosed():
self.release_conn()
|
python
|
def _error_catcher(self):
"""
Catch low-level python exceptions, instead re-raising urllib3
variants, so that low-level exceptions are not leaked in the
high-level api.
On exit, release the connection back to the pool.
"""
clean_exit = False
try:
try:
yield
except SocketTimeout:
# FIXME: Ideally we'd like to include the url in the ReadTimeoutError but
# there is yet no clean way to get at it from this context.
raise ReadTimeoutError(self._pool, None, 'Read timed out.')
except BaseSSLError as e:
# FIXME: Is there a better way to differentiate between SSLErrors?
if 'read operation timed out' not in str(e): # Defensive:
# This shouldn't happen but just in case we're missing an edge
# case, let's avoid swallowing SSL errors.
raise
raise ReadTimeoutError(self._pool, None, 'Read timed out.')
except (HTTPException, SocketError) as e:
# This includes IncompleteRead.
raise ProtocolError('Connection broken: %r' % e, e)
# If no exception is thrown, we should avoid cleaning up
# unnecessarily.
clean_exit = True
finally:
# If we didn't terminate cleanly, we need to throw away our
# connection.
if not clean_exit:
# The response may not be closed but we're not going to use it
# anymore so close it now to ensure that the connection is
# released back to the pool.
if self._original_response:
self._original_response.close()
# Closing the response may not actually be sufficient to close
# everything, so if we have a hold of the connection close that
# too.
if self._connection:
self._connection.close()
# If we hold the original response but it's closed now, we should
# return the connection back to the pool.
if self._original_response and self._original_response.isclosed():
self.release_conn()
|
[
"def",
"_error_catcher",
"(",
"self",
")",
":",
"clean_exit",
"=",
"False",
"try",
":",
"try",
":",
"yield",
"except",
"SocketTimeout",
":",
"# FIXME: Ideally we'd like to include the url in the ReadTimeoutError but",
"# there is yet no clean way to get at it from this context.",
"raise",
"ReadTimeoutError",
"(",
"self",
".",
"_pool",
",",
"None",
",",
"'Read timed out.'",
")",
"except",
"BaseSSLError",
"as",
"e",
":",
"# FIXME: Is there a better way to differentiate between SSLErrors?",
"if",
"'read operation timed out'",
"not",
"in",
"str",
"(",
"e",
")",
":",
"# Defensive:",
"# This shouldn't happen but just in case we're missing an edge",
"# case, let's avoid swallowing SSL errors.",
"raise",
"raise",
"ReadTimeoutError",
"(",
"self",
".",
"_pool",
",",
"None",
",",
"'Read timed out.'",
")",
"except",
"(",
"HTTPException",
",",
"SocketError",
")",
"as",
"e",
":",
"# This includes IncompleteRead.",
"raise",
"ProtocolError",
"(",
"'Connection broken: %r'",
"%",
"e",
",",
"e",
")",
"# If no exception is thrown, we should avoid cleaning up",
"# unnecessarily.",
"clean_exit",
"=",
"True",
"finally",
":",
"# If we didn't terminate cleanly, we need to throw away our",
"# connection.",
"if",
"not",
"clean_exit",
":",
"# The response may not be closed but we're not going to use it",
"# anymore so close it now to ensure that the connection is",
"# released back to the pool.",
"if",
"self",
".",
"_original_response",
":",
"self",
".",
"_original_response",
".",
"close",
"(",
")",
"# Closing the response may not actually be sufficient to close",
"# everything, so if we have a hold of the connection close that",
"# too.",
"if",
"self",
".",
"_connection",
":",
"self",
".",
"_connection",
".",
"close",
"(",
")",
"# If we hold the original response but it's closed now, we should",
"# return the connection back to the pool.",
"if",
"self",
".",
"_original_response",
"and",
"self",
".",
"_original_response",
".",
"isclosed",
"(",
")",
":",
"self",
".",
"release_conn",
"(",
")"
] |
Catch low-level python exceptions, instead re-raising urllib3
variants, so that low-level exceptions are not leaked in the
high-level api.
On exit, release the connection back to the pool.
|
[
"Catch",
"low",
"-",
"level",
"python",
"exceptions",
"instead",
"re",
"-",
"raising",
"urllib3",
"variants",
"so",
"that",
"low",
"-",
"level",
"exceptions",
"are",
"not",
"leaked",
"in",
"the",
"high",
"-",
"level",
"api",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L348-L402
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/response.py
|
HTTPResponse.read
|
def read(self, amt=None, decode_content=None, cache_content=False):
"""
Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
:param cache_content:
If True, will save the returned data such that the same result is
returned despite of the state of the underlying file object. This
is useful if you want the ``.data`` property to continue working
after having ``.read()`` the file object. (Overridden if ``amt`` is
set.)
"""
self._init_decoder()
if decode_content is None:
decode_content = self.decode_content
if self._fp is None:
return
flush_decoder = False
data = None
with self._error_catcher():
if amt is None:
# cStringIO doesn't like amt=None
data = self._fp.read()
flush_decoder = True
else:
cache_content = False
data = self._fp.read(amt)
if amt != 0 and not data: # Platform-specific: Buggy versions of Python.
# Close the connection when no data is returned
#
# This is redundant to what httplib/http.client _should_
# already do. However, versions of python released before
# December 15, 2012 (http://bugs.python.org/issue16298) do
# not properly close the connection in all cases. There is
# no harm in redundantly calling close.
self._fp.close()
flush_decoder = True
if self.enforce_content_length and self.length_remaining not in (0, None):
# This is an edge case that httplib failed to cover due
# to concerns of backward compatibility. We're
# addressing it here to make sure IncompleteRead is
# raised during streaming, so all calls with incorrect
# Content-Length are caught.
raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
if data:
self._fp_bytes_read += len(data)
if self.length_remaining is not None:
self.length_remaining -= len(data)
data = self._decode(data, decode_content, flush_decoder)
if cache_content:
self._body = data
return data
|
python
|
def read(self, amt=None, decode_content=None, cache_content=False):
"""
Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
:param cache_content:
If True, will save the returned data such that the same result is
returned despite of the state of the underlying file object. This
is useful if you want the ``.data`` property to continue working
after having ``.read()`` the file object. (Overridden if ``amt`` is
set.)
"""
self._init_decoder()
if decode_content is None:
decode_content = self.decode_content
if self._fp is None:
return
flush_decoder = False
data = None
with self._error_catcher():
if amt is None:
# cStringIO doesn't like amt=None
data = self._fp.read()
flush_decoder = True
else:
cache_content = False
data = self._fp.read(amt)
if amt != 0 and not data: # Platform-specific: Buggy versions of Python.
# Close the connection when no data is returned
#
# This is redundant to what httplib/http.client _should_
# already do. However, versions of python released before
# December 15, 2012 (http://bugs.python.org/issue16298) do
# not properly close the connection in all cases. There is
# no harm in redundantly calling close.
self._fp.close()
flush_decoder = True
if self.enforce_content_length and self.length_remaining not in (0, None):
# This is an edge case that httplib failed to cover due
# to concerns of backward compatibility. We're
# addressing it here to make sure IncompleteRead is
# raised during streaming, so all calls with incorrect
# Content-Length are caught.
raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
if data:
self._fp_bytes_read += len(data)
if self.length_remaining is not None:
self.length_remaining -= len(data)
data = self._decode(data, decode_content, flush_decoder)
if cache_content:
self._body = data
return data
|
[
"def",
"read",
"(",
"self",
",",
"amt",
"=",
"None",
",",
"decode_content",
"=",
"None",
",",
"cache_content",
"=",
"False",
")",
":",
"self",
".",
"_init_decoder",
"(",
")",
"if",
"decode_content",
"is",
"None",
":",
"decode_content",
"=",
"self",
".",
"decode_content",
"if",
"self",
".",
"_fp",
"is",
"None",
":",
"return",
"flush_decoder",
"=",
"False",
"data",
"=",
"None",
"with",
"self",
".",
"_error_catcher",
"(",
")",
":",
"if",
"amt",
"is",
"None",
":",
"# cStringIO doesn't like amt=None",
"data",
"=",
"self",
".",
"_fp",
".",
"read",
"(",
")",
"flush_decoder",
"=",
"True",
"else",
":",
"cache_content",
"=",
"False",
"data",
"=",
"self",
".",
"_fp",
".",
"read",
"(",
"amt",
")",
"if",
"amt",
"!=",
"0",
"and",
"not",
"data",
":",
"# Platform-specific: Buggy versions of Python.",
"# Close the connection when no data is returned",
"#",
"# This is redundant to what httplib/http.client _should_",
"# already do. However, versions of python released before",
"# December 15, 2012 (http://bugs.python.org/issue16298) do",
"# not properly close the connection in all cases. There is",
"# no harm in redundantly calling close.",
"self",
".",
"_fp",
".",
"close",
"(",
")",
"flush_decoder",
"=",
"True",
"if",
"self",
".",
"enforce_content_length",
"and",
"self",
".",
"length_remaining",
"not",
"in",
"(",
"0",
",",
"None",
")",
":",
"# This is an edge case that httplib failed to cover due",
"# to concerns of backward compatibility. We're",
"# addressing it here to make sure IncompleteRead is",
"# raised during streaming, so all calls with incorrect",
"# Content-Length are caught.",
"raise",
"IncompleteRead",
"(",
"self",
".",
"_fp_bytes_read",
",",
"self",
".",
"length_remaining",
")",
"if",
"data",
":",
"self",
".",
"_fp_bytes_read",
"+=",
"len",
"(",
"data",
")",
"if",
"self",
".",
"length_remaining",
"is",
"not",
"None",
":",
"self",
".",
"length_remaining",
"-=",
"len",
"(",
"data",
")",
"data",
"=",
"self",
".",
"_decode",
"(",
"data",
",",
"decode_content",
",",
"flush_decoder",
")",
"if",
"cache_content",
":",
"self",
".",
"_body",
"=",
"data",
"return",
"data"
] |
Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
:param cache_content:
If True, will save the returned data such that the same result is
returned despite of the state of the underlying file object. This
is useful if you want the ``.data`` property to continue working
after having ``.read()`` the file object. (Overridden if ``amt`` is
set.)
|
[
"Similar",
"to",
":",
"meth",
":",
"httplib",
".",
"HTTPResponse",
".",
"read",
"but",
"with",
"two",
"additional",
"parameters",
":",
"decode_content",
"and",
"cache_content",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L404-L471
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/response.py
|
HTTPResponse.from_httplib
|
def from_httplib(ResponseCls, r, **response_kw):
"""
Given an :class:`httplib.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object.
Remaining parameters are passed to the HTTPResponse constructor, along
with ``original_response=r``.
"""
headers = r.msg
if not isinstance(headers, HTTPHeaderDict):
if PY3: # Python 3
headers = HTTPHeaderDict(headers.items())
else: # Python 2
headers = HTTPHeaderDict.from_httplib(headers)
# HTTPResponse objects in Python 3 don't have a .strict attribute
strict = getattr(r, 'strict', 0)
resp = ResponseCls(body=r,
headers=headers,
status=r.status,
version=r.version,
reason=r.reason,
strict=strict,
original_response=r,
**response_kw)
return resp
|
python
|
def from_httplib(ResponseCls, r, **response_kw):
"""
Given an :class:`httplib.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object.
Remaining parameters are passed to the HTTPResponse constructor, along
with ``original_response=r``.
"""
headers = r.msg
if not isinstance(headers, HTTPHeaderDict):
if PY3: # Python 3
headers = HTTPHeaderDict(headers.items())
else: # Python 2
headers = HTTPHeaderDict.from_httplib(headers)
# HTTPResponse objects in Python 3 don't have a .strict attribute
strict = getattr(r, 'strict', 0)
resp = ResponseCls(body=r,
headers=headers,
status=r.status,
version=r.version,
reason=r.reason,
strict=strict,
original_response=r,
**response_kw)
return resp
|
[
"def",
"from_httplib",
"(",
"ResponseCls",
",",
"r",
",",
"*",
"*",
"response_kw",
")",
":",
"headers",
"=",
"r",
".",
"msg",
"if",
"not",
"isinstance",
"(",
"headers",
",",
"HTTPHeaderDict",
")",
":",
"if",
"PY3",
":",
"# Python 3",
"headers",
"=",
"HTTPHeaderDict",
"(",
"headers",
".",
"items",
"(",
")",
")",
"else",
":",
"# Python 2",
"headers",
"=",
"HTTPHeaderDict",
".",
"from_httplib",
"(",
"headers",
")",
"# HTTPResponse objects in Python 3 don't have a .strict attribute",
"strict",
"=",
"getattr",
"(",
"r",
",",
"'strict'",
",",
"0",
")",
"resp",
"=",
"ResponseCls",
"(",
"body",
"=",
"r",
",",
"headers",
"=",
"headers",
",",
"status",
"=",
"r",
".",
"status",
",",
"version",
"=",
"r",
".",
"version",
",",
"reason",
"=",
"r",
".",
"reason",
",",
"strict",
"=",
"strict",
",",
"original_response",
"=",
"r",
",",
"*",
"*",
"response_kw",
")",
"return",
"resp"
] |
Given an :class:`httplib.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object.
Remaining parameters are passed to the HTTPResponse constructor, along
with ``original_response=r``.
|
[
"Given",
"an",
":",
"class",
":",
"httplib",
".",
"HTTPResponse",
"instance",
"r",
"return",
"a",
"corresponding",
":",
"class",
":",
"urllib3",
".",
"response",
".",
"HTTPResponse",
"object",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L500-L526
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/response.py
|
HTTPResponse.read_chunked
|
def read_chunked(self, amt=None, decode_content=None):
"""
Similar to :meth:`HTTPResponse.read`, but with an additional
parameter: ``decode_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
"""
self._init_decoder()
# FIXME: Rewrite this method and make it a class with a better structured logic.
if not self.chunked:
raise ResponseNotChunked(
"Response is not chunked. "
"Header 'transfer-encoding: chunked' is missing.")
if not self.supports_chunked_reads():
raise BodyNotHttplibCompatible(
"Body should be httplib.HTTPResponse like. "
"It should have have an fp attribute which returns raw chunks.")
with self._error_catcher():
# Don't bother reading the body of a HEAD request.
if self._original_response and is_response_to_head(self._original_response):
self._original_response.close()
return
# If a response is already read and closed
# then return immediately.
if self._fp.fp is None:
return
while True:
self._update_chunk_length()
if self.chunk_left == 0:
break
chunk = self._handle_chunk(amt)
decoded = self._decode(chunk, decode_content=decode_content,
flush_decoder=False)
if decoded:
yield decoded
if decode_content:
# On CPython and PyPy, we should never need to flush the
# decoder. However, on Jython we *might* need to, so
# lets defensively do it anyway.
decoded = self._flush_decoder()
if decoded: # Platform-specific: Jython.
yield decoded
# Chunk content ends with \r\n: discard it.
while True:
line = self._fp.fp.readline()
if not line:
# Some sites may not end with '\r\n'.
break
if line == b'\r\n':
break
# We read everything; close the "file".
if self._original_response:
self._original_response.close()
|
python
|
def read_chunked(self, amt=None, decode_content=None):
"""
Similar to :meth:`HTTPResponse.read`, but with an additional
parameter: ``decode_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
"""
self._init_decoder()
# FIXME: Rewrite this method and make it a class with a better structured logic.
if not self.chunked:
raise ResponseNotChunked(
"Response is not chunked. "
"Header 'transfer-encoding: chunked' is missing.")
if not self.supports_chunked_reads():
raise BodyNotHttplibCompatible(
"Body should be httplib.HTTPResponse like. "
"It should have have an fp attribute which returns raw chunks.")
with self._error_catcher():
# Don't bother reading the body of a HEAD request.
if self._original_response and is_response_to_head(self._original_response):
self._original_response.close()
return
# If a response is already read and closed
# then return immediately.
if self._fp.fp is None:
return
while True:
self._update_chunk_length()
if self.chunk_left == 0:
break
chunk = self._handle_chunk(amt)
decoded = self._decode(chunk, decode_content=decode_content,
flush_decoder=False)
if decoded:
yield decoded
if decode_content:
# On CPython and PyPy, we should never need to flush the
# decoder. However, on Jython we *might* need to, so
# lets defensively do it anyway.
decoded = self._flush_decoder()
if decoded: # Platform-specific: Jython.
yield decoded
# Chunk content ends with \r\n: discard it.
while True:
line = self._fp.fp.readline()
if not line:
# Some sites may not end with '\r\n'.
break
if line == b'\r\n':
break
# We read everything; close the "file".
if self._original_response:
self._original_response.close()
|
[
"def",
"read_chunked",
"(",
"self",
",",
"amt",
"=",
"None",
",",
"decode_content",
"=",
"None",
")",
":",
"self",
".",
"_init_decoder",
"(",
")",
"# FIXME: Rewrite this method and make it a class with a better structured logic.",
"if",
"not",
"self",
".",
"chunked",
":",
"raise",
"ResponseNotChunked",
"(",
"\"Response is not chunked. \"",
"\"Header 'transfer-encoding: chunked' is missing.\"",
")",
"if",
"not",
"self",
".",
"supports_chunked_reads",
"(",
")",
":",
"raise",
"BodyNotHttplibCompatible",
"(",
"\"Body should be httplib.HTTPResponse like. \"",
"\"It should have have an fp attribute which returns raw chunks.\"",
")",
"with",
"self",
".",
"_error_catcher",
"(",
")",
":",
"# Don't bother reading the body of a HEAD request.",
"if",
"self",
".",
"_original_response",
"and",
"is_response_to_head",
"(",
"self",
".",
"_original_response",
")",
":",
"self",
".",
"_original_response",
".",
"close",
"(",
")",
"return",
"# If a response is already read and closed",
"# then return immediately.",
"if",
"self",
".",
"_fp",
".",
"fp",
"is",
"None",
":",
"return",
"while",
"True",
":",
"self",
".",
"_update_chunk_length",
"(",
")",
"if",
"self",
".",
"chunk_left",
"==",
"0",
":",
"break",
"chunk",
"=",
"self",
".",
"_handle_chunk",
"(",
"amt",
")",
"decoded",
"=",
"self",
".",
"_decode",
"(",
"chunk",
",",
"decode_content",
"=",
"decode_content",
",",
"flush_decoder",
"=",
"False",
")",
"if",
"decoded",
":",
"yield",
"decoded",
"if",
"decode_content",
":",
"# On CPython and PyPy, we should never need to flush the",
"# decoder. However, on Jython we *might* need to, so",
"# lets defensively do it anyway.",
"decoded",
"=",
"self",
".",
"_flush_decoder",
"(",
")",
"if",
"decoded",
":",
"# Platform-specific: Jython.",
"yield",
"decoded",
"# Chunk content ends with \\r\\n: discard it.",
"while",
"True",
":",
"line",
"=",
"self",
".",
"_fp",
".",
"fp",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"# Some sites may not end with '\\r\\n'.",
"break",
"if",
"line",
"==",
"b'\\r\\n'",
":",
"break",
"# We read everything; close the \"file\".",
"if",
"self",
".",
"_original_response",
":",
"self",
".",
"_original_response",
".",
"close",
"(",
")"
] |
Similar to :meth:`HTTPResponse.read`, but with an additional
parameter: ``decode_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
|
[
"Similar",
"to",
":",
"meth",
":",
"HTTPResponse",
".",
"read",
"but",
"with",
"an",
"additional",
"parameter",
":",
"decode_content",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L629-L694
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/response.py
|
HTTPResponse.geturl
|
def geturl(self):
"""
Returns the URL that was the source of this response.
If the request that generated this response redirected, this method
will return the final redirect location.
"""
if self.retries is not None and len(self.retries.history):
return self.retries.history[-1].redirect_location
else:
return self._request_url
|
python
|
def geturl(self):
"""
Returns the URL that was the source of this response.
If the request that generated this response redirected, this method
will return the final redirect location.
"""
if self.retries is not None and len(self.retries.history):
return self.retries.history[-1].redirect_location
else:
return self._request_url
|
[
"def",
"geturl",
"(",
"self",
")",
":",
"if",
"self",
".",
"retries",
"is",
"not",
"None",
"and",
"len",
"(",
"self",
".",
"retries",
".",
"history",
")",
":",
"return",
"self",
".",
"retries",
".",
"history",
"[",
"-",
"1",
"]",
".",
"redirect_location",
"else",
":",
"return",
"self",
".",
"_request_url"
] |
Returns the URL that was the source of this response.
If the request that generated this response redirected, this method
will return the final redirect location.
|
[
"Returns",
"the",
"URL",
"that",
"was",
"the",
"source",
"of",
"this",
"response",
".",
"If",
"the",
"request",
"that",
"generated",
"this",
"response",
"redirected",
"this",
"method",
"will",
"return",
"the",
"final",
"redirect",
"location",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L696-L705
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/spin.py
|
VistirSpinner.ok
|
def ok(self, text=u"OK", err=False):
"""Set Ok (success) finalizer to a spinner."""
# Do not display spin text for ok state
self._text = None
_text = to_text(text) if text else u"OK"
err = err or not self.write_to_stdout
self._freeze(_text, err=err)
|
python
|
def ok(self, text=u"OK", err=False):
"""Set Ok (success) finalizer to a spinner."""
# Do not display spin text for ok state
self._text = None
_text = to_text(text) if text else u"OK"
err = err or not self.write_to_stdout
self._freeze(_text, err=err)
|
[
"def",
"ok",
"(",
"self",
",",
"text",
"=",
"u\"OK\"",
",",
"err",
"=",
"False",
")",
":",
"# Do not display spin text for ok state",
"self",
".",
"_text",
"=",
"None",
"_text",
"=",
"to_text",
"(",
"text",
")",
"if",
"text",
"else",
"u\"OK\"",
"err",
"=",
"err",
"or",
"not",
"self",
".",
"write_to_stdout",
"self",
".",
"_freeze",
"(",
"_text",
",",
"err",
"=",
"err",
")"
] |
Set Ok (success) finalizer to a spinner.
|
[
"Set",
"Ok",
"(",
"success",
")",
"finalizer",
"to",
"a",
"spinner",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/spin.py#L227-L234
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/spin.py
|
VistirSpinner.fail
|
def fail(self, text=u"FAIL", err=False):
"""Set fail finalizer to a spinner."""
# Do not display spin text for fail state
self._text = None
_text = text if text else u"FAIL"
err = err or not self.write_to_stdout
self._freeze(_text, err=err)
|
python
|
def fail(self, text=u"FAIL", err=False):
"""Set fail finalizer to a spinner."""
# Do not display spin text for fail state
self._text = None
_text = text if text else u"FAIL"
err = err or not self.write_to_stdout
self._freeze(_text, err=err)
|
[
"def",
"fail",
"(",
"self",
",",
"text",
"=",
"u\"FAIL\"",
",",
"err",
"=",
"False",
")",
":",
"# Do not display spin text for fail state",
"self",
".",
"_text",
"=",
"None",
"_text",
"=",
"text",
"if",
"text",
"else",
"u\"FAIL\"",
"err",
"=",
"err",
"or",
"not",
"self",
".",
"write_to_stdout",
"self",
".",
"_freeze",
"(",
"_text",
",",
"err",
"=",
"err",
")"
] |
Set fail finalizer to a spinner.
|
[
"Set",
"fail",
"finalizer",
"to",
"a",
"spinner",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/spin.py#L236-L243
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/spin.py
|
VistirSpinner.write_err
|
def write_err(self, text):
"""Write error text in the terminal without breaking the spinner."""
stderr = self.stderr
if self.stderr.closed:
stderr = sys.stderr
stderr.write(decode_output(u"\r", target_stream=stderr))
stderr.write(decode_output(CLEAR_LINE, target_stream=stderr))
if text is None:
text = ""
text = decode_output(u"{0}\n".format(text), target_stream=stderr)
self.stderr.write(text)
self.out_buff.write(decode_output(text, target_stream=self.out_buff))
|
python
|
def write_err(self, text):
"""Write error text in the terminal without breaking the spinner."""
stderr = self.stderr
if self.stderr.closed:
stderr = sys.stderr
stderr.write(decode_output(u"\r", target_stream=stderr))
stderr.write(decode_output(CLEAR_LINE, target_stream=stderr))
if text is None:
text = ""
text = decode_output(u"{0}\n".format(text), target_stream=stderr)
self.stderr.write(text)
self.out_buff.write(decode_output(text, target_stream=self.out_buff))
|
[
"def",
"write_err",
"(",
"self",
",",
"text",
")",
":",
"stderr",
"=",
"self",
".",
"stderr",
"if",
"self",
".",
"stderr",
".",
"closed",
":",
"stderr",
"=",
"sys",
".",
"stderr",
"stderr",
".",
"write",
"(",
"decode_output",
"(",
"u\"\\r\"",
",",
"target_stream",
"=",
"stderr",
")",
")",
"stderr",
".",
"write",
"(",
"decode_output",
"(",
"CLEAR_LINE",
",",
"target_stream",
"=",
"stderr",
")",
")",
"if",
"text",
"is",
"None",
":",
"text",
"=",
"\"\"",
"text",
"=",
"decode_output",
"(",
"u\"{0}\\n\"",
".",
"format",
"(",
"text",
")",
",",
"target_stream",
"=",
"stderr",
")",
"self",
".",
"stderr",
".",
"write",
"(",
"text",
")",
"self",
".",
"out_buff",
".",
"write",
"(",
"decode_output",
"(",
"text",
",",
"target_stream",
"=",
"self",
".",
"out_buff",
")",
")"
] |
Write error text in the terminal without breaking the spinner.
|
[
"Write",
"error",
"text",
"in",
"the",
"terminal",
"without",
"breaking",
"the",
"spinner",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/spin.py#L270-L281
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/spin.py
|
VistirSpinner._freeze
|
def _freeze(self, final_text, err=False):
"""Stop spinner, compose last frame and 'freeze' it."""
if not final_text:
final_text = ""
target = self.stderr if err else self.stdout
if target.closed:
target = sys.stderr if err else sys.stdout
text = to_text(final_text)
last_frame = self._compose_out(text, mode="last")
self._last_frame = decode_output(last_frame, target_stream=target)
# Should be stopped here, otherwise prints after
# self._freeze call will mess up the spinner
self.stop()
target.write(self._last_frame)
|
python
|
def _freeze(self, final_text, err=False):
"""Stop spinner, compose last frame and 'freeze' it."""
if not final_text:
final_text = ""
target = self.stderr if err else self.stdout
if target.closed:
target = sys.stderr if err else sys.stdout
text = to_text(final_text)
last_frame = self._compose_out(text, mode="last")
self._last_frame = decode_output(last_frame, target_stream=target)
# Should be stopped here, otherwise prints after
# self._freeze call will mess up the spinner
self.stop()
target.write(self._last_frame)
|
[
"def",
"_freeze",
"(",
"self",
",",
"final_text",
",",
"err",
"=",
"False",
")",
":",
"if",
"not",
"final_text",
":",
"final_text",
"=",
"\"\"",
"target",
"=",
"self",
".",
"stderr",
"if",
"err",
"else",
"self",
".",
"stdout",
"if",
"target",
".",
"closed",
":",
"target",
"=",
"sys",
".",
"stderr",
"if",
"err",
"else",
"sys",
".",
"stdout",
"text",
"=",
"to_text",
"(",
"final_text",
")",
"last_frame",
"=",
"self",
".",
"_compose_out",
"(",
"text",
",",
"mode",
"=",
"\"last\"",
")",
"self",
".",
"_last_frame",
"=",
"decode_output",
"(",
"last_frame",
",",
"target_stream",
"=",
"target",
")",
"# Should be stopped here, otherwise prints after",
"# self._freeze call will mess up the spinner",
"self",
".",
"stop",
"(",
")",
"target",
".",
"write",
"(",
"self",
".",
"_last_frame",
")"
] |
Stop spinner, compose last frame and 'freeze' it.
|
[
"Stop",
"spinner",
"compose",
"last",
"frame",
"and",
"freeze",
"it",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/spin.py#L318-L332
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/lexer.py
|
describe_token_expr
|
def describe_token_expr(expr):
"""Like `describe_token` but for token expressions."""
if ':' in expr:
type, value = expr.split(':', 1)
if type == 'name':
return value
else:
type = expr
return _describe_token_type(type)
|
python
|
def describe_token_expr(expr):
"""Like `describe_token` but for token expressions."""
if ':' in expr:
type, value = expr.split(':', 1)
if type == 'name':
return value
else:
type = expr
return _describe_token_type(type)
|
[
"def",
"describe_token_expr",
"(",
"expr",
")",
":",
"if",
"':'",
"in",
"expr",
":",
"type",
",",
"value",
"=",
"expr",
".",
"split",
"(",
"':'",
",",
"1",
")",
"if",
"type",
"==",
"'name'",
":",
"return",
"value",
"else",
":",
"type",
"=",
"expr",
"return",
"_describe_token_type",
"(",
"type",
")"
] |
Like `describe_token` but for token expressions.
|
[
"Like",
"describe_token",
"but",
"for",
"token",
"expressions",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/lexer.py#L178-L186
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/lexer.py
|
get_lexer
|
def get_lexer(environment):
"""Return a lexer which is probably cached."""
key = (environment.block_start_string,
environment.block_end_string,
environment.variable_start_string,
environment.variable_end_string,
environment.comment_start_string,
environment.comment_end_string,
environment.line_statement_prefix,
environment.line_comment_prefix,
environment.trim_blocks,
environment.lstrip_blocks,
environment.newline_sequence,
environment.keep_trailing_newline)
lexer = _lexer_cache.get(key)
if lexer is None:
lexer = Lexer(environment)
_lexer_cache[key] = lexer
return lexer
|
python
|
def get_lexer(environment):
"""Return a lexer which is probably cached."""
key = (environment.block_start_string,
environment.block_end_string,
environment.variable_start_string,
environment.variable_end_string,
environment.comment_start_string,
environment.comment_end_string,
environment.line_statement_prefix,
environment.line_comment_prefix,
environment.trim_blocks,
environment.lstrip_blocks,
environment.newline_sequence,
environment.keep_trailing_newline)
lexer = _lexer_cache.get(key)
if lexer is None:
lexer = Lexer(environment)
_lexer_cache[key] = lexer
return lexer
|
[
"def",
"get_lexer",
"(",
"environment",
")",
":",
"key",
"=",
"(",
"environment",
".",
"block_start_string",
",",
"environment",
".",
"block_end_string",
",",
"environment",
".",
"variable_start_string",
",",
"environment",
".",
"variable_end_string",
",",
"environment",
".",
"comment_start_string",
",",
"environment",
".",
"comment_end_string",
",",
"environment",
".",
"line_statement_prefix",
",",
"environment",
".",
"line_comment_prefix",
",",
"environment",
".",
"trim_blocks",
",",
"environment",
".",
"lstrip_blocks",
",",
"environment",
".",
"newline_sequence",
",",
"environment",
".",
"keep_trailing_newline",
")",
"lexer",
"=",
"_lexer_cache",
".",
"get",
"(",
"key",
")",
"if",
"lexer",
"is",
"None",
":",
"lexer",
"=",
"Lexer",
"(",
"environment",
")",
"_lexer_cache",
"[",
"key",
"]",
"=",
"lexer",
"return",
"lexer"
] |
Return a lexer which is probably cached.
|
[
"Return",
"a",
"lexer",
"which",
"is",
"probably",
"cached",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/lexer.py#L391-L409
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/lexer.py
|
Lexer.tokenize
|
def tokenize(self, source, name=None, filename=None, state=None):
"""Calls tokeniter + tokenize and wraps it in a token stream.
"""
stream = self.tokeniter(source, name, filename, state)
return TokenStream(self.wrap(stream, name, filename), name, filename)
|
python
|
def tokenize(self, source, name=None, filename=None, state=None):
"""Calls tokeniter + tokenize and wraps it in a token stream.
"""
stream = self.tokeniter(source, name, filename, state)
return TokenStream(self.wrap(stream, name, filename), name, filename)
|
[
"def",
"tokenize",
"(",
"self",
",",
"source",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"state",
"=",
"None",
")",
":",
"stream",
"=",
"self",
".",
"tokeniter",
"(",
"source",
",",
"name",
",",
"filename",
",",
"state",
")",
"return",
"TokenStream",
"(",
"self",
".",
"wrap",
"(",
"stream",
",",
"name",
",",
"filename",
")",
",",
"name",
",",
"filename",
")"
] |
Calls tokeniter + tokenize and wraps it in a token stream.
|
[
"Calls",
"tokeniter",
"+",
"tokenize",
"and",
"wraps",
"it",
"in",
"a",
"token",
"stream",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/lexer.py#L552-L556
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/lexer.py
|
Lexer.wrap
|
def wrap(self, stream, name=None, filename=None):
"""This is called with the stream as returned by `tokenize` and wraps
every token in a :class:`Token` and converts the value.
"""
for lineno, token, value in stream:
if token in ignored_tokens:
continue
elif token == 'linestatement_begin':
token = 'block_begin'
elif token == 'linestatement_end':
token = 'block_end'
# we are not interested in those tokens in the parser
elif token in ('raw_begin', 'raw_end'):
continue
elif token == 'data':
value = self._normalize_newlines(value)
elif token == 'keyword':
token = value
elif token == 'name':
value = str(value)
if check_ident and not value.isidentifier():
raise TemplateSyntaxError(
'Invalid character in identifier',
lineno, name, filename)
elif token == 'string':
# try to unescape string
try:
value = self._normalize_newlines(value[1:-1]) \
.encode('ascii', 'backslashreplace') \
.decode('unicode-escape')
except Exception as e:
msg = str(e).split(':')[-1].strip()
raise TemplateSyntaxError(msg, lineno, name, filename)
elif token == 'integer':
value = int(value)
elif token == 'float':
value = float(value)
elif token == 'operator':
token = operators[value]
yield Token(lineno, token, value)
|
python
|
def wrap(self, stream, name=None, filename=None):
"""This is called with the stream as returned by `tokenize` and wraps
every token in a :class:`Token` and converts the value.
"""
for lineno, token, value in stream:
if token in ignored_tokens:
continue
elif token == 'linestatement_begin':
token = 'block_begin'
elif token == 'linestatement_end':
token = 'block_end'
# we are not interested in those tokens in the parser
elif token in ('raw_begin', 'raw_end'):
continue
elif token == 'data':
value = self._normalize_newlines(value)
elif token == 'keyword':
token = value
elif token == 'name':
value = str(value)
if check_ident and not value.isidentifier():
raise TemplateSyntaxError(
'Invalid character in identifier',
lineno, name, filename)
elif token == 'string':
# try to unescape string
try:
value = self._normalize_newlines(value[1:-1]) \
.encode('ascii', 'backslashreplace') \
.decode('unicode-escape')
except Exception as e:
msg = str(e).split(':')[-1].strip()
raise TemplateSyntaxError(msg, lineno, name, filename)
elif token == 'integer':
value = int(value)
elif token == 'float':
value = float(value)
elif token == 'operator':
token = operators[value]
yield Token(lineno, token, value)
|
[
"def",
"wrap",
"(",
"self",
",",
"stream",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"for",
"lineno",
",",
"token",
",",
"value",
"in",
"stream",
":",
"if",
"token",
"in",
"ignored_tokens",
":",
"continue",
"elif",
"token",
"==",
"'linestatement_begin'",
":",
"token",
"=",
"'block_begin'",
"elif",
"token",
"==",
"'linestatement_end'",
":",
"token",
"=",
"'block_end'",
"# we are not interested in those tokens in the parser",
"elif",
"token",
"in",
"(",
"'raw_begin'",
",",
"'raw_end'",
")",
":",
"continue",
"elif",
"token",
"==",
"'data'",
":",
"value",
"=",
"self",
".",
"_normalize_newlines",
"(",
"value",
")",
"elif",
"token",
"==",
"'keyword'",
":",
"token",
"=",
"value",
"elif",
"token",
"==",
"'name'",
":",
"value",
"=",
"str",
"(",
"value",
")",
"if",
"check_ident",
"and",
"not",
"value",
".",
"isidentifier",
"(",
")",
":",
"raise",
"TemplateSyntaxError",
"(",
"'Invalid character in identifier'",
",",
"lineno",
",",
"name",
",",
"filename",
")",
"elif",
"token",
"==",
"'string'",
":",
"# try to unescape string",
"try",
":",
"value",
"=",
"self",
".",
"_normalize_newlines",
"(",
"value",
"[",
"1",
":",
"-",
"1",
"]",
")",
".",
"encode",
"(",
"'ascii'",
",",
"'backslashreplace'",
")",
".",
"decode",
"(",
"'unicode-escape'",
")",
"except",
"Exception",
"as",
"e",
":",
"msg",
"=",
"str",
"(",
"e",
")",
".",
"split",
"(",
"':'",
")",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
")",
"raise",
"TemplateSyntaxError",
"(",
"msg",
",",
"lineno",
",",
"name",
",",
"filename",
")",
"elif",
"token",
"==",
"'integer'",
":",
"value",
"=",
"int",
"(",
"value",
")",
"elif",
"token",
"==",
"'float'",
":",
"value",
"=",
"float",
"(",
"value",
")",
"elif",
"token",
"==",
"'operator'",
":",
"token",
"=",
"operators",
"[",
"value",
"]",
"yield",
"Token",
"(",
"lineno",
",",
"token",
",",
"value",
")"
] |
This is called with the stream as returned by `tokenize` and wraps
every token in a :class:`Token` and converts the value.
|
[
"This",
"is",
"called",
"with",
"the",
"stream",
"as",
"returned",
"by",
"tokenize",
"and",
"wraps",
"every",
"token",
"in",
"a",
":",
"class",
":",
"Token",
"and",
"converts",
"the",
"value",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/lexer.py#L558-L597
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/pyproject.py
|
load_pyproject_toml
|
def load_pyproject_toml(
use_pep517, # type: Optional[bool]
pyproject_toml, # type: str
setup_py, # type: str
req_name # type: str
):
# type: (...) -> Optional[Tuple[List[str], str, List[str]]]
"""Load the pyproject.toml file.
Parameters:
use_pep517 - Has the user requested PEP 517 processing? None
means the user hasn't explicitly specified.
pyproject_toml - Location of the project's pyproject.toml file
setup_py - Location of the project's setup.py file
req_name - The name of the requirement we're processing (for
error reporting)
Returns:
None if we should use the legacy code path, otherwise a tuple
(
requirements from pyproject.toml,
name of PEP 517 backend,
requirements we should check are installed after setting
up the build environment
)
"""
has_pyproject = os.path.isfile(pyproject_toml)
has_setup = os.path.isfile(setup_py)
if has_pyproject:
with io.open(pyproject_toml, encoding="utf-8") as f:
pp_toml = pytoml.load(f)
build_system = pp_toml.get("build-system")
else:
build_system = None
# The following cases must use PEP 517
# We check for use_pep517 being non-None and falsey because that means
# the user explicitly requested --no-use-pep517. The value 0 as
# opposed to False can occur when the value is provided via an
# environment variable or config file option (due to the quirk of
# strtobool() returning an integer in pip's configuration code).
if has_pyproject and not has_setup:
if use_pep517 is not None and not use_pep517:
raise InstallationError(
"Disabling PEP 517 processing is invalid: "
"project does not have a setup.py"
)
use_pep517 = True
elif build_system and "build-backend" in build_system:
if use_pep517 is not None and not use_pep517:
raise InstallationError(
"Disabling PEP 517 processing is invalid: "
"project specifies a build backend of {} "
"in pyproject.toml".format(
build_system["build-backend"]
)
)
use_pep517 = True
# If we haven't worked out whether to use PEP 517 yet,
# and the user hasn't explicitly stated a preference,
# we do so if the project has a pyproject.toml file.
elif use_pep517 is None:
use_pep517 = has_pyproject
# At this point, we know whether we're going to use PEP 517.
assert use_pep517 is not None
# If we're using the legacy code path, there is nothing further
# for us to do here.
if not use_pep517:
return None
if build_system is None:
# Either the user has a pyproject.toml with no build-system
# section, or the user has no pyproject.toml, but has opted in
# explicitly via --use-pep517.
# In the absence of any explicit backend specification, we
# assume the setuptools backend that most closely emulates the
# traditional direct setup.py execution, and require wheel and
# a version of setuptools that supports that backend.
build_system = {
"requires": ["setuptools>=40.8.0", "wheel"],
"build-backend": "setuptools.build_meta:__legacy__",
}
# If we're using PEP 517, we have build system information (either
# from pyproject.toml, or defaulted by the code above).
# Note that at this point, we do not know if the user has actually
# specified a backend, though.
assert build_system is not None
# Ensure that the build-system section in pyproject.toml conforms
# to PEP 518.
error_template = (
"{package} has a pyproject.toml file that does not comply "
"with PEP 518: {reason}"
)
# Specifying the build-system table but not the requires key is invalid
if "requires" not in build_system:
raise InstallationError(
error_template.format(package=req_name, reason=(
"it has a 'build-system' table but not "
"'build-system.requires' which is mandatory in the table"
))
)
# Error out if requires is not a list of strings
requires = build_system["requires"]
if not _is_list_of_str(requires):
raise InstallationError(error_template.format(
package=req_name,
reason="'build-system.requires' is not a list of strings.",
))
backend = build_system.get("build-backend")
check = [] # type: List[str]
if backend is None:
# If the user didn't specify a backend, we assume they want to use
# the setuptools backend. But we can't be sure they have included
# a version of setuptools which supplies the backend, or wheel
# (which is needed by the backend) in their requirements. So we
# make a note to check that those requirements are present once
# we have set up the environment.
# This is quite a lot of work to check for a very specific case. But
# the problem is, that case is potentially quite common - projects that
# adopted PEP 518 early for the ability to specify requirements to
# execute setup.py, but never considered needing to mention the build
# tools themselves. The original PEP 518 code had a similar check (but
# implemented in a different way).
backend = "setuptools.build_meta:__legacy__"
check = ["setuptools>=40.8.0", "wheel"]
return (requires, backend, check)
|
python
|
def load_pyproject_toml(
use_pep517, # type: Optional[bool]
pyproject_toml, # type: str
setup_py, # type: str
req_name # type: str
):
# type: (...) -> Optional[Tuple[List[str], str, List[str]]]
"""Load the pyproject.toml file.
Parameters:
use_pep517 - Has the user requested PEP 517 processing? None
means the user hasn't explicitly specified.
pyproject_toml - Location of the project's pyproject.toml file
setup_py - Location of the project's setup.py file
req_name - The name of the requirement we're processing (for
error reporting)
Returns:
None if we should use the legacy code path, otherwise a tuple
(
requirements from pyproject.toml,
name of PEP 517 backend,
requirements we should check are installed after setting
up the build environment
)
"""
has_pyproject = os.path.isfile(pyproject_toml)
has_setup = os.path.isfile(setup_py)
if has_pyproject:
with io.open(pyproject_toml, encoding="utf-8") as f:
pp_toml = pytoml.load(f)
build_system = pp_toml.get("build-system")
else:
build_system = None
# The following cases must use PEP 517
# We check for use_pep517 being non-None and falsey because that means
# the user explicitly requested --no-use-pep517. The value 0 as
# opposed to False can occur when the value is provided via an
# environment variable or config file option (due to the quirk of
# strtobool() returning an integer in pip's configuration code).
if has_pyproject and not has_setup:
if use_pep517 is not None and not use_pep517:
raise InstallationError(
"Disabling PEP 517 processing is invalid: "
"project does not have a setup.py"
)
use_pep517 = True
elif build_system and "build-backend" in build_system:
if use_pep517 is not None and not use_pep517:
raise InstallationError(
"Disabling PEP 517 processing is invalid: "
"project specifies a build backend of {} "
"in pyproject.toml".format(
build_system["build-backend"]
)
)
use_pep517 = True
# If we haven't worked out whether to use PEP 517 yet,
# and the user hasn't explicitly stated a preference,
# we do so if the project has a pyproject.toml file.
elif use_pep517 is None:
use_pep517 = has_pyproject
# At this point, we know whether we're going to use PEP 517.
assert use_pep517 is not None
# If we're using the legacy code path, there is nothing further
# for us to do here.
if not use_pep517:
return None
if build_system is None:
# Either the user has a pyproject.toml with no build-system
# section, or the user has no pyproject.toml, but has opted in
# explicitly via --use-pep517.
# In the absence of any explicit backend specification, we
# assume the setuptools backend that most closely emulates the
# traditional direct setup.py execution, and require wheel and
# a version of setuptools that supports that backend.
build_system = {
"requires": ["setuptools>=40.8.0", "wheel"],
"build-backend": "setuptools.build_meta:__legacy__",
}
# If we're using PEP 517, we have build system information (either
# from pyproject.toml, or defaulted by the code above).
# Note that at this point, we do not know if the user has actually
# specified a backend, though.
assert build_system is not None
# Ensure that the build-system section in pyproject.toml conforms
# to PEP 518.
error_template = (
"{package} has a pyproject.toml file that does not comply "
"with PEP 518: {reason}"
)
# Specifying the build-system table but not the requires key is invalid
if "requires" not in build_system:
raise InstallationError(
error_template.format(package=req_name, reason=(
"it has a 'build-system' table but not "
"'build-system.requires' which is mandatory in the table"
))
)
# Error out if requires is not a list of strings
requires = build_system["requires"]
if not _is_list_of_str(requires):
raise InstallationError(error_template.format(
package=req_name,
reason="'build-system.requires' is not a list of strings.",
))
backend = build_system.get("build-backend")
check = [] # type: List[str]
if backend is None:
# If the user didn't specify a backend, we assume they want to use
# the setuptools backend. But we can't be sure they have included
# a version of setuptools which supplies the backend, or wheel
# (which is needed by the backend) in their requirements. So we
# make a note to check that those requirements are present once
# we have set up the environment.
# This is quite a lot of work to check for a very specific case. But
# the problem is, that case is potentially quite common - projects that
# adopted PEP 518 early for the ability to specify requirements to
# execute setup.py, but never considered needing to mention the build
# tools themselves. The original PEP 518 code had a similar check (but
# implemented in a different way).
backend = "setuptools.build_meta:__legacy__"
check = ["setuptools>=40.8.0", "wheel"]
return (requires, backend, check)
|
[
"def",
"load_pyproject_toml",
"(",
"use_pep517",
",",
"# type: Optional[bool]",
"pyproject_toml",
",",
"# type: str",
"setup_py",
",",
"# type: str",
"req_name",
"# type: str",
")",
":",
"# type: (...) -> Optional[Tuple[List[str], str, List[str]]]",
"has_pyproject",
"=",
"os",
".",
"path",
".",
"isfile",
"(",
"pyproject_toml",
")",
"has_setup",
"=",
"os",
".",
"path",
".",
"isfile",
"(",
"setup_py",
")",
"if",
"has_pyproject",
":",
"with",
"io",
".",
"open",
"(",
"pyproject_toml",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"f",
":",
"pp_toml",
"=",
"pytoml",
".",
"load",
"(",
"f",
")",
"build_system",
"=",
"pp_toml",
".",
"get",
"(",
"\"build-system\"",
")",
"else",
":",
"build_system",
"=",
"None",
"# The following cases must use PEP 517",
"# We check for use_pep517 being non-None and falsey because that means",
"# the user explicitly requested --no-use-pep517. The value 0 as",
"# opposed to False can occur when the value is provided via an",
"# environment variable or config file option (due to the quirk of",
"# strtobool() returning an integer in pip's configuration code).",
"if",
"has_pyproject",
"and",
"not",
"has_setup",
":",
"if",
"use_pep517",
"is",
"not",
"None",
"and",
"not",
"use_pep517",
":",
"raise",
"InstallationError",
"(",
"\"Disabling PEP 517 processing is invalid: \"",
"\"project does not have a setup.py\"",
")",
"use_pep517",
"=",
"True",
"elif",
"build_system",
"and",
"\"build-backend\"",
"in",
"build_system",
":",
"if",
"use_pep517",
"is",
"not",
"None",
"and",
"not",
"use_pep517",
":",
"raise",
"InstallationError",
"(",
"\"Disabling PEP 517 processing is invalid: \"",
"\"project specifies a build backend of {} \"",
"\"in pyproject.toml\"",
".",
"format",
"(",
"build_system",
"[",
"\"build-backend\"",
"]",
")",
")",
"use_pep517",
"=",
"True",
"# If we haven't worked out whether to use PEP 517 yet,",
"# and the user hasn't explicitly stated a preference,",
"# we do so if the project has a pyproject.toml file.",
"elif",
"use_pep517",
"is",
"None",
":",
"use_pep517",
"=",
"has_pyproject",
"# At this point, we know whether we're going to use PEP 517.",
"assert",
"use_pep517",
"is",
"not",
"None",
"# If we're using the legacy code path, there is nothing further",
"# for us to do here.",
"if",
"not",
"use_pep517",
":",
"return",
"None",
"if",
"build_system",
"is",
"None",
":",
"# Either the user has a pyproject.toml with no build-system",
"# section, or the user has no pyproject.toml, but has opted in",
"# explicitly via --use-pep517.",
"# In the absence of any explicit backend specification, we",
"# assume the setuptools backend that most closely emulates the",
"# traditional direct setup.py execution, and require wheel and",
"# a version of setuptools that supports that backend.",
"build_system",
"=",
"{",
"\"requires\"",
":",
"[",
"\"setuptools>=40.8.0\"",
",",
"\"wheel\"",
"]",
",",
"\"build-backend\"",
":",
"\"setuptools.build_meta:__legacy__\"",
",",
"}",
"# If we're using PEP 517, we have build system information (either",
"# from pyproject.toml, or defaulted by the code above).",
"# Note that at this point, we do not know if the user has actually",
"# specified a backend, though.",
"assert",
"build_system",
"is",
"not",
"None",
"# Ensure that the build-system section in pyproject.toml conforms",
"# to PEP 518.",
"error_template",
"=",
"(",
"\"{package} has a pyproject.toml file that does not comply \"",
"\"with PEP 518: {reason}\"",
")",
"# Specifying the build-system table but not the requires key is invalid",
"if",
"\"requires\"",
"not",
"in",
"build_system",
":",
"raise",
"InstallationError",
"(",
"error_template",
".",
"format",
"(",
"package",
"=",
"req_name",
",",
"reason",
"=",
"(",
"\"it has a 'build-system' table but not \"",
"\"'build-system.requires' which is mandatory in the table\"",
")",
")",
")",
"# Error out if requires is not a list of strings",
"requires",
"=",
"build_system",
"[",
"\"requires\"",
"]",
"if",
"not",
"_is_list_of_str",
"(",
"requires",
")",
":",
"raise",
"InstallationError",
"(",
"error_template",
".",
"format",
"(",
"package",
"=",
"req_name",
",",
"reason",
"=",
"\"'build-system.requires' is not a list of strings.\"",
",",
")",
")",
"backend",
"=",
"build_system",
".",
"get",
"(",
"\"build-backend\"",
")",
"check",
"=",
"[",
"]",
"# type: List[str]",
"if",
"backend",
"is",
"None",
":",
"# If the user didn't specify a backend, we assume they want to use",
"# the setuptools backend. But we can't be sure they have included",
"# a version of setuptools which supplies the backend, or wheel",
"# (which is needed by the backend) in their requirements. So we",
"# make a note to check that those requirements are present once",
"# we have set up the environment.",
"# This is quite a lot of work to check for a very specific case. But",
"# the problem is, that case is potentially quite common - projects that",
"# adopted PEP 518 early for the ability to specify requirements to",
"# execute setup.py, but never considered needing to mention the build",
"# tools themselves. The original PEP 518 code had a similar check (but",
"# implemented in a different way).",
"backend",
"=",
"\"setuptools.build_meta:__legacy__\"",
"check",
"=",
"[",
"\"setuptools>=40.8.0\"",
",",
"\"wheel\"",
"]",
"return",
"(",
"requires",
",",
"backend",
",",
"check",
")"
] |
Load the pyproject.toml file.
Parameters:
use_pep517 - Has the user requested PEP 517 processing? None
means the user hasn't explicitly specified.
pyproject_toml - Location of the project's pyproject.toml file
setup_py - Location of the project's setup.py file
req_name - The name of the requirement we're processing (for
error reporting)
Returns:
None if we should use the legacy code path, otherwise a tuple
(
requirements from pyproject.toml,
name of PEP 517 backend,
requirements we should check are installed after setting
up the build environment
)
|
[
"Load",
"the",
"pyproject",
".",
"toml",
"file",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/pyproject.py#L35-L171
|
train
|
pypa/pipenv
|
pipenv/pyenv.py
|
Runner.iter_installable_versions
|
def iter_installable_versions(self):
"""Iterate through CPython versions available for Pipenv to install.
"""
for name in self._pyenv('install', '--list').out.splitlines():
try:
version = Version.parse(name.strip())
except ValueError:
continue
yield version
|
python
|
def iter_installable_versions(self):
"""Iterate through CPython versions available for Pipenv to install.
"""
for name in self._pyenv('install', '--list').out.splitlines():
try:
version = Version.parse(name.strip())
except ValueError:
continue
yield version
|
[
"def",
"iter_installable_versions",
"(",
"self",
")",
":",
"for",
"name",
"in",
"self",
".",
"_pyenv",
"(",
"'install'",
",",
"'--list'",
")",
".",
"out",
".",
"splitlines",
"(",
")",
":",
"try",
":",
"version",
"=",
"Version",
".",
"parse",
"(",
"name",
".",
"strip",
"(",
")",
")",
"except",
"ValueError",
":",
"continue",
"yield",
"version"
] |
Iterate through CPython versions available for Pipenv to install.
|
[
"Iterate",
"through",
"CPython",
"versions",
"available",
"for",
"Pipenv",
"to",
"install",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/pyenv.py#L75-L83
|
train
|
pypa/pipenv
|
pipenv/pyenv.py
|
Runner.find_version_to_install
|
def find_version_to_install(self, name):
"""Find a version in pyenv from the version supplied.
A ValueError is raised if a matching version cannot be found.
"""
version = Version.parse(name)
if version.patch is not None:
return name
try:
best_match = max((
inst_version
for inst_version in self.iter_installable_versions()
if inst_version.matches_minor(version)
), key=operator.attrgetter('cmpkey'))
except ValueError:
raise ValueError(
'no installable version found for {0!r}'.format(name),
)
return best_match
|
python
|
def find_version_to_install(self, name):
"""Find a version in pyenv from the version supplied.
A ValueError is raised if a matching version cannot be found.
"""
version = Version.parse(name)
if version.patch is not None:
return name
try:
best_match = max((
inst_version
for inst_version in self.iter_installable_versions()
if inst_version.matches_minor(version)
), key=operator.attrgetter('cmpkey'))
except ValueError:
raise ValueError(
'no installable version found for {0!r}'.format(name),
)
return best_match
|
[
"def",
"find_version_to_install",
"(",
"self",
",",
"name",
")",
":",
"version",
"=",
"Version",
".",
"parse",
"(",
"name",
")",
"if",
"version",
".",
"patch",
"is",
"not",
"None",
":",
"return",
"name",
"try",
":",
"best_match",
"=",
"max",
"(",
"(",
"inst_version",
"for",
"inst_version",
"in",
"self",
".",
"iter_installable_versions",
"(",
")",
"if",
"inst_version",
".",
"matches_minor",
"(",
"version",
")",
")",
",",
"key",
"=",
"operator",
".",
"attrgetter",
"(",
"'cmpkey'",
")",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'no installable version found for {0!r}'",
".",
"format",
"(",
"name",
")",
",",
")",
"return",
"best_match"
] |
Find a version in pyenv from the version supplied.
A ValueError is raised if a matching version cannot be found.
|
[
"Find",
"a",
"version",
"in",
"pyenv",
"from",
"the",
"version",
"supplied",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/pyenv.py#L85-L103
|
train
|
pypa/pipenv
|
pipenv/pyenv.py
|
Runner.install
|
def install(self, version):
"""Install the given version with pyenv.
The version must be a ``Version`` instance representing a version
found in pyenv.
A ValueError is raised if the given version does not have a match in
pyenv. A PyenvError is raised if the pyenv command fails.
"""
c = self._pyenv(
'install', '-s', str(version),
timeout=PIPENV_INSTALL_TIMEOUT,
)
return c
|
python
|
def install(self, version):
"""Install the given version with pyenv.
The version must be a ``Version`` instance representing a version
found in pyenv.
A ValueError is raised if the given version does not have a match in
pyenv. A PyenvError is raised if the pyenv command fails.
"""
c = self._pyenv(
'install', '-s', str(version),
timeout=PIPENV_INSTALL_TIMEOUT,
)
return c
|
[
"def",
"install",
"(",
"self",
",",
"version",
")",
":",
"c",
"=",
"self",
".",
"_pyenv",
"(",
"'install'",
",",
"'-s'",
",",
"str",
"(",
"version",
")",
",",
"timeout",
"=",
"PIPENV_INSTALL_TIMEOUT",
",",
")",
"return",
"c"
] |
Install the given version with pyenv.
The version must be a ``Version`` instance representing a version
found in pyenv.
A ValueError is raised if the given version does not have a match in
pyenv. A PyenvError is raised if the pyenv command fails.
|
[
"Install",
"the",
"given",
"version",
"with",
"pyenv",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/pyenv.py#L105-L118
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/req/constructors.py
|
parse_editable
|
def parse_editable(editable_req):
# type: (str) -> Tuple[Optional[str], str, Optional[Set[str]]]
"""Parses an editable requirement into:
- a requirement name
- an URL
- extras
- editable options
Accepted requirements:
svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir
.[some_extra]
"""
url = editable_req
# If a file path is specified with extras, strip off the extras.
url_no_extras, extras = _strip_extras(url)
if os.path.isdir(url_no_extras):
if not os.path.exists(os.path.join(url_no_extras, 'setup.py')):
msg = (
'File "setup.py" not found. Directory cannot be installed '
'in editable mode: {}'.format(os.path.abspath(url_no_extras))
)
pyproject_path = make_pyproject_path(url_no_extras)
if os.path.isfile(pyproject_path):
msg += (
'\n(A "pyproject.toml" file was found, but editable '
'mode currently requires a setup.py based build.)'
)
raise InstallationError(msg)
# Treating it as code that has already been checked out
url_no_extras = path_to_url(url_no_extras)
if url_no_extras.lower().startswith('file:'):
package_name = Link(url_no_extras).egg_fragment
if extras:
return (
package_name,
url_no_extras,
Requirement("placeholder" + extras.lower()).extras,
)
else:
return package_name, url_no_extras, None
for version_control in vcs:
if url.lower().startswith('%s:' % version_control):
url = '%s+%s' % (version_control, url)
break
if '+' not in url:
raise InstallationError(
'%s should either be a path to a local project or a VCS url '
'beginning with svn+, git+, hg+, or bzr+' %
editable_req
)
vc_type = url.split('+', 1)[0].lower()
if not vcs.get_backend(vc_type):
error_message = 'For --editable=%s only ' % editable_req + \
', '.join([backend.name + '+URL' for backend in vcs.backends]) + \
' is currently supported'
raise InstallationError(error_message)
package_name = Link(url).egg_fragment
if not package_name:
raise InstallationError(
"Could not detect requirement name for '%s', please specify one "
"with #egg=your_package_name" % editable_req
)
return package_name, url, None
|
python
|
def parse_editable(editable_req):
# type: (str) -> Tuple[Optional[str], str, Optional[Set[str]]]
"""Parses an editable requirement into:
- a requirement name
- an URL
- extras
- editable options
Accepted requirements:
svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir
.[some_extra]
"""
url = editable_req
# If a file path is specified with extras, strip off the extras.
url_no_extras, extras = _strip_extras(url)
if os.path.isdir(url_no_extras):
if not os.path.exists(os.path.join(url_no_extras, 'setup.py')):
msg = (
'File "setup.py" not found. Directory cannot be installed '
'in editable mode: {}'.format(os.path.abspath(url_no_extras))
)
pyproject_path = make_pyproject_path(url_no_extras)
if os.path.isfile(pyproject_path):
msg += (
'\n(A "pyproject.toml" file was found, but editable '
'mode currently requires a setup.py based build.)'
)
raise InstallationError(msg)
# Treating it as code that has already been checked out
url_no_extras = path_to_url(url_no_extras)
if url_no_extras.lower().startswith('file:'):
package_name = Link(url_no_extras).egg_fragment
if extras:
return (
package_name,
url_no_extras,
Requirement("placeholder" + extras.lower()).extras,
)
else:
return package_name, url_no_extras, None
for version_control in vcs:
if url.lower().startswith('%s:' % version_control):
url = '%s+%s' % (version_control, url)
break
if '+' not in url:
raise InstallationError(
'%s should either be a path to a local project or a VCS url '
'beginning with svn+, git+, hg+, or bzr+' %
editable_req
)
vc_type = url.split('+', 1)[0].lower()
if not vcs.get_backend(vc_type):
error_message = 'For --editable=%s only ' % editable_req + \
', '.join([backend.name + '+URL' for backend in vcs.backends]) + \
' is currently supported'
raise InstallationError(error_message)
package_name = Link(url).egg_fragment
if not package_name:
raise InstallationError(
"Could not detect requirement name for '%s', please specify one "
"with #egg=your_package_name" % editable_req
)
return package_name, url, None
|
[
"def",
"parse_editable",
"(",
"editable_req",
")",
":",
"# type: (str) -> Tuple[Optional[str], str, Optional[Set[str]]]",
"url",
"=",
"editable_req",
"# If a file path is specified with extras, strip off the extras.",
"url_no_extras",
",",
"extras",
"=",
"_strip_extras",
"(",
"url",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"url_no_extras",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"url_no_extras",
",",
"'setup.py'",
")",
")",
":",
"msg",
"=",
"(",
"'File \"setup.py\" not found. Directory cannot be installed '",
"'in editable mode: {}'",
".",
"format",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"url_no_extras",
")",
")",
")",
"pyproject_path",
"=",
"make_pyproject_path",
"(",
"url_no_extras",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"pyproject_path",
")",
":",
"msg",
"+=",
"(",
"'\\n(A \"pyproject.toml\" file was found, but editable '",
"'mode currently requires a setup.py based build.)'",
")",
"raise",
"InstallationError",
"(",
"msg",
")",
"# Treating it as code that has already been checked out",
"url_no_extras",
"=",
"path_to_url",
"(",
"url_no_extras",
")",
"if",
"url_no_extras",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'file:'",
")",
":",
"package_name",
"=",
"Link",
"(",
"url_no_extras",
")",
".",
"egg_fragment",
"if",
"extras",
":",
"return",
"(",
"package_name",
",",
"url_no_extras",
",",
"Requirement",
"(",
"\"placeholder\"",
"+",
"extras",
".",
"lower",
"(",
")",
")",
".",
"extras",
",",
")",
"else",
":",
"return",
"package_name",
",",
"url_no_extras",
",",
"None",
"for",
"version_control",
"in",
"vcs",
":",
"if",
"url",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'%s:'",
"%",
"version_control",
")",
":",
"url",
"=",
"'%s+%s'",
"%",
"(",
"version_control",
",",
"url",
")",
"break",
"if",
"'+'",
"not",
"in",
"url",
":",
"raise",
"InstallationError",
"(",
"'%s should either be a path to a local project or a VCS url '",
"'beginning with svn+, git+, hg+, or bzr+'",
"%",
"editable_req",
")",
"vc_type",
"=",
"url",
".",
"split",
"(",
"'+'",
",",
"1",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"if",
"not",
"vcs",
".",
"get_backend",
"(",
"vc_type",
")",
":",
"error_message",
"=",
"'For --editable=%s only '",
"%",
"editable_req",
"+",
"', '",
".",
"join",
"(",
"[",
"backend",
".",
"name",
"+",
"'+URL'",
"for",
"backend",
"in",
"vcs",
".",
"backends",
"]",
")",
"+",
"' is currently supported'",
"raise",
"InstallationError",
"(",
"error_message",
")",
"package_name",
"=",
"Link",
"(",
"url",
")",
".",
"egg_fragment",
"if",
"not",
"package_name",
":",
"raise",
"InstallationError",
"(",
"\"Could not detect requirement name for '%s', please specify one \"",
"\"with #egg=your_package_name\"",
"%",
"editable_req",
")",
"return",
"package_name",
",",
"url",
",",
"None"
] |
Parses an editable requirement into:
- a requirement name
- an URL
- extras
- editable options
Accepted requirements:
svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir
.[some_extra]
|
[
"Parses",
"an",
"editable",
"requirement",
"into",
":",
"-",
"a",
"requirement",
"name",
"-",
"an",
"URL",
"-",
"extras",
"-",
"editable",
"options",
"Accepted",
"requirements",
":",
"svn",
"+",
"http",
":",
"//",
"blahblah"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/constructors.py#L62-L133
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/req/constructors.py
|
deduce_helpful_msg
|
def deduce_helpful_msg(req):
# type: (str) -> str
"""Returns helpful msg in case requirements file does not exist,
or cannot be parsed.
:params req: Requirements file path
"""
msg = ""
if os.path.exists(req):
msg = " It does exist."
# Try to parse and check if it is a requirements file.
try:
with open(req, 'r') as fp:
# parse first line only
next(parse_requirements(fp.read()))
msg += " The argument you provided " + \
"(%s) appears to be a" % (req) + \
" requirements file. If that is the" + \
" case, use the '-r' flag to install" + \
" the packages specified within it."
except RequirementParseError:
logger.debug("Cannot parse '%s' as requirements \
file" % (req), exc_info=True)
else:
msg += " File '%s' does not exist." % (req)
return msg
|
python
|
def deduce_helpful_msg(req):
# type: (str) -> str
"""Returns helpful msg in case requirements file does not exist,
or cannot be parsed.
:params req: Requirements file path
"""
msg = ""
if os.path.exists(req):
msg = " It does exist."
# Try to parse and check if it is a requirements file.
try:
with open(req, 'r') as fp:
# parse first line only
next(parse_requirements(fp.read()))
msg += " The argument you provided " + \
"(%s) appears to be a" % (req) + \
" requirements file. If that is the" + \
" case, use the '-r' flag to install" + \
" the packages specified within it."
except RequirementParseError:
logger.debug("Cannot parse '%s' as requirements \
file" % (req), exc_info=True)
else:
msg += " File '%s' does not exist." % (req)
return msg
|
[
"def",
"deduce_helpful_msg",
"(",
"req",
")",
":",
"# type: (str) -> str",
"msg",
"=",
"\"\"",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"req",
")",
":",
"msg",
"=",
"\" It does exist.\"",
"# Try to parse and check if it is a requirements file.",
"try",
":",
"with",
"open",
"(",
"req",
",",
"'r'",
")",
"as",
"fp",
":",
"# parse first line only",
"next",
"(",
"parse_requirements",
"(",
"fp",
".",
"read",
"(",
")",
")",
")",
"msg",
"+=",
"\" The argument you provided \"",
"+",
"\"(%s) appears to be a\"",
"%",
"(",
"req",
")",
"+",
"\" requirements file. If that is the\"",
"+",
"\" case, use the '-r' flag to install\"",
"+",
"\" the packages specified within it.\"",
"except",
"RequirementParseError",
":",
"logger",
".",
"debug",
"(",
"\"Cannot parse '%s' as requirements \\\n file\"",
"%",
"(",
"req",
")",
",",
"exc_info",
"=",
"True",
")",
"else",
":",
"msg",
"+=",
"\" File '%s' does not exist.\"",
"%",
"(",
"req",
")",
"return",
"msg"
] |
Returns helpful msg in case requirements file does not exist,
or cannot be parsed.
:params req: Requirements file path
|
[
"Returns",
"helpful",
"msg",
"in",
"case",
"requirements",
"file",
"does",
"not",
"exist",
"or",
"cannot",
"be",
"parsed",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/constructors.py#L136-L161
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/req/constructors.py
|
install_req_from_line
|
def install_req_from_line(
name, # type: str
comes_from=None, # type: Optional[Union[str, InstallRequirement]]
use_pep517=None, # type: Optional[bool]
isolated=False, # type: bool
options=None, # type: Optional[Dict[str, Any]]
wheel_cache=None, # type: Optional[WheelCache]
constraint=False # type: bool
):
# type: (...) -> InstallRequirement
"""Creates an InstallRequirement from a name, which might be a
requirement, directory containing 'setup.py', filename, or URL.
"""
if is_url(name):
marker_sep = '; '
else:
marker_sep = ';'
if marker_sep in name:
name, markers_as_string = name.split(marker_sep, 1)
markers_as_string = markers_as_string.strip()
if not markers_as_string:
markers = None
else:
markers = Marker(markers_as_string)
else:
markers = None
name = name.strip()
req_as_string = None
path = os.path.normpath(os.path.abspath(name))
link = None
extras_as_string = None
if is_url(name):
link = Link(name)
else:
p, extras_as_string = _strip_extras(path)
looks_like_dir = os.path.isdir(p) and (
os.path.sep in name or
(os.path.altsep is not None and os.path.altsep in name) or
name.startswith('.')
)
if looks_like_dir:
if not is_installable_dir(p):
raise InstallationError(
"Directory %r is not installable. Neither 'setup.py' "
"nor 'pyproject.toml' found." % name
)
link = Link(path_to_url(p))
elif is_archive_file(p):
if not os.path.isfile(p):
logger.warning(
'Requirement %r looks like a filename, but the '
'file does not exist',
name
)
link = Link(path_to_url(p))
# it's a local file, dir, or url
if link:
# Handle relative file URLs
if link.scheme == 'file' and re.search(r'\.\./', link.url):
link = Link(
path_to_url(os.path.normpath(os.path.abspath(link.path))))
# wheel file
if link.is_wheel:
wheel = Wheel(link.filename) # can raise InvalidWheelFilename
req_as_string = "%s==%s" % (wheel.name, wheel.version)
else:
# set the req to the egg fragment. when it's not there, this
# will become an 'unnamed' requirement
req_as_string = link.egg_fragment
# a requirement specifier
else:
req_as_string = name
if extras_as_string:
extras = Requirement("placeholder" + extras_as_string.lower()).extras
else:
extras = ()
if req_as_string is not None:
try:
req = Requirement(req_as_string)
except InvalidRequirement:
if os.path.sep in req_as_string:
add_msg = "It looks like a path."
add_msg += deduce_helpful_msg(req_as_string)
elif ('=' in req_as_string and
not any(op in req_as_string for op in operators)):
add_msg = "= is not a valid operator. Did you mean == ?"
else:
add_msg = ""
raise InstallationError(
"Invalid requirement: '%s'\n%s" % (req_as_string, add_msg)
)
else:
req = None
return InstallRequirement(
req, comes_from, link=link, markers=markers,
use_pep517=use_pep517, isolated=isolated,
options=options if options else {},
wheel_cache=wheel_cache,
constraint=constraint,
extras=extras,
)
|
python
|
def install_req_from_line(
name, # type: str
comes_from=None, # type: Optional[Union[str, InstallRequirement]]
use_pep517=None, # type: Optional[bool]
isolated=False, # type: bool
options=None, # type: Optional[Dict[str, Any]]
wheel_cache=None, # type: Optional[WheelCache]
constraint=False # type: bool
):
# type: (...) -> InstallRequirement
"""Creates an InstallRequirement from a name, which might be a
requirement, directory containing 'setup.py', filename, or URL.
"""
if is_url(name):
marker_sep = '; '
else:
marker_sep = ';'
if marker_sep in name:
name, markers_as_string = name.split(marker_sep, 1)
markers_as_string = markers_as_string.strip()
if not markers_as_string:
markers = None
else:
markers = Marker(markers_as_string)
else:
markers = None
name = name.strip()
req_as_string = None
path = os.path.normpath(os.path.abspath(name))
link = None
extras_as_string = None
if is_url(name):
link = Link(name)
else:
p, extras_as_string = _strip_extras(path)
looks_like_dir = os.path.isdir(p) and (
os.path.sep in name or
(os.path.altsep is not None and os.path.altsep in name) or
name.startswith('.')
)
if looks_like_dir:
if not is_installable_dir(p):
raise InstallationError(
"Directory %r is not installable. Neither 'setup.py' "
"nor 'pyproject.toml' found." % name
)
link = Link(path_to_url(p))
elif is_archive_file(p):
if not os.path.isfile(p):
logger.warning(
'Requirement %r looks like a filename, but the '
'file does not exist',
name
)
link = Link(path_to_url(p))
# it's a local file, dir, or url
if link:
# Handle relative file URLs
if link.scheme == 'file' and re.search(r'\.\./', link.url):
link = Link(
path_to_url(os.path.normpath(os.path.abspath(link.path))))
# wheel file
if link.is_wheel:
wheel = Wheel(link.filename) # can raise InvalidWheelFilename
req_as_string = "%s==%s" % (wheel.name, wheel.version)
else:
# set the req to the egg fragment. when it's not there, this
# will become an 'unnamed' requirement
req_as_string = link.egg_fragment
# a requirement specifier
else:
req_as_string = name
if extras_as_string:
extras = Requirement("placeholder" + extras_as_string.lower()).extras
else:
extras = ()
if req_as_string is not None:
try:
req = Requirement(req_as_string)
except InvalidRequirement:
if os.path.sep in req_as_string:
add_msg = "It looks like a path."
add_msg += deduce_helpful_msg(req_as_string)
elif ('=' in req_as_string and
not any(op in req_as_string for op in operators)):
add_msg = "= is not a valid operator. Did you mean == ?"
else:
add_msg = ""
raise InstallationError(
"Invalid requirement: '%s'\n%s" % (req_as_string, add_msg)
)
else:
req = None
return InstallRequirement(
req, comes_from, link=link, markers=markers,
use_pep517=use_pep517, isolated=isolated,
options=options if options else {},
wheel_cache=wheel_cache,
constraint=constraint,
extras=extras,
)
|
[
"def",
"install_req_from_line",
"(",
"name",
",",
"# type: str",
"comes_from",
"=",
"None",
",",
"# type: Optional[Union[str, InstallRequirement]]",
"use_pep517",
"=",
"None",
",",
"# type: Optional[bool]",
"isolated",
"=",
"False",
",",
"# type: bool",
"options",
"=",
"None",
",",
"# type: Optional[Dict[str, Any]]",
"wheel_cache",
"=",
"None",
",",
"# type: Optional[WheelCache]",
"constraint",
"=",
"False",
"# type: bool",
")",
":",
"# type: (...) -> InstallRequirement",
"if",
"is_url",
"(",
"name",
")",
":",
"marker_sep",
"=",
"'; '",
"else",
":",
"marker_sep",
"=",
"';'",
"if",
"marker_sep",
"in",
"name",
":",
"name",
",",
"markers_as_string",
"=",
"name",
".",
"split",
"(",
"marker_sep",
",",
"1",
")",
"markers_as_string",
"=",
"markers_as_string",
".",
"strip",
"(",
")",
"if",
"not",
"markers_as_string",
":",
"markers",
"=",
"None",
"else",
":",
"markers",
"=",
"Marker",
"(",
"markers_as_string",
")",
"else",
":",
"markers",
"=",
"None",
"name",
"=",
"name",
".",
"strip",
"(",
")",
"req_as_string",
"=",
"None",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"name",
")",
")",
"link",
"=",
"None",
"extras_as_string",
"=",
"None",
"if",
"is_url",
"(",
"name",
")",
":",
"link",
"=",
"Link",
"(",
"name",
")",
"else",
":",
"p",
",",
"extras_as_string",
"=",
"_strip_extras",
"(",
"path",
")",
"looks_like_dir",
"=",
"os",
".",
"path",
".",
"isdir",
"(",
"p",
")",
"and",
"(",
"os",
".",
"path",
".",
"sep",
"in",
"name",
"or",
"(",
"os",
".",
"path",
".",
"altsep",
"is",
"not",
"None",
"and",
"os",
".",
"path",
".",
"altsep",
"in",
"name",
")",
"or",
"name",
".",
"startswith",
"(",
"'.'",
")",
")",
"if",
"looks_like_dir",
":",
"if",
"not",
"is_installable_dir",
"(",
"p",
")",
":",
"raise",
"InstallationError",
"(",
"\"Directory %r is not installable. Neither 'setup.py' \"",
"\"nor 'pyproject.toml' found.\"",
"%",
"name",
")",
"link",
"=",
"Link",
"(",
"path_to_url",
"(",
"p",
")",
")",
"elif",
"is_archive_file",
"(",
"p",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"p",
")",
":",
"logger",
".",
"warning",
"(",
"'Requirement %r looks like a filename, but the '",
"'file does not exist'",
",",
"name",
")",
"link",
"=",
"Link",
"(",
"path_to_url",
"(",
"p",
")",
")",
"# it's a local file, dir, or url",
"if",
"link",
":",
"# Handle relative file URLs",
"if",
"link",
".",
"scheme",
"==",
"'file'",
"and",
"re",
".",
"search",
"(",
"r'\\.\\./'",
",",
"link",
".",
"url",
")",
":",
"link",
"=",
"Link",
"(",
"path_to_url",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"link",
".",
"path",
")",
")",
")",
")",
"# wheel file",
"if",
"link",
".",
"is_wheel",
":",
"wheel",
"=",
"Wheel",
"(",
"link",
".",
"filename",
")",
"# can raise InvalidWheelFilename",
"req_as_string",
"=",
"\"%s==%s\"",
"%",
"(",
"wheel",
".",
"name",
",",
"wheel",
".",
"version",
")",
"else",
":",
"# set the req to the egg fragment. when it's not there, this",
"# will become an 'unnamed' requirement",
"req_as_string",
"=",
"link",
".",
"egg_fragment",
"# a requirement specifier",
"else",
":",
"req_as_string",
"=",
"name",
"if",
"extras_as_string",
":",
"extras",
"=",
"Requirement",
"(",
"\"placeholder\"",
"+",
"extras_as_string",
".",
"lower",
"(",
")",
")",
".",
"extras",
"else",
":",
"extras",
"=",
"(",
")",
"if",
"req_as_string",
"is",
"not",
"None",
":",
"try",
":",
"req",
"=",
"Requirement",
"(",
"req_as_string",
")",
"except",
"InvalidRequirement",
":",
"if",
"os",
".",
"path",
".",
"sep",
"in",
"req_as_string",
":",
"add_msg",
"=",
"\"It looks like a path.\"",
"add_msg",
"+=",
"deduce_helpful_msg",
"(",
"req_as_string",
")",
"elif",
"(",
"'='",
"in",
"req_as_string",
"and",
"not",
"any",
"(",
"op",
"in",
"req_as_string",
"for",
"op",
"in",
"operators",
")",
")",
":",
"add_msg",
"=",
"\"= is not a valid operator. Did you mean == ?\"",
"else",
":",
"add_msg",
"=",
"\"\"",
"raise",
"InstallationError",
"(",
"\"Invalid requirement: '%s'\\n%s\"",
"%",
"(",
"req_as_string",
",",
"add_msg",
")",
")",
"else",
":",
"req",
"=",
"None",
"return",
"InstallRequirement",
"(",
"req",
",",
"comes_from",
",",
"link",
"=",
"link",
",",
"markers",
"=",
"markers",
",",
"use_pep517",
"=",
"use_pep517",
",",
"isolated",
"=",
"isolated",
",",
"options",
"=",
"options",
"if",
"options",
"else",
"{",
"}",
",",
"wheel_cache",
"=",
"wheel_cache",
",",
"constraint",
"=",
"constraint",
",",
"extras",
"=",
"extras",
",",
")"
] |
Creates an InstallRequirement from a name, which might be a
requirement, directory containing 'setup.py', filename, or URL.
|
[
"Creates",
"an",
"InstallRequirement",
"from",
"a",
"name",
"which",
"might",
"be",
"a",
"requirement",
"directory",
"containing",
"setup",
".",
"py",
"filename",
"or",
"URL",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/constructors.py#L203-L308
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/cachecontrol/caches/file_cache.py
|
url_to_file_path
|
def url_to_file_path(url, filecache):
"""Return the file cache path based on the URL.
This does not ensure the file exists!
"""
key = CacheController.cache_url(url)
return filecache._fn(key)
|
python
|
def url_to_file_path(url, filecache):
"""Return the file cache path based on the URL.
This does not ensure the file exists!
"""
key = CacheController.cache_url(url)
return filecache._fn(key)
|
[
"def",
"url_to_file_path",
"(",
"url",
",",
"filecache",
")",
":",
"key",
"=",
"CacheController",
".",
"cache_url",
"(",
"url",
")",
"return",
"filecache",
".",
"_fn",
"(",
"key",
")"
] |
Return the file cache path based on the URL.
This does not ensure the file exists!
|
[
"Return",
"the",
"file",
"cache",
"path",
"based",
"on",
"the",
"URL",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/cachecontrol/caches/file_cache.py#L140-L146
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/lockfile/pidlockfile.py
|
write_pid_to_pidfile
|
def write_pid_to_pidfile(pidfile_path):
""" Write the PID in the named PID file.
Get the numeric process ID (“PID”) of the current process
and write it to the named file as a line of text.
"""
open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
open_mode = 0o644
pidfile_fd = os.open(pidfile_path, open_flags, open_mode)
pidfile = os.fdopen(pidfile_fd, 'w')
# According to the FHS 2.3 section on PID files in /var/run:
#
# The file must consist of the process identifier in
# ASCII-encoded decimal, followed by a newline character. For
# example, if crond was process number 25, /var/run/crond.pid
# would contain three characters: two, five, and newline.
pid = os.getpid()
pidfile.write("%s\n" % pid)
pidfile.close()
|
python
|
def write_pid_to_pidfile(pidfile_path):
""" Write the PID in the named PID file.
Get the numeric process ID (“PID”) of the current process
and write it to the named file as a line of text.
"""
open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
open_mode = 0o644
pidfile_fd = os.open(pidfile_path, open_flags, open_mode)
pidfile = os.fdopen(pidfile_fd, 'w')
# According to the FHS 2.3 section on PID files in /var/run:
#
# The file must consist of the process identifier in
# ASCII-encoded decimal, followed by a newline character. For
# example, if crond was process number 25, /var/run/crond.pid
# would contain three characters: two, five, and newline.
pid = os.getpid()
pidfile.write("%s\n" % pid)
pidfile.close()
|
[
"def",
"write_pid_to_pidfile",
"(",
"pidfile_path",
")",
":",
"open_flags",
"=",
"(",
"os",
".",
"O_CREAT",
"|",
"os",
".",
"O_EXCL",
"|",
"os",
".",
"O_WRONLY",
")",
"open_mode",
"=",
"0o644",
"pidfile_fd",
"=",
"os",
".",
"open",
"(",
"pidfile_path",
",",
"open_flags",
",",
"open_mode",
")",
"pidfile",
"=",
"os",
".",
"fdopen",
"(",
"pidfile_fd",
",",
"'w'",
")",
"# According to the FHS 2.3 section on PID files in /var/run:",
"#",
"# The file must consist of the process identifier in",
"# ASCII-encoded decimal, followed by a newline character. For",
"# example, if crond was process number 25, /var/run/crond.pid",
"# would contain three characters: two, five, and newline.",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"pidfile",
".",
"write",
"(",
"\"%s\\n\"",
"%",
"pid",
")",
"pidfile",
".",
"close",
"(",
")"
] |
Write the PID in the named PID file.
Get the numeric process ID (“PID”) of the current process
and write it to the named file as a line of text.
|
[
"Write",
"the",
"PID",
"in",
"the",
"named",
"PID",
"file",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/lockfile/pidlockfile.py#L152-L173
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/lockfile/pidlockfile.py
|
remove_existing_pidfile
|
def remove_existing_pidfile(pidfile_path):
""" Remove the named PID file if it exists.
Removing a PID file that doesn't already exist puts us in the
desired state, so we ignore the condition if the file does not
exist.
"""
try:
os.remove(pidfile_path)
except OSError as exc:
if exc.errno == errno.ENOENT:
pass
else:
raise
|
python
|
def remove_existing_pidfile(pidfile_path):
""" Remove the named PID file if it exists.
Removing a PID file that doesn't already exist puts us in the
desired state, so we ignore the condition if the file does not
exist.
"""
try:
os.remove(pidfile_path)
except OSError as exc:
if exc.errno == errno.ENOENT:
pass
else:
raise
|
[
"def",
"remove_existing_pidfile",
"(",
"pidfile_path",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"pidfile_path",
")",
"except",
"OSError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"pass",
"else",
":",
"raise"
] |
Remove the named PID file if it exists.
Removing a PID file that doesn't already exist puts us in the
desired state, so we ignore the condition if the file does not
exist.
|
[
"Remove",
"the",
"named",
"PID",
"file",
"if",
"it",
"exists",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/lockfile/pidlockfile.py#L176-L190
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/lockfile/pidlockfile.py
|
PIDLockFile.release
|
def release(self):
""" Release the lock.
Removes the PID file to release the lock, or raises an
error if the current process does not hold the lock.
"""
if not self.is_locked():
raise NotLocked("%s is not locked" % self.path)
if not self.i_am_locking():
raise NotMyLock("%s is locked, but not by me" % self.path)
remove_existing_pidfile(self.path)
|
python
|
def release(self):
""" Release the lock.
Removes the PID file to release the lock, or raises an
error if the current process does not hold the lock.
"""
if not self.is_locked():
raise NotLocked("%s is not locked" % self.path)
if not self.i_am_locking():
raise NotMyLock("%s is locked, but not by me" % self.path)
remove_existing_pidfile(self.path)
|
[
"def",
"release",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_locked",
"(",
")",
":",
"raise",
"NotLocked",
"(",
"\"%s is not locked\"",
"%",
"self",
".",
"path",
")",
"if",
"not",
"self",
".",
"i_am_locking",
"(",
")",
":",
"raise",
"NotMyLock",
"(",
"\"%s is locked, but not by me\"",
"%",
"self",
".",
"path",
")",
"remove_existing_pidfile",
"(",
"self",
".",
"path",
")"
] |
Release the lock.
Removes the PID file to release the lock, or raises an
error if the current process does not hold the lock.
|
[
"Release",
"the",
"lock",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/lockfile/pidlockfile.py#L95-L106
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/vcs/bazaar.py
|
Bazaar.export
|
def export(self, location):
"""
Export the Bazaar repository at the url to the destination location
"""
# Remove the location to make sure Bazaar can export it correctly
if os.path.exists(location):
rmtree(location)
with TempDirectory(kind="export") as temp_dir:
self.unpack(temp_dir.path)
self.run_command(
['export', location],
cwd=temp_dir.path, show_stdout=False,
)
|
python
|
def export(self, location):
"""
Export the Bazaar repository at the url to the destination location
"""
# Remove the location to make sure Bazaar can export it correctly
if os.path.exists(location):
rmtree(location)
with TempDirectory(kind="export") as temp_dir:
self.unpack(temp_dir.path)
self.run_command(
['export', location],
cwd=temp_dir.path, show_stdout=False,
)
|
[
"def",
"export",
"(",
"self",
",",
"location",
")",
":",
"# Remove the location to make sure Bazaar can export it correctly",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"location",
")",
":",
"rmtree",
"(",
"location",
")",
"with",
"TempDirectory",
"(",
"kind",
"=",
"\"export\"",
")",
"as",
"temp_dir",
":",
"self",
".",
"unpack",
"(",
"temp_dir",
".",
"path",
")",
"self",
".",
"run_command",
"(",
"[",
"'export'",
",",
"location",
"]",
",",
"cwd",
"=",
"temp_dir",
".",
"path",
",",
"show_stdout",
"=",
"False",
",",
")"
] |
Export the Bazaar repository at the url to the destination location
|
[
"Export",
"the",
"Bazaar",
"repository",
"at",
"the",
"url",
"to",
"the",
"destination",
"location"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/bazaar.py#L37-L51
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/commands/show.py
|
search_packages_info
|
def search_packages_info(query):
"""
Gather details from installed distributions. Print distribution name,
version, location, and installed files. Installed files requires a
pip generated 'installed-files.txt' in the distributions '.egg-info'
directory.
"""
installed = {}
for p in pkg_resources.working_set:
installed[canonicalize_name(p.project_name)] = p
query_names = [canonicalize_name(name) for name in query]
for dist in [installed[pkg] for pkg in query_names if pkg in installed]:
package = {
'name': dist.project_name,
'version': dist.version,
'location': dist.location,
'requires': [dep.project_name for dep in dist.requires()],
}
file_list = None
metadata = None
if isinstance(dist, pkg_resources.DistInfoDistribution):
# RECORDs should be part of .dist-info metadatas
if dist.has_metadata('RECORD'):
lines = dist.get_metadata_lines('RECORD')
paths = [l.split(',')[0] for l in lines]
paths = [os.path.join(dist.location, p) for p in paths]
file_list = [os.path.relpath(p, dist.location) for p in paths]
if dist.has_metadata('METADATA'):
metadata = dist.get_metadata('METADATA')
else:
# Otherwise use pip's log for .egg-info's
if dist.has_metadata('installed-files.txt'):
paths = dist.get_metadata_lines('installed-files.txt')
paths = [os.path.join(dist.egg_info, p) for p in paths]
file_list = [os.path.relpath(p, dist.location) for p in paths]
if dist.has_metadata('PKG-INFO'):
metadata = dist.get_metadata('PKG-INFO')
if dist.has_metadata('entry_points.txt'):
entry_points = dist.get_metadata_lines('entry_points.txt')
package['entry_points'] = entry_points
if dist.has_metadata('INSTALLER'):
for line in dist.get_metadata_lines('INSTALLER'):
if line.strip():
package['installer'] = line.strip()
break
# @todo: Should pkg_resources.Distribution have a
# `get_pkg_info` method?
feed_parser = FeedParser()
feed_parser.feed(metadata)
pkg_info_dict = feed_parser.close()
for key in ('metadata-version', 'summary',
'home-page', 'author', 'author-email', 'license'):
package[key] = pkg_info_dict.get(key)
# It looks like FeedParser cannot deal with repeated headers
classifiers = []
for line in metadata.splitlines():
if line.startswith('Classifier: '):
classifiers.append(line[len('Classifier: '):])
package['classifiers'] = classifiers
if file_list:
package['files'] = sorted(file_list)
yield package
|
python
|
def search_packages_info(query):
"""
Gather details from installed distributions. Print distribution name,
version, location, and installed files. Installed files requires a
pip generated 'installed-files.txt' in the distributions '.egg-info'
directory.
"""
installed = {}
for p in pkg_resources.working_set:
installed[canonicalize_name(p.project_name)] = p
query_names = [canonicalize_name(name) for name in query]
for dist in [installed[pkg] for pkg in query_names if pkg in installed]:
package = {
'name': dist.project_name,
'version': dist.version,
'location': dist.location,
'requires': [dep.project_name for dep in dist.requires()],
}
file_list = None
metadata = None
if isinstance(dist, pkg_resources.DistInfoDistribution):
# RECORDs should be part of .dist-info metadatas
if dist.has_metadata('RECORD'):
lines = dist.get_metadata_lines('RECORD')
paths = [l.split(',')[0] for l in lines]
paths = [os.path.join(dist.location, p) for p in paths]
file_list = [os.path.relpath(p, dist.location) for p in paths]
if dist.has_metadata('METADATA'):
metadata = dist.get_metadata('METADATA')
else:
# Otherwise use pip's log for .egg-info's
if dist.has_metadata('installed-files.txt'):
paths = dist.get_metadata_lines('installed-files.txt')
paths = [os.path.join(dist.egg_info, p) for p in paths]
file_list = [os.path.relpath(p, dist.location) for p in paths]
if dist.has_metadata('PKG-INFO'):
metadata = dist.get_metadata('PKG-INFO')
if dist.has_metadata('entry_points.txt'):
entry_points = dist.get_metadata_lines('entry_points.txt')
package['entry_points'] = entry_points
if dist.has_metadata('INSTALLER'):
for line in dist.get_metadata_lines('INSTALLER'):
if line.strip():
package['installer'] = line.strip()
break
# @todo: Should pkg_resources.Distribution have a
# `get_pkg_info` method?
feed_parser = FeedParser()
feed_parser.feed(metadata)
pkg_info_dict = feed_parser.close()
for key in ('metadata-version', 'summary',
'home-page', 'author', 'author-email', 'license'):
package[key] = pkg_info_dict.get(key)
# It looks like FeedParser cannot deal with repeated headers
classifiers = []
for line in metadata.splitlines():
if line.startswith('Classifier: '):
classifiers.append(line[len('Classifier: '):])
package['classifiers'] = classifiers
if file_list:
package['files'] = sorted(file_list)
yield package
|
[
"def",
"search_packages_info",
"(",
"query",
")",
":",
"installed",
"=",
"{",
"}",
"for",
"p",
"in",
"pkg_resources",
".",
"working_set",
":",
"installed",
"[",
"canonicalize_name",
"(",
"p",
".",
"project_name",
")",
"]",
"=",
"p",
"query_names",
"=",
"[",
"canonicalize_name",
"(",
"name",
")",
"for",
"name",
"in",
"query",
"]",
"for",
"dist",
"in",
"[",
"installed",
"[",
"pkg",
"]",
"for",
"pkg",
"in",
"query_names",
"if",
"pkg",
"in",
"installed",
"]",
":",
"package",
"=",
"{",
"'name'",
":",
"dist",
".",
"project_name",
",",
"'version'",
":",
"dist",
".",
"version",
",",
"'location'",
":",
"dist",
".",
"location",
",",
"'requires'",
":",
"[",
"dep",
".",
"project_name",
"for",
"dep",
"in",
"dist",
".",
"requires",
"(",
")",
"]",
",",
"}",
"file_list",
"=",
"None",
"metadata",
"=",
"None",
"if",
"isinstance",
"(",
"dist",
",",
"pkg_resources",
".",
"DistInfoDistribution",
")",
":",
"# RECORDs should be part of .dist-info metadatas",
"if",
"dist",
".",
"has_metadata",
"(",
"'RECORD'",
")",
":",
"lines",
"=",
"dist",
".",
"get_metadata_lines",
"(",
"'RECORD'",
")",
"paths",
"=",
"[",
"l",
".",
"split",
"(",
"','",
")",
"[",
"0",
"]",
"for",
"l",
"in",
"lines",
"]",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"dist",
".",
"location",
",",
"p",
")",
"for",
"p",
"in",
"paths",
"]",
"file_list",
"=",
"[",
"os",
".",
"path",
".",
"relpath",
"(",
"p",
",",
"dist",
".",
"location",
")",
"for",
"p",
"in",
"paths",
"]",
"if",
"dist",
".",
"has_metadata",
"(",
"'METADATA'",
")",
":",
"metadata",
"=",
"dist",
".",
"get_metadata",
"(",
"'METADATA'",
")",
"else",
":",
"# Otherwise use pip's log for .egg-info's",
"if",
"dist",
".",
"has_metadata",
"(",
"'installed-files.txt'",
")",
":",
"paths",
"=",
"dist",
".",
"get_metadata_lines",
"(",
"'installed-files.txt'",
")",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"dist",
".",
"egg_info",
",",
"p",
")",
"for",
"p",
"in",
"paths",
"]",
"file_list",
"=",
"[",
"os",
".",
"path",
".",
"relpath",
"(",
"p",
",",
"dist",
".",
"location",
")",
"for",
"p",
"in",
"paths",
"]",
"if",
"dist",
".",
"has_metadata",
"(",
"'PKG-INFO'",
")",
":",
"metadata",
"=",
"dist",
".",
"get_metadata",
"(",
"'PKG-INFO'",
")",
"if",
"dist",
".",
"has_metadata",
"(",
"'entry_points.txt'",
")",
":",
"entry_points",
"=",
"dist",
".",
"get_metadata_lines",
"(",
"'entry_points.txt'",
")",
"package",
"[",
"'entry_points'",
"]",
"=",
"entry_points",
"if",
"dist",
".",
"has_metadata",
"(",
"'INSTALLER'",
")",
":",
"for",
"line",
"in",
"dist",
".",
"get_metadata_lines",
"(",
"'INSTALLER'",
")",
":",
"if",
"line",
".",
"strip",
"(",
")",
":",
"package",
"[",
"'installer'",
"]",
"=",
"line",
".",
"strip",
"(",
")",
"break",
"# @todo: Should pkg_resources.Distribution have a",
"# `get_pkg_info` method?",
"feed_parser",
"=",
"FeedParser",
"(",
")",
"feed_parser",
".",
"feed",
"(",
"metadata",
")",
"pkg_info_dict",
"=",
"feed_parser",
".",
"close",
"(",
")",
"for",
"key",
"in",
"(",
"'metadata-version'",
",",
"'summary'",
",",
"'home-page'",
",",
"'author'",
",",
"'author-email'",
",",
"'license'",
")",
":",
"package",
"[",
"key",
"]",
"=",
"pkg_info_dict",
".",
"get",
"(",
"key",
")",
"# It looks like FeedParser cannot deal with repeated headers",
"classifiers",
"=",
"[",
"]",
"for",
"line",
"in",
"metadata",
".",
"splitlines",
"(",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'Classifier: '",
")",
":",
"classifiers",
".",
"append",
"(",
"line",
"[",
"len",
"(",
"'Classifier: '",
")",
":",
"]",
")",
"package",
"[",
"'classifiers'",
"]",
"=",
"classifiers",
"if",
"file_list",
":",
"package",
"[",
"'files'",
"]",
"=",
"sorted",
"(",
"file_list",
")",
"yield",
"package"
] |
Gather details from installed distributions. Print distribution name,
version, location, and installed files. Installed files requires a
pip generated 'installed-files.txt' in the distributions '.egg-info'
directory.
|
[
"Gather",
"details",
"from",
"installed",
"distributions",
".",
"Print",
"distribution",
"name",
"version",
"location",
"and",
"installed",
"files",
".",
"Installed",
"files",
"requires",
"a",
"pip",
"generated",
"installed",
"-",
"files",
".",
"txt",
"in",
"the",
"distributions",
".",
"egg",
"-",
"info",
"directory",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/commands/show.py#L52-L122
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/commands/show.py
|
print_results
|
def print_results(distributions, list_files=False, verbose=False):
"""
Print the informations from installed distributions found.
"""
results_printed = False
for i, dist in enumerate(distributions):
results_printed = True
if i > 0:
logger.info("---")
name = dist.get('name', '')
required_by = [
pkg.project_name for pkg in pkg_resources.working_set
if name in [required.name for required in pkg.requires()]
]
logger.info("Name: %s", name)
logger.info("Version: %s", dist.get('version', ''))
logger.info("Summary: %s", dist.get('summary', ''))
logger.info("Home-page: %s", dist.get('home-page', ''))
logger.info("Author: %s", dist.get('author', ''))
logger.info("Author-email: %s", dist.get('author-email', ''))
logger.info("License: %s", dist.get('license', ''))
logger.info("Location: %s", dist.get('location', ''))
logger.info("Requires: %s", ', '.join(dist.get('requires', [])))
logger.info("Required-by: %s", ', '.join(required_by))
if verbose:
logger.info("Metadata-Version: %s",
dist.get('metadata-version', ''))
logger.info("Installer: %s", dist.get('installer', ''))
logger.info("Classifiers:")
for classifier in dist.get('classifiers', []):
logger.info(" %s", classifier)
logger.info("Entry-points:")
for entry in dist.get('entry_points', []):
logger.info(" %s", entry.strip())
if list_files:
logger.info("Files:")
for line in dist.get('files', []):
logger.info(" %s", line.strip())
if "files" not in dist:
logger.info("Cannot locate installed-files.txt")
return results_printed
|
python
|
def print_results(distributions, list_files=False, verbose=False):
"""
Print the informations from installed distributions found.
"""
results_printed = False
for i, dist in enumerate(distributions):
results_printed = True
if i > 0:
logger.info("---")
name = dist.get('name', '')
required_by = [
pkg.project_name for pkg in pkg_resources.working_set
if name in [required.name for required in pkg.requires()]
]
logger.info("Name: %s", name)
logger.info("Version: %s", dist.get('version', ''))
logger.info("Summary: %s", dist.get('summary', ''))
logger.info("Home-page: %s", dist.get('home-page', ''))
logger.info("Author: %s", dist.get('author', ''))
logger.info("Author-email: %s", dist.get('author-email', ''))
logger.info("License: %s", dist.get('license', ''))
logger.info("Location: %s", dist.get('location', ''))
logger.info("Requires: %s", ', '.join(dist.get('requires', [])))
logger.info("Required-by: %s", ', '.join(required_by))
if verbose:
logger.info("Metadata-Version: %s",
dist.get('metadata-version', ''))
logger.info("Installer: %s", dist.get('installer', ''))
logger.info("Classifiers:")
for classifier in dist.get('classifiers', []):
logger.info(" %s", classifier)
logger.info("Entry-points:")
for entry in dist.get('entry_points', []):
logger.info(" %s", entry.strip())
if list_files:
logger.info("Files:")
for line in dist.get('files', []):
logger.info(" %s", line.strip())
if "files" not in dist:
logger.info("Cannot locate installed-files.txt")
return results_printed
|
[
"def",
"print_results",
"(",
"distributions",
",",
"list_files",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"results_printed",
"=",
"False",
"for",
"i",
",",
"dist",
"in",
"enumerate",
"(",
"distributions",
")",
":",
"results_printed",
"=",
"True",
"if",
"i",
">",
"0",
":",
"logger",
".",
"info",
"(",
"\"---\"",
")",
"name",
"=",
"dist",
".",
"get",
"(",
"'name'",
",",
"''",
")",
"required_by",
"=",
"[",
"pkg",
".",
"project_name",
"for",
"pkg",
"in",
"pkg_resources",
".",
"working_set",
"if",
"name",
"in",
"[",
"required",
".",
"name",
"for",
"required",
"in",
"pkg",
".",
"requires",
"(",
")",
"]",
"]",
"logger",
".",
"info",
"(",
"\"Name: %s\"",
",",
"name",
")",
"logger",
".",
"info",
"(",
"\"Version: %s\"",
",",
"dist",
".",
"get",
"(",
"'version'",
",",
"''",
")",
")",
"logger",
".",
"info",
"(",
"\"Summary: %s\"",
",",
"dist",
".",
"get",
"(",
"'summary'",
",",
"''",
")",
")",
"logger",
".",
"info",
"(",
"\"Home-page: %s\"",
",",
"dist",
".",
"get",
"(",
"'home-page'",
",",
"''",
")",
")",
"logger",
".",
"info",
"(",
"\"Author: %s\"",
",",
"dist",
".",
"get",
"(",
"'author'",
",",
"''",
")",
")",
"logger",
".",
"info",
"(",
"\"Author-email: %s\"",
",",
"dist",
".",
"get",
"(",
"'author-email'",
",",
"''",
")",
")",
"logger",
".",
"info",
"(",
"\"License: %s\"",
",",
"dist",
".",
"get",
"(",
"'license'",
",",
"''",
")",
")",
"logger",
".",
"info",
"(",
"\"Location: %s\"",
",",
"dist",
".",
"get",
"(",
"'location'",
",",
"''",
")",
")",
"logger",
".",
"info",
"(",
"\"Requires: %s\"",
",",
"', '",
".",
"join",
"(",
"dist",
".",
"get",
"(",
"'requires'",
",",
"[",
"]",
")",
")",
")",
"logger",
".",
"info",
"(",
"\"Required-by: %s\"",
",",
"', '",
".",
"join",
"(",
"required_by",
")",
")",
"if",
"verbose",
":",
"logger",
".",
"info",
"(",
"\"Metadata-Version: %s\"",
",",
"dist",
".",
"get",
"(",
"'metadata-version'",
",",
"''",
")",
")",
"logger",
".",
"info",
"(",
"\"Installer: %s\"",
",",
"dist",
".",
"get",
"(",
"'installer'",
",",
"''",
")",
")",
"logger",
".",
"info",
"(",
"\"Classifiers:\"",
")",
"for",
"classifier",
"in",
"dist",
".",
"get",
"(",
"'classifiers'",
",",
"[",
"]",
")",
":",
"logger",
".",
"info",
"(",
"\" %s\"",
",",
"classifier",
")",
"logger",
".",
"info",
"(",
"\"Entry-points:\"",
")",
"for",
"entry",
"in",
"dist",
".",
"get",
"(",
"'entry_points'",
",",
"[",
"]",
")",
":",
"logger",
".",
"info",
"(",
"\" %s\"",
",",
"entry",
".",
"strip",
"(",
")",
")",
"if",
"list_files",
":",
"logger",
".",
"info",
"(",
"\"Files:\"",
")",
"for",
"line",
"in",
"dist",
".",
"get",
"(",
"'files'",
",",
"[",
"]",
")",
":",
"logger",
".",
"info",
"(",
"\" %s\"",
",",
"line",
".",
"strip",
"(",
")",
")",
"if",
"\"files\"",
"not",
"in",
"dist",
":",
"logger",
".",
"info",
"(",
"\"Cannot locate installed-files.txt\"",
")",
"return",
"results_printed"
] |
Print the informations from installed distributions found.
|
[
"Print",
"the",
"informations",
"from",
"installed",
"distributions",
"found",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/commands/show.py#L125-L168
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/parser.py
|
Parser.fail
|
def fail(self, msg, lineno=None, exc=TemplateSyntaxError):
"""Convenience method that raises `exc` with the message, passed
line number or last line number as well as the current name and
filename.
"""
if lineno is None:
lineno = self.stream.current.lineno
raise exc(msg, lineno, self.name, self.filename)
|
python
|
def fail(self, msg, lineno=None, exc=TemplateSyntaxError):
"""Convenience method that raises `exc` with the message, passed
line number or last line number as well as the current name and
filename.
"""
if lineno is None:
lineno = self.stream.current.lineno
raise exc(msg, lineno, self.name, self.filename)
|
[
"def",
"fail",
"(",
"self",
",",
"msg",
",",
"lineno",
"=",
"None",
",",
"exc",
"=",
"TemplateSyntaxError",
")",
":",
"if",
"lineno",
"is",
"None",
":",
"lineno",
"=",
"self",
".",
"stream",
".",
"current",
".",
"lineno",
"raise",
"exc",
"(",
"msg",
",",
"lineno",
",",
"self",
".",
"name",
",",
"self",
".",
"filename",
")"
] |
Convenience method that raises `exc` with the message, passed
line number or last line number as well as the current name and
filename.
|
[
"Convenience",
"method",
"that",
"raises",
"exc",
"with",
"the",
"message",
"passed",
"line",
"number",
"or",
"last",
"line",
"number",
"as",
"well",
"as",
"the",
"current",
"name",
"and",
"filename",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L52-L59
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/parser.py
|
Parser.fail_unknown_tag
|
def fail_unknown_tag(self, name, lineno=None):
"""Called if the parser encounters an unknown tag. Tries to fail
with a human readable error message that could help to identify
the problem.
"""
return self._fail_ut_eof(name, self._end_token_stack, lineno)
|
python
|
def fail_unknown_tag(self, name, lineno=None):
"""Called if the parser encounters an unknown tag. Tries to fail
with a human readable error message that could help to identify
the problem.
"""
return self._fail_ut_eof(name, self._end_token_stack, lineno)
|
[
"def",
"fail_unknown_tag",
"(",
"self",
",",
"name",
",",
"lineno",
"=",
"None",
")",
":",
"return",
"self",
".",
"_fail_ut_eof",
"(",
"name",
",",
"self",
".",
"_end_token_stack",
",",
"lineno",
")"
] |
Called if the parser encounters an unknown tag. Tries to fail
with a human readable error message that could help to identify
the problem.
|
[
"Called",
"if",
"the",
"parser",
"encounters",
"an",
"unknown",
"tag",
".",
"Tries",
"to",
"fail",
"with",
"a",
"human",
"readable",
"error",
"message",
"that",
"could",
"help",
"to",
"identify",
"the",
"problem",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L92-L97
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/parser.py
|
Parser.fail_eof
|
def fail_eof(self, end_tokens=None, lineno=None):
"""Like fail_unknown_tag but for end of template situations."""
stack = list(self._end_token_stack)
if end_tokens is not None:
stack.append(end_tokens)
return self._fail_ut_eof(None, stack, lineno)
|
python
|
def fail_eof(self, end_tokens=None, lineno=None):
"""Like fail_unknown_tag but for end of template situations."""
stack = list(self._end_token_stack)
if end_tokens is not None:
stack.append(end_tokens)
return self._fail_ut_eof(None, stack, lineno)
|
[
"def",
"fail_eof",
"(",
"self",
",",
"end_tokens",
"=",
"None",
",",
"lineno",
"=",
"None",
")",
":",
"stack",
"=",
"list",
"(",
"self",
".",
"_end_token_stack",
")",
"if",
"end_tokens",
"is",
"not",
"None",
":",
"stack",
".",
"append",
"(",
"end_tokens",
")",
"return",
"self",
".",
"_fail_ut_eof",
"(",
"None",
",",
"stack",
",",
"lineno",
")"
] |
Like fail_unknown_tag but for end of template situations.
|
[
"Like",
"fail_unknown_tag",
"but",
"for",
"end",
"of",
"template",
"situations",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L99-L104
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/parser.py
|
Parser.is_tuple_end
|
def is_tuple_end(self, extra_end_rules=None):
"""Are we at the end of a tuple?"""
if self.stream.current.type in ('variable_end', 'block_end', 'rparen'):
return True
elif extra_end_rules is not None:
return self.stream.current.test_any(extra_end_rules)
return False
|
python
|
def is_tuple_end(self, extra_end_rules=None):
"""Are we at the end of a tuple?"""
if self.stream.current.type in ('variable_end', 'block_end', 'rparen'):
return True
elif extra_end_rules is not None:
return self.stream.current.test_any(extra_end_rules)
return False
|
[
"def",
"is_tuple_end",
"(",
"self",
",",
"extra_end_rules",
"=",
"None",
")",
":",
"if",
"self",
".",
"stream",
".",
"current",
".",
"type",
"in",
"(",
"'variable_end'",
",",
"'block_end'",
",",
"'rparen'",
")",
":",
"return",
"True",
"elif",
"extra_end_rules",
"is",
"not",
"None",
":",
"return",
"self",
".",
"stream",
".",
"current",
".",
"test_any",
"(",
"extra_end_rules",
")",
"return",
"False"
] |
Are we at the end of a tuple?
|
[
"Are",
"we",
"at",
"the",
"end",
"of",
"a",
"tuple?"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L106-L112
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/parser.py
|
Parser.free_identifier
|
def free_identifier(self, lineno=None):
"""Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""
self._last_identifier += 1
rv = object.__new__(nodes.InternalName)
nodes.Node.__init__(rv, 'fi%d' % self._last_identifier, lineno=lineno)
return rv
|
python
|
def free_identifier(self, lineno=None):
"""Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""
self._last_identifier += 1
rv = object.__new__(nodes.InternalName)
nodes.Node.__init__(rv, 'fi%d' % self._last_identifier, lineno=lineno)
return rv
|
[
"def",
"free_identifier",
"(",
"self",
",",
"lineno",
"=",
"None",
")",
":",
"self",
".",
"_last_identifier",
"+=",
"1",
"rv",
"=",
"object",
".",
"__new__",
"(",
"nodes",
".",
"InternalName",
")",
"nodes",
".",
"Node",
".",
"__init__",
"(",
"rv",
",",
"'fi%d'",
"%",
"self",
".",
"_last_identifier",
",",
"lineno",
"=",
"lineno",
")",
"return",
"rv"
] |
Return a new free identifier as :class:`~jinja2.nodes.InternalName`.
|
[
"Return",
"a",
"new",
"free",
"identifier",
"as",
":",
"class",
":",
"~jinja2",
".",
"nodes",
".",
"InternalName",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L114-L119
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/parser.py
|
Parser.parse_statement
|
def parse_statement(self):
"""Parse a single statement."""
token = self.stream.current
if token.type != 'name':
self.fail('tag name expected', token.lineno)
self._tag_stack.append(token.value)
pop_tag = True
try:
if token.value in _statement_keywords:
return getattr(self, 'parse_' + self.stream.current.value)()
if token.value == 'call':
return self.parse_call_block()
if token.value == 'filter':
return self.parse_filter_block()
ext = self.extensions.get(token.value)
if ext is not None:
return ext(self)
# did not work out, remove the token we pushed by accident
# from the stack so that the unknown tag fail function can
# produce a proper error message.
self._tag_stack.pop()
pop_tag = False
self.fail_unknown_tag(token.value, token.lineno)
finally:
if pop_tag:
self._tag_stack.pop()
|
python
|
def parse_statement(self):
"""Parse a single statement."""
token = self.stream.current
if token.type != 'name':
self.fail('tag name expected', token.lineno)
self._tag_stack.append(token.value)
pop_tag = True
try:
if token.value in _statement_keywords:
return getattr(self, 'parse_' + self.stream.current.value)()
if token.value == 'call':
return self.parse_call_block()
if token.value == 'filter':
return self.parse_filter_block()
ext = self.extensions.get(token.value)
if ext is not None:
return ext(self)
# did not work out, remove the token we pushed by accident
# from the stack so that the unknown tag fail function can
# produce a proper error message.
self._tag_stack.pop()
pop_tag = False
self.fail_unknown_tag(token.value, token.lineno)
finally:
if pop_tag:
self._tag_stack.pop()
|
[
"def",
"parse_statement",
"(",
"self",
")",
":",
"token",
"=",
"self",
".",
"stream",
".",
"current",
"if",
"token",
".",
"type",
"!=",
"'name'",
":",
"self",
".",
"fail",
"(",
"'tag name expected'",
",",
"token",
".",
"lineno",
")",
"self",
".",
"_tag_stack",
".",
"append",
"(",
"token",
".",
"value",
")",
"pop_tag",
"=",
"True",
"try",
":",
"if",
"token",
".",
"value",
"in",
"_statement_keywords",
":",
"return",
"getattr",
"(",
"self",
",",
"'parse_'",
"+",
"self",
".",
"stream",
".",
"current",
".",
"value",
")",
"(",
")",
"if",
"token",
".",
"value",
"==",
"'call'",
":",
"return",
"self",
".",
"parse_call_block",
"(",
")",
"if",
"token",
".",
"value",
"==",
"'filter'",
":",
"return",
"self",
".",
"parse_filter_block",
"(",
")",
"ext",
"=",
"self",
".",
"extensions",
".",
"get",
"(",
"token",
".",
"value",
")",
"if",
"ext",
"is",
"not",
"None",
":",
"return",
"ext",
"(",
"self",
")",
"# did not work out, remove the token we pushed by accident",
"# from the stack so that the unknown tag fail function can",
"# produce a proper error message.",
"self",
".",
"_tag_stack",
".",
"pop",
"(",
")",
"pop_tag",
"=",
"False",
"self",
".",
"fail_unknown_tag",
"(",
"token",
".",
"value",
",",
"token",
".",
"lineno",
")",
"finally",
":",
"if",
"pop_tag",
":",
"self",
".",
"_tag_stack",
".",
"pop",
"(",
")"
] |
Parse a single statement.
|
[
"Parse",
"a",
"single",
"statement",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L121-L147
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/parser.py
|
Parser.parse_statements
|
def parse_statements(self, end_tokens, drop_needle=False):
"""Parse multiple statements into a list until one of the end tokens
is reached. This is used to parse the body of statements as it also
parses template data if appropriate. The parser checks first if the
current token is a colon and skips it if there is one. Then it checks
for the block end and parses until if one of the `end_tokens` is
reached. Per default the active token in the stream at the end of
the call is the matched end token. If this is not wanted `drop_needle`
can be set to `True` and the end token is removed.
"""
# the first token may be a colon for python compatibility
self.stream.skip_if('colon')
# in the future it would be possible to add whole code sections
# by adding some sort of end of statement token and parsing those here.
self.stream.expect('block_end')
result = self.subparse(end_tokens)
# we reached the end of the template too early, the subparser
# does not check for this, so we do that now
if self.stream.current.type == 'eof':
self.fail_eof(end_tokens)
if drop_needle:
next(self.stream)
return result
|
python
|
def parse_statements(self, end_tokens, drop_needle=False):
"""Parse multiple statements into a list until one of the end tokens
is reached. This is used to parse the body of statements as it also
parses template data if appropriate. The parser checks first if the
current token is a colon and skips it if there is one. Then it checks
for the block end and parses until if one of the `end_tokens` is
reached. Per default the active token in the stream at the end of
the call is the matched end token. If this is not wanted `drop_needle`
can be set to `True` and the end token is removed.
"""
# the first token may be a colon for python compatibility
self.stream.skip_if('colon')
# in the future it would be possible to add whole code sections
# by adding some sort of end of statement token and parsing those here.
self.stream.expect('block_end')
result = self.subparse(end_tokens)
# we reached the end of the template too early, the subparser
# does not check for this, so we do that now
if self.stream.current.type == 'eof':
self.fail_eof(end_tokens)
if drop_needle:
next(self.stream)
return result
|
[
"def",
"parse_statements",
"(",
"self",
",",
"end_tokens",
",",
"drop_needle",
"=",
"False",
")",
":",
"# the first token may be a colon for python compatibility",
"self",
".",
"stream",
".",
"skip_if",
"(",
"'colon'",
")",
"# in the future it would be possible to add whole code sections",
"# by adding some sort of end of statement token and parsing those here.",
"self",
".",
"stream",
".",
"expect",
"(",
"'block_end'",
")",
"result",
"=",
"self",
".",
"subparse",
"(",
"end_tokens",
")",
"# we reached the end of the template too early, the subparser",
"# does not check for this, so we do that now",
"if",
"self",
".",
"stream",
".",
"current",
".",
"type",
"==",
"'eof'",
":",
"self",
".",
"fail_eof",
"(",
"end_tokens",
")",
"if",
"drop_needle",
":",
"next",
"(",
"self",
".",
"stream",
")",
"return",
"result"
] |
Parse multiple statements into a list until one of the end tokens
is reached. This is used to parse the body of statements as it also
parses template data if appropriate. The parser checks first if the
current token is a colon and skips it if there is one. Then it checks
for the block end and parses until if one of the `end_tokens` is
reached. Per default the active token in the stream at the end of
the call is the matched end token. If this is not wanted `drop_needle`
can be set to `True` and the end token is removed.
|
[
"Parse",
"multiple",
"statements",
"into",
"a",
"list",
"until",
"one",
"of",
"the",
"end",
"tokens",
"is",
"reached",
".",
"This",
"is",
"used",
"to",
"parse",
"the",
"body",
"of",
"statements",
"as",
"it",
"also",
"parses",
"template",
"data",
"if",
"appropriate",
".",
"The",
"parser",
"checks",
"first",
"if",
"the",
"current",
"token",
"is",
"a",
"colon",
"and",
"skips",
"it",
"if",
"there",
"is",
"one",
".",
"Then",
"it",
"checks",
"for",
"the",
"block",
"end",
"and",
"parses",
"until",
"if",
"one",
"of",
"the",
"end_tokens",
"is",
"reached",
".",
"Per",
"default",
"the",
"active",
"token",
"in",
"the",
"stream",
"at",
"the",
"end",
"of",
"the",
"call",
"is",
"the",
"matched",
"end",
"token",
".",
"If",
"this",
"is",
"not",
"wanted",
"drop_needle",
"can",
"be",
"set",
"to",
"True",
"and",
"the",
"end",
"token",
"is",
"removed",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L149-L174
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/parser.py
|
Parser.parse_set
|
def parse_set(self):
"""Parse an assign statement."""
lineno = next(self.stream).lineno
target = self.parse_assign_target(with_namespace=True)
if self.stream.skip_if('assign'):
expr = self.parse_tuple()
return nodes.Assign(target, expr, lineno=lineno)
filter_node = self.parse_filter(None)
body = self.parse_statements(('name:endset',),
drop_needle=True)
return nodes.AssignBlock(target, filter_node, body, lineno=lineno)
|
python
|
def parse_set(self):
"""Parse an assign statement."""
lineno = next(self.stream).lineno
target = self.parse_assign_target(with_namespace=True)
if self.stream.skip_if('assign'):
expr = self.parse_tuple()
return nodes.Assign(target, expr, lineno=lineno)
filter_node = self.parse_filter(None)
body = self.parse_statements(('name:endset',),
drop_needle=True)
return nodes.AssignBlock(target, filter_node, body, lineno=lineno)
|
[
"def",
"parse_set",
"(",
"self",
")",
":",
"lineno",
"=",
"next",
"(",
"self",
".",
"stream",
")",
".",
"lineno",
"target",
"=",
"self",
".",
"parse_assign_target",
"(",
"with_namespace",
"=",
"True",
")",
"if",
"self",
".",
"stream",
".",
"skip_if",
"(",
"'assign'",
")",
":",
"expr",
"=",
"self",
".",
"parse_tuple",
"(",
")",
"return",
"nodes",
".",
"Assign",
"(",
"target",
",",
"expr",
",",
"lineno",
"=",
"lineno",
")",
"filter_node",
"=",
"self",
".",
"parse_filter",
"(",
"None",
")",
"body",
"=",
"self",
".",
"parse_statements",
"(",
"(",
"'name:endset'",
",",
")",
",",
"drop_needle",
"=",
"True",
")",
"return",
"nodes",
".",
"AssignBlock",
"(",
"target",
",",
"filter_node",
",",
"body",
",",
"lineno",
"=",
"lineno",
")"
] |
Parse an assign statement.
|
[
"Parse",
"an",
"assign",
"statement",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L176-L186
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/parser.py
|
Parser.parse_for
|
def parse_for(self):
"""Parse a for loop."""
lineno = self.stream.expect('name:for').lineno
target = self.parse_assign_target(extra_end_rules=('name:in',))
self.stream.expect('name:in')
iter = self.parse_tuple(with_condexpr=False,
extra_end_rules=('name:recursive',))
test = None
if self.stream.skip_if('name:if'):
test = self.parse_expression()
recursive = self.stream.skip_if('name:recursive')
body = self.parse_statements(('name:endfor', 'name:else'))
if next(self.stream).value == 'endfor':
else_ = []
else:
else_ = self.parse_statements(('name:endfor',), drop_needle=True)
return nodes.For(target, iter, body, else_, test,
recursive, lineno=lineno)
|
python
|
def parse_for(self):
"""Parse a for loop."""
lineno = self.stream.expect('name:for').lineno
target = self.parse_assign_target(extra_end_rules=('name:in',))
self.stream.expect('name:in')
iter = self.parse_tuple(with_condexpr=False,
extra_end_rules=('name:recursive',))
test = None
if self.stream.skip_if('name:if'):
test = self.parse_expression()
recursive = self.stream.skip_if('name:recursive')
body = self.parse_statements(('name:endfor', 'name:else'))
if next(self.stream).value == 'endfor':
else_ = []
else:
else_ = self.parse_statements(('name:endfor',), drop_needle=True)
return nodes.For(target, iter, body, else_, test,
recursive, lineno=lineno)
|
[
"def",
"parse_for",
"(",
"self",
")",
":",
"lineno",
"=",
"self",
".",
"stream",
".",
"expect",
"(",
"'name:for'",
")",
".",
"lineno",
"target",
"=",
"self",
".",
"parse_assign_target",
"(",
"extra_end_rules",
"=",
"(",
"'name:in'",
",",
")",
")",
"self",
".",
"stream",
".",
"expect",
"(",
"'name:in'",
")",
"iter",
"=",
"self",
".",
"parse_tuple",
"(",
"with_condexpr",
"=",
"False",
",",
"extra_end_rules",
"=",
"(",
"'name:recursive'",
",",
")",
")",
"test",
"=",
"None",
"if",
"self",
".",
"stream",
".",
"skip_if",
"(",
"'name:if'",
")",
":",
"test",
"=",
"self",
".",
"parse_expression",
"(",
")",
"recursive",
"=",
"self",
".",
"stream",
".",
"skip_if",
"(",
"'name:recursive'",
")",
"body",
"=",
"self",
".",
"parse_statements",
"(",
"(",
"'name:endfor'",
",",
"'name:else'",
")",
")",
"if",
"next",
"(",
"self",
".",
"stream",
")",
".",
"value",
"==",
"'endfor'",
":",
"else_",
"=",
"[",
"]",
"else",
":",
"else_",
"=",
"self",
".",
"parse_statements",
"(",
"(",
"'name:endfor'",
",",
")",
",",
"drop_needle",
"=",
"True",
")",
"return",
"nodes",
".",
"For",
"(",
"target",
",",
"iter",
",",
"body",
",",
"else_",
",",
"test",
",",
"recursive",
",",
"lineno",
"=",
"lineno",
")"
] |
Parse a for loop.
|
[
"Parse",
"a",
"for",
"loop",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L188-L205
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/parser.py
|
Parser.parse_if
|
def parse_if(self):
"""Parse an if construct."""
node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)
while 1:
node.test = self.parse_tuple(with_condexpr=False)
node.body = self.parse_statements(('name:elif', 'name:else',
'name:endif'))
node.elif_ = []
node.else_ = []
token = next(self.stream)
if token.test('name:elif'):
node = nodes.If(lineno=self.stream.current.lineno)
result.elif_.append(node)
continue
elif token.test('name:else'):
result.else_ = self.parse_statements(('name:endif',),
drop_needle=True)
break
return result
|
python
|
def parse_if(self):
"""Parse an if construct."""
node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)
while 1:
node.test = self.parse_tuple(with_condexpr=False)
node.body = self.parse_statements(('name:elif', 'name:else',
'name:endif'))
node.elif_ = []
node.else_ = []
token = next(self.stream)
if token.test('name:elif'):
node = nodes.If(lineno=self.stream.current.lineno)
result.elif_.append(node)
continue
elif token.test('name:else'):
result.else_ = self.parse_statements(('name:endif',),
drop_needle=True)
break
return result
|
[
"def",
"parse_if",
"(",
"self",
")",
":",
"node",
"=",
"result",
"=",
"nodes",
".",
"If",
"(",
"lineno",
"=",
"self",
".",
"stream",
".",
"expect",
"(",
"'name:if'",
")",
".",
"lineno",
")",
"while",
"1",
":",
"node",
".",
"test",
"=",
"self",
".",
"parse_tuple",
"(",
"with_condexpr",
"=",
"False",
")",
"node",
".",
"body",
"=",
"self",
".",
"parse_statements",
"(",
"(",
"'name:elif'",
",",
"'name:else'",
",",
"'name:endif'",
")",
")",
"node",
".",
"elif_",
"=",
"[",
"]",
"node",
".",
"else_",
"=",
"[",
"]",
"token",
"=",
"next",
"(",
"self",
".",
"stream",
")",
"if",
"token",
".",
"test",
"(",
"'name:elif'",
")",
":",
"node",
"=",
"nodes",
".",
"If",
"(",
"lineno",
"=",
"self",
".",
"stream",
".",
"current",
".",
"lineno",
")",
"result",
".",
"elif_",
".",
"append",
"(",
"node",
")",
"continue",
"elif",
"token",
".",
"test",
"(",
"'name:else'",
")",
":",
"result",
".",
"else_",
"=",
"self",
".",
"parse_statements",
"(",
"(",
"'name:endif'",
",",
")",
",",
"drop_needle",
"=",
"True",
")",
"break",
"return",
"result"
] |
Parse an if construct.
|
[
"Parse",
"an",
"if",
"construct",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L207-L225
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/parser.py
|
Parser.parse_assign_target
|
def parse_assign_target(self, with_tuple=True, name_only=False,
extra_end_rules=None, with_namespace=False):
"""Parse an assignment target. As Jinja2 allows assignments to
tuples, this function can parse all allowed assignment targets. Per
default assignments to tuples are parsed, that can be disable however
by setting `with_tuple` to `False`. If only assignments to names are
wanted `name_only` can be set to `True`. The `extra_end_rules`
parameter is forwarded to the tuple parsing function. If
`with_namespace` is enabled, a namespace assignment may be parsed.
"""
if with_namespace and self.stream.look().type == 'dot':
token = self.stream.expect('name')
next(self.stream) # dot
attr = self.stream.expect('name')
target = nodes.NSRef(token.value, attr.value, lineno=token.lineno)
elif name_only:
token = self.stream.expect('name')
target = nodes.Name(token.value, 'store', lineno=token.lineno)
else:
if with_tuple:
target = self.parse_tuple(simplified=True,
extra_end_rules=extra_end_rules)
else:
target = self.parse_primary()
target.set_ctx('store')
if not target.can_assign():
self.fail('can\'t assign to %r' % target.__class__.
__name__.lower(), target.lineno)
return target
|
python
|
def parse_assign_target(self, with_tuple=True, name_only=False,
extra_end_rules=None, with_namespace=False):
"""Parse an assignment target. As Jinja2 allows assignments to
tuples, this function can parse all allowed assignment targets. Per
default assignments to tuples are parsed, that can be disable however
by setting `with_tuple` to `False`. If only assignments to names are
wanted `name_only` can be set to `True`. The `extra_end_rules`
parameter is forwarded to the tuple parsing function. If
`with_namespace` is enabled, a namespace assignment may be parsed.
"""
if with_namespace and self.stream.look().type == 'dot':
token = self.stream.expect('name')
next(self.stream) # dot
attr = self.stream.expect('name')
target = nodes.NSRef(token.value, attr.value, lineno=token.lineno)
elif name_only:
token = self.stream.expect('name')
target = nodes.Name(token.value, 'store', lineno=token.lineno)
else:
if with_tuple:
target = self.parse_tuple(simplified=True,
extra_end_rules=extra_end_rules)
else:
target = self.parse_primary()
target.set_ctx('store')
if not target.can_assign():
self.fail('can\'t assign to %r' % target.__class__.
__name__.lower(), target.lineno)
return target
|
[
"def",
"parse_assign_target",
"(",
"self",
",",
"with_tuple",
"=",
"True",
",",
"name_only",
"=",
"False",
",",
"extra_end_rules",
"=",
"None",
",",
"with_namespace",
"=",
"False",
")",
":",
"if",
"with_namespace",
"and",
"self",
".",
"stream",
".",
"look",
"(",
")",
".",
"type",
"==",
"'dot'",
":",
"token",
"=",
"self",
".",
"stream",
".",
"expect",
"(",
"'name'",
")",
"next",
"(",
"self",
".",
"stream",
")",
"# dot",
"attr",
"=",
"self",
".",
"stream",
".",
"expect",
"(",
"'name'",
")",
"target",
"=",
"nodes",
".",
"NSRef",
"(",
"token",
".",
"value",
",",
"attr",
".",
"value",
",",
"lineno",
"=",
"token",
".",
"lineno",
")",
"elif",
"name_only",
":",
"token",
"=",
"self",
".",
"stream",
".",
"expect",
"(",
"'name'",
")",
"target",
"=",
"nodes",
".",
"Name",
"(",
"token",
".",
"value",
",",
"'store'",
",",
"lineno",
"=",
"token",
".",
"lineno",
")",
"else",
":",
"if",
"with_tuple",
":",
"target",
"=",
"self",
".",
"parse_tuple",
"(",
"simplified",
"=",
"True",
",",
"extra_end_rules",
"=",
"extra_end_rules",
")",
"else",
":",
"target",
"=",
"self",
".",
"parse_primary",
"(",
")",
"target",
".",
"set_ctx",
"(",
"'store'",
")",
"if",
"not",
"target",
".",
"can_assign",
"(",
")",
":",
"self",
".",
"fail",
"(",
"'can\\'t assign to %r'",
"%",
"target",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
",",
"target",
".",
"lineno",
")",
"return",
"target"
] |
Parse an assignment target. As Jinja2 allows assignments to
tuples, this function can parse all allowed assignment targets. Per
default assignments to tuples are parsed, that can be disable however
by setting `with_tuple` to `False`. If only assignments to names are
wanted `name_only` can be set to `True`. The `extra_end_rules`
parameter is forwarded to the tuple parsing function. If
`with_namespace` is enabled, a namespace assignment may be parsed.
|
[
"Parse",
"an",
"assignment",
"target",
".",
"As",
"Jinja2",
"allows",
"assignments",
"to",
"tuples",
"this",
"function",
"can",
"parse",
"all",
"allowed",
"assignment",
"targets",
".",
"Per",
"default",
"assignments",
"to",
"tuples",
"are",
"parsed",
"that",
"can",
"be",
"disable",
"however",
"by",
"setting",
"with_tuple",
"to",
"False",
".",
"If",
"only",
"assignments",
"to",
"names",
"are",
"wanted",
"name_only",
"can",
"be",
"set",
"to",
"True",
".",
"The",
"extra_end_rules",
"parameter",
"is",
"forwarded",
"to",
"the",
"tuple",
"parsing",
"function",
".",
"If",
"with_namespace",
"is",
"enabled",
"a",
"namespace",
"assignment",
"may",
"be",
"parsed",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L396-L424
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/parser.py
|
Parser.parse
|
def parse(self):
"""Parse the whole template into a `Template` node."""
result = nodes.Template(self.subparse(), lineno=1)
result.set_environment(self.environment)
return result
|
python
|
def parse(self):
"""Parse the whole template into a `Template` node."""
result = nodes.Template(self.subparse(), lineno=1)
result.set_environment(self.environment)
return result
|
[
"def",
"parse",
"(",
"self",
")",
":",
"result",
"=",
"nodes",
".",
"Template",
"(",
"self",
".",
"subparse",
"(",
")",
",",
"lineno",
"=",
"1",
")",
"result",
".",
"set_environment",
"(",
"self",
".",
"environment",
")",
"return",
"result"
] |
Parse the whole template into a `Template` node.
|
[
"Parse",
"the",
"whole",
"template",
"into",
"a",
"Template",
"node",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L899-L903
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/exceptions.py
|
ExceptionPexpect.get_trace
|
def get_trace(self):
'''This returns an abbreviated stack trace with lines that only concern
the caller. In other words, the stack trace inside the Pexpect module
is not included. '''
tblist = traceback.extract_tb(sys.exc_info()[2])
tblist = [item for item in tblist if ('pexpect/__init__' not in item[0])
and ('pexpect/expect' not in item[0])]
tblist = traceback.format_list(tblist)
return ''.join(tblist)
|
python
|
def get_trace(self):
'''This returns an abbreviated stack trace with lines that only concern
the caller. In other words, the stack trace inside the Pexpect module
is not included. '''
tblist = traceback.extract_tb(sys.exc_info()[2])
tblist = [item for item in tblist if ('pexpect/__init__' not in item[0])
and ('pexpect/expect' not in item[0])]
tblist = traceback.format_list(tblist)
return ''.join(tblist)
|
[
"def",
"get_trace",
"(",
"self",
")",
":",
"tblist",
"=",
"traceback",
".",
"extract_tb",
"(",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
")",
"tblist",
"=",
"[",
"item",
"for",
"item",
"in",
"tblist",
"if",
"(",
"'pexpect/__init__'",
"not",
"in",
"item",
"[",
"0",
"]",
")",
"and",
"(",
"'pexpect/expect'",
"not",
"in",
"item",
"[",
"0",
"]",
")",
"]",
"tblist",
"=",
"traceback",
".",
"format_list",
"(",
"tblist",
")",
"return",
"''",
".",
"join",
"(",
"tblist",
")"
] |
This returns an abbreviated stack trace with lines that only concern
the caller. In other words, the stack trace inside the Pexpect module
is not included.
|
[
"This",
"returns",
"an",
"abbreviated",
"stack",
"trace",
"with",
"lines",
"that",
"only",
"concern",
"the",
"caller",
".",
"In",
"other",
"words",
"the",
"stack",
"trace",
"inside",
"the",
"Pexpect",
"module",
"is",
"not",
"included",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/exceptions.py#L17-L26
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/cachecontrol/controller.py
|
parse_uri
|
def parse_uri(uri):
"""Parses a URI using the regex given in Appendix B of RFC 3986.
(scheme, authority, path, query, fragment) = parse_uri(uri)
"""
groups = URI.match(uri).groups()
return (groups[1], groups[3], groups[4], groups[6], groups[8])
|
python
|
def parse_uri(uri):
"""Parses a URI using the regex given in Appendix B of RFC 3986.
(scheme, authority, path, query, fragment) = parse_uri(uri)
"""
groups = URI.match(uri).groups()
return (groups[1], groups[3], groups[4], groups[6], groups[8])
|
[
"def",
"parse_uri",
"(",
"uri",
")",
":",
"groups",
"=",
"URI",
".",
"match",
"(",
"uri",
")",
".",
"groups",
"(",
")",
"return",
"(",
"groups",
"[",
"1",
"]",
",",
"groups",
"[",
"3",
"]",
",",
"groups",
"[",
"4",
"]",
",",
"groups",
"[",
"6",
"]",
",",
"groups",
"[",
"8",
"]",
")"
] |
Parses a URI using the regex given in Appendix B of RFC 3986.
(scheme, authority, path, query, fragment) = parse_uri(uri)
|
[
"Parses",
"a",
"URI",
"using",
"the",
"regex",
"given",
"in",
"Appendix",
"B",
"of",
"RFC",
"3986",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/cachecontrol/controller.py#L21-L27
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/cachecontrol/controller.py
|
CacheController._urlnorm
|
def _urlnorm(cls, uri):
"""Normalize the URL to create a safe key for the cache"""
(scheme, authority, path, query, fragment) = parse_uri(uri)
if not scheme or not authority:
raise Exception("Only absolute URIs are allowed. uri = %s" % uri)
scheme = scheme.lower()
authority = authority.lower()
if not path:
path = "/"
# Could do syntax based normalization of the URI before
# computing the digest. See Section 6.2.2 of Std 66.
request_uri = query and "?".join([path, query]) or path
defrag_uri = scheme + "://" + authority + request_uri
return defrag_uri
|
python
|
def _urlnorm(cls, uri):
"""Normalize the URL to create a safe key for the cache"""
(scheme, authority, path, query, fragment) = parse_uri(uri)
if not scheme or not authority:
raise Exception("Only absolute URIs are allowed. uri = %s" % uri)
scheme = scheme.lower()
authority = authority.lower()
if not path:
path = "/"
# Could do syntax based normalization of the URI before
# computing the digest. See Section 6.2.2 of Std 66.
request_uri = query and "?".join([path, query]) or path
defrag_uri = scheme + "://" + authority + request_uri
return defrag_uri
|
[
"def",
"_urlnorm",
"(",
"cls",
",",
"uri",
")",
":",
"(",
"scheme",
",",
"authority",
",",
"path",
",",
"query",
",",
"fragment",
")",
"=",
"parse_uri",
"(",
"uri",
")",
"if",
"not",
"scheme",
"or",
"not",
"authority",
":",
"raise",
"Exception",
"(",
"\"Only absolute URIs are allowed. uri = %s\"",
"%",
"uri",
")",
"scheme",
"=",
"scheme",
".",
"lower",
"(",
")",
"authority",
"=",
"authority",
".",
"lower",
"(",
")",
"if",
"not",
"path",
":",
"path",
"=",
"\"/\"",
"# Could do syntax based normalization of the URI before",
"# computing the digest. See Section 6.2.2 of Std 66.",
"request_uri",
"=",
"query",
"and",
"\"?\"",
".",
"join",
"(",
"[",
"path",
",",
"query",
"]",
")",
"or",
"path",
"defrag_uri",
"=",
"scheme",
"+",
"\"://\"",
"+",
"authority",
"+",
"request_uri",
"return",
"defrag_uri"
] |
Normalize the URL to create a safe key for the cache
|
[
"Normalize",
"the",
"URL",
"to",
"create",
"a",
"safe",
"key",
"for",
"the",
"cache"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/cachecontrol/controller.py#L43-L60
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/cachecontrol/controller.py
|
CacheController.cached_request
|
def cached_request(self, request):
"""
Return a cached response if it exists in the cache, otherwise
return False.
"""
cache_url = self.cache_url(request.url)
logger.debug('Looking up "%s" in the cache', cache_url)
cc = self.parse_cache_control(request.headers)
# Bail out if the request insists on fresh data
if "no-cache" in cc:
logger.debug('Request header has "no-cache", cache bypassed')
return False
if "max-age" in cc and cc["max-age"] == 0:
logger.debug('Request header has "max_age" as 0, cache bypassed')
return False
# Request allows serving from the cache, let's see if we find something
cache_data = self.cache.get(cache_url)
if cache_data is None:
logger.debug("No cache entry available")
return False
# Check whether it can be deserialized
resp = self.serializer.loads(request, cache_data)
if not resp:
logger.warning("Cache entry deserialization failed, entry ignored")
return False
# If we have a cached 301, return it immediately. We don't
# need to test our response for other headers b/c it is
# intrinsically "cacheable" as it is Permanent.
# See:
# https://tools.ietf.org/html/rfc7231#section-6.4.2
#
# Client can try to refresh the value by repeating the request
# with cache busting headers as usual (ie no-cache).
if resp.status == 301:
msg = (
'Returning cached "301 Moved Permanently" response '
"(ignoring date and etag information)"
)
logger.debug(msg)
return resp
headers = CaseInsensitiveDict(resp.headers)
if not headers or "date" not in headers:
if "etag" not in headers:
# Without date or etag, the cached response can never be used
# and should be deleted.
logger.debug("Purging cached response: no date or etag")
self.cache.delete(cache_url)
logger.debug("Ignoring cached response: no date")
return False
now = time.time()
date = calendar.timegm(parsedate_tz(headers["date"]))
current_age = max(0, now - date)
logger.debug("Current age based on date: %i", current_age)
# TODO: There is an assumption that the result will be a
# urllib3 response object. This may not be best since we
# could probably avoid instantiating or constructing the
# response until we know we need it.
resp_cc = self.parse_cache_control(headers)
# determine freshness
freshness_lifetime = 0
# Check the max-age pragma in the cache control header
if "max-age" in resp_cc:
freshness_lifetime = resp_cc["max-age"]
logger.debug("Freshness lifetime from max-age: %i", freshness_lifetime)
# If there isn't a max-age, check for an expires header
elif "expires" in headers:
expires = parsedate_tz(headers["expires"])
if expires is not None:
expire_time = calendar.timegm(expires) - date
freshness_lifetime = max(0, expire_time)
logger.debug("Freshness lifetime from expires: %i", freshness_lifetime)
# Determine if we are setting freshness limit in the
# request. Note, this overrides what was in the response.
if "max-age" in cc:
freshness_lifetime = cc["max-age"]
logger.debug(
"Freshness lifetime from request max-age: %i", freshness_lifetime
)
if "min-fresh" in cc:
min_fresh = cc["min-fresh"]
# adjust our current age by our min fresh
current_age += min_fresh
logger.debug("Adjusted current age from min-fresh: %i", current_age)
# Return entry if it is fresh enough
if freshness_lifetime > current_age:
logger.debug('The response is "fresh", returning cached response')
logger.debug("%i > %i", freshness_lifetime, current_age)
return resp
# we're not fresh. If we don't have an Etag, clear it out
if "etag" not in headers:
logger.debug('The cached response is "stale" with no etag, purging')
self.cache.delete(cache_url)
# return the original handler
return False
|
python
|
def cached_request(self, request):
"""
Return a cached response if it exists in the cache, otherwise
return False.
"""
cache_url = self.cache_url(request.url)
logger.debug('Looking up "%s" in the cache', cache_url)
cc = self.parse_cache_control(request.headers)
# Bail out if the request insists on fresh data
if "no-cache" in cc:
logger.debug('Request header has "no-cache", cache bypassed')
return False
if "max-age" in cc and cc["max-age"] == 0:
logger.debug('Request header has "max_age" as 0, cache bypassed')
return False
# Request allows serving from the cache, let's see if we find something
cache_data = self.cache.get(cache_url)
if cache_data is None:
logger.debug("No cache entry available")
return False
# Check whether it can be deserialized
resp = self.serializer.loads(request, cache_data)
if not resp:
logger.warning("Cache entry deserialization failed, entry ignored")
return False
# If we have a cached 301, return it immediately. We don't
# need to test our response for other headers b/c it is
# intrinsically "cacheable" as it is Permanent.
# See:
# https://tools.ietf.org/html/rfc7231#section-6.4.2
#
# Client can try to refresh the value by repeating the request
# with cache busting headers as usual (ie no-cache).
if resp.status == 301:
msg = (
'Returning cached "301 Moved Permanently" response '
"(ignoring date and etag information)"
)
logger.debug(msg)
return resp
headers = CaseInsensitiveDict(resp.headers)
if not headers or "date" not in headers:
if "etag" not in headers:
# Without date or etag, the cached response can never be used
# and should be deleted.
logger.debug("Purging cached response: no date or etag")
self.cache.delete(cache_url)
logger.debug("Ignoring cached response: no date")
return False
now = time.time()
date = calendar.timegm(parsedate_tz(headers["date"]))
current_age = max(0, now - date)
logger.debug("Current age based on date: %i", current_age)
# TODO: There is an assumption that the result will be a
# urllib3 response object. This may not be best since we
# could probably avoid instantiating or constructing the
# response until we know we need it.
resp_cc = self.parse_cache_control(headers)
# determine freshness
freshness_lifetime = 0
# Check the max-age pragma in the cache control header
if "max-age" in resp_cc:
freshness_lifetime = resp_cc["max-age"]
logger.debug("Freshness lifetime from max-age: %i", freshness_lifetime)
# If there isn't a max-age, check for an expires header
elif "expires" in headers:
expires = parsedate_tz(headers["expires"])
if expires is not None:
expire_time = calendar.timegm(expires) - date
freshness_lifetime = max(0, expire_time)
logger.debug("Freshness lifetime from expires: %i", freshness_lifetime)
# Determine if we are setting freshness limit in the
# request. Note, this overrides what was in the response.
if "max-age" in cc:
freshness_lifetime = cc["max-age"]
logger.debug(
"Freshness lifetime from request max-age: %i", freshness_lifetime
)
if "min-fresh" in cc:
min_fresh = cc["min-fresh"]
# adjust our current age by our min fresh
current_age += min_fresh
logger.debug("Adjusted current age from min-fresh: %i", current_age)
# Return entry if it is fresh enough
if freshness_lifetime > current_age:
logger.debug('The response is "fresh", returning cached response')
logger.debug("%i > %i", freshness_lifetime, current_age)
return resp
# we're not fresh. If we don't have an Etag, clear it out
if "etag" not in headers:
logger.debug('The cached response is "stale" with no etag, purging')
self.cache.delete(cache_url)
# return the original handler
return False
|
[
"def",
"cached_request",
"(",
"self",
",",
"request",
")",
":",
"cache_url",
"=",
"self",
".",
"cache_url",
"(",
"request",
".",
"url",
")",
"logger",
".",
"debug",
"(",
"'Looking up \"%s\" in the cache'",
",",
"cache_url",
")",
"cc",
"=",
"self",
".",
"parse_cache_control",
"(",
"request",
".",
"headers",
")",
"# Bail out if the request insists on fresh data",
"if",
"\"no-cache\"",
"in",
"cc",
":",
"logger",
".",
"debug",
"(",
"'Request header has \"no-cache\", cache bypassed'",
")",
"return",
"False",
"if",
"\"max-age\"",
"in",
"cc",
"and",
"cc",
"[",
"\"max-age\"",
"]",
"==",
"0",
":",
"logger",
".",
"debug",
"(",
"'Request header has \"max_age\" as 0, cache bypassed'",
")",
"return",
"False",
"# Request allows serving from the cache, let's see if we find something",
"cache_data",
"=",
"self",
".",
"cache",
".",
"get",
"(",
"cache_url",
")",
"if",
"cache_data",
"is",
"None",
":",
"logger",
".",
"debug",
"(",
"\"No cache entry available\"",
")",
"return",
"False",
"# Check whether it can be deserialized",
"resp",
"=",
"self",
".",
"serializer",
".",
"loads",
"(",
"request",
",",
"cache_data",
")",
"if",
"not",
"resp",
":",
"logger",
".",
"warning",
"(",
"\"Cache entry deserialization failed, entry ignored\"",
")",
"return",
"False",
"# If we have a cached 301, return it immediately. We don't",
"# need to test our response for other headers b/c it is",
"# intrinsically \"cacheable\" as it is Permanent.",
"# See:",
"# https://tools.ietf.org/html/rfc7231#section-6.4.2",
"#",
"# Client can try to refresh the value by repeating the request",
"# with cache busting headers as usual (ie no-cache).",
"if",
"resp",
".",
"status",
"==",
"301",
":",
"msg",
"=",
"(",
"'Returning cached \"301 Moved Permanently\" response '",
"\"(ignoring date and etag information)\"",
")",
"logger",
".",
"debug",
"(",
"msg",
")",
"return",
"resp",
"headers",
"=",
"CaseInsensitiveDict",
"(",
"resp",
".",
"headers",
")",
"if",
"not",
"headers",
"or",
"\"date\"",
"not",
"in",
"headers",
":",
"if",
"\"etag\"",
"not",
"in",
"headers",
":",
"# Without date or etag, the cached response can never be used",
"# and should be deleted.",
"logger",
".",
"debug",
"(",
"\"Purging cached response: no date or etag\"",
")",
"self",
".",
"cache",
".",
"delete",
"(",
"cache_url",
")",
"logger",
".",
"debug",
"(",
"\"Ignoring cached response: no date\"",
")",
"return",
"False",
"now",
"=",
"time",
".",
"time",
"(",
")",
"date",
"=",
"calendar",
".",
"timegm",
"(",
"parsedate_tz",
"(",
"headers",
"[",
"\"date\"",
"]",
")",
")",
"current_age",
"=",
"max",
"(",
"0",
",",
"now",
"-",
"date",
")",
"logger",
".",
"debug",
"(",
"\"Current age based on date: %i\"",
",",
"current_age",
")",
"# TODO: There is an assumption that the result will be a",
"# urllib3 response object. This may not be best since we",
"# could probably avoid instantiating or constructing the",
"# response until we know we need it.",
"resp_cc",
"=",
"self",
".",
"parse_cache_control",
"(",
"headers",
")",
"# determine freshness",
"freshness_lifetime",
"=",
"0",
"# Check the max-age pragma in the cache control header",
"if",
"\"max-age\"",
"in",
"resp_cc",
":",
"freshness_lifetime",
"=",
"resp_cc",
"[",
"\"max-age\"",
"]",
"logger",
".",
"debug",
"(",
"\"Freshness lifetime from max-age: %i\"",
",",
"freshness_lifetime",
")",
"# If there isn't a max-age, check for an expires header",
"elif",
"\"expires\"",
"in",
"headers",
":",
"expires",
"=",
"parsedate_tz",
"(",
"headers",
"[",
"\"expires\"",
"]",
")",
"if",
"expires",
"is",
"not",
"None",
":",
"expire_time",
"=",
"calendar",
".",
"timegm",
"(",
"expires",
")",
"-",
"date",
"freshness_lifetime",
"=",
"max",
"(",
"0",
",",
"expire_time",
")",
"logger",
".",
"debug",
"(",
"\"Freshness lifetime from expires: %i\"",
",",
"freshness_lifetime",
")",
"# Determine if we are setting freshness limit in the",
"# request. Note, this overrides what was in the response.",
"if",
"\"max-age\"",
"in",
"cc",
":",
"freshness_lifetime",
"=",
"cc",
"[",
"\"max-age\"",
"]",
"logger",
".",
"debug",
"(",
"\"Freshness lifetime from request max-age: %i\"",
",",
"freshness_lifetime",
")",
"if",
"\"min-fresh\"",
"in",
"cc",
":",
"min_fresh",
"=",
"cc",
"[",
"\"min-fresh\"",
"]",
"# adjust our current age by our min fresh",
"current_age",
"+=",
"min_fresh",
"logger",
".",
"debug",
"(",
"\"Adjusted current age from min-fresh: %i\"",
",",
"current_age",
")",
"# Return entry if it is fresh enough",
"if",
"freshness_lifetime",
">",
"current_age",
":",
"logger",
".",
"debug",
"(",
"'The response is \"fresh\", returning cached response'",
")",
"logger",
".",
"debug",
"(",
"\"%i > %i\"",
",",
"freshness_lifetime",
",",
"current_age",
")",
"return",
"resp",
"# we're not fresh. If we don't have an Etag, clear it out",
"if",
"\"etag\"",
"not",
"in",
"headers",
":",
"logger",
".",
"debug",
"(",
"'The cached response is \"stale\" with no etag, purging'",
")",
"self",
".",
"cache",
".",
"delete",
"(",
"cache_url",
")",
"# return the original handler",
"return",
"False"
] |
Return a cached response if it exists in the cache, otherwise
return False.
|
[
"Return",
"a",
"cached",
"response",
"if",
"it",
"exists",
"in",
"the",
"cache",
"otherwise",
"return",
"False",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/cachecontrol/controller.py#L120-L229
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/cachecontrol/controller.py
|
CacheController.cache_response
|
def cache_response(self, request, response, body=None, status_codes=None):
"""
Algorithm for caching requests.
This assumes a requests Response object.
"""
# From httplib2: Don't cache 206's since we aren't going to
# handle byte range requests
cacheable_status_codes = status_codes or self.cacheable_status_codes
if response.status not in cacheable_status_codes:
logger.debug(
"Status code %s not in %s", response.status, cacheable_status_codes
)
return
response_headers = CaseInsensitiveDict(response.headers)
# If we've been given a body, our response has a Content-Length, that
# Content-Length is valid then we can check to see if the body we've
# been given matches the expected size, and if it doesn't we'll just
# skip trying to cache it.
if (
body is not None
and "content-length" in response_headers
and response_headers["content-length"].isdigit()
and int(response_headers["content-length"]) != len(body)
):
return
cc_req = self.parse_cache_control(request.headers)
cc = self.parse_cache_control(response_headers)
cache_url = self.cache_url(request.url)
logger.debug('Updating cache with response from "%s"', cache_url)
# Delete it from the cache if we happen to have it stored there
no_store = False
if "no-store" in cc:
no_store = True
logger.debug('Response header has "no-store"')
if "no-store" in cc_req:
no_store = True
logger.debug('Request header has "no-store"')
if no_store and self.cache.get(cache_url):
logger.debug('Purging existing cache entry to honor "no-store"')
self.cache.delete(cache_url)
if no_store:
return
# If we've been given an etag, then keep the response
if self.cache_etags and "etag" in response_headers:
logger.debug("Caching due to etag")
self.cache.set(
cache_url, self.serializer.dumps(request, response, body=body)
)
# Add to the cache any 301s. We do this before looking that
# the Date headers.
elif response.status == 301:
logger.debug("Caching permanant redirect")
self.cache.set(cache_url, self.serializer.dumps(request, response))
# Add to the cache if the response headers demand it. If there
# is no date header then we can't do anything about expiring
# the cache.
elif "date" in response_headers:
# cache when there is a max-age > 0
if "max-age" in cc and cc["max-age"] > 0:
logger.debug("Caching b/c date exists and max-age > 0")
self.cache.set(
cache_url, self.serializer.dumps(request, response, body=body)
)
# If the request can expire, it means we should cache it
# in the meantime.
elif "expires" in response_headers:
if response_headers["expires"]:
logger.debug("Caching b/c of expires header")
self.cache.set(
cache_url, self.serializer.dumps(request, response, body=body)
)
|
python
|
def cache_response(self, request, response, body=None, status_codes=None):
"""
Algorithm for caching requests.
This assumes a requests Response object.
"""
# From httplib2: Don't cache 206's since we aren't going to
# handle byte range requests
cacheable_status_codes = status_codes or self.cacheable_status_codes
if response.status not in cacheable_status_codes:
logger.debug(
"Status code %s not in %s", response.status, cacheable_status_codes
)
return
response_headers = CaseInsensitiveDict(response.headers)
# If we've been given a body, our response has a Content-Length, that
# Content-Length is valid then we can check to see if the body we've
# been given matches the expected size, and if it doesn't we'll just
# skip trying to cache it.
if (
body is not None
and "content-length" in response_headers
and response_headers["content-length"].isdigit()
and int(response_headers["content-length"]) != len(body)
):
return
cc_req = self.parse_cache_control(request.headers)
cc = self.parse_cache_control(response_headers)
cache_url = self.cache_url(request.url)
logger.debug('Updating cache with response from "%s"', cache_url)
# Delete it from the cache if we happen to have it stored there
no_store = False
if "no-store" in cc:
no_store = True
logger.debug('Response header has "no-store"')
if "no-store" in cc_req:
no_store = True
logger.debug('Request header has "no-store"')
if no_store and self.cache.get(cache_url):
logger.debug('Purging existing cache entry to honor "no-store"')
self.cache.delete(cache_url)
if no_store:
return
# If we've been given an etag, then keep the response
if self.cache_etags and "etag" in response_headers:
logger.debug("Caching due to etag")
self.cache.set(
cache_url, self.serializer.dumps(request, response, body=body)
)
# Add to the cache any 301s. We do this before looking that
# the Date headers.
elif response.status == 301:
logger.debug("Caching permanant redirect")
self.cache.set(cache_url, self.serializer.dumps(request, response))
# Add to the cache if the response headers demand it. If there
# is no date header then we can't do anything about expiring
# the cache.
elif "date" in response_headers:
# cache when there is a max-age > 0
if "max-age" in cc and cc["max-age"] > 0:
logger.debug("Caching b/c date exists and max-age > 0")
self.cache.set(
cache_url, self.serializer.dumps(request, response, body=body)
)
# If the request can expire, it means we should cache it
# in the meantime.
elif "expires" in response_headers:
if response_headers["expires"]:
logger.debug("Caching b/c of expires header")
self.cache.set(
cache_url, self.serializer.dumps(request, response, body=body)
)
|
[
"def",
"cache_response",
"(",
"self",
",",
"request",
",",
"response",
",",
"body",
"=",
"None",
",",
"status_codes",
"=",
"None",
")",
":",
"# From httplib2: Don't cache 206's since we aren't going to",
"# handle byte range requests",
"cacheable_status_codes",
"=",
"status_codes",
"or",
"self",
".",
"cacheable_status_codes",
"if",
"response",
".",
"status",
"not",
"in",
"cacheable_status_codes",
":",
"logger",
".",
"debug",
"(",
"\"Status code %s not in %s\"",
",",
"response",
".",
"status",
",",
"cacheable_status_codes",
")",
"return",
"response_headers",
"=",
"CaseInsensitiveDict",
"(",
"response",
".",
"headers",
")",
"# If we've been given a body, our response has a Content-Length, that",
"# Content-Length is valid then we can check to see if the body we've",
"# been given matches the expected size, and if it doesn't we'll just",
"# skip trying to cache it.",
"if",
"(",
"body",
"is",
"not",
"None",
"and",
"\"content-length\"",
"in",
"response_headers",
"and",
"response_headers",
"[",
"\"content-length\"",
"]",
".",
"isdigit",
"(",
")",
"and",
"int",
"(",
"response_headers",
"[",
"\"content-length\"",
"]",
")",
"!=",
"len",
"(",
"body",
")",
")",
":",
"return",
"cc_req",
"=",
"self",
".",
"parse_cache_control",
"(",
"request",
".",
"headers",
")",
"cc",
"=",
"self",
".",
"parse_cache_control",
"(",
"response_headers",
")",
"cache_url",
"=",
"self",
".",
"cache_url",
"(",
"request",
".",
"url",
")",
"logger",
".",
"debug",
"(",
"'Updating cache with response from \"%s\"'",
",",
"cache_url",
")",
"# Delete it from the cache if we happen to have it stored there",
"no_store",
"=",
"False",
"if",
"\"no-store\"",
"in",
"cc",
":",
"no_store",
"=",
"True",
"logger",
".",
"debug",
"(",
"'Response header has \"no-store\"'",
")",
"if",
"\"no-store\"",
"in",
"cc_req",
":",
"no_store",
"=",
"True",
"logger",
".",
"debug",
"(",
"'Request header has \"no-store\"'",
")",
"if",
"no_store",
"and",
"self",
".",
"cache",
".",
"get",
"(",
"cache_url",
")",
":",
"logger",
".",
"debug",
"(",
"'Purging existing cache entry to honor \"no-store\"'",
")",
"self",
".",
"cache",
".",
"delete",
"(",
"cache_url",
")",
"if",
"no_store",
":",
"return",
"# If we've been given an etag, then keep the response",
"if",
"self",
".",
"cache_etags",
"and",
"\"etag\"",
"in",
"response_headers",
":",
"logger",
".",
"debug",
"(",
"\"Caching due to etag\"",
")",
"self",
".",
"cache",
".",
"set",
"(",
"cache_url",
",",
"self",
".",
"serializer",
".",
"dumps",
"(",
"request",
",",
"response",
",",
"body",
"=",
"body",
")",
")",
"# Add to the cache any 301s. We do this before looking that",
"# the Date headers.",
"elif",
"response",
".",
"status",
"==",
"301",
":",
"logger",
".",
"debug",
"(",
"\"Caching permanant redirect\"",
")",
"self",
".",
"cache",
".",
"set",
"(",
"cache_url",
",",
"self",
".",
"serializer",
".",
"dumps",
"(",
"request",
",",
"response",
")",
")",
"# Add to the cache if the response headers demand it. If there",
"# is no date header then we can't do anything about expiring",
"# the cache.",
"elif",
"\"date\"",
"in",
"response_headers",
":",
"# cache when there is a max-age > 0",
"if",
"\"max-age\"",
"in",
"cc",
"and",
"cc",
"[",
"\"max-age\"",
"]",
">",
"0",
":",
"logger",
".",
"debug",
"(",
"\"Caching b/c date exists and max-age > 0\"",
")",
"self",
".",
"cache",
".",
"set",
"(",
"cache_url",
",",
"self",
".",
"serializer",
".",
"dumps",
"(",
"request",
",",
"response",
",",
"body",
"=",
"body",
")",
")",
"# If the request can expire, it means we should cache it",
"# in the meantime.",
"elif",
"\"expires\"",
"in",
"response_headers",
":",
"if",
"response_headers",
"[",
"\"expires\"",
"]",
":",
"logger",
".",
"debug",
"(",
"\"Caching b/c of expires header\"",
")",
"self",
".",
"cache",
".",
"set",
"(",
"cache_url",
",",
"self",
".",
"serializer",
".",
"dumps",
"(",
"request",
",",
"response",
",",
"body",
"=",
"body",
")",
")"
] |
Algorithm for caching requests.
This assumes a requests Response object.
|
[
"Algorithm",
"for",
"caching",
"requests",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/cachecontrol/controller.py#L247-L327
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/cachecontrol/controller.py
|
CacheController.update_cached_response
|
def update_cached_response(self, request, response):
"""On a 304 we will get a new set of headers that we want to
update our cached value with, assuming we have one.
This should only ever be called when we've sent an ETag and
gotten a 304 as the response.
"""
cache_url = self.cache_url(request.url)
cached_response = self.serializer.loads(request, self.cache.get(cache_url))
if not cached_response:
# we didn't have a cached response
return response
# Lets update our headers with the headers from the new request:
# http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-26#section-4.1
#
# The server isn't supposed to send headers that would make
# the cached body invalid. But... just in case, we'll be sure
# to strip out ones we know that might be problmatic due to
# typical assumptions.
excluded_headers = ["content-length"]
cached_response.headers.update(
dict(
(k, v)
for k, v in response.headers.items()
if k.lower() not in excluded_headers
)
)
# we want a 200 b/c we have content via the cache
cached_response.status = 200
# update our cache
self.cache.set(cache_url, self.serializer.dumps(request, cached_response))
return cached_response
|
python
|
def update_cached_response(self, request, response):
"""On a 304 we will get a new set of headers that we want to
update our cached value with, assuming we have one.
This should only ever be called when we've sent an ETag and
gotten a 304 as the response.
"""
cache_url = self.cache_url(request.url)
cached_response = self.serializer.loads(request, self.cache.get(cache_url))
if not cached_response:
# we didn't have a cached response
return response
# Lets update our headers with the headers from the new request:
# http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-26#section-4.1
#
# The server isn't supposed to send headers that would make
# the cached body invalid. But... just in case, we'll be sure
# to strip out ones we know that might be problmatic due to
# typical assumptions.
excluded_headers = ["content-length"]
cached_response.headers.update(
dict(
(k, v)
for k, v in response.headers.items()
if k.lower() not in excluded_headers
)
)
# we want a 200 b/c we have content via the cache
cached_response.status = 200
# update our cache
self.cache.set(cache_url, self.serializer.dumps(request, cached_response))
return cached_response
|
[
"def",
"update_cached_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"cache_url",
"=",
"self",
".",
"cache_url",
"(",
"request",
".",
"url",
")",
"cached_response",
"=",
"self",
".",
"serializer",
".",
"loads",
"(",
"request",
",",
"self",
".",
"cache",
".",
"get",
"(",
"cache_url",
")",
")",
"if",
"not",
"cached_response",
":",
"# we didn't have a cached response",
"return",
"response",
"# Lets update our headers with the headers from the new request:",
"# http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-26#section-4.1",
"#",
"# The server isn't supposed to send headers that would make",
"# the cached body invalid. But... just in case, we'll be sure",
"# to strip out ones we know that might be problmatic due to",
"# typical assumptions.",
"excluded_headers",
"=",
"[",
"\"content-length\"",
"]",
"cached_response",
".",
"headers",
".",
"update",
"(",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"response",
".",
"headers",
".",
"items",
"(",
")",
"if",
"k",
".",
"lower",
"(",
")",
"not",
"in",
"excluded_headers",
")",
")",
"# we want a 200 b/c we have content via the cache",
"cached_response",
".",
"status",
"=",
"200",
"# update our cache",
"self",
".",
"cache",
".",
"set",
"(",
"cache_url",
",",
"self",
".",
"serializer",
".",
"dumps",
"(",
"request",
",",
"cached_response",
")",
")",
"return",
"cached_response"
] |
On a 304 we will get a new set of headers that we want to
update our cached value with, assuming we have one.
This should only ever be called when we've sent an ETag and
gotten a 304 as the response.
|
[
"On",
"a",
"304",
"we",
"will",
"get",
"a",
"new",
"set",
"of",
"headers",
"that",
"we",
"want",
"to",
"update",
"our",
"cached",
"value",
"with",
"assuming",
"we",
"have",
"one",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/cachecontrol/controller.py#L329-L367
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/fdpexpect.py
|
fdspawn.close
|
def close (self):
"""Close the file descriptor.
Calling this method a second time does nothing, but if the file
descriptor was closed elsewhere, :class:`OSError` will be raised.
"""
if self.child_fd == -1:
return
self.flush()
os.close(self.child_fd)
self.child_fd = -1
self.closed = True
|
python
|
def close (self):
"""Close the file descriptor.
Calling this method a second time does nothing, but if the file
descriptor was closed elsewhere, :class:`OSError` will be raised.
"""
if self.child_fd == -1:
return
self.flush()
os.close(self.child_fd)
self.child_fd = -1
self.closed = True
|
[
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"child_fd",
"==",
"-",
"1",
":",
"return",
"self",
".",
"flush",
"(",
")",
"os",
".",
"close",
"(",
"self",
".",
"child_fd",
")",
"self",
".",
"child_fd",
"=",
"-",
"1",
"self",
".",
"closed",
"=",
"True"
] |
Close the file descriptor.
Calling this method a second time does nothing, but if the file
descriptor was closed elsewhere, :class:`OSError` will be raised.
|
[
"Close",
"the",
"file",
"descriptor",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/fdpexpect.py#L63-L75
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/fdpexpect.py
|
fdspawn.isalive
|
def isalive (self):
'''This checks if the file descriptor is still valid. If :func:`os.fstat`
does not raise an exception then we assume it is alive. '''
if self.child_fd == -1:
return False
try:
os.fstat(self.child_fd)
return True
except:
return False
|
python
|
def isalive (self):
'''This checks if the file descriptor is still valid. If :func:`os.fstat`
does not raise an exception then we assume it is alive. '''
if self.child_fd == -1:
return False
try:
os.fstat(self.child_fd)
return True
except:
return False
|
[
"def",
"isalive",
"(",
"self",
")",
":",
"if",
"self",
".",
"child_fd",
"==",
"-",
"1",
":",
"return",
"False",
"try",
":",
"os",
".",
"fstat",
"(",
"self",
".",
"child_fd",
")",
"return",
"True",
"except",
":",
"return",
"False"
] |
This checks if the file descriptor is still valid. If :func:`os.fstat`
does not raise an exception then we assume it is alive.
|
[
"This",
"checks",
"if",
"the",
"file",
"descriptor",
"is",
"still",
"valid",
".",
"If",
":",
"func",
":",
"os",
".",
"fstat",
"does",
"not",
"raise",
"an",
"exception",
"then",
"we",
"assume",
"it",
"is",
"alive",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/fdpexpect.py#L77-L87
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/fdpexpect.py
|
fdspawn.read_nonblocking
|
def read_nonblocking(self, size=1, timeout=-1):
"""
Read from the file descriptor and return the result as a string.
The read_nonblocking method of :class:`SpawnBase` assumes that a call
to os.read will not block (timeout parameter is ignored). This is not
the case for POSIX file-like objects such as sockets and serial ports.
Use :func:`select.select`, timeout is implemented conditionally for
POSIX systems.
:param int size: Read at most *size* bytes.
:param int timeout: Wait timeout seconds for file descriptor to be
ready to read. When -1 (default), use self.timeout. When 0, poll.
:return: String containing the bytes read
"""
if os.name == 'posix':
if timeout == -1:
timeout = self.timeout
rlist = [self.child_fd]
wlist = []
xlist = []
if self.use_poll:
rlist = poll_ignore_interrupts(rlist, timeout)
else:
rlist, wlist, xlist = select_ignore_interrupts(
rlist, wlist, xlist, timeout
)
if self.child_fd not in rlist:
raise TIMEOUT('Timeout exceeded.')
return super(fdspawn, self).read_nonblocking(size)
|
python
|
def read_nonblocking(self, size=1, timeout=-1):
"""
Read from the file descriptor and return the result as a string.
The read_nonblocking method of :class:`SpawnBase` assumes that a call
to os.read will not block (timeout parameter is ignored). This is not
the case for POSIX file-like objects such as sockets and serial ports.
Use :func:`select.select`, timeout is implemented conditionally for
POSIX systems.
:param int size: Read at most *size* bytes.
:param int timeout: Wait timeout seconds for file descriptor to be
ready to read. When -1 (default), use self.timeout. When 0, poll.
:return: String containing the bytes read
"""
if os.name == 'posix':
if timeout == -1:
timeout = self.timeout
rlist = [self.child_fd]
wlist = []
xlist = []
if self.use_poll:
rlist = poll_ignore_interrupts(rlist, timeout)
else:
rlist, wlist, xlist = select_ignore_interrupts(
rlist, wlist, xlist, timeout
)
if self.child_fd not in rlist:
raise TIMEOUT('Timeout exceeded.')
return super(fdspawn, self).read_nonblocking(size)
|
[
"def",
"read_nonblocking",
"(",
"self",
",",
"size",
"=",
"1",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"if",
"os",
".",
"name",
"==",
"'posix'",
":",
"if",
"timeout",
"==",
"-",
"1",
":",
"timeout",
"=",
"self",
".",
"timeout",
"rlist",
"=",
"[",
"self",
".",
"child_fd",
"]",
"wlist",
"=",
"[",
"]",
"xlist",
"=",
"[",
"]",
"if",
"self",
".",
"use_poll",
":",
"rlist",
"=",
"poll_ignore_interrupts",
"(",
"rlist",
",",
"timeout",
")",
"else",
":",
"rlist",
",",
"wlist",
",",
"xlist",
"=",
"select_ignore_interrupts",
"(",
"rlist",
",",
"wlist",
",",
"xlist",
",",
"timeout",
")",
"if",
"self",
".",
"child_fd",
"not",
"in",
"rlist",
":",
"raise",
"TIMEOUT",
"(",
"'Timeout exceeded.'",
")",
"return",
"super",
"(",
"fdspawn",
",",
"self",
")",
".",
"read_nonblocking",
"(",
"size",
")"
] |
Read from the file descriptor and return the result as a string.
The read_nonblocking method of :class:`SpawnBase` assumes that a call
to os.read will not block (timeout parameter is ignored). This is not
the case for POSIX file-like objects such as sockets and serial ports.
Use :func:`select.select`, timeout is implemented conditionally for
POSIX systems.
:param int size: Read at most *size* bytes.
:param int timeout: Wait timeout seconds for file descriptor to be
ready to read. When -1 (default), use self.timeout. When 0, poll.
:return: String containing the bytes read
|
[
"Read",
"from",
"the",
"file",
"descriptor",
"and",
"return",
"the",
"result",
"as",
"a",
"string",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/fdpexpect.py#L118-L148
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/utils.py
|
clear_caches
|
def clear_caches():
"""Jinja2 keeps internal caches for environments and lexers. These are
used so that Jinja2 doesn't have to recreate environments and lexers all
the time. Normally you don't have to care about that but if you are
measuring memory consumption you may want to clean the caches.
"""
from jinja2.environment import _spontaneous_environments
from jinja2.lexer import _lexer_cache
_spontaneous_environments.clear()
_lexer_cache.clear()
|
python
|
def clear_caches():
"""Jinja2 keeps internal caches for environments and lexers. These are
used so that Jinja2 doesn't have to recreate environments and lexers all
the time. Normally you don't have to care about that but if you are
measuring memory consumption you may want to clean the caches.
"""
from jinja2.environment import _spontaneous_environments
from jinja2.lexer import _lexer_cache
_spontaneous_environments.clear()
_lexer_cache.clear()
|
[
"def",
"clear_caches",
"(",
")",
":",
"from",
"jinja2",
".",
"environment",
"import",
"_spontaneous_environments",
"from",
"jinja2",
".",
"lexer",
"import",
"_lexer_cache",
"_spontaneous_environments",
".",
"clear",
"(",
")",
"_lexer_cache",
".",
"clear",
"(",
")"
] |
Jinja2 keeps internal caches for environments and lexers. These are
used so that Jinja2 doesn't have to recreate environments and lexers all
the time. Normally you don't have to care about that but if you are
measuring memory consumption you may want to clean the caches.
|
[
"Jinja2",
"keeps",
"internal",
"caches",
"for",
"environments",
"and",
"lexers",
".",
"These",
"are",
"used",
"so",
"that",
"Jinja2",
"doesn",
"t",
"have",
"to",
"recreate",
"environments",
"and",
"lexers",
"all",
"the",
"time",
".",
"Normally",
"you",
"don",
"t",
"have",
"to",
"care",
"about",
"that",
"but",
"if",
"you",
"are",
"measuring",
"memory",
"consumption",
"you",
"may",
"want",
"to",
"clean",
"the",
"caches",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L111-L120
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/utils.py
|
import_string
|
def import_string(import_name, silent=False):
"""Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax.saxutils:escape``).
If the `silent` is True the return value will be `None` if the import
fails.
:return: imported object
"""
try:
if ':' in import_name:
module, obj = import_name.split(':', 1)
elif '.' in import_name:
items = import_name.split('.')
module = '.'.join(items[:-1])
obj = items[-1]
else:
return __import__(import_name)
return getattr(__import__(module, None, None, [obj]), obj)
except (ImportError, AttributeError):
if not silent:
raise
|
python
|
def import_string(import_name, silent=False):
"""Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax.saxutils:escape``).
If the `silent` is True the return value will be `None` if the import
fails.
:return: imported object
"""
try:
if ':' in import_name:
module, obj = import_name.split(':', 1)
elif '.' in import_name:
items = import_name.split('.')
module = '.'.join(items[:-1])
obj = items[-1]
else:
return __import__(import_name)
return getattr(__import__(module, None, None, [obj]), obj)
except (ImportError, AttributeError):
if not silent:
raise
|
[
"def",
"import_string",
"(",
"import_name",
",",
"silent",
"=",
"False",
")",
":",
"try",
":",
"if",
"':'",
"in",
"import_name",
":",
"module",
",",
"obj",
"=",
"import_name",
".",
"split",
"(",
"':'",
",",
"1",
")",
"elif",
"'.'",
"in",
"import_name",
":",
"items",
"=",
"import_name",
".",
"split",
"(",
"'.'",
")",
"module",
"=",
"'.'",
".",
"join",
"(",
"items",
"[",
":",
"-",
"1",
"]",
")",
"obj",
"=",
"items",
"[",
"-",
"1",
"]",
"else",
":",
"return",
"__import__",
"(",
"import_name",
")",
"return",
"getattr",
"(",
"__import__",
"(",
"module",
",",
"None",
",",
"None",
",",
"[",
"obj",
"]",
")",
",",
"obj",
")",
"except",
"(",
"ImportError",
",",
"AttributeError",
")",
":",
"if",
"not",
"silent",
":",
"raise"
] |
Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax.saxutils:escape``).
If the `silent` is True the return value will be `None` if the import
fails.
:return: imported object
|
[
"Imports",
"an",
"object",
"based",
"on",
"a",
"string",
".",
"This",
"is",
"useful",
"if",
"you",
"want",
"to",
"use",
"import",
"paths",
"as",
"endpoints",
"or",
"something",
"similar",
".",
"An",
"import",
"path",
"can",
"be",
"specified",
"either",
"in",
"dotted",
"notation",
"(",
"xml",
".",
"sax",
".",
"saxutils",
".",
"escape",
")",
"or",
"with",
"a",
"colon",
"as",
"object",
"delimiter",
"(",
"xml",
".",
"sax",
".",
"saxutils",
":",
"escape",
")",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L123-L146
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/utils.py
|
pformat
|
def pformat(obj, verbose=False):
"""Prettyprint an object. Either use the `pretty` library or the
builtin `pprint`.
"""
try:
from pretty import pretty
return pretty(obj, verbose=verbose)
except ImportError:
from pprint import pformat
return pformat(obj)
|
python
|
def pformat(obj, verbose=False):
"""Prettyprint an object. Either use the `pretty` library or the
builtin `pprint`.
"""
try:
from pretty import pretty
return pretty(obj, verbose=verbose)
except ImportError:
from pprint import pformat
return pformat(obj)
|
[
"def",
"pformat",
"(",
"obj",
",",
"verbose",
"=",
"False",
")",
":",
"try",
":",
"from",
"pretty",
"import",
"pretty",
"return",
"pretty",
"(",
"obj",
",",
"verbose",
"=",
"verbose",
")",
"except",
"ImportError",
":",
"from",
"pprint",
"import",
"pformat",
"return",
"pformat",
"(",
"obj",
")"
] |
Prettyprint an object. Either use the `pretty` library or the
builtin `pprint`.
|
[
"Prettyprint",
"an",
"object",
".",
"Either",
"use",
"the",
"pretty",
"library",
"or",
"the",
"builtin",
"pprint",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L177-L186
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/utils.py
|
unicode_urlencode
|
def unicode_urlencode(obj, charset='utf-8', for_qs=False):
"""URL escapes a single bytestring or unicode string with the
given charset if applicable to URL safe quoting under all rules
that need to be considered under all supported Python versions.
If non strings are provided they are converted to their unicode
representation first.
"""
if not isinstance(obj, string_types):
obj = text_type(obj)
if isinstance(obj, text_type):
obj = obj.encode(charset)
safe = not for_qs and b'/' or b''
rv = text_type(url_quote(obj, safe))
if for_qs:
rv = rv.replace('%20', '+')
return rv
|
python
|
def unicode_urlencode(obj, charset='utf-8', for_qs=False):
"""URL escapes a single bytestring or unicode string with the
given charset if applicable to URL safe quoting under all rules
that need to be considered under all supported Python versions.
If non strings are provided they are converted to their unicode
representation first.
"""
if not isinstance(obj, string_types):
obj = text_type(obj)
if isinstance(obj, text_type):
obj = obj.encode(charset)
safe = not for_qs and b'/' or b''
rv = text_type(url_quote(obj, safe))
if for_qs:
rv = rv.replace('%20', '+')
return rv
|
[
"def",
"unicode_urlencode",
"(",
"obj",
",",
"charset",
"=",
"'utf-8'",
",",
"for_qs",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"string_types",
")",
":",
"obj",
"=",
"text_type",
"(",
"obj",
")",
"if",
"isinstance",
"(",
"obj",
",",
"text_type",
")",
":",
"obj",
"=",
"obj",
".",
"encode",
"(",
"charset",
")",
"safe",
"=",
"not",
"for_qs",
"and",
"b'/'",
"or",
"b''",
"rv",
"=",
"text_type",
"(",
"url_quote",
"(",
"obj",
",",
"safe",
")",
")",
"if",
"for_qs",
":",
"rv",
"=",
"rv",
".",
"replace",
"(",
"'%20'",
",",
"'+'",
")",
"return",
"rv"
] |
URL escapes a single bytestring or unicode string with the
given charset if applicable to URL safe quoting under all rules
that need to be considered under all supported Python versions.
If non strings are provided they are converted to their unicode
representation first.
|
[
"URL",
"escapes",
"a",
"single",
"bytestring",
"or",
"unicode",
"string",
"with",
"the",
"given",
"charset",
"if",
"applicable",
"to",
"URL",
"safe",
"quoting",
"under",
"all",
"rules",
"that",
"need",
"to",
"be",
"considered",
"under",
"all",
"supported",
"Python",
"versions",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L287-L303
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/utils.py
|
select_autoescape
|
def select_autoescape(enabled_extensions=('html', 'htm', 'xml'),
disabled_extensions=(),
default_for_string=True,
default=False):
"""Intelligently sets the initial value of autoescaping based on the
filename of the template. This is the recommended way to configure
autoescaping if you do not want to write a custom function yourself.
If you want to enable it for all templates created from strings or
for all templates with `.html` and `.xml` extensions::
from jinja2 import Environment, select_autoescape
env = Environment(autoescape=select_autoescape(
enabled_extensions=('html', 'xml'),
default_for_string=True,
))
Example configuration to turn it on at all times except if the template
ends with `.txt`::
from jinja2 import Environment, select_autoescape
env = Environment(autoescape=select_autoescape(
disabled_extensions=('txt',),
default_for_string=True,
default=True,
))
The `enabled_extensions` is an iterable of all the extensions that
autoescaping should be enabled for. Likewise `disabled_extensions` is
a list of all templates it should be disabled for. If a template is
loaded from a string then the default from `default_for_string` is used.
If nothing matches then the initial value of autoescaping is set to the
value of `default`.
For security reasons this function operates case insensitive.
.. versionadded:: 2.9
"""
enabled_patterns = tuple('.' + x.lstrip('.').lower()
for x in enabled_extensions)
disabled_patterns = tuple('.' + x.lstrip('.').lower()
for x in disabled_extensions)
def autoescape(template_name):
if template_name is None:
return default_for_string
template_name = template_name.lower()
if template_name.endswith(enabled_patterns):
return True
if template_name.endswith(disabled_patterns):
return False
return default
return autoescape
|
python
|
def select_autoescape(enabled_extensions=('html', 'htm', 'xml'),
disabled_extensions=(),
default_for_string=True,
default=False):
"""Intelligently sets the initial value of autoescaping based on the
filename of the template. This is the recommended way to configure
autoescaping if you do not want to write a custom function yourself.
If you want to enable it for all templates created from strings or
for all templates with `.html` and `.xml` extensions::
from jinja2 import Environment, select_autoescape
env = Environment(autoescape=select_autoescape(
enabled_extensions=('html', 'xml'),
default_for_string=True,
))
Example configuration to turn it on at all times except if the template
ends with `.txt`::
from jinja2 import Environment, select_autoescape
env = Environment(autoescape=select_autoescape(
disabled_extensions=('txt',),
default_for_string=True,
default=True,
))
The `enabled_extensions` is an iterable of all the extensions that
autoescaping should be enabled for. Likewise `disabled_extensions` is
a list of all templates it should be disabled for. If a template is
loaded from a string then the default from `default_for_string` is used.
If nothing matches then the initial value of autoescaping is set to the
value of `default`.
For security reasons this function operates case insensitive.
.. versionadded:: 2.9
"""
enabled_patterns = tuple('.' + x.lstrip('.').lower()
for x in enabled_extensions)
disabled_patterns = tuple('.' + x.lstrip('.').lower()
for x in disabled_extensions)
def autoescape(template_name):
if template_name is None:
return default_for_string
template_name = template_name.lower()
if template_name.endswith(enabled_patterns):
return True
if template_name.endswith(disabled_patterns):
return False
return default
return autoescape
|
[
"def",
"select_autoescape",
"(",
"enabled_extensions",
"=",
"(",
"'html'",
",",
"'htm'",
",",
"'xml'",
")",
",",
"disabled_extensions",
"=",
"(",
")",
",",
"default_for_string",
"=",
"True",
",",
"default",
"=",
"False",
")",
":",
"enabled_patterns",
"=",
"tuple",
"(",
"'.'",
"+",
"x",
".",
"lstrip",
"(",
"'.'",
")",
".",
"lower",
"(",
")",
"for",
"x",
"in",
"enabled_extensions",
")",
"disabled_patterns",
"=",
"tuple",
"(",
"'.'",
"+",
"x",
".",
"lstrip",
"(",
"'.'",
")",
".",
"lower",
"(",
")",
"for",
"x",
"in",
"disabled_extensions",
")",
"def",
"autoescape",
"(",
"template_name",
")",
":",
"if",
"template_name",
"is",
"None",
":",
"return",
"default_for_string",
"template_name",
"=",
"template_name",
".",
"lower",
"(",
")",
"if",
"template_name",
".",
"endswith",
"(",
"enabled_patterns",
")",
":",
"return",
"True",
"if",
"template_name",
".",
"endswith",
"(",
"disabled_patterns",
")",
":",
"return",
"False",
"return",
"default",
"return",
"autoescape"
] |
Intelligently sets the initial value of autoescaping based on the
filename of the template. This is the recommended way to configure
autoescaping if you do not want to write a custom function yourself.
If you want to enable it for all templates created from strings or
for all templates with `.html` and `.xml` extensions::
from jinja2 import Environment, select_autoescape
env = Environment(autoescape=select_autoescape(
enabled_extensions=('html', 'xml'),
default_for_string=True,
))
Example configuration to turn it on at all times except if the template
ends with `.txt`::
from jinja2 import Environment, select_autoescape
env = Environment(autoescape=select_autoescape(
disabled_extensions=('txt',),
default_for_string=True,
default=True,
))
The `enabled_extensions` is an iterable of all the extensions that
autoescaping should be enabled for. Likewise `disabled_extensions` is
a list of all templates it should be disabled for. If a template is
loaded from a string then the default from `default_for_string` is used.
If nothing matches then the initial value of autoescaping is set to the
value of `default`.
For security reasons this function operates case insensitive.
.. versionadded:: 2.9
|
[
"Intelligently",
"sets",
"the",
"initial",
"value",
"of",
"autoescaping",
"based",
"on",
"the",
"filename",
"of",
"the",
"template",
".",
"This",
"is",
"the",
"recommended",
"way",
"to",
"configure",
"autoescaping",
"if",
"you",
"do",
"not",
"want",
"to",
"write",
"a",
"custom",
"function",
"yourself",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L491-L542
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/utils.py
|
htmlsafe_json_dumps
|
def htmlsafe_json_dumps(obj, dumper=None, **kwargs):
"""Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags.
The following characters are escaped in strings:
- ``<``
- ``>``
- ``&``
- ``'``
This makes it safe to embed such strings in any place in HTML with the
notable exception of double quoted attributes. In that case single
quote your attributes or HTML escape it in addition.
"""
if dumper is None:
dumper = json.dumps
rv = dumper(obj, **kwargs) \
.replace(u'<', u'\\u003c') \
.replace(u'>', u'\\u003e') \
.replace(u'&', u'\\u0026') \
.replace(u"'", u'\\u0027')
return Markup(rv)
|
python
|
def htmlsafe_json_dumps(obj, dumper=None, **kwargs):
"""Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags.
The following characters are escaped in strings:
- ``<``
- ``>``
- ``&``
- ``'``
This makes it safe to embed such strings in any place in HTML with the
notable exception of double quoted attributes. In that case single
quote your attributes or HTML escape it in addition.
"""
if dumper is None:
dumper = json.dumps
rv = dumper(obj, **kwargs) \
.replace(u'<', u'\\u003c') \
.replace(u'>', u'\\u003e') \
.replace(u'&', u'\\u0026') \
.replace(u"'", u'\\u0027')
return Markup(rv)
|
[
"def",
"htmlsafe_json_dumps",
"(",
"obj",
",",
"dumper",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"dumper",
"is",
"None",
":",
"dumper",
"=",
"json",
".",
"dumps",
"rv",
"=",
"dumper",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
".",
"replace",
"(",
"u'<'",
",",
"u'\\\\u003c'",
")",
".",
"replace",
"(",
"u'>'",
",",
"u'\\\\u003e'",
")",
".",
"replace",
"(",
"u'&'",
",",
"u'\\\\u0026'",
")",
".",
"replace",
"(",
"u\"'\"",
",",
"u'\\\\u0027'",
")",
"return",
"Markup",
"(",
"rv",
")"
] |
Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags.
The following characters are escaped in strings:
- ``<``
- ``>``
- ``&``
- ``'``
This makes it safe to embed such strings in any place in HTML with the
notable exception of double quoted attributes. In that case single
quote your attributes or HTML escape it in addition.
|
[
"Works",
"exactly",
"like",
":",
"func",
":",
"dumps",
"but",
"is",
"safe",
"for",
"use",
"in",
"<script",
">",
"tags",
".",
"It",
"accepts",
"the",
"same",
"arguments",
"and",
"returns",
"a",
"JSON",
"string",
".",
"Note",
"that",
"this",
"is",
"available",
"in",
"templates",
"through",
"the",
"|tojson",
"filter",
"which",
"will",
"also",
"mark",
"the",
"result",
"as",
"safe",
".",
"Due",
"to",
"how",
"this",
"function",
"escapes",
"certain",
"characters",
"this",
"is",
"safe",
"even",
"if",
"used",
"outside",
"of",
"<script",
">",
"tags",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L545-L570
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/utils.py
|
LRUCache.copy
|
def copy(self):
"""Return a shallow copy of the instance."""
rv = self.__class__(self.capacity)
rv._mapping.update(self._mapping)
rv._queue = deque(self._queue)
return rv
|
python
|
def copy(self):
"""Return a shallow copy of the instance."""
rv = self.__class__(self.capacity)
rv._mapping.update(self._mapping)
rv._queue = deque(self._queue)
return rv
|
[
"def",
"copy",
"(",
"self",
")",
":",
"rv",
"=",
"self",
".",
"__class__",
"(",
"self",
".",
"capacity",
")",
"rv",
".",
"_mapping",
".",
"update",
"(",
"self",
".",
"_mapping",
")",
"rv",
".",
"_queue",
"=",
"deque",
"(",
"self",
".",
"_queue",
")",
"return",
"rv"
] |
Return a shallow copy of the instance.
|
[
"Return",
"a",
"shallow",
"copy",
"of",
"the",
"instance",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L341-L346
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/utils.py
|
LRUCache.setdefault
|
def setdefault(self, key, default=None):
"""Set `default` if the key is not in the cache otherwise
leave unchanged. Return the value of this key.
"""
self._wlock.acquire()
try:
try:
return self[key]
except KeyError:
self[key] = default
return default
finally:
self._wlock.release()
|
python
|
def setdefault(self, key, default=None):
"""Set `default` if the key is not in the cache otherwise
leave unchanged. Return the value of this key.
"""
self._wlock.acquire()
try:
try:
return self[key]
except KeyError:
self[key] = default
return default
finally:
self._wlock.release()
|
[
"def",
"setdefault",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"self",
".",
"_wlock",
".",
"acquire",
"(",
")",
"try",
":",
"try",
":",
"return",
"self",
"[",
"key",
"]",
"except",
"KeyError",
":",
"self",
"[",
"key",
"]",
"=",
"default",
"return",
"default",
"finally",
":",
"self",
".",
"_wlock",
".",
"release",
"(",
")"
] |
Set `default` if the key is not in the cache otherwise
leave unchanged. Return the value of this key.
|
[
"Set",
"default",
"if",
"the",
"key",
"is",
"not",
"in",
"the",
"cache",
"otherwise",
"leave",
"unchanged",
".",
"Return",
"the",
"value",
"of",
"this",
"key",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L355-L367
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/utils.py
|
LRUCache.clear
|
def clear(self):
"""Clear the cache."""
self._wlock.acquire()
try:
self._mapping.clear()
self._queue.clear()
finally:
self._wlock.release()
|
python
|
def clear(self):
"""Clear the cache."""
self._wlock.acquire()
try:
self._mapping.clear()
self._queue.clear()
finally:
self._wlock.release()
|
[
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_wlock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"_mapping",
".",
"clear",
"(",
")",
"self",
".",
"_queue",
".",
"clear",
"(",
")",
"finally",
":",
"self",
".",
"_wlock",
".",
"release",
"(",
")"
] |
Clear the cache.
|
[
"Clear",
"the",
"cache",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L369-L376
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/utils.py
|
LRUCache.items
|
def items(self):
"""Return a list of items."""
result = [(key, self._mapping[key]) for key in list(self._queue)]
result.reverse()
return result
|
python
|
def items(self):
"""Return a list of items."""
result = [(key, self._mapping[key]) for key in list(self._queue)]
result.reverse()
return result
|
[
"def",
"items",
"(",
"self",
")",
":",
"result",
"=",
"[",
"(",
"key",
",",
"self",
".",
"_mapping",
"[",
"key",
"]",
")",
"for",
"key",
"in",
"list",
"(",
"self",
".",
"_queue",
")",
"]",
"result",
".",
"reverse",
"(",
")",
"return",
"result"
] |
Return a list of items.
|
[
"Return",
"a",
"list",
"of",
"items",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L444-L448
|
train
|
pypa/pipenv
|
tasks/vendoring/__init__.py
|
license_fallback
|
def license_fallback(vendor_dir, sdist_name):
"""Hardcoded license URLs. Check when updating if those are still needed"""
libname = libname_from_dir(sdist_name)
if libname not in HARDCODED_LICENSE_URLS:
raise ValueError('No hardcoded URL for {} license'.format(libname))
url = HARDCODED_LICENSE_URLS[libname]
_, _, name = url.rpartition('/')
dest = license_destination(vendor_dir, libname, name)
r = requests.get(url, allow_redirects=True)
log('Downloading {}'.format(url))
r.raise_for_status()
dest.write_bytes(r.content)
|
python
|
def license_fallback(vendor_dir, sdist_name):
"""Hardcoded license URLs. Check when updating if those are still needed"""
libname = libname_from_dir(sdist_name)
if libname not in HARDCODED_LICENSE_URLS:
raise ValueError('No hardcoded URL for {} license'.format(libname))
url = HARDCODED_LICENSE_URLS[libname]
_, _, name = url.rpartition('/')
dest = license_destination(vendor_dir, libname, name)
r = requests.get(url, allow_redirects=True)
log('Downloading {}'.format(url))
r.raise_for_status()
dest.write_bytes(r.content)
|
[
"def",
"license_fallback",
"(",
"vendor_dir",
",",
"sdist_name",
")",
":",
"libname",
"=",
"libname_from_dir",
"(",
"sdist_name",
")",
"if",
"libname",
"not",
"in",
"HARDCODED_LICENSE_URLS",
":",
"raise",
"ValueError",
"(",
"'No hardcoded URL for {} license'",
".",
"format",
"(",
"libname",
")",
")",
"url",
"=",
"HARDCODED_LICENSE_URLS",
"[",
"libname",
"]",
"_",
",",
"_",
",",
"name",
"=",
"url",
".",
"rpartition",
"(",
"'/'",
")",
"dest",
"=",
"license_destination",
"(",
"vendor_dir",
",",
"libname",
",",
"name",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"allow_redirects",
"=",
"True",
")",
"log",
"(",
"'Downloading {}'",
".",
"format",
"(",
"url",
")",
")",
"r",
".",
"raise_for_status",
"(",
")",
"dest",
".",
"write_bytes",
"(",
"r",
".",
"content",
")"
] |
Hardcoded license URLs. Check when updating if those are still needed
|
[
"Hardcoded",
"license",
"URLs",
".",
"Check",
"when",
"updating",
"if",
"those",
"are",
"still",
"needed"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/tasks/vendoring/__init__.py#L588-L600
|
train
|
pypa/pipenv
|
tasks/vendoring/__init__.py
|
libname_from_dir
|
def libname_from_dir(dirname):
"""Reconstruct the library name without it's version"""
parts = []
for part in dirname.split('-'):
if part[0].isdigit():
break
parts.append(part)
return '-'.join(parts)
|
python
|
def libname_from_dir(dirname):
"""Reconstruct the library name without it's version"""
parts = []
for part in dirname.split('-'):
if part[0].isdigit():
break
parts.append(part)
return '-'.join(parts)
|
[
"def",
"libname_from_dir",
"(",
"dirname",
")",
":",
"parts",
"=",
"[",
"]",
"for",
"part",
"in",
"dirname",
".",
"split",
"(",
"'-'",
")",
":",
"if",
"part",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
":",
"break",
"parts",
".",
"append",
"(",
"part",
")",
"return",
"'-'",
".",
"join",
"(",
"parts",
")"
] |
Reconstruct the library name without it's version
|
[
"Reconstruct",
"the",
"library",
"name",
"without",
"it",
"s",
"version"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/tasks/vendoring/__init__.py#L603-L610
|
train
|
pypa/pipenv
|
tasks/vendoring/__init__.py
|
license_destination
|
def license_destination(vendor_dir, libname, filename):
"""Given the (reconstructed) library name, find appropriate destination"""
normal = vendor_dir / libname
if normal.is_dir():
return normal / filename
lowercase = vendor_dir / libname.lower().replace('-', '_')
if lowercase.is_dir():
return lowercase / filename
rename_dict = LIBRARY_RENAMES if vendor_dir.name != 'patched' else PATCHED_RENAMES
# Short circuit all logic if we are renaming the whole library
if libname in rename_dict:
return vendor_dir / rename_dict[libname] / filename
if libname in LIBRARY_DIRNAMES:
override = vendor_dir / LIBRARY_DIRNAMES[libname]
if not override.exists() and override.parent.exists():
# for flattened subdeps, specifically backports/weakref.py
return (
vendor_dir / override.parent
) / '{0}.{1}'.format(override.name, filename)
return vendor_dir / LIBRARY_DIRNAMES[libname] / filename
# fallback to libname.LICENSE (used for nondirs)
return vendor_dir / '{}.{}'.format(libname, filename)
|
python
|
def license_destination(vendor_dir, libname, filename):
"""Given the (reconstructed) library name, find appropriate destination"""
normal = vendor_dir / libname
if normal.is_dir():
return normal / filename
lowercase = vendor_dir / libname.lower().replace('-', '_')
if lowercase.is_dir():
return lowercase / filename
rename_dict = LIBRARY_RENAMES if vendor_dir.name != 'patched' else PATCHED_RENAMES
# Short circuit all logic if we are renaming the whole library
if libname in rename_dict:
return vendor_dir / rename_dict[libname] / filename
if libname in LIBRARY_DIRNAMES:
override = vendor_dir / LIBRARY_DIRNAMES[libname]
if not override.exists() and override.parent.exists():
# for flattened subdeps, specifically backports/weakref.py
return (
vendor_dir / override.parent
) / '{0}.{1}'.format(override.name, filename)
return vendor_dir / LIBRARY_DIRNAMES[libname] / filename
# fallback to libname.LICENSE (used for nondirs)
return vendor_dir / '{}.{}'.format(libname, filename)
|
[
"def",
"license_destination",
"(",
"vendor_dir",
",",
"libname",
",",
"filename",
")",
":",
"normal",
"=",
"vendor_dir",
"/",
"libname",
"if",
"normal",
".",
"is_dir",
"(",
")",
":",
"return",
"normal",
"/",
"filename",
"lowercase",
"=",
"vendor_dir",
"/",
"libname",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"if",
"lowercase",
".",
"is_dir",
"(",
")",
":",
"return",
"lowercase",
"/",
"filename",
"rename_dict",
"=",
"LIBRARY_RENAMES",
"if",
"vendor_dir",
".",
"name",
"!=",
"'patched'",
"else",
"PATCHED_RENAMES",
"# Short circuit all logic if we are renaming the whole library",
"if",
"libname",
"in",
"rename_dict",
":",
"return",
"vendor_dir",
"/",
"rename_dict",
"[",
"libname",
"]",
"/",
"filename",
"if",
"libname",
"in",
"LIBRARY_DIRNAMES",
":",
"override",
"=",
"vendor_dir",
"/",
"LIBRARY_DIRNAMES",
"[",
"libname",
"]",
"if",
"not",
"override",
".",
"exists",
"(",
")",
"and",
"override",
".",
"parent",
".",
"exists",
"(",
")",
":",
"# for flattened subdeps, specifically backports/weakref.py",
"return",
"(",
"vendor_dir",
"/",
"override",
".",
"parent",
")",
"/",
"'{0}.{1}'",
".",
"format",
"(",
"override",
".",
"name",
",",
"filename",
")",
"return",
"vendor_dir",
"/",
"LIBRARY_DIRNAMES",
"[",
"libname",
"]",
"/",
"filename",
"# fallback to libname.LICENSE (used for nondirs)",
"return",
"vendor_dir",
"/",
"'{}.{}'",
".",
"format",
"(",
"libname",
",",
"filename",
")"
] |
Given the (reconstructed) library name, find appropriate destination
|
[
"Given",
"the",
"(",
"reconstructed",
")",
"library",
"name",
"find",
"appropriate",
"destination"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/tasks/vendoring/__init__.py#L613-L634
|
train
|
pypa/pipenv
|
pipenv/vendor/passa/internals/_pip.py
|
_convert_hashes
|
def _convert_hashes(values):
"""Convert Pipfile.lock hash lines into InstallRequirement option format.
The option format uses a str-list mapping. Keys are hash algorithms, and
the list contains all values of that algorithm.
"""
hashes = {}
if not values:
return hashes
for value in values:
try:
name, value = value.split(":", 1)
except ValueError:
name = "sha256"
if name not in hashes:
hashes[name] = []
hashes[name].append(value)
return hashes
|
python
|
def _convert_hashes(values):
"""Convert Pipfile.lock hash lines into InstallRequirement option format.
The option format uses a str-list mapping. Keys are hash algorithms, and
the list contains all values of that algorithm.
"""
hashes = {}
if not values:
return hashes
for value in values:
try:
name, value = value.split(":", 1)
except ValueError:
name = "sha256"
if name not in hashes:
hashes[name] = []
hashes[name].append(value)
return hashes
|
[
"def",
"_convert_hashes",
"(",
"values",
")",
":",
"hashes",
"=",
"{",
"}",
"if",
"not",
"values",
":",
"return",
"hashes",
"for",
"value",
"in",
"values",
":",
"try",
":",
"name",
",",
"value",
"=",
"value",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"except",
"ValueError",
":",
"name",
"=",
"\"sha256\"",
"if",
"name",
"not",
"in",
"hashes",
":",
"hashes",
"[",
"name",
"]",
"=",
"[",
"]",
"hashes",
"[",
"name",
"]",
".",
"append",
"(",
"value",
")",
"return",
"hashes"
] |
Convert Pipfile.lock hash lines into InstallRequirement option format.
The option format uses a str-list mapping. Keys are hash algorithms, and
the list contains all values of that algorithm.
|
[
"Convert",
"Pipfile",
".",
"lock",
"hash",
"lines",
"into",
"InstallRequirement",
"option",
"format",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/_pip.py#L113-L130
|
train
|
pypa/pipenv
|
pipenv/vendor/passa/internals/_pip.py
|
_suppress_distutils_logs
|
def _suppress_distutils_logs():
"""Hack to hide noise generated by `setup.py develop`.
There isn't a good way to suppress them now, so let's monky-patch.
See https://bugs.python.org/issue25392.
"""
f = distutils.log.Log._log
def _log(log, level, msg, args):
if level >= distutils.log.ERROR:
f(log, level, msg, args)
distutils.log.Log._log = _log
yield
distutils.log.Log._log = f
|
python
|
def _suppress_distutils_logs():
"""Hack to hide noise generated by `setup.py develop`.
There isn't a good way to suppress them now, so let's monky-patch.
See https://bugs.python.org/issue25392.
"""
f = distutils.log.Log._log
def _log(log, level, msg, args):
if level >= distutils.log.ERROR:
f(log, level, msg, args)
distutils.log.Log._log = _log
yield
distutils.log.Log._log = f
|
[
"def",
"_suppress_distutils_logs",
"(",
")",
":",
"f",
"=",
"distutils",
".",
"log",
".",
"Log",
".",
"_log",
"def",
"_log",
"(",
"log",
",",
"level",
",",
"msg",
",",
"args",
")",
":",
"if",
"level",
">=",
"distutils",
".",
"log",
".",
"ERROR",
":",
"f",
"(",
"log",
",",
"level",
",",
"msg",
",",
"args",
")",
"distutils",
".",
"log",
".",
"Log",
".",
"_log",
"=",
"_log",
"yield",
"distutils",
".",
"log",
".",
"Log",
".",
"_log",
"=",
"f"
] |
Hack to hide noise generated by `setup.py develop`.
There isn't a good way to suppress them now, so let's monky-patch.
See https://bugs.python.org/issue25392.
|
[
"Hack",
"to",
"hide",
"noise",
"generated",
"by",
"setup",
".",
"py",
"develop",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/_pip.py#L258-L272
|
train
|
pypa/pipenv
|
pipenv/vendor/passa/internals/_pip.py
|
_find_egg_info
|
def _find_egg_info(ireq):
"""Find this package's .egg-info directory.
Due to how sdists are designed, the .egg-info directory cannot be reliably
found without running setup.py to aggregate all configurations. This
function instead uses some heuristics to locate the egg-info directory
that most likely represents this package.
The best .egg-info directory's path is returned as a string. None is
returned if no matches can be found.
"""
root = ireq.setup_py_dir
directory_iterator = _iter_egg_info_directories(root, ireq.name)
try:
top_egg_info = next(directory_iterator)
except StopIteration: # No egg-info found. Wat.
return None
directory_iterator = itertools.chain([top_egg_info], directory_iterator)
# Read the sdist's PKG-INFO to determine which egg_info is best.
pkg_info = _read_pkg_info(root)
# PKG-INFO not readable. Just return whatever comes first, I guess.
if pkg_info is None:
return top_egg_info
# Walk the sdist to find the egg-info with matching PKG-INFO.
for directory in directory_iterator:
egg_pkg_info = _read_pkg_info(directory)
if egg_pkg_info == pkg_info:
return directory
# Nothing matches...? Use the first one we found, I guess.
return top_egg_info
|
python
|
def _find_egg_info(ireq):
"""Find this package's .egg-info directory.
Due to how sdists are designed, the .egg-info directory cannot be reliably
found without running setup.py to aggregate all configurations. This
function instead uses some heuristics to locate the egg-info directory
that most likely represents this package.
The best .egg-info directory's path is returned as a string. None is
returned if no matches can be found.
"""
root = ireq.setup_py_dir
directory_iterator = _iter_egg_info_directories(root, ireq.name)
try:
top_egg_info = next(directory_iterator)
except StopIteration: # No egg-info found. Wat.
return None
directory_iterator = itertools.chain([top_egg_info], directory_iterator)
# Read the sdist's PKG-INFO to determine which egg_info is best.
pkg_info = _read_pkg_info(root)
# PKG-INFO not readable. Just return whatever comes first, I guess.
if pkg_info is None:
return top_egg_info
# Walk the sdist to find the egg-info with matching PKG-INFO.
for directory in directory_iterator:
egg_pkg_info = _read_pkg_info(directory)
if egg_pkg_info == pkg_info:
return directory
# Nothing matches...? Use the first one we found, I guess.
return top_egg_info
|
[
"def",
"_find_egg_info",
"(",
"ireq",
")",
":",
"root",
"=",
"ireq",
".",
"setup_py_dir",
"directory_iterator",
"=",
"_iter_egg_info_directories",
"(",
"root",
",",
"ireq",
".",
"name",
")",
"try",
":",
"top_egg_info",
"=",
"next",
"(",
"directory_iterator",
")",
"except",
"StopIteration",
":",
"# No egg-info found. Wat.",
"return",
"None",
"directory_iterator",
"=",
"itertools",
".",
"chain",
"(",
"[",
"top_egg_info",
"]",
",",
"directory_iterator",
")",
"# Read the sdist's PKG-INFO to determine which egg_info is best.",
"pkg_info",
"=",
"_read_pkg_info",
"(",
"root",
")",
"# PKG-INFO not readable. Just return whatever comes first, I guess.",
"if",
"pkg_info",
"is",
"None",
":",
"return",
"top_egg_info",
"# Walk the sdist to find the egg-info with matching PKG-INFO.",
"for",
"directory",
"in",
"directory_iterator",
":",
"egg_pkg_info",
"=",
"_read_pkg_info",
"(",
"directory",
")",
"if",
"egg_pkg_info",
"==",
"pkg_info",
":",
"return",
"directory",
"# Nothing matches...? Use the first one we found, I guess.",
"return",
"top_egg_info"
] |
Find this package's .egg-info directory.
Due to how sdists are designed, the .egg-info directory cannot be reliably
found without running setup.py to aggregate all configurations. This
function instead uses some heuristics to locate the egg-info directory
that most likely represents this package.
The best .egg-info directory's path is returned as a string. None is
returned if no matches can be found.
|
[
"Find",
"this",
"package",
"s",
".",
"egg",
"-",
"info",
"directory",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/_pip.py#L355-L389
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/compat.py
|
fs_str
|
def fs_str(string):
"""Encodes a string into the proper filesystem encoding
Borrowed from pip-tools
"""
if isinstance(string, str):
return string
assert not isinstance(string, bytes)
return string.encode(_fs_encoding)
|
python
|
def fs_str(string):
"""Encodes a string into the proper filesystem encoding
Borrowed from pip-tools
"""
if isinstance(string, str):
return string
assert not isinstance(string, bytes)
return string.encode(_fs_encoding)
|
[
"def",
"fs_str",
"(",
"string",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"str",
")",
":",
"return",
"string",
"assert",
"not",
"isinstance",
"(",
"string",
",",
"bytes",
")",
"return",
"string",
".",
"encode",
"(",
"_fs_encoding",
")"
] |
Encodes a string into the proper filesystem encoding
Borrowed from pip-tools
|
[
"Encodes",
"a",
"string",
"into",
"the",
"proper",
"filesystem",
"encoding"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/compat.py#L208-L217
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/compat.py
|
_get_path
|
def _get_path(path):
"""
Fetch the string value from a path-like object
Returns **None** if there is no string value.
"""
if isinstance(path, (six.string_types, bytes)):
return path
path_type = type(path)
try:
path_repr = path_type.__fspath__(path)
except AttributeError:
return
if isinstance(path_repr, (six.string_types, bytes)):
return path_repr
return
|
python
|
def _get_path(path):
"""
Fetch the string value from a path-like object
Returns **None** if there is no string value.
"""
if isinstance(path, (six.string_types, bytes)):
return path
path_type = type(path)
try:
path_repr = path_type.__fspath__(path)
except AttributeError:
return
if isinstance(path_repr, (six.string_types, bytes)):
return path_repr
return
|
[
"def",
"_get_path",
"(",
"path",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"(",
"six",
".",
"string_types",
",",
"bytes",
")",
")",
":",
"return",
"path",
"path_type",
"=",
"type",
"(",
"path",
")",
"try",
":",
"path_repr",
"=",
"path_type",
".",
"__fspath__",
"(",
"path",
")",
"except",
"AttributeError",
":",
"return",
"if",
"isinstance",
"(",
"path_repr",
",",
"(",
"six",
".",
"string_types",
",",
"bytes",
")",
")",
":",
"return",
"path_repr",
"return"
] |
Fetch the string value from a path-like object
Returns **None** if there is no string value.
|
[
"Fetch",
"the",
"string",
"value",
"from",
"a",
"path",
"-",
"like",
"object"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/compat.py#L220-L236
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/compat.py
|
fs_encode
|
def fs_encode(path):
"""
Encode a filesystem path to the proper filesystem encoding
:param Union[str, bytes] path: A string-like path
:returns: A bytes-encoded filesystem path representation
"""
path = _get_path(path)
if path is None:
raise TypeError("expected a valid path to encode")
if isinstance(path, six.text_type):
path = path.encode(_fs_encoding, _fs_encode_errors)
return path
|
python
|
def fs_encode(path):
"""
Encode a filesystem path to the proper filesystem encoding
:param Union[str, bytes] path: A string-like path
:returns: A bytes-encoded filesystem path representation
"""
path = _get_path(path)
if path is None:
raise TypeError("expected a valid path to encode")
if isinstance(path, six.text_type):
path = path.encode(_fs_encoding, _fs_encode_errors)
return path
|
[
"def",
"fs_encode",
"(",
"path",
")",
":",
"path",
"=",
"_get_path",
"(",
"path",
")",
"if",
"path",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"expected a valid path to encode\"",
")",
"if",
"isinstance",
"(",
"path",
",",
"six",
".",
"text_type",
")",
":",
"path",
"=",
"path",
".",
"encode",
"(",
"_fs_encoding",
",",
"_fs_encode_errors",
")",
"return",
"path"
] |
Encode a filesystem path to the proper filesystem encoding
:param Union[str, bytes] path: A string-like path
:returns: A bytes-encoded filesystem path representation
|
[
"Encode",
"a",
"filesystem",
"path",
"to",
"the",
"proper",
"filesystem",
"encoding"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/compat.py#L239-L252
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/compat.py
|
fs_decode
|
def fs_decode(path):
"""
Decode a filesystem path using the proper filesystem encoding
:param path: The filesystem path to decode from bytes or string
:return: [description]
:rtype: [type]
"""
path = _get_path(path)
if path is None:
raise TypeError("expected a valid path to decode")
if isinstance(path, six.binary_type):
path = path.decode(_fs_encoding, _fs_decode_errors)
return path
|
python
|
def fs_decode(path):
"""
Decode a filesystem path using the proper filesystem encoding
:param path: The filesystem path to decode from bytes or string
:return: [description]
:rtype: [type]
"""
path = _get_path(path)
if path is None:
raise TypeError("expected a valid path to decode")
if isinstance(path, six.binary_type):
path = path.decode(_fs_encoding, _fs_decode_errors)
return path
|
[
"def",
"fs_decode",
"(",
"path",
")",
":",
"path",
"=",
"_get_path",
"(",
"path",
")",
"if",
"path",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"expected a valid path to decode\"",
")",
"if",
"isinstance",
"(",
"path",
",",
"six",
".",
"binary_type",
")",
":",
"path",
"=",
"path",
".",
"decode",
"(",
"_fs_encoding",
",",
"_fs_decode_errors",
")",
"return",
"path"
] |
Decode a filesystem path using the proper filesystem encoding
:param path: The filesystem path to decode from bytes or string
:return: [description]
:rtype: [type]
|
[
"Decode",
"a",
"filesystem",
"path",
"using",
"the",
"proper",
"filesystem",
"encoding"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/compat.py#L255-L269
|
train
|
pypa/pipenv
|
pipenv/vendor/passa/internals/traces.py
|
trace_graph
|
def trace_graph(graph):
"""Build a collection of "traces" for each package.
A trace is a list of names that eventually leads to the package. For
example, if A and B are root dependencies, A depends on C and D, B
depends on C, and C depends on D, the return value would be like::
{
None: [],
"A": [None],
"B": [None],
"C": [[None, "A"], [None, "B"]],
"D": [[None, "B", "C"], [None, "A"]],
}
"""
result = {None: []}
for vertex in graph:
result[vertex] = []
for root in graph.iter_children(None):
paths = []
_trace_visit_vertex(graph, root, vertex, {None}, [None], paths)
result[vertex].extend(paths)
return result
|
python
|
def trace_graph(graph):
"""Build a collection of "traces" for each package.
A trace is a list of names that eventually leads to the package. For
example, if A and B are root dependencies, A depends on C and D, B
depends on C, and C depends on D, the return value would be like::
{
None: [],
"A": [None],
"B": [None],
"C": [[None, "A"], [None, "B"]],
"D": [[None, "B", "C"], [None, "A"]],
}
"""
result = {None: []}
for vertex in graph:
result[vertex] = []
for root in graph.iter_children(None):
paths = []
_trace_visit_vertex(graph, root, vertex, {None}, [None], paths)
result[vertex].extend(paths)
return result
|
[
"def",
"trace_graph",
"(",
"graph",
")",
":",
"result",
"=",
"{",
"None",
":",
"[",
"]",
"}",
"for",
"vertex",
"in",
"graph",
":",
"result",
"[",
"vertex",
"]",
"=",
"[",
"]",
"for",
"root",
"in",
"graph",
".",
"iter_children",
"(",
"None",
")",
":",
"paths",
"=",
"[",
"]",
"_trace_visit_vertex",
"(",
"graph",
",",
"root",
",",
"vertex",
",",
"{",
"None",
"}",
",",
"[",
"None",
"]",
",",
"paths",
")",
"result",
"[",
"vertex",
"]",
".",
"extend",
"(",
"paths",
")",
"return",
"result"
] |
Build a collection of "traces" for each package.
A trace is a list of names that eventually leads to the package. For
example, if A and B are root dependencies, A depends on C and D, B
depends on C, and C depends on D, the return value would be like::
{
None: [],
"A": [None],
"B": [None],
"C": [[None, "A"], [None, "B"]],
"D": [[None, "B", "C"], [None, "A"]],
}
|
[
"Build",
"a",
"collection",
"of",
"traces",
"for",
"each",
"package",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/traces.py#L18-L40
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/util/timeout.py
|
Timeout._validate_timeout
|
def _validate_timeout(cls, value, name):
""" Check that a timeout attribute is valid.
:param value: The timeout value to validate
:param name: The name of the timeout attribute to validate. This is
used to specify in error messages.
:return: The validated and casted version of the given value.
:raises ValueError: If it is a numeric value less than or equal to
zero, or the type is not an integer, float, or None.
"""
if value is _Default:
return cls.DEFAULT_TIMEOUT
if value is None or value is cls.DEFAULT_TIMEOUT:
return value
if isinstance(value, bool):
raise ValueError("Timeout cannot be a boolean value. It must "
"be an int, float or None.")
try:
float(value)
except (TypeError, ValueError):
raise ValueError("Timeout value %s was %s, but it must be an "
"int, float or None." % (name, value))
try:
if value <= 0:
raise ValueError("Attempted to set %s timeout to %s, but the "
"timeout cannot be set to a value less "
"than or equal to 0." % (name, value))
except TypeError: # Python 3
raise ValueError("Timeout value %s was %s, but it must be an "
"int, float or None." % (name, value))
return value
|
python
|
def _validate_timeout(cls, value, name):
""" Check that a timeout attribute is valid.
:param value: The timeout value to validate
:param name: The name of the timeout attribute to validate. This is
used to specify in error messages.
:return: The validated and casted version of the given value.
:raises ValueError: If it is a numeric value less than or equal to
zero, or the type is not an integer, float, or None.
"""
if value is _Default:
return cls.DEFAULT_TIMEOUT
if value is None or value is cls.DEFAULT_TIMEOUT:
return value
if isinstance(value, bool):
raise ValueError("Timeout cannot be a boolean value. It must "
"be an int, float or None.")
try:
float(value)
except (TypeError, ValueError):
raise ValueError("Timeout value %s was %s, but it must be an "
"int, float or None." % (name, value))
try:
if value <= 0:
raise ValueError("Attempted to set %s timeout to %s, but the "
"timeout cannot be set to a value less "
"than or equal to 0." % (name, value))
except TypeError: # Python 3
raise ValueError("Timeout value %s was %s, but it must be an "
"int, float or None." % (name, value))
return value
|
[
"def",
"_validate_timeout",
"(",
"cls",
",",
"value",
",",
"name",
")",
":",
"if",
"value",
"is",
"_Default",
":",
"return",
"cls",
".",
"DEFAULT_TIMEOUT",
"if",
"value",
"is",
"None",
"or",
"value",
"is",
"cls",
".",
"DEFAULT_TIMEOUT",
":",
"return",
"value",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"raise",
"ValueError",
"(",
"\"Timeout cannot be a boolean value. It must \"",
"\"be an int, float or None.\"",
")",
"try",
":",
"float",
"(",
"value",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"ValueError",
"(",
"\"Timeout value %s was %s, but it must be an \"",
"\"int, float or None.\"",
"%",
"(",
"name",
",",
"value",
")",
")",
"try",
":",
"if",
"value",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Attempted to set %s timeout to %s, but the \"",
"\"timeout cannot be set to a value less \"",
"\"than or equal to 0.\"",
"%",
"(",
"name",
",",
"value",
")",
")",
"except",
"TypeError",
":",
"# Python 3",
"raise",
"ValueError",
"(",
"\"Timeout value %s was %s, but it must be an \"",
"\"int, float or None.\"",
"%",
"(",
"name",
",",
"value",
")",
")",
"return",
"value"
] |
Check that a timeout attribute is valid.
:param value: The timeout value to validate
:param name: The name of the timeout attribute to validate. This is
used to specify in error messages.
:return: The validated and casted version of the given value.
:raises ValueError: If it is a numeric value less than or equal to
zero, or the type is not an integer, float, or None.
|
[
"Check",
"that",
"a",
"timeout",
"attribute",
"is",
"valid",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/timeout.py#L104-L138
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/util/timeout.py
|
Timeout.clone
|
def clone(self):
""" Create a copy of the timeout object
Timeout properties are stored per-pool but each request needs a fresh
Timeout object to ensure each one has its own start/stop configured.
:return: a copy of the timeout object
:rtype: :class:`Timeout`
"""
# We can't use copy.deepcopy because that will also create a new object
# for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to
# detect the user default.
return Timeout(connect=self._connect, read=self._read,
total=self.total)
|
python
|
def clone(self):
""" Create a copy of the timeout object
Timeout properties are stored per-pool but each request needs a fresh
Timeout object to ensure each one has its own start/stop configured.
:return: a copy of the timeout object
:rtype: :class:`Timeout`
"""
# We can't use copy.deepcopy because that will also create a new object
# for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to
# detect the user default.
return Timeout(connect=self._connect, read=self._read,
total=self.total)
|
[
"def",
"clone",
"(",
"self",
")",
":",
"# We can't use copy.deepcopy because that will also create a new object",
"# for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to",
"# detect the user default.",
"return",
"Timeout",
"(",
"connect",
"=",
"self",
".",
"_connect",
",",
"read",
"=",
"self",
".",
"_read",
",",
"total",
"=",
"self",
".",
"total",
")"
] |
Create a copy of the timeout object
Timeout properties are stored per-pool but each request needs a fresh
Timeout object to ensure each one has its own start/stop configured.
:return: a copy of the timeout object
:rtype: :class:`Timeout`
|
[
"Create",
"a",
"copy",
"of",
"the",
"timeout",
"object"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/timeout.py#L156-L169
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/util/timeout.py
|
Timeout.start_connect
|
def start_connect(self):
""" Start the timeout clock, used during a connect() attempt
:raises urllib3.exceptions.TimeoutStateError: if you attempt
to start a timer that has been started already.
"""
if self._start_connect is not None:
raise TimeoutStateError("Timeout timer has already been started.")
self._start_connect = current_time()
return self._start_connect
|
python
|
def start_connect(self):
""" Start the timeout clock, used during a connect() attempt
:raises urllib3.exceptions.TimeoutStateError: if you attempt
to start a timer that has been started already.
"""
if self._start_connect is not None:
raise TimeoutStateError("Timeout timer has already been started.")
self._start_connect = current_time()
return self._start_connect
|
[
"def",
"start_connect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_start_connect",
"is",
"not",
"None",
":",
"raise",
"TimeoutStateError",
"(",
"\"Timeout timer has already been started.\"",
")",
"self",
".",
"_start_connect",
"=",
"current_time",
"(",
")",
"return",
"self",
".",
"_start_connect"
] |
Start the timeout clock, used during a connect() attempt
:raises urllib3.exceptions.TimeoutStateError: if you attempt
to start a timer that has been started already.
|
[
"Start",
"the",
"timeout",
"clock",
"used",
"during",
"a",
"connect",
"()",
"attempt"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/timeout.py#L171-L180
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/util/timeout.py
|
Timeout.connect_timeout
|
def connect_timeout(self):
""" Get the value to use when setting a connection timeout.
This will be a positive float or integer, the value None
(never timeout), or the default system timeout.
:return: Connect timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
"""
if self.total is None:
return self._connect
if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:
return self.total
return min(self._connect, self.total)
|
python
|
def connect_timeout(self):
""" Get the value to use when setting a connection timeout.
This will be a positive float or integer, the value None
(never timeout), or the default system timeout.
:return: Connect timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
"""
if self.total is None:
return self._connect
if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:
return self.total
return min(self._connect, self.total)
|
[
"def",
"connect_timeout",
"(",
"self",
")",
":",
"if",
"self",
".",
"total",
"is",
"None",
":",
"return",
"self",
".",
"_connect",
"if",
"self",
".",
"_connect",
"is",
"None",
"or",
"self",
".",
"_connect",
"is",
"self",
".",
"DEFAULT_TIMEOUT",
":",
"return",
"self",
".",
"total",
"return",
"min",
"(",
"self",
".",
"_connect",
",",
"self",
".",
"total",
")"
] |
Get the value to use when setting a connection timeout.
This will be a positive float or integer, the value None
(never timeout), or the default system timeout.
:return: Connect timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
|
[
"Get",
"the",
"value",
"to",
"use",
"when",
"setting",
"a",
"connection",
"timeout",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/timeout.py#L196-L211
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/util/timeout.py
|
Timeout.read_timeout
|
def read_timeout(self):
""" Get the value for the read timeout.
This assumes some time has elapsed in the connection timeout and
computes the read timeout appropriately.
If self.total is set, the read timeout is dependent on the amount of
time taken by the connect timeout. If the connection time has not been
established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be
raised.
:return: Value to use for the read timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
:raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`
has not yet been called on this object.
"""
if (self.total is not None and
self.total is not self.DEFAULT_TIMEOUT and
self._read is not None and
self._read is not self.DEFAULT_TIMEOUT):
# In case the connect timeout has not yet been established.
if self._start_connect is None:
return self._read
return max(0, min(self.total - self.get_connect_duration(),
self._read))
elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT:
return max(0, self.total - self.get_connect_duration())
else:
return self._read
|
python
|
def read_timeout(self):
""" Get the value for the read timeout.
This assumes some time has elapsed in the connection timeout and
computes the read timeout appropriately.
If self.total is set, the read timeout is dependent on the amount of
time taken by the connect timeout. If the connection time has not been
established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be
raised.
:return: Value to use for the read timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
:raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`
has not yet been called on this object.
"""
if (self.total is not None and
self.total is not self.DEFAULT_TIMEOUT and
self._read is not None and
self._read is not self.DEFAULT_TIMEOUT):
# In case the connect timeout has not yet been established.
if self._start_connect is None:
return self._read
return max(0, min(self.total - self.get_connect_duration(),
self._read))
elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT:
return max(0, self.total - self.get_connect_duration())
else:
return self._read
|
[
"def",
"read_timeout",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"total",
"is",
"not",
"None",
"and",
"self",
".",
"total",
"is",
"not",
"self",
".",
"DEFAULT_TIMEOUT",
"and",
"self",
".",
"_read",
"is",
"not",
"None",
"and",
"self",
".",
"_read",
"is",
"not",
"self",
".",
"DEFAULT_TIMEOUT",
")",
":",
"# In case the connect timeout has not yet been established.",
"if",
"self",
".",
"_start_connect",
"is",
"None",
":",
"return",
"self",
".",
"_read",
"return",
"max",
"(",
"0",
",",
"min",
"(",
"self",
".",
"total",
"-",
"self",
".",
"get_connect_duration",
"(",
")",
",",
"self",
".",
"_read",
")",
")",
"elif",
"self",
".",
"total",
"is",
"not",
"None",
"and",
"self",
".",
"total",
"is",
"not",
"self",
".",
"DEFAULT_TIMEOUT",
":",
"return",
"max",
"(",
"0",
",",
"self",
".",
"total",
"-",
"self",
".",
"get_connect_duration",
"(",
")",
")",
"else",
":",
"return",
"self",
".",
"_read"
] |
Get the value for the read timeout.
This assumes some time has elapsed in the connection timeout and
computes the read timeout appropriately.
If self.total is set, the read timeout is dependent on the amount of
time taken by the connect timeout. If the connection time has not been
established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be
raised.
:return: Value to use for the read timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
:raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`
has not yet been called on this object.
|
[
"Get",
"the",
"value",
"for",
"the",
"read",
"timeout",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/timeout.py#L214-L242
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/contrib/socks.py
|
SOCKSConnection._new_conn
|
def _new_conn(self):
"""
Establish a new connection via the SOCKS proxy.
"""
extra_kw = {}
if self.source_address:
extra_kw['source_address'] = self.source_address
if self.socket_options:
extra_kw['socket_options'] = self.socket_options
try:
conn = socks.create_connection(
(self.host, self.port),
proxy_type=self._socks_options['socks_version'],
proxy_addr=self._socks_options['proxy_host'],
proxy_port=self._socks_options['proxy_port'],
proxy_username=self._socks_options['username'],
proxy_password=self._socks_options['password'],
proxy_rdns=self._socks_options['rdns'],
timeout=self.timeout,
**extra_kw
)
except SocketTimeout as e:
raise ConnectTimeoutError(
self, "Connection to %s timed out. (connect timeout=%s)" %
(self.host, self.timeout))
except socks.ProxyError as e:
# This is fragile as hell, but it seems to be the only way to raise
# useful errors here.
if e.socket_err:
error = e.socket_err
if isinstance(error, SocketTimeout):
raise ConnectTimeoutError(
self,
"Connection to %s timed out. (connect timeout=%s)" %
(self.host, self.timeout)
)
else:
raise NewConnectionError(
self,
"Failed to establish a new connection: %s" % error
)
else:
raise NewConnectionError(
self,
"Failed to establish a new connection: %s" % e
)
except SocketError as e: # Defensive: PySocks should catch all these.
raise NewConnectionError(
self, "Failed to establish a new connection: %s" % e)
return conn
|
python
|
def _new_conn(self):
"""
Establish a new connection via the SOCKS proxy.
"""
extra_kw = {}
if self.source_address:
extra_kw['source_address'] = self.source_address
if self.socket_options:
extra_kw['socket_options'] = self.socket_options
try:
conn = socks.create_connection(
(self.host, self.port),
proxy_type=self._socks_options['socks_version'],
proxy_addr=self._socks_options['proxy_host'],
proxy_port=self._socks_options['proxy_port'],
proxy_username=self._socks_options['username'],
proxy_password=self._socks_options['password'],
proxy_rdns=self._socks_options['rdns'],
timeout=self.timeout,
**extra_kw
)
except SocketTimeout as e:
raise ConnectTimeoutError(
self, "Connection to %s timed out. (connect timeout=%s)" %
(self.host, self.timeout))
except socks.ProxyError as e:
# This is fragile as hell, but it seems to be the only way to raise
# useful errors here.
if e.socket_err:
error = e.socket_err
if isinstance(error, SocketTimeout):
raise ConnectTimeoutError(
self,
"Connection to %s timed out. (connect timeout=%s)" %
(self.host, self.timeout)
)
else:
raise NewConnectionError(
self,
"Failed to establish a new connection: %s" % error
)
else:
raise NewConnectionError(
self,
"Failed to establish a new connection: %s" % e
)
except SocketError as e: # Defensive: PySocks should catch all these.
raise NewConnectionError(
self, "Failed to establish a new connection: %s" % e)
return conn
|
[
"def",
"_new_conn",
"(",
"self",
")",
":",
"extra_kw",
"=",
"{",
"}",
"if",
"self",
".",
"source_address",
":",
"extra_kw",
"[",
"'source_address'",
"]",
"=",
"self",
".",
"source_address",
"if",
"self",
".",
"socket_options",
":",
"extra_kw",
"[",
"'socket_options'",
"]",
"=",
"self",
".",
"socket_options",
"try",
":",
"conn",
"=",
"socks",
".",
"create_connection",
"(",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
",",
"proxy_type",
"=",
"self",
".",
"_socks_options",
"[",
"'socks_version'",
"]",
",",
"proxy_addr",
"=",
"self",
".",
"_socks_options",
"[",
"'proxy_host'",
"]",
",",
"proxy_port",
"=",
"self",
".",
"_socks_options",
"[",
"'proxy_port'",
"]",
",",
"proxy_username",
"=",
"self",
".",
"_socks_options",
"[",
"'username'",
"]",
",",
"proxy_password",
"=",
"self",
".",
"_socks_options",
"[",
"'password'",
"]",
",",
"proxy_rdns",
"=",
"self",
".",
"_socks_options",
"[",
"'rdns'",
"]",
",",
"timeout",
"=",
"self",
".",
"timeout",
",",
"*",
"*",
"extra_kw",
")",
"except",
"SocketTimeout",
"as",
"e",
":",
"raise",
"ConnectTimeoutError",
"(",
"self",
",",
"\"Connection to %s timed out. (connect timeout=%s)\"",
"%",
"(",
"self",
".",
"host",
",",
"self",
".",
"timeout",
")",
")",
"except",
"socks",
".",
"ProxyError",
"as",
"e",
":",
"# This is fragile as hell, but it seems to be the only way to raise",
"# useful errors here.",
"if",
"e",
".",
"socket_err",
":",
"error",
"=",
"e",
".",
"socket_err",
"if",
"isinstance",
"(",
"error",
",",
"SocketTimeout",
")",
":",
"raise",
"ConnectTimeoutError",
"(",
"self",
",",
"\"Connection to %s timed out. (connect timeout=%s)\"",
"%",
"(",
"self",
".",
"host",
",",
"self",
".",
"timeout",
")",
")",
"else",
":",
"raise",
"NewConnectionError",
"(",
"self",
",",
"\"Failed to establish a new connection: %s\"",
"%",
"error",
")",
"else",
":",
"raise",
"NewConnectionError",
"(",
"self",
",",
"\"Failed to establish a new connection: %s\"",
"%",
"e",
")",
"except",
"SocketError",
"as",
"e",
":",
"# Defensive: PySocks should catch all these.",
"raise",
"NewConnectionError",
"(",
"self",
",",
"\"Failed to establish a new connection: %s\"",
"%",
"e",
")",
"return",
"conn"
] |
Establish a new connection via the SOCKS proxy.
|
[
"Establish",
"a",
"new",
"connection",
"via",
"the",
"SOCKS",
"proxy",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/socks.py#L67-L122
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/operations/freeze.py
|
get_requirement_info
|
def get_requirement_info(dist):
# type: (Distribution) -> RequirementInfo
"""
Compute and return values (req, editable, comments) for use in
FrozenRequirement.from_dist().
"""
if not dist_is_editable(dist):
return (None, False, [])
location = os.path.normcase(os.path.abspath(dist.location))
from pipenv.patched.notpip._internal.vcs import vcs, RemoteNotFoundError
vc_type = vcs.get_backend_type(location)
if not vc_type:
req = dist.as_requirement()
logger.debug(
'No VCS found for editable requirement {!r} in: {!r}', req,
location,
)
comments = [
'# Editable install with no version control ({})'.format(req)
]
return (location, True, comments)
try:
req = vc_type.get_src_requirement(location, dist.project_name)
except RemoteNotFoundError:
req = dist.as_requirement()
comments = [
'# Editable {} install with no remote ({})'.format(
vc_type.__name__, req,
)
]
return (location, True, comments)
except BadCommand:
logger.warning(
'cannot determine version of editable source in %s '
'(%s command not found in path)',
location,
vc_type.name,
)
return (None, True, [])
except InstallationError as exc:
logger.warning(
"Error when trying to get requirement for VCS system %s, "
"falling back to uneditable format", exc
)
else:
if req is not None:
return (req, True, [])
logger.warning(
'Could not determine repository location of %s', location
)
comments = ['## !! Could not determine repository location']
return (None, False, comments)
|
python
|
def get_requirement_info(dist):
# type: (Distribution) -> RequirementInfo
"""
Compute and return values (req, editable, comments) for use in
FrozenRequirement.from_dist().
"""
if not dist_is_editable(dist):
return (None, False, [])
location = os.path.normcase(os.path.abspath(dist.location))
from pipenv.patched.notpip._internal.vcs import vcs, RemoteNotFoundError
vc_type = vcs.get_backend_type(location)
if not vc_type:
req = dist.as_requirement()
logger.debug(
'No VCS found for editable requirement {!r} in: {!r}', req,
location,
)
comments = [
'# Editable install with no version control ({})'.format(req)
]
return (location, True, comments)
try:
req = vc_type.get_src_requirement(location, dist.project_name)
except RemoteNotFoundError:
req = dist.as_requirement()
comments = [
'# Editable {} install with no remote ({})'.format(
vc_type.__name__, req,
)
]
return (location, True, comments)
except BadCommand:
logger.warning(
'cannot determine version of editable source in %s '
'(%s command not found in path)',
location,
vc_type.name,
)
return (None, True, [])
except InstallationError as exc:
logger.warning(
"Error when trying to get requirement for VCS system %s, "
"falling back to uneditable format", exc
)
else:
if req is not None:
return (req, True, [])
logger.warning(
'Could not determine repository location of %s', location
)
comments = ['## !! Could not determine repository location']
return (None, False, comments)
|
[
"def",
"get_requirement_info",
"(",
"dist",
")",
":",
"# type: (Distribution) -> RequirementInfo",
"if",
"not",
"dist_is_editable",
"(",
"dist",
")",
":",
"return",
"(",
"None",
",",
"False",
",",
"[",
"]",
")",
"location",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"dist",
".",
"location",
")",
")",
"from",
"pipenv",
".",
"patched",
".",
"notpip",
".",
"_internal",
".",
"vcs",
"import",
"vcs",
",",
"RemoteNotFoundError",
"vc_type",
"=",
"vcs",
".",
"get_backend_type",
"(",
"location",
")",
"if",
"not",
"vc_type",
":",
"req",
"=",
"dist",
".",
"as_requirement",
"(",
")",
"logger",
".",
"debug",
"(",
"'No VCS found for editable requirement {!r} in: {!r}'",
",",
"req",
",",
"location",
",",
")",
"comments",
"=",
"[",
"'# Editable install with no version control ({})'",
".",
"format",
"(",
"req",
")",
"]",
"return",
"(",
"location",
",",
"True",
",",
"comments",
")",
"try",
":",
"req",
"=",
"vc_type",
".",
"get_src_requirement",
"(",
"location",
",",
"dist",
".",
"project_name",
")",
"except",
"RemoteNotFoundError",
":",
"req",
"=",
"dist",
".",
"as_requirement",
"(",
")",
"comments",
"=",
"[",
"'# Editable {} install with no remote ({})'",
".",
"format",
"(",
"vc_type",
".",
"__name__",
",",
"req",
",",
")",
"]",
"return",
"(",
"location",
",",
"True",
",",
"comments",
")",
"except",
"BadCommand",
":",
"logger",
".",
"warning",
"(",
"'cannot determine version of editable source in %s '",
"'(%s command not found in path)'",
",",
"location",
",",
"vc_type",
".",
"name",
",",
")",
"return",
"(",
"None",
",",
"True",
",",
"[",
"]",
")",
"except",
"InstallationError",
"as",
"exc",
":",
"logger",
".",
"warning",
"(",
"\"Error when trying to get requirement for VCS system %s, \"",
"\"falling back to uneditable format\"",
",",
"exc",
")",
"else",
":",
"if",
"req",
"is",
"not",
"None",
":",
"return",
"(",
"req",
",",
"True",
",",
"[",
"]",
")",
"logger",
".",
"warning",
"(",
"'Could not determine repository location of %s'",
",",
"location",
")",
"comments",
"=",
"[",
"'## !! Could not determine repository location'",
"]",
"return",
"(",
"None",
",",
"False",
",",
"comments",
")"
] |
Compute and return values (req, editable, comments) for use in
FrozenRequirement.from_dist().
|
[
"Compute",
"and",
"return",
"values",
"(",
"req",
"editable",
"comments",
")",
"for",
"use",
"in",
"FrozenRequirement",
".",
"from_dist",
"()",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/operations/freeze.py#L164-L223
|
train
|
pypa/pipenv
|
pipenv/vendor/shellingham/posix/proc.py
|
detect_proc
|
def detect_proc():
"""Detect /proc filesystem style.
This checks the /proc/{pid} directory for possible formats. Returns one of
the followings as str:
* `stat`: Linux-style, i.e. ``/proc/{pid}/stat``.
* `status`: BSD-style, i.e. ``/proc/{pid}/status``.
"""
pid = os.getpid()
for name in ('stat', 'status'):
if os.path.exists(os.path.join('/proc', str(pid), name)):
return name
raise ProcFormatError('unsupported proc format')
|
python
|
def detect_proc():
"""Detect /proc filesystem style.
This checks the /proc/{pid} directory for possible formats. Returns one of
the followings as str:
* `stat`: Linux-style, i.e. ``/proc/{pid}/stat``.
* `status`: BSD-style, i.e. ``/proc/{pid}/status``.
"""
pid = os.getpid()
for name in ('stat', 'status'):
if os.path.exists(os.path.join('/proc', str(pid), name)):
return name
raise ProcFormatError('unsupported proc format')
|
[
"def",
"detect_proc",
"(",
")",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"for",
"name",
"in",
"(",
"'stat'",
",",
"'status'",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'/proc'",
",",
"str",
"(",
"pid",
")",
",",
"name",
")",
")",
":",
"return",
"name",
"raise",
"ProcFormatError",
"(",
"'unsupported proc format'",
")"
] |
Detect /proc filesystem style.
This checks the /proc/{pid} directory for possible formats. Returns one of
the followings as str:
* `stat`: Linux-style, i.e. ``/proc/{pid}/stat``.
* `status`: BSD-style, i.e. ``/proc/{pid}/status``.
|
[
"Detect",
"/",
"proc",
"filesystem",
"style",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/shellingham/posix/proc.py#L15-L28
|
train
|
pypa/pipenv
|
pipenv/vendor/shellingham/posix/proc.py
|
get_process_mapping
|
def get_process_mapping():
"""Try to look up the process tree via the /proc interface.
"""
stat_name = detect_proc()
self_tty = _get_stat(os.getpid(), stat_name)[0]
processes = {}
for pid in os.listdir('/proc'):
if not pid.isdigit():
continue
try:
tty, ppid = _get_stat(pid, stat_name)
if tty != self_tty:
continue
args = _get_cmdline(pid)
processes[pid] = Process(args=args, pid=pid, ppid=ppid)
except IOError:
# Process has disappeared - just ignore it.
continue
return processes
|
python
|
def get_process_mapping():
"""Try to look up the process tree via the /proc interface.
"""
stat_name = detect_proc()
self_tty = _get_stat(os.getpid(), stat_name)[0]
processes = {}
for pid in os.listdir('/proc'):
if not pid.isdigit():
continue
try:
tty, ppid = _get_stat(pid, stat_name)
if tty != self_tty:
continue
args = _get_cmdline(pid)
processes[pid] = Process(args=args, pid=pid, ppid=ppid)
except IOError:
# Process has disappeared - just ignore it.
continue
return processes
|
[
"def",
"get_process_mapping",
"(",
")",
":",
"stat_name",
"=",
"detect_proc",
"(",
")",
"self_tty",
"=",
"_get_stat",
"(",
"os",
".",
"getpid",
"(",
")",
",",
"stat_name",
")",
"[",
"0",
"]",
"processes",
"=",
"{",
"}",
"for",
"pid",
"in",
"os",
".",
"listdir",
"(",
"'/proc'",
")",
":",
"if",
"not",
"pid",
".",
"isdigit",
"(",
")",
":",
"continue",
"try",
":",
"tty",
",",
"ppid",
"=",
"_get_stat",
"(",
"pid",
",",
"stat_name",
")",
"if",
"tty",
"!=",
"self_tty",
":",
"continue",
"args",
"=",
"_get_cmdline",
"(",
"pid",
")",
"processes",
"[",
"pid",
"]",
"=",
"Process",
"(",
"args",
"=",
"args",
",",
"pid",
"=",
"pid",
",",
"ppid",
"=",
"ppid",
")",
"except",
"IOError",
":",
"# Process has disappeared - just ignore it.",
"continue",
"return",
"processes"
] |
Try to look up the process tree via the /proc interface.
|
[
"Try",
"to",
"look",
"up",
"the",
"process",
"tree",
"via",
"the",
"/",
"proc",
"interface",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/shellingham/posix/proc.py#L54-L72
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/backports/tempfile.py
|
NamedTemporaryFile
|
def NamedTemporaryFile(
mode="w+b",
buffering=-1,
encoding=None,
newline=None,
suffix=None,
prefix=None,
dir=None,
delete=True,
wrapper_class_override=None,
):
"""Create and return a temporary file.
Arguments:
'prefix', 'suffix', 'dir' -- as for mkstemp.
'mode' -- the mode argument to io.open (default "w+b").
'buffering' -- the buffer size argument to io.open (default -1).
'encoding' -- the encoding argument to io.open (default None)
'newline' -- the newline argument to io.open (default None)
'delete' -- whether the file is deleted on close (default True).
The file is created as mkstemp() would do it.
Returns an object with a file-like interface; the name of the file
is accessible as its 'name' attribute. The file will be automatically
deleted when it is closed unless the 'delete' argument is set to False.
"""
prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
flags = _bin_openflags
# Setting O_TEMPORARY in the flags causes the OS to delete
# the file when it is closed. This is only supported by Windows.
if not wrapper_class_override:
wrapper_class_override = _TemporaryFileWrapper
if os.name == "nt" and delete:
flags |= os.O_TEMPORARY
if sys.version_info < (3, 5):
(fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
else:
(fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
try:
file = io.open(fd, mode, buffering=buffering, newline=newline, encoding=encoding)
if wrapper_class_override is not None:
return type(str("_TempFileWrapper"), (wrapper_class_override, object), {})(
file, name, delete
)
else:
return _TemporaryFileWrapper(file, name, delete)
except BaseException:
os.unlink(name)
os.close(fd)
raise
|
python
|
def NamedTemporaryFile(
mode="w+b",
buffering=-1,
encoding=None,
newline=None,
suffix=None,
prefix=None,
dir=None,
delete=True,
wrapper_class_override=None,
):
"""Create and return a temporary file.
Arguments:
'prefix', 'suffix', 'dir' -- as for mkstemp.
'mode' -- the mode argument to io.open (default "w+b").
'buffering' -- the buffer size argument to io.open (default -1).
'encoding' -- the encoding argument to io.open (default None)
'newline' -- the newline argument to io.open (default None)
'delete' -- whether the file is deleted on close (default True).
The file is created as mkstemp() would do it.
Returns an object with a file-like interface; the name of the file
is accessible as its 'name' attribute. The file will be automatically
deleted when it is closed unless the 'delete' argument is set to False.
"""
prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
flags = _bin_openflags
# Setting O_TEMPORARY in the flags causes the OS to delete
# the file when it is closed. This is only supported by Windows.
if not wrapper_class_override:
wrapper_class_override = _TemporaryFileWrapper
if os.name == "nt" and delete:
flags |= os.O_TEMPORARY
if sys.version_info < (3, 5):
(fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
else:
(fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
try:
file = io.open(fd, mode, buffering=buffering, newline=newline, encoding=encoding)
if wrapper_class_override is not None:
return type(str("_TempFileWrapper"), (wrapper_class_override, object), {})(
file, name, delete
)
else:
return _TemporaryFileWrapper(file, name, delete)
except BaseException:
os.unlink(name)
os.close(fd)
raise
|
[
"def",
"NamedTemporaryFile",
"(",
"mode",
"=",
"\"w+b\"",
",",
"buffering",
"=",
"-",
"1",
",",
"encoding",
"=",
"None",
",",
"newline",
"=",
"None",
",",
"suffix",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"dir",
"=",
"None",
",",
"delete",
"=",
"True",
",",
"wrapper_class_override",
"=",
"None",
",",
")",
":",
"prefix",
",",
"suffix",
",",
"dir",
",",
"output_type",
"=",
"_sanitize_params",
"(",
"prefix",
",",
"suffix",
",",
"dir",
")",
"flags",
"=",
"_bin_openflags",
"# Setting O_TEMPORARY in the flags causes the OS to delete",
"# the file when it is closed. This is only supported by Windows.",
"if",
"not",
"wrapper_class_override",
":",
"wrapper_class_override",
"=",
"_TemporaryFileWrapper",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
"and",
"delete",
":",
"flags",
"|=",
"os",
".",
"O_TEMPORARY",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"5",
")",
":",
"(",
"fd",
",",
"name",
")",
"=",
"_mkstemp_inner",
"(",
"dir",
",",
"prefix",
",",
"suffix",
",",
"flags",
")",
"else",
":",
"(",
"fd",
",",
"name",
")",
"=",
"_mkstemp_inner",
"(",
"dir",
",",
"prefix",
",",
"suffix",
",",
"flags",
",",
"output_type",
")",
"try",
":",
"file",
"=",
"io",
".",
"open",
"(",
"fd",
",",
"mode",
",",
"buffering",
"=",
"buffering",
",",
"newline",
"=",
"newline",
",",
"encoding",
"=",
"encoding",
")",
"if",
"wrapper_class_override",
"is",
"not",
"None",
":",
"return",
"type",
"(",
"str",
"(",
"\"_TempFileWrapper\"",
")",
",",
"(",
"wrapper_class_override",
",",
"object",
")",
",",
"{",
"}",
")",
"(",
"file",
",",
"name",
",",
"delete",
")",
"else",
":",
"return",
"_TemporaryFileWrapper",
"(",
"file",
",",
"name",
",",
"delete",
")",
"except",
"BaseException",
":",
"os",
".",
"unlink",
"(",
"name",
")",
"os",
".",
"close",
"(",
"fd",
")",
"raise"
] |
Create and return a temporary file.
Arguments:
'prefix', 'suffix', 'dir' -- as for mkstemp.
'mode' -- the mode argument to io.open (default "w+b").
'buffering' -- the buffer size argument to io.open (default -1).
'encoding' -- the encoding argument to io.open (default None)
'newline' -- the newline argument to io.open (default None)
'delete' -- whether the file is deleted on close (default True).
The file is created as mkstemp() would do it.
Returns an object with a file-like interface; the name of the file
is accessible as its 'name' attribute. The file will be automatically
deleted when it is closed unless the 'delete' argument is set to False.
|
[
"Create",
"and",
"return",
"a",
"temporary",
"file",
".",
"Arguments",
":",
"prefix",
"suffix",
"dir",
"--",
"as",
"for",
"mkstemp",
".",
"mode",
"--",
"the",
"mode",
"argument",
"to",
"io",
".",
"open",
"(",
"default",
"w",
"+",
"b",
")",
".",
"buffering",
"--",
"the",
"buffer",
"size",
"argument",
"to",
"io",
".",
"open",
"(",
"default",
"-",
"1",
")",
".",
"encoding",
"--",
"the",
"encoding",
"argument",
"to",
"io",
".",
"open",
"(",
"default",
"None",
")",
"newline",
"--",
"the",
"newline",
"argument",
"to",
"io",
".",
"open",
"(",
"default",
"None",
")",
"delete",
"--",
"whether",
"the",
"file",
"is",
"deleted",
"on",
"close",
"(",
"default",
"True",
")",
".",
"The",
"file",
"is",
"created",
"as",
"mkstemp",
"()",
"would",
"do",
"it",
".",
"Returns",
"an",
"object",
"with",
"a",
"file",
"-",
"like",
"interface",
";",
"the",
"name",
"of",
"the",
"file",
"is",
"accessible",
"as",
"its",
"name",
"attribute",
".",
"The",
"file",
"will",
"be",
"automatically",
"deleted",
"when",
"it",
"is",
"closed",
"unless",
"the",
"delete",
"argument",
"is",
"set",
"to",
"False",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/backports/tempfile.py#L168-L216
|
train
|
pypa/pipenv
|
pipenv/vendor/click/core.py
|
fast_exit
|
def fast_exit(code):
"""Exit without garbage collection, this speeds up exit by about 10ms for
things like bash completion.
"""
sys.stdout.flush()
sys.stderr.flush()
os._exit(code)
|
python
|
def fast_exit(code):
"""Exit without garbage collection, this speeds up exit by about 10ms for
things like bash completion.
"""
sys.stdout.flush()
sys.stderr.flush()
os._exit(code)
|
[
"def",
"fast_exit",
"(",
"code",
")",
":",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")",
"os",
".",
"_exit",
"(",
"code",
")"
] |
Exit without garbage collection, this speeds up exit by about 10ms for
things like bash completion.
|
[
"Exit",
"without",
"garbage",
"collection",
"this",
"speeds",
"up",
"exit",
"by",
"about",
"10ms",
"for",
"things",
"like",
"bash",
"completion",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L39-L45
|
train
|
pypa/pipenv
|
pipenv/vendor/click/core.py
|
_bashcomplete
|
def _bashcomplete(cmd, prog_name, complete_var=None):
"""Internal handler for the bash completion support."""
if complete_var is None:
complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper()
complete_instr = os.environ.get(complete_var)
if not complete_instr:
return
from ._bashcomplete import bashcomplete
if bashcomplete(cmd, prog_name, complete_var, complete_instr):
fast_exit(1)
|
python
|
def _bashcomplete(cmd, prog_name, complete_var=None):
"""Internal handler for the bash completion support."""
if complete_var is None:
complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper()
complete_instr = os.environ.get(complete_var)
if not complete_instr:
return
from ._bashcomplete import bashcomplete
if bashcomplete(cmd, prog_name, complete_var, complete_instr):
fast_exit(1)
|
[
"def",
"_bashcomplete",
"(",
"cmd",
",",
"prog_name",
",",
"complete_var",
"=",
"None",
")",
":",
"if",
"complete_var",
"is",
"None",
":",
"complete_var",
"=",
"'_%s_COMPLETE'",
"%",
"(",
"prog_name",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
")",
".",
"upper",
"(",
")",
"complete_instr",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"complete_var",
")",
"if",
"not",
"complete_instr",
":",
"return",
"from",
".",
"_bashcomplete",
"import",
"bashcomplete",
"if",
"bashcomplete",
"(",
"cmd",
",",
"prog_name",
",",
"complete_var",
",",
"complete_instr",
")",
":",
"fast_exit",
"(",
"1",
")"
] |
Internal handler for the bash completion support.
|
[
"Internal",
"handler",
"for",
"the",
"bash",
"completion",
"support",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L48-L58
|
train
|
pypa/pipenv
|
pipenv/vendor/click/core.py
|
augment_usage_errors
|
def augment_usage_errors(ctx, param=None):
"""Context manager that attaches extra information to exceptions that
fly.
"""
try:
yield
except BadParameter as e:
if e.ctx is None:
e.ctx = ctx
if param is not None and e.param is None:
e.param = param
raise
except UsageError as e:
if e.ctx is None:
e.ctx = ctx
raise
|
python
|
def augment_usage_errors(ctx, param=None):
"""Context manager that attaches extra information to exceptions that
fly.
"""
try:
yield
except BadParameter as e:
if e.ctx is None:
e.ctx = ctx
if param is not None and e.param is None:
e.param = param
raise
except UsageError as e:
if e.ctx is None:
e.ctx = ctx
raise
|
[
"def",
"augment_usage_errors",
"(",
"ctx",
",",
"param",
"=",
"None",
")",
":",
"try",
":",
"yield",
"except",
"BadParameter",
"as",
"e",
":",
"if",
"e",
".",
"ctx",
"is",
"None",
":",
"e",
".",
"ctx",
"=",
"ctx",
"if",
"param",
"is",
"not",
"None",
"and",
"e",
".",
"param",
"is",
"None",
":",
"e",
".",
"param",
"=",
"param",
"raise",
"except",
"UsageError",
"as",
"e",
":",
"if",
"e",
".",
"ctx",
"is",
"None",
":",
"e",
".",
"ctx",
"=",
"ctx",
"raise"
] |
Context manager that attaches extra information to exceptions that
fly.
|
[
"Context",
"manager",
"that",
"attaches",
"extra",
"information",
"to",
"exceptions",
"that",
"fly",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L100-L115
|
train
|
pypa/pipenv
|
pipenv/vendor/click/core.py
|
iter_params_for_processing
|
def iter_params_for_processing(invocation_order, declaration_order):
"""Given a sequence of parameters in the order as should be considered
for processing and an iterable of parameters that exist, this returns
a list in the correct order as they should be processed.
"""
def sort_key(item):
try:
idx = invocation_order.index(item)
except ValueError:
idx = float('inf')
return (not item.is_eager, idx)
return sorted(declaration_order, key=sort_key)
|
python
|
def iter_params_for_processing(invocation_order, declaration_order):
"""Given a sequence of parameters in the order as should be considered
for processing and an iterable of parameters that exist, this returns
a list in the correct order as they should be processed.
"""
def sort_key(item):
try:
idx = invocation_order.index(item)
except ValueError:
idx = float('inf')
return (not item.is_eager, idx)
return sorted(declaration_order, key=sort_key)
|
[
"def",
"iter_params_for_processing",
"(",
"invocation_order",
",",
"declaration_order",
")",
":",
"def",
"sort_key",
"(",
"item",
")",
":",
"try",
":",
"idx",
"=",
"invocation_order",
".",
"index",
"(",
"item",
")",
"except",
"ValueError",
":",
"idx",
"=",
"float",
"(",
"'inf'",
")",
"return",
"(",
"not",
"item",
".",
"is_eager",
",",
"idx",
")",
"return",
"sorted",
"(",
"declaration_order",
",",
"key",
"=",
"sort_key",
")"
] |
Given a sequence of parameters in the order as should be considered
for processing and an iterable of parameters that exist, this returns
a list in the correct order as they should be processed.
|
[
"Given",
"a",
"sequence",
"of",
"parameters",
"in",
"the",
"order",
"as",
"should",
"be",
"considered",
"for",
"processing",
"and",
"an",
"iterable",
"of",
"parameters",
"that",
"exist",
"this",
"returns",
"a",
"list",
"in",
"the",
"correct",
"order",
"as",
"they",
"should",
"be",
"processed",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L118-L130
|
train
|
pypa/pipenv
|
pipenv/vendor/click/core.py
|
Context.scope
|
def scope(self, cleanup=True):
"""This helper method can be used with the context object to promote
it to the current thread local (see :func:`get_current_context`).
The default behavior of this is to invoke the cleanup functions which
can be disabled by setting `cleanup` to `False`. The cleanup
functions are typically used for things such as closing file handles.
If the cleanup is intended the context object can also be directly
used as a context manager.
Example usage::
with ctx.scope():
assert get_current_context() is ctx
This is equivalent::
with ctx:
assert get_current_context() is ctx
.. versionadded:: 5.0
:param cleanup: controls if the cleanup functions should be run or
not. The default is to run these functions. In
some situations the context only wants to be
temporarily pushed in which case this can be disabled.
Nested pushes automatically defer the cleanup.
"""
if not cleanup:
self._depth += 1
try:
with self as rv:
yield rv
finally:
if not cleanup:
self._depth -= 1
|
python
|
def scope(self, cleanup=True):
"""This helper method can be used with the context object to promote
it to the current thread local (see :func:`get_current_context`).
The default behavior of this is to invoke the cleanup functions which
can be disabled by setting `cleanup` to `False`. The cleanup
functions are typically used for things such as closing file handles.
If the cleanup is intended the context object can also be directly
used as a context manager.
Example usage::
with ctx.scope():
assert get_current_context() is ctx
This is equivalent::
with ctx:
assert get_current_context() is ctx
.. versionadded:: 5.0
:param cleanup: controls if the cleanup functions should be run or
not. The default is to run these functions. In
some situations the context only wants to be
temporarily pushed in which case this can be disabled.
Nested pushes automatically defer the cleanup.
"""
if not cleanup:
self._depth += 1
try:
with self as rv:
yield rv
finally:
if not cleanup:
self._depth -= 1
|
[
"def",
"scope",
"(",
"self",
",",
"cleanup",
"=",
"True",
")",
":",
"if",
"not",
"cleanup",
":",
"self",
".",
"_depth",
"+=",
"1",
"try",
":",
"with",
"self",
"as",
"rv",
":",
"yield",
"rv",
"finally",
":",
"if",
"not",
"cleanup",
":",
"self",
".",
"_depth",
"-=",
"1"
] |
This helper method can be used with the context object to promote
it to the current thread local (see :func:`get_current_context`).
The default behavior of this is to invoke the cleanup functions which
can be disabled by setting `cleanup` to `False`. The cleanup
functions are typically used for things such as closing file handles.
If the cleanup is intended the context object can also be directly
used as a context manager.
Example usage::
with ctx.scope():
assert get_current_context() is ctx
This is equivalent::
with ctx:
assert get_current_context() is ctx
.. versionadded:: 5.0
:param cleanup: controls if the cleanup functions should be run or
not. The default is to run these functions. In
some situations the context only wants to be
temporarily pushed in which case this can be disabled.
Nested pushes automatically defer the cleanup.
|
[
"This",
"helper",
"method",
"can",
"be",
"used",
"with",
"the",
"context",
"object",
"to",
"promote",
"it",
"to",
"the",
"current",
"thread",
"local",
"(",
"see",
":",
"func",
":",
"get_current_context",
")",
".",
"The",
"default",
"behavior",
"of",
"this",
"is",
"to",
"invoke",
"the",
"cleanup",
"functions",
"which",
"can",
"be",
"disabled",
"by",
"setting",
"cleanup",
"to",
"False",
".",
"The",
"cleanup",
"functions",
"are",
"typically",
"used",
"for",
"things",
"such",
"as",
"closing",
"file",
"handles",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L355-L390
|
train
|
pypa/pipenv
|
pipenv/vendor/click/core.py
|
Context.command_path
|
def command_path(self):
"""The computed command path. This is used for the ``usage``
information on the help page. It's automatically created by
combining the info names of the chain of contexts to the root.
"""
rv = ''
if self.info_name is not None:
rv = self.info_name
if self.parent is not None:
rv = self.parent.command_path + ' ' + rv
return rv.lstrip()
|
python
|
def command_path(self):
"""The computed command path. This is used for the ``usage``
information on the help page. It's automatically created by
combining the info names of the chain of contexts to the root.
"""
rv = ''
if self.info_name is not None:
rv = self.info_name
if self.parent is not None:
rv = self.parent.command_path + ' ' + rv
return rv.lstrip()
|
[
"def",
"command_path",
"(",
"self",
")",
":",
"rv",
"=",
"''",
"if",
"self",
".",
"info_name",
"is",
"not",
"None",
":",
"rv",
"=",
"self",
".",
"info_name",
"if",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"rv",
"=",
"self",
".",
"parent",
".",
"command_path",
"+",
"' '",
"+",
"rv",
"return",
"rv",
".",
"lstrip",
"(",
")"
] |
The computed command path. This is used for the ``usage``
information on the help page. It's automatically created by
combining the info names of the chain of contexts to the root.
|
[
"The",
"computed",
"command",
"path",
".",
"This",
"is",
"used",
"for",
"the",
"usage",
"information",
"on",
"the",
"help",
"page",
".",
"It",
"s",
"automatically",
"created",
"by",
"combining",
"the",
"info",
"names",
"of",
"the",
"chain",
"of",
"contexts",
"to",
"the",
"root",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L444-L454
|
train
|
pypa/pipenv
|
pipenv/vendor/click/core.py
|
Context.find_root
|
def find_root(self):
"""Finds the outermost context."""
node = self
while node.parent is not None:
node = node.parent
return node
|
python
|
def find_root(self):
"""Finds the outermost context."""
node = self
while node.parent is not None:
node = node.parent
return node
|
[
"def",
"find_root",
"(",
"self",
")",
":",
"node",
"=",
"self",
"while",
"node",
".",
"parent",
"is",
"not",
"None",
":",
"node",
"=",
"node",
".",
"parent",
"return",
"node"
] |
Finds the outermost context.
|
[
"Finds",
"the",
"outermost",
"context",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L456-L461
|
train
|
pypa/pipenv
|
pipenv/vendor/click/core.py
|
Context.find_object
|
def find_object(self, object_type):
"""Finds the closest object of a given type."""
node = self
while node is not None:
if isinstance(node.obj, object_type):
return node.obj
node = node.parent
|
python
|
def find_object(self, object_type):
"""Finds the closest object of a given type."""
node = self
while node is not None:
if isinstance(node.obj, object_type):
return node.obj
node = node.parent
|
[
"def",
"find_object",
"(",
"self",
",",
"object_type",
")",
":",
"node",
"=",
"self",
"while",
"node",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"node",
".",
"obj",
",",
"object_type",
")",
":",
"return",
"node",
".",
"obj",
"node",
"=",
"node",
".",
"parent"
] |
Finds the closest object of a given type.
|
[
"Finds",
"the",
"closest",
"object",
"of",
"a",
"given",
"type",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L463-L469
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.