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/msgpack/fallback.py
Unpacker._consume
def _consume(self): """ Gets rid of the used parts of the buffer. """ self._stream_offset += self._buff_i - self._buf_checkpoint self._buf_checkpoint = self._buff_i
python
def _consume(self): """ Gets rid of the used parts of the buffer. """ self._stream_offset += self._buff_i - self._buf_checkpoint self._buf_checkpoint = self._buff_i
[ "def", "_consume", "(", "self", ")", ":", "self", ".", "_stream_offset", "+=", "self", ".", "_buff_i", "-", "self", ".", "_buf_checkpoint", "self", ".", "_buf_checkpoint", "=", "self", ".", "_buff_i" ]
Gets rid of the used parts of the buffer.
[ "Gets", "rid", "of", "the", "used", "parts", "of", "the", "buffer", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/msgpack/fallback.py#L300-L303
train
pypa/pipenv
pipenv/vendor/urllib3/connection.py
HTTPConnection._new_conn
def _new_conn(self): """ Establish a socket connection and set nodelay settings on it. :return: New socket connection. """ 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 = connection.create_connection( (self._dns_host, self.port), self.timeout, **extra_kw) except SocketTimeout as e: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout)) except SocketError as e: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e) return conn
python
def _new_conn(self): """ Establish a socket connection and set nodelay settings on it. :return: New socket connection. """ 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 = connection.create_connection( (self._dns_host, self.port), self.timeout, **extra_kw) except SocketTimeout as e: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout)) except SocketError as e: 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", "=", "connection", ".", "create_connection", "(", "(", "self", ".", "_dns_host", ",", "self", ".", "port", ")", ",", "self", ".", "timeout", ",", "*", "*", "extra_kw", ")", "except", "SocketTimeout", "as", "e", ":", "raise", "ConnectTimeoutError", "(", "self", ",", "\"Connection to %s timed out. (connect timeout=%s)\"", "%", "(", "self", ".", "host", ",", "self", ".", "timeout", ")", ")", "except", "SocketError", "as", "e", ":", "raise", "NewConnectionError", "(", "self", ",", "\"Failed to establish a new connection: %s\"", "%", "e", ")", "return", "conn" ]
Establish a socket connection and set nodelay settings on it. :return: New socket connection.
[ "Establish", "a", "socket", "connection", "and", "set", "nodelay", "settings", "on", "it", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/connection.py#L145-L170
train
pypa/pipenv
pipenv/vendor/urllib3/connection.py
HTTPConnection.request_chunked
def request_chunked(self, method, url, body=None, headers=None): """ Alternative to the common request method, which sends the body with chunked encoding and not as one block """ headers = HTTPHeaderDict(headers if headers is not None else {}) skip_accept_encoding = 'accept-encoding' in headers skip_host = 'host' in headers self.putrequest( method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host ) for header, value in headers.items(): self.putheader(header, value) if 'transfer-encoding' not in headers: self.putheader('Transfer-Encoding', 'chunked') self.endheaders() if body is not None: stringish_types = six.string_types + (bytes,) if isinstance(body, stringish_types): body = (body,) for chunk in body: if not chunk: continue if not isinstance(chunk, bytes): chunk = chunk.encode('utf8') len_str = hex(len(chunk))[2:] self.send(len_str.encode('utf-8')) self.send(b'\r\n') self.send(chunk) self.send(b'\r\n') # After the if clause, to always have a closed body self.send(b'0\r\n\r\n')
python
def request_chunked(self, method, url, body=None, headers=None): """ Alternative to the common request method, which sends the body with chunked encoding and not as one block """ headers = HTTPHeaderDict(headers if headers is not None else {}) skip_accept_encoding = 'accept-encoding' in headers skip_host = 'host' in headers self.putrequest( method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host ) for header, value in headers.items(): self.putheader(header, value) if 'transfer-encoding' not in headers: self.putheader('Transfer-Encoding', 'chunked') self.endheaders() if body is not None: stringish_types = six.string_types + (bytes,) if isinstance(body, stringish_types): body = (body,) for chunk in body: if not chunk: continue if not isinstance(chunk, bytes): chunk = chunk.encode('utf8') len_str = hex(len(chunk))[2:] self.send(len_str.encode('utf-8')) self.send(b'\r\n') self.send(chunk) self.send(b'\r\n') # After the if clause, to always have a closed body self.send(b'0\r\n\r\n')
[ "def", "request_chunked", "(", "self", ",", "method", ",", "url", ",", "body", "=", "None", ",", "headers", "=", "None", ")", ":", "headers", "=", "HTTPHeaderDict", "(", "headers", "if", "headers", "is", "not", "None", "else", "{", "}", ")", "skip_accept_encoding", "=", "'accept-encoding'", "in", "headers", "skip_host", "=", "'host'", "in", "headers", "self", ".", "putrequest", "(", "method", ",", "url", ",", "skip_accept_encoding", "=", "skip_accept_encoding", ",", "skip_host", "=", "skip_host", ")", "for", "header", ",", "value", "in", "headers", ".", "items", "(", ")", ":", "self", ".", "putheader", "(", "header", ",", "value", ")", "if", "'transfer-encoding'", "not", "in", "headers", ":", "self", ".", "putheader", "(", "'Transfer-Encoding'", ",", "'chunked'", ")", "self", ".", "endheaders", "(", ")", "if", "body", "is", "not", "None", ":", "stringish_types", "=", "six", ".", "string_types", "+", "(", "bytes", ",", ")", "if", "isinstance", "(", "body", ",", "stringish_types", ")", ":", "body", "=", "(", "body", ",", ")", "for", "chunk", "in", "body", ":", "if", "not", "chunk", ":", "continue", "if", "not", "isinstance", "(", "chunk", ",", "bytes", ")", ":", "chunk", "=", "chunk", ".", "encode", "(", "'utf8'", ")", "len_str", "=", "hex", "(", "len", "(", "chunk", ")", ")", "[", "2", ":", "]", "self", ".", "send", "(", "len_str", ".", "encode", "(", "'utf-8'", ")", ")", "self", ".", "send", "(", "b'\\r\\n'", ")", "self", ".", "send", "(", "chunk", ")", "self", ".", "send", "(", "b'\\r\\n'", ")", "# After the if clause, to always have a closed body", "self", ".", "send", "(", "b'0\\r\\n\\r\\n'", ")" ]
Alternative to the common request method, which sends the body with chunked encoding and not as one block
[ "Alternative", "to", "the", "common", "request", "method", "which", "sends", "the", "body", "with", "chunked", "encoding", "and", "not", "as", "one", "block" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/connection.py#L184-L220
train
pypa/pipenv
pipenv/vendor/urllib3/connection.py
VerifiedHTTPSConnection.set_cert
def set_cert(self, key_file=None, cert_file=None, cert_reqs=None, ca_certs=None, assert_hostname=None, assert_fingerprint=None, ca_cert_dir=None): """ This method should only be called once, before the connection is used. """ # If cert_reqs is not provided, we can try to guess. If the user gave # us a cert database, we assume they want to use it: otherwise, if # they gave us an SSL Context object we should use whatever is set for # it. if cert_reqs is None: if ca_certs or ca_cert_dir: cert_reqs = 'CERT_REQUIRED' elif self.ssl_context is not None: cert_reqs = self.ssl_context.verify_mode self.key_file = key_file self.cert_file = cert_file self.cert_reqs = cert_reqs self.assert_hostname = assert_hostname self.assert_fingerprint = assert_fingerprint self.ca_certs = ca_certs and os.path.expanduser(ca_certs) self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
python
def set_cert(self, key_file=None, cert_file=None, cert_reqs=None, ca_certs=None, assert_hostname=None, assert_fingerprint=None, ca_cert_dir=None): """ This method should only be called once, before the connection is used. """ # If cert_reqs is not provided, we can try to guess. If the user gave # us a cert database, we assume they want to use it: otherwise, if # they gave us an SSL Context object we should use whatever is set for # it. if cert_reqs is None: if ca_certs or ca_cert_dir: cert_reqs = 'CERT_REQUIRED' elif self.ssl_context is not None: cert_reqs = self.ssl_context.verify_mode self.key_file = key_file self.cert_file = cert_file self.cert_reqs = cert_reqs self.assert_hostname = assert_hostname self.assert_fingerprint = assert_fingerprint self.ca_certs = ca_certs and os.path.expanduser(ca_certs) self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
[ "def", "set_cert", "(", "self", ",", "key_file", "=", "None", ",", "cert_file", "=", "None", ",", "cert_reqs", "=", "None", ",", "ca_certs", "=", "None", ",", "assert_hostname", "=", "None", ",", "assert_fingerprint", "=", "None", ",", "ca_cert_dir", "=", "None", ")", ":", "# If cert_reqs is not provided, we can try to guess. If the user gave", "# us a cert database, we assume they want to use it: otherwise, if", "# they gave us an SSL Context object we should use whatever is set for", "# it.", "if", "cert_reqs", "is", "None", ":", "if", "ca_certs", "or", "ca_cert_dir", ":", "cert_reqs", "=", "'CERT_REQUIRED'", "elif", "self", ".", "ssl_context", "is", "not", "None", ":", "cert_reqs", "=", "self", ".", "ssl_context", ".", "verify_mode", "self", ".", "key_file", "=", "key_file", "self", ".", "cert_file", "=", "cert_file", "self", ".", "cert_reqs", "=", "cert_reqs", "self", ".", "assert_hostname", "=", "assert_hostname", "self", ".", "assert_fingerprint", "=", "assert_fingerprint", "self", ".", "ca_certs", "=", "ca_certs", "and", "os", ".", "path", ".", "expanduser", "(", "ca_certs", ")", "self", ".", "ca_cert_dir", "=", "ca_cert_dir", "and", "os", ".", "path", ".", "expanduser", "(", "ca_cert_dir", ")" ]
This method should only be called once, before the connection is used.
[ "This", "method", "should", "only", "be", "called", "once", "before", "the", "connection", "is", "used", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/connection.py#L274-L297
train
pypa/pipenv
pipenv/exceptions.py
prettify_exc
def prettify_exc(error): """Catch known errors and prettify them instead of showing the entire traceback, for better UX""" matched_exceptions = [k for k in KNOWN_EXCEPTIONS.keys() if k in error] if not matched_exceptions: return "{}".format(vistir.misc.decode_for_output(error)) errors = [] for match in matched_exceptions: _, error, info = error.rpartition(KNOWN_EXCEPTIONS[match]) errors.append("{} {}".format(error, info)) return "\n".join(errors)
python
def prettify_exc(error): """Catch known errors and prettify them instead of showing the entire traceback, for better UX""" matched_exceptions = [k for k in KNOWN_EXCEPTIONS.keys() if k in error] if not matched_exceptions: return "{}".format(vistir.misc.decode_for_output(error)) errors = [] for match in matched_exceptions: _, error, info = error.rpartition(KNOWN_EXCEPTIONS[match]) errors.append("{} {}".format(error, info)) return "\n".join(errors)
[ "def", "prettify_exc", "(", "error", ")", ":", "matched_exceptions", "=", "[", "k", "for", "k", "in", "KNOWN_EXCEPTIONS", ".", "keys", "(", ")", "if", "k", "in", "error", "]", "if", "not", "matched_exceptions", ":", "return", "\"{}\"", ".", "format", "(", "vistir", ".", "misc", ".", "decode_for_output", "(", "error", ")", ")", "errors", "=", "[", "]", "for", "match", "in", "matched_exceptions", ":", "_", ",", "error", ",", "info", "=", "error", ".", "rpartition", "(", "KNOWN_EXCEPTIONS", "[", "match", "]", ")", "errors", ".", "append", "(", "\"{} {}\"", ".", "format", "(", "error", ",", "info", ")", ")", "return", "\"\\n\"", ".", "join", "(", "errors", ")" ]
Catch known errors and prettify them instead of showing the entire traceback, for better UX
[ "Catch", "known", "errors", "and", "prettify", "them", "instead", "of", "showing", "the", "entire", "traceback", "for", "better", "UX" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/exceptions.py#L412-L423
train
pypa/pipenv
pipenv/vendor/vistir/cursor.py
get_stream_handle
def get_stream_handle(stream=sys.stdout): """ Get the OS appropriate handle for the corresponding output stream. :param str stream: The the stream to get the handle for :return: A handle to the appropriate stream, either a ctypes buffer or **sys.stdout** or **sys.stderr**. """ handle = stream if os.name == "nt": from ctypes import windll handle_id = WIN_STDOUT_HANDLE_ID handle = windll.kernel32.GetStdHandle(handle_id) return handle
python
def get_stream_handle(stream=sys.stdout): """ Get the OS appropriate handle for the corresponding output stream. :param str stream: The the stream to get the handle for :return: A handle to the appropriate stream, either a ctypes buffer or **sys.stdout** or **sys.stderr**. """ handle = stream if os.name == "nt": from ctypes import windll handle_id = WIN_STDOUT_HANDLE_ID handle = windll.kernel32.GetStdHandle(handle_id) return handle
[ "def", "get_stream_handle", "(", "stream", "=", "sys", ".", "stdout", ")", ":", "handle", "=", "stream", "if", "os", ".", "name", "==", "\"nt\"", ":", "from", "ctypes", "import", "windll", "handle_id", "=", "WIN_STDOUT_HANDLE_ID", "handle", "=", "windll", ".", "kernel32", ".", "GetStdHandle", "(", "handle_id", ")", "return", "handle" ]
Get the OS appropriate handle for the corresponding output stream. :param str stream: The the stream to get the handle for :return: A handle to the appropriate stream, either a ctypes buffer or **sys.stdout** or **sys.stderr**.
[ "Get", "the", "OS", "appropriate", "handle", "for", "the", "corresponding", "output", "stream", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/cursor.py#L19-L33
train
pypa/pipenv
pipenv/vendor/vistir/cursor.py
hide_cursor
def hide_cursor(stream=sys.stdout): """ Hide the console cursor on the given stream :param stream: The name of the stream to get the handle for :return: None :rtype: None """ handle = get_stream_handle(stream=stream) if os.name == "nt": from ctypes import windll cursor_info = CONSOLE_CURSOR_INFO() windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(cursor_info)) cursor_info.visible = False windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(cursor_info)) else: handle.write("\033[?25l") handle.flush()
python
def hide_cursor(stream=sys.stdout): """ Hide the console cursor on the given stream :param stream: The name of the stream to get the handle for :return: None :rtype: None """ handle = get_stream_handle(stream=stream) if os.name == "nt": from ctypes import windll cursor_info = CONSOLE_CURSOR_INFO() windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(cursor_info)) cursor_info.visible = False windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(cursor_info)) else: handle.write("\033[?25l") handle.flush()
[ "def", "hide_cursor", "(", "stream", "=", "sys", ".", "stdout", ")", ":", "handle", "=", "get_stream_handle", "(", "stream", "=", "stream", ")", "if", "os", ".", "name", "==", "\"nt\"", ":", "from", "ctypes", "import", "windll", "cursor_info", "=", "CONSOLE_CURSOR_INFO", "(", ")", "windll", ".", "kernel32", ".", "GetConsoleCursorInfo", "(", "handle", ",", "ctypes", ".", "byref", "(", "cursor_info", ")", ")", "cursor_info", ".", "visible", "=", "False", "windll", ".", "kernel32", ".", "SetConsoleCursorInfo", "(", "handle", ",", "ctypes", ".", "byref", "(", "cursor_info", ")", ")", "else", ":", "handle", ".", "write", "(", "\"\\033[?25l\"", ")", "handle", ".", "flush", "(", ")" ]
Hide the console cursor on the given stream :param stream: The name of the stream to get the handle for :return: None :rtype: None
[ "Hide", "the", "console", "cursor", "on", "the", "given", "stream" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/cursor.py#L36-L55
train
pypa/pipenv
pipenv/vendor/click_completion/patch.py
choice_complete
def choice_complete(self, ctx, incomplete): """Returns the completion results for click.core.Choice Parameters ---------- ctx : click.core.Context The current context incomplete : The string to complete Returns ------- [(str, str)] A list of completion results """ return [ (c, None) for c in self.choices if completion_configuration.match_incomplete(c, incomplete) ]
python
def choice_complete(self, ctx, incomplete): """Returns the completion results for click.core.Choice Parameters ---------- ctx : click.core.Context The current context incomplete : The string to complete Returns ------- [(str, str)] A list of completion results """ return [ (c, None) for c in self.choices if completion_configuration.match_incomplete(c, incomplete) ]
[ "def", "choice_complete", "(", "self", ",", "ctx", ",", "incomplete", ")", ":", "return", "[", "(", "c", ",", "None", ")", "for", "c", "in", "self", ".", "choices", "if", "completion_configuration", ".", "match_incomplete", "(", "c", ",", "incomplete", ")", "]" ]
Returns the completion results for click.core.Choice Parameters ---------- ctx : click.core.Context The current context incomplete : The string to complete Returns ------- [(str, str)] A list of completion results
[ "Returns", "the", "completion", "results", "for", "click", ".", "core", ".", "Choice" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click_completion/patch.py#L39-L57
train
pypa/pipenv
pipenv/vendor/click_completion/patch.py
_shellcomplete
def _shellcomplete(cli, prog_name, complete_var=None): """Internal handler for the bash completion support. Parameters ---------- cli : click.Command The main click Command of the program prog_name : str The program name on the command line complete_var : str The environment variable name used to control the completion behavior (Default value = 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 if complete_instr == 'source': echo(get_code(prog_name=prog_name, env_name=complete_var)) elif complete_instr == 'source-bash': echo(get_code('bash', prog_name, complete_var)) elif complete_instr == 'source-fish': echo(get_code('fish', prog_name, complete_var)) elif complete_instr == 'source-powershell': echo(get_code('powershell', prog_name, complete_var)) elif complete_instr == 'source-zsh': echo(get_code('zsh', prog_name, complete_var)) elif complete_instr in ['complete', 'complete-bash']: # keep 'complete' for bash for backward compatibility do_bash_complete(cli, prog_name) elif complete_instr == 'complete-fish': do_fish_complete(cli, prog_name) elif complete_instr == 'complete-powershell': do_powershell_complete(cli, prog_name) elif complete_instr == 'complete-zsh': do_zsh_complete(cli, prog_name) elif complete_instr == 'install': shell, path = install(prog_name=prog_name, env_name=complete_var) click.echo('%s completion installed in %s' % (shell, path)) elif complete_instr == 'install-bash': shell, path = install(shell='bash', prog_name=prog_name, env_name=complete_var) click.echo('%s completion installed in %s' % (shell, path)) elif complete_instr == 'install-fish': shell, path = install(shell='fish', prog_name=prog_name, env_name=complete_var) click.echo('%s completion installed in %s' % (shell, path)) elif complete_instr == 'install-zsh': shell, path = install(shell='zsh', prog_name=prog_name, env_name=complete_var) click.echo('%s completion installed in %s' % (shell, path)) elif complete_instr == 'install-powershell': shell, path = install(shell='powershell', prog_name=prog_name, env_name=complete_var) click.echo('%s completion installed in %s' % (shell, path)) sys.exit()
python
def _shellcomplete(cli, prog_name, complete_var=None): """Internal handler for the bash completion support. Parameters ---------- cli : click.Command The main click Command of the program prog_name : str The program name on the command line complete_var : str The environment variable name used to control the completion behavior (Default value = 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 if complete_instr == 'source': echo(get_code(prog_name=prog_name, env_name=complete_var)) elif complete_instr == 'source-bash': echo(get_code('bash', prog_name, complete_var)) elif complete_instr == 'source-fish': echo(get_code('fish', prog_name, complete_var)) elif complete_instr == 'source-powershell': echo(get_code('powershell', prog_name, complete_var)) elif complete_instr == 'source-zsh': echo(get_code('zsh', prog_name, complete_var)) elif complete_instr in ['complete', 'complete-bash']: # keep 'complete' for bash for backward compatibility do_bash_complete(cli, prog_name) elif complete_instr == 'complete-fish': do_fish_complete(cli, prog_name) elif complete_instr == 'complete-powershell': do_powershell_complete(cli, prog_name) elif complete_instr == 'complete-zsh': do_zsh_complete(cli, prog_name) elif complete_instr == 'install': shell, path = install(prog_name=prog_name, env_name=complete_var) click.echo('%s completion installed in %s' % (shell, path)) elif complete_instr == 'install-bash': shell, path = install(shell='bash', prog_name=prog_name, env_name=complete_var) click.echo('%s completion installed in %s' % (shell, path)) elif complete_instr == 'install-fish': shell, path = install(shell='fish', prog_name=prog_name, env_name=complete_var) click.echo('%s completion installed in %s' % (shell, path)) elif complete_instr == 'install-zsh': shell, path = install(shell='zsh', prog_name=prog_name, env_name=complete_var) click.echo('%s completion installed in %s' % (shell, path)) elif complete_instr == 'install-powershell': shell, path = install(shell='powershell', prog_name=prog_name, env_name=complete_var) click.echo('%s completion installed in %s' % (shell, path)) sys.exit()
[ "def", "_shellcomplete", "(", "cli", ",", "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", "if", "complete_instr", "==", "'source'", ":", "echo", "(", "get_code", "(", "prog_name", "=", "prog_name", ",", "env_name", "=", "complete_var", ")", ")", "elif", "complete_instr", "==", "'source-bash'", ":", "echo", "(", "get_code", "(", "'bash'", ",", "prog_name", ",", "complete_var", ")", ")", "elif", "complete_instr", "==", "'source-fish'", ":", "echo", "(", "get_code", "(", "'fish'", ",", "prog_name", ",", "complete_var", ")", ")", "elif", "complete_instr", "==", "'source-powershell'", ":", "echo", "(", "get_code", "(", "'powershell'", ",", "prog_name", ",", "complete_var", ")", ")", "elif", "complete_instr", "==", "'source-zsh'", ":", "echo", "(", "get_code", "(", "'zsh'", ",", "prog_name", ",", "complete_var", ")", ")", "elif", "complete_instr", "in", "[", "'complete'", ",", "'complete-bash'", "]", ":", "# keep 'complete' for bash for backward compatibility", "do_bash_complete", "(", "cli", ",", "prog_name", ")", "elif", "complete_instr", "==", "'complete-fish'", ":", "do_fish_complete", "(", "cli", ",", "prog_name", ")", "elif", "complete_instr", "==", "'complete-powershell'", ":", "do_powershell_complete", "(", "cli", ",", "prog_name", ")", "elif", "complete_instr", "==", "'complete-zsh'", ":", "do_zsh_complete", "(", "cli", ",", "prog_name", ")", "elif", "complete_instr", "==", "'install'", ":", "shell", ",", "path", "=", "install", "(", "prog_name", "=", "prog_name", ",", "env_name", "=", "complete_var", ")", "click", ".", "echo", "(", "'%s completion installed in %s'", "%", "(", "shell", ",", "path", ")", ")", "elif", "complete_instr", "==", "'install-bash'", ":", "shell", ",", "path", "=", "install", "(", "shell", "=", "'bash'", ",", "prog_name", "=", "prog_name", ",", "env_name", "=", "complete_var", ")", "click", ".", "echo", "(", "'%s completion installed in %s'", "%", "(", "shell", ",", "path", ")", ")", "elif", "complete_instr", "==", "'install-fish'", ":", "shell", ",", "path", "=", "install", "(", "shell", "=", "'fish'", ",", "prog_name", "=", "prog_name", ",", "env_name", "=", "complete_var", ")", "click", ".", "echo", "(", "'%s completion installed in %s'", "%", "(", "shell", ",", "path", ")", ")", "elif", "complete_instr", "==", "'install-zsh'", ":", "shell", ",", "path", "=", "install", "(", "shell", "=", "'zsh'", ",", "prog_name", "=", "prog_name", ",", "env_name", "=", "complete_var", ")", "click", ".", "echo", "(", "'%s completion installed in %s'", "%", "(", "shell", ",", "path", ")", ")", "elif", "complete_instr", "==", "'install-powershell'", ":", "shell", ",", "path", "=", "install", "(", "shell", "=", "'powershell'", ",", "prog_name", "=", "prog_name", ",", "env_name", "=", "complete_var", ")", "click", ".", "echo", "(", "'%s completion installed in %s'", "%", "(", "shell", ",", "path", ")", ")", "sys", ".", "exit", "(", ")" ]
Internal handler for the bash completion support. Parameters ---------- cli : click.Command The main click Command of the program prog_name : str The program name on the command line complete_var : str The environment variable name used to control the completion behavior (Default value = None)
[ "Internal", "handler", "for", "the", "bash", "completion", "support", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click_completion/patch.py#L81-L133
train
pypa/pipenv
pipenv/vendor/click_completion/patch.py
patch
def patch(): """Patch click""" import click click.types.ParamType.complete = param_type_complete click.types.Choice.complete = choice_complete click.core.MultiCommand.get_command_short_help = multicommand_get_command_short_help click.core._bashcomplete = _shellcomplete
python
def patch(): """Patch click""" import click click.types.ParamType.complete = param_type_complete click.types.Choice.complete = choice_complete click.core.MultiCommand.get_command_short_help = multicommand_get_command_short_help click.core._bashcomplete = _shellcomplete
[ "def", "patch", "(", ")", ":", "import", "click", "click", ".", "types", ".", "ParamType", ".", "complete", "=", "param_type_complete", "click", ".", "types", ".", "Choice", ".", "complete", "=", "choice_complete", "click", ".", "core", ".", "MultiCommand", ".", "get_command_short_help", "=", "multicommand_get_command_short_help", "click", ".", "core", ".", "_bashcomplete", "=", "_shellcomplete" ]
Patch click
[ "Patch", "click" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click_completion/patch.py#L136-L142
train
pypa/pipenv
pipenv/vendor/docopt.py
parse_expr
def parse_expr(tokens, options): """expr ::= seq ( '|' seq )* ;""" seq = parse_seq(tokens, options) if tokens.current() != '|': return seq result = [Required(*seq)] if len(seq) > 1 else seq while tokens.current() == '|': tokens.move() seq = parse_seq(tokens, options) result += [Required(*seq)] if len(seq) > 1 else seq return [Either(*result)] if len(result) > 1 else result
python
def parse_expr(tokens, options): """expr ::= seq ( '|' seq )* ;""" seq = parse_seq(tokens, options) if tokens.current() != '|': return seq result = [Required(*seq)] if len(seq) > 1 else seq while tokens.current() == '|': tokens.move() seq = parse_seq(tokens, options) result += [Required(*seq)] if len(seq) > 1 else seq return [Either(*result)] if len(result) > 1 else result
[ "def", "parse_expr", "(", "tokens", ",", "options", ")", ":", "seq", "=", "parse_seq", "(", "tokens", ",", "options", ")", "if", "tokens", ".", "current", "(", ")", "!=", "'|'", ":", "return", "seq", "result", "=", "[", "Required", "(", "*", "seq", ")", "]", "if", "len", "(", "seq", ")", ">", "1", "else", "seq", "while", "tokens", ".", "current", "(", ")", "==", "'|'", ":", "tokens", ".", "move", "(", ")", "seq", "=", "parse_seq", "(", "tokens", ",", "options", ")", "result", "+=", "[", "Required", "(", "*", "seq", ")", "]", "if", "len", "(", "seq", ")", ">", "1", "else", "seq", "return", "[", "Either", "(", "*", "result", ")", "]", "if", "len", "(", "result", ")", ">", "1", "else", "result" ]
expr ::= seq ( '|' seq )* ;
[ "expr", "::", "=", "seq", "(", "|", "seq", ")", "*", ";" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/docopt.py#L379-L389
train
pypa/pipenv
pipenv/vendor/docopt.py
parse_seq
def parse_seq(tokens, options): """seq ::= ( atom [ '...' ] )* ;""" result = [] while tokens.current() not in [None, ']', ')', '|']: atom = parse_atom(tokens, options) if tokens.current() == '...': atom = [OneOrMore(*atom)] tokens.move() result += atom return result
python
def parse_seq(tokens, options): """seq ::= ( atom [ '...' ] )* ;""" result = [] while tokens.current() not in [None, ']', ')', '|']: atom = parse_atom(tokens, options) if tokens.current() == '...': atom = [OneOrMore(*atom)] tokens.move() result += atom return result
[ "def", "parse_seq", "(", "tokens", ",", "options", ")", ":", "result", "=", "[", "]", "while", "tokens", ".", "current", "(", ")", "not", "in", "[", "None", ",", "']'", ",", "')'", ",", "'|'", "]", ":", "atom", "=", "parse_atom", "(", "tokens", ",", "options", ")", "if", "tokens", ".", "current", "(", ")", "==", "'...'", ":", "atom", "=", "[", "OneOrMore", "(", "*", "atom", ")", "]", "tokens", ".", "move", "(", ")", "result", "+=", "atom", "return", "result" ]
seq ::= ( atom [ '...' ] )* ;
[ "seq", "::", "=", "(", "atom", "[", "...", "]", ")", "*", ";" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/docopt.py#L392-L401
train
pypa/pipenv
pipenv/vendor/docopt.py
parse_argv
def parse_argv(tokens, options, options_first=False): """Parse command-line argument vector. If options_first: argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ; else: argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ; """ parsed = [] while tokens.current() is not None: if tokens.current() == '--': return parsed + [Argument(None, v) for v in tokens] elif tokens.current().startswith('--'): parsed += parse_long(tokens, options) elif tokens.current().startswith('-') and tokens.current() != '-': parsed += parse_shorts(tokens, options) elif options_first: return parsed + [Argument(None, v) for v in tokens] else: parsed.append(Argument(None, tokens.move())) return parsed
python
def parse_argv(tokens, options, options_first=False): """Parse command-line argument vector. If options_first: argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ; else: argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ; """ parsed = [] while tokens.current() is not None: if tokens.current() == '--': return parsed + [Argument(None, v) for v in tokens] elif tokens.current().startswith('--'): parsed += parse_long(tokens, options) elif tokens.current().startswith('-') and tokens.current() != '-': parsed += parse_shorts(tokens, options) elif options_first: return parsed + [Argument(None, v) for v in tokens] else: parsed.append(Argument(None, tokens.move())) return parsed
[ "def", "parse_argv", "(", "tokens", ",", "options", ",", "options_first", "=", "False", ")", ":", "parsed", "=", "[", "]", "while", "tokens", ".", "current", "(", ")", "is", "not", "None", ":", "if", "tokens", ".", "current", "(", ")", "==", "'--'", ":", "return", "parsed", "+", "[", "Argument", "(", "None", ",", "v", ")", "for", "v", "in", "tokens", "]", "elif", "tokens", ".", "current", "(", ")", ".", "startswith", "(", "'--'", ")", ":", "parsed", "+=", "parse_long", "(", "tokens", ",", "options", ")", "elif", "tokens", ".", "current", "(", ")", ".", "startswith", "(", "'-'", ")", "and", "tokens", ".", "current", "(", ")", "!=", "'-'", ":", "parsed", "+=", "parse_shorts", "(", "tokens", ",", "options", ")", "elif", "options_first", ":", "return", "parsed", "+", "[", "Argument", "(", "None", ",", "v", ")", "for", "v", "in", "tokens", "]", "else", ":", "parsed", ".", "append", "(", "Argument", "(", "None", ",", "tokens", ".", "move", "(", ")", ")", ")", "return", "parsed" ]
Parse command-line argument vector. If options_first: argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ; else: argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ;
[ "Parse", "command", "-", "line", "argument", "vector", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/docopt.py#L430-L451
train
pypa/pipenv
pipenv/vendor/vistir/misc.py
unnest
def unnest(elem): """Flatten an arbitrarily nested iterable :param elem: An iterable to flatten :type elem: :class:`~collections.Iterable` >>> nested_iterable = (1234, (3456, 4398345, (234234)), (2396, (23895750, 9283798, 29384, (289375983275, 293759, 2347, (2098, 7987, 27599))))) >>> list(vistir.misc.unnest(nested_iterable)) [1234, 3456, 4398345, 234234, 2396, 23895750, 9283798, 29384, 289375983275, 293759, 2347, 2098, 7987, 27599] """ if isinstance(elem, Iterable) and not isinstance(elem, six.string_types): elem, target = tee(elem, 2) else: target = elem for el in target: if isinstance(el, Iterable) and not isinstance(el, six.string_types): el, el_copy = tee(el, 2) for sub in unnest(el_copy): yield sub else: yield el
python
def unnest(elem): """Flatten an arbitrarily nested iterable :param elem: An iterable to flatten :type elem: :class:`~collections.Iterable` >>> nested_iterable = (1234, (3456, 4398345, (234234)), (2396, (23895750, 9283798, 29384, (289375983275, 293759, 2347, (2098, 7987, 27599))))) >>> list(vistir.misc.unnest(nested_iterable)) [1234, 3456, 4398345, 234234, 2396, 23895750, 9283798, 29384, 289375983275, 293759, 2347, 2098, 7987, 27599] """ if isinstance(elem, Iterable) and not isinstance(elem, six.string_types): elem, target = tee(elem, 2) else: target = elem for el in target: if isinstance(el, Iterable) and not isinstance(el, six.string_types): el, el_copy = tee(el, 2) for sub in unnest(el_copy): yield sub else: yield el
[ "def", "unnest", "(", "elem", ")", ":", "if", "isinstance", "(", "elem", ",", "Iterable", ")", "and", "not", "isinstance", "(", "elem", ",", "six", ".", "string_types", ")", ":", "elem", ",", "target", "=", "tee", "(", "elem", ",", "2", ")", "else", ":", "target", "=", "elem", "for", "el", "in", "target", ":", "if", "isinstance", "(", "el", ",", "Iterable", ")", "and", "not", "isinstance", "(", "el", ",", "six", ".", "string_types", ")", ":", "el", ",", "el_copy", "=", "tee", "(", "el", ",", "2", ")", "for", "sub", "in", "unnest", "(", "el_copy", ")", ":", "yield", "sub", "else", ":", "yield", "el" ]
Flatten an arbitrarily nested iterable :param elem: An iterable to flatten :type elem: :class:`~collections.Iterable` >>> nested_iterable = (1234, (3456, 4398345, (234234)), (2396, (23895750, 9283798, 29384, (289375983275, 293759, 2347, (2098, 7987, 27599))))) >>> list(vistir.misc.unnest(nested_iterable)) [1234, 3456, 4398345, 234234, 2396, 23895750, 9283798, 29384, 289375983275, 293759, 2347, 2098, 7987, 27599]
[ "Flatten", "an", "arbitrarily", "nested", "iterable" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/misc.py#L74-L95
train
pypa/pipenv
pipenv/vendor/vistir/misc.py
run
def run( cmd, env=None, return_object=False, block=True, cwd=None, verbose=False, nospin=False, spinner_name=None, combine_stderr=True, display_limit=200, write_to_stdout=True, ): """Use `subprocess.Popen` to get the output of a command and decode it. :param list cmd: A list representing the command you want to run. :param dict env: Additional environment settings to pass through to the subprocess. :param bool return_object: When True, returns the whole subprocess instance :param bool block: When False, returns a potentially still-running :class:`subprocess.Popen` instance :param str cwd: Current working directory contect to use for spawning the subprocess. :param bool verbose: Whether to print stdout in real time when non-blocking. :param bool nospin: Whether to disable the cli spinner. :param str spinner_name: The name of the spinner to use if enabled, defaults to bouncingBar :param bool combine_stderr: Optionally merge stdout and stderr in the subprocess, false if nonblocking. :param int dispay_limit: The max width of output lines to display when using a spinner. :param bool write_to_stdout: Whether to write to stdout when using a spinner, default True. :returns: A 2-tuple of (output, error) or a :class:`subprocess.Popen` object. .. Warning:: Merging standard out and standarad error in a nonblocking subprocess can cause errors in some cases and may not be ideal. Consider disabling this functionality. """ _env = os.environ.copy() if env: _env.update(env) if six.PY2: fs_encode = partial(to_bytes, encoding=locale_encoding) _env = {fs_encode(k): fs_encode(v) for k, v in _env.items()} else: _env = {k: fs_str(v) for k, v in _env.items()} if not spinner_name: spinner_name = "bouncingBar" if six.PY2: if isinstance(cmd, six.string_types): cmd = cmd.encode("utf-8") elif isinstance(cmd, (list, tuple)): cmd = [c.encode("utf-8") for c in cmd] if not isinstance(cmd, Script): cmd = Script.parse(cmd) if block or not return_object: combine_stderr = False start_text = "" with spinner( spinner_name=spinner_name, start_text=start_text, nospin=nospin, write_to_stdout=write_to_stdout, ) as sp: return _create_subprocess( cmd, env=_env, return_object=return_object, block=block, cwd=cwd, verbose=verbose, spinner=sp, combine_stderr=combine_stderr, start_text=start_text, write_to_stdout=True, )
python
def run( cmd, env=None, return_object=False, block=True, cwd=None, verbose=False, nospin=False, spinner_name=None, combine_stderr=True, display_limit=200, write_to_stdout=True, ): """Use `subprocess.Popen` to get the output of a command and decode it. :param list cmd: A list representing the command you want to run. :param dict env: Additional environment settings to pass through to the subprocess. :param bool return_object: When True, returns the whole subprocess instance :param bool block: When False, returns a potentially still-running :class:`subprocess.Popen` instance :param str cwd: Current working directory contect to use for spawning the subprocess. :param bool verbose: Whether to print stdout in real time when non-blocking. :param bool nospin: Whether to disable the cli spinner. :param str spinner_name: The name of the spinner to use if enabled, defaults to bouncingBar :param bool combine_stderr: Optionally merge stdout and stderr in the subprocess, false if nonblocking. :param int dispay_limit: The max width of output lines to display when using a spinner. :param bool write_to_stdout: Whether to write to stdout when using a spinner, default True. :returns: A 2-tuple of (output, error) or a :class:`subprocess.Popen` object. .. Warning:: Merging standard out and standarad error in a nonblocking subprocess can cause errors in some cases and may not be ideal. Consider disabling this functionality. """ _env = os.environ.copy() if env: _env.update(env) if six.PY2: fs_encode = partial(to_bytes, encoding=locale_encoding) _env = {fs_encode(k): fs_encode(v) for k, v in _env.items()} else: _env = {k: fs_str(v) for k, v in _env.items()} if not spinner_name: spinner_name = "bouncingBar" if six.PY2: if isinstance(cmd, six.string_types): cmd = cmd.encode("utf-8") elif isinstance(cmd, (list, tuple)): cmd = [c.encode("utf-8") for c in cmd] if not isinstance(cmd, Script): cmd = Script.parse(cmd) if block or not return_object: combine_stderr = False start_text = "" with spinner( spinner_name=spinner_name, start_text=start_text, nospin=nospin, write_to_stdout=write_to_stdout, ) as sp: return _create_subprocess( cmd, env=_env, return_object=return_object, block=block, cwd=cwd, verbose=verbose, spinner=sp, combine_stderr=combine_stderr, start_text=start_text, write_to_stdout=True, )
[ "def", "run", "(", "cmd", ",", "env", "=", "None", ",", "return_object", "=", "False", ",", "block", "=", "True", ",", "cwd", "=", "None", ",", "verbose", "=", "False", ",", "nospin", "=", "False", ",", "spinner_name", "=", "None", ",", "combine_stderr", "=", "True", ",", "display_limit", "=", "200", ",", "write_to_stdout", "=", "True", ",", ")", ":", "_env", "=", "os", ".", "environ", ".", "copy", "(", ")", "if", "env", ":", "_env", ".", "update", "(", "env", ")", "if", "six", ".", "PY2", ":", "fs_encode", "=", "partial", "(", "to_bytes", ",", "encoding", "=", "locale_encoding", ")", "_env", "=", "{", "fs_encode", "(", "k", ")", ":", "fs_encode", "(", "v", ")", "for", "k", ",", "v", "in", "_env", ".", "items", "(", ")", "}", "else", ":", "_env", "=", "{", "k", ":", "fs_str", "(", "v", ")", "for", "k", ",", "v", "in", "_env", ".", "items", "(", ")", "}", "if", "not", "spinner_name", ":", "spinner_name", "=", "\"bouncingBar\"", "if", "six", ".", "PY2", ":", "if", "isinstance", "(", "cmd", ",", "six", ".", "string_types", ")", ":", "cmd", "=", "cmd", ".", "encode", "(", "\"utf-8\"", ")", "elif", "isinstance", "(", "cmd", ",", "(", "list", ",", "tuple", ")", ")", ":", "cmd", "=", "[", "c", ".", "encode", "(", "\"utf-8\"", ")", "for", "c", "in", "cmd", "]", "if", "not", "isinstance", "(", "cmd", ",", "Script", ")", ":", "cmd", "=", "Script", ".", "parse", "(", "cmd", ")", "if", "block", "or", "not", "return_object", ":", "combine_stderr", "=", "False", "start_text", "=", "\"\"", "with", "spinner", "(", "spinner_name", "=", "spinner_name", ",", "start_text", "=", "start_text", ",", "nospin", "=", "nospin", ",", "write_to_stdout", "=", "write_to_stdout", ",", ")", "as", "sp", ":", "return", "_create_subprocess", "(", "cmd", ",", "env", "=", "_env", ",", "return_object", "=", "return_object", ",", "block", "=", "block", ",", "cwd", "=", "cwd", ",", "verbose", "=", "verbose", ",", "spinner", "=", "sp", ",", "combine_stderr", "=", "combine_stderr", ",", "start_text", "=", "start_text", ",", "write_to_stdout", "=", "True", ",", ")" ]
Use `subprocess.Popen` to get the output of a command and decode it. :param list cmd: A list representing the command you want to run. :param dict env: Additional environment settings to pass through to the subprocess. :param bool return_object: When True, returns the whole subprocess instance :param bool block: When False, returns a potentially still-running :class:`subprocess.Popen` instance :param str cwd: Current working directory contect to use for spawning the subprocess. :param bool verbose: Whether to print stdout in real time when non-blocking. :param bool nospin: Whether to disable the cli spinner. :param str spinner_name: The name of the spinner to use if enabled, defaults to bouncingBar :param bool combine_stderr: Optionally merge stdout and stderr in the subprocess, false if nonblocking. :param int dispay_limit: The max width of output lines to display when using a spinner. :param bool write_to_stdout: Whether to write to stdout when using a spinner, default True. :returns: A 2-tuple of (output, error) or a :class:`subprocess.Popen` object. .. Warning:: Merging standard out and standarad error in a nonblocking subprocess can cause errors in some cases and may not be ideal. Consider disabling this functionality.
[ "Use", "subprocess", ".", "Popen", "to", "get", "the", "output", "of", "a", "command", "and", "decode", "it", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/misc.py#L265-L335
train
pypa/pipenv
pipenv/vendor/vistir/misc.py
load_path
def load_path(python): """Load the :mod:`sys.path` from the given python executable's environment as json :param str python: Path to a valid python executable :return: A python representation of the `sys.path` value of the given python executable. :rtype: list >>> load_path("/home/user/.virtualenvs/requirementslib-5MhGuG3C/bin/python") ['', '/home/user/.virtualenvs/requirementslib-5MhGuG3C/lib/python37.zip', '/home/user/.virtualenvs/requirementslib-5MhGuG3C/lib/python3.7', '/home/user/.virtualenvs/requirementslib-5MhGuG3C/lib/python3.7/lib-dynload', '/home/user/.pyenv/versions/3.7.0/lib/python3.7', '/home/user/.virtualenvs/requirementslib-5MhGuG3C/lib/python3.7/site-packages', '/home/user/git/requirementslib/src'] """ python = Path(python).as_posix() out, err = run( [python, "-c", "import json, sys; print(json.dumps(sys.path))"], nospin=True ) if out: return json.loads(out) else: return []
python
def load_path(python): """Load the :mod:`sys.path` from the given python executable's environment as json :param str python: Path to a valid python executable :return: A python representation of the `sys.path` value of the given python executable. :rtype: list >>> load_path("/home/user/.virtualenvs/requirementslib-5MhGuG3C/bin/python") ['', '/home/user/.virtualenvs/requirementslib-5MhGuG3C/lib/python37.zip', '/home/user/.virtualenvs/requirementslib-5MhGuG3C/lib/python3.7', '/home/user/.virtualenvs/requirementslib-5MhGuG3C/lib/python3.7/lib-dynload', '/home/user/.pyenv/versions/3.7.0/lib/python3.7', '/home/user/.virtualenvs/requirementslib-5MhGuG3C/lib/python3.7/site-packages', '/home/user/git/requirementslib/src'] """ python = Path(python).as_posix() out, err = run( [python, "-c", "import json, sys; print(json.dumps(sys.path))"], nospin=True ) if out: return json.loads(out) else: return []
[ "def", "load_path", "(", "python", ")", ":", "python", "=", "Path", "(", "python", ")", ".", "as_posix", "(", ")", "out", ",", "err", "=", "run", "(", "[", "python", ",", "\"-c\"", ",", "\"import json, sys; print(json.dumps(sys.path))\"", "]", ",", "nospin", "=", "True", ")", "if", "out", ":", "return", "json", ".", "loads", "(", "out", ")", "else", ":", "return", "[", "]" ]
Load the :mod:`sys.path` from the given python executable's environment as json :param str python: Path to a valid python executable :return: A python representation of the `sys.path` value of the given python executable. :rtype: list >>> load_path("/home/user/.virtualenvs/requirementslib-5MhGuG3C/bin/python") ['', '/home/user/.virtualenvs/requirementslib-5MhGuG3C/lib/python37.zip', '/home/user/.virtualenvs/requirementslib-5MhGuG3C/lib/python3.7', '/home/user/.virtualenvs/requirementslib-5MhGuG3C/lib/python3.7/lib-dynload', '/home/user/.pyenv/versions/3.7.0/lib/python3.7', '/home/user/.virtualenvs/requirementslib-5MhGuG3C/lib/python3.7/site-packages', '/home/user/git/requirementslib/src']
[ "Load", "the", ":", "mod", ":", "sys", ".", "path", "from", "the", "given", "python", "executable", "s", "environment", "as", "json" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/misc.py#L338-L356
train
pypa/pipenv
pipenv/vendor/vistir/misc.py
to_bytes
def to_bytes(string, encoding="utf-8", errors="ignore"): """Force a value to bytes. :param string: Some input that can be converted to a bytes. :type string: str or bytes unicode or a memoryview subclass :param encoding: The encoding to use for conversions, defaults to "utf-8" :param encoding: str, optional :return: Corresponding byte representation (for use in filesystem operations) :rtype: bytes """ if not errors: if encoding.lower() == "utf-8": errors = "surrogateescape" if six.PY3 else "ignore" else: errors = "strict" if isinstance(string, bytes): if encoding.lower() == "utf-8": return string else: return string.decode("utf-8").encode(encoding, errors) elif isinstance(string, memoryview): return bytes(string) elif not isinstance(string, six.string_types): try: if six.PY3: return six.text_type(string).encode(encoding, errors) else: return bytes(string) except UnicodeEncodeError: if isinstance(string, Exception): return b" ".join(to_bytes(arg, encoding, errors) for arg in string) return six.text_type(string).encode(encoding, errors) else: return string.encode(encoding, errors)
python
def to_bytes(string, encoding="utf-8", errors="ignore"): """Force a value to bytes. :param string: Some input that can be converted to a bytes. :type string: str or bytes unicode or a memoryview subclass :param encoding: The encoding to use for conversions, defaults to "utf-8" :param encoding: str, optional :return: Corresponding byte representation (for use in filesystem operations) :rtype: bytes """ if not errors: if encoding.lower() == "utf-8": errors = "surrogateescape" if six.PY3 else "ignore" else: errors = "strict" if isinstance(string, bytes): if encoding.lower() == "utf-8": return string else: return string.decode("utf-8").encode(encoding, errors) elif isinstance(string, memoryview): return bytes(string) elif not isinstance(string, six.string_types): try: if six.PY3: return six.text_type(string).encode(encoding, errors) else: return bytes(string) except UnicodeEncodeError: if isinstance(string, Exception): return b" ".join(to_bytes(arg, encoding, errors) for arg in string) return six.text_type(string).encode(encoding, errors) else: return string.encode(encoding, errors)
[ "def", "to_bytes", "(", "string", ",", "encoding", "=", "\"utf-8\"", ",", "errors", "=", "\"ignore\"", ")", ":", "if", "not", "errors", ":", "if", "encoding", ".", "lower", "(", ")", "==", "\"utf-8\"", ":", "errors", "=", "\"surrogateescape\"", "if", "six", ".", "PY3", "else", "\"ignore\"", "else", ":", "errors", "=", "\"strict\"", "if", "isinstance", "(", "string", ",", "bytes", ")", ":", "if", "encoding", ".", "lower", "(", ")", "==", "\"utf-8\"", ":", "return", "string", "else", ":", "return", "string", ".", "decode", "(", "\"utf-8\"", ")", ".", "encode", "(", "encoding", ",", "errors", ")", "elif", "isinstance", "(", "string", ",", "memoryview", ")", ":", "return", "bytes", "(", "string", ")", "elif", "not", "isinstance", "(", "string", ",", "six", ".", "string_types", ")", ":", "try", ":", "if", "six", ".", "PY3", ":", "return", "six", ".", "text_type", "(", "string", ")", ".", "encode", "(", "encoding", ",", "errors", ")", "else", ":", "return", "bytes", "(", "string", ")", "except", "UnicodeEncodeError", ":", "if", "isinstance", "(", "string", ",", "Exception", ")", ":", "return", "b\" \"", ".", "join", "(", "to_bytes", "(", "arg", ",", "encoding", ",", "errors", ")", "for", "arg", "in", "string", ")", "return", "six", ".", "text_type", "(", "string", ")", ".", "encode", "(", "encoding", ",", "errors", ")", "else", ":", "return", "string", ".", "encode", "(", "encoding", ",", "errors", ")" ]
Force a value to bytes. :param string: Some input that can be converted to a bytes. :type string: str or bytes unicode or a memoryview subclass :param encoding: The encoding to use for conversions, defaults to "utf-8" :param encoding: str, optional :return: Corresponding byte representation (for use in filesystem operations) :rtype: bytes
[ "Force", "a", "value", "to", "bytes", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/misc.py#L397-L431
train
pypa/pipenv
pipenv/vendor/vistir/misc.py
to_text
def to_text(string, encoding="utf-8", errors=None): """Force a value to a text-type. :param string: Some input that can be converted to a unicode representation. :type string: str or bytes unicode :param encoding: The encoding to use for conversions, defaults to "utf-8" :param encoding: str, optional :return: The unicode representation of the string :rtype: str """ if not errors: if encoding.lower() == "utf-8": errors = "surrogateescape" if six.PY3 else "ignore" else: errors = "strict" if issubclass(type(string), six.text_type): return string try: if not issubclass(type(string), six.string_types): if six.PY3: if isinstance(string, bytes): string = six.text_type(string, encoding, errors) else: string = six.text_type(string) elif hasattr(string, "__unicode__"): string = six.text_type(string) else: string = six.text_type(bytes(string), encoding, errors) else: string = string.decode(encoding, errors) except UnicodeDecodeError: string = " ".join(to_text(arg, encoding, errors) for arg in string) return string
python
def to_text(string, encoding="utf-8", errors=None): """Force a value to a text-type. :param string: Some input that can be converted to a unicode representation. :type string: str or bytes unicode :param encoding: The encoding to use for conversions, defaults to "utf-8" :param encoding: str, optional :return: The unicode representation of the string :rtype: str """ if not errors: if encoding.lower() == "utf-8": errors = "surrogateescape" if six.PY3 else "ignore" else: errors = "strict" if issubclass(type(string), six.text_type): return string try: if not issubclass(type(string), six.string_types): if six.PY3: if isinstance(string, bytes): string = six.text_type(string, encoding, errors) else: string = six.text_type(string) elif hasattr(string, "__unicode__"): string = six.text_type(string) else: string = six.text_type(bytes(string), encoding, errors) else: string = string.decode(encoding, errors) except UnicodeDecodeError: string = " ".join(to_text(arg, encoding, errors) for arg in string) return string
[ "def", "to_text", "(", "string", ",", "encoding", "=", "\"utf-8\"", ",", "errors", "=", "None", ")", ":", "if", "not", "errors", ":", "if", "encoding", ".", "lower", "(", ")", "==", "\"utf-8\"", ":", "errors", "=", "\"surrogateescape\"", "if", "six", ".", "PY3", "else", "\"ignore\"", "else", ":", "errors", "=", "\"strict\"", "if", "issubclass", "(", "type", "(", "string", ")", ",", "six", ".", "text_type", ")", ":", "return", "string", "try", ":", "if", "not", "issubclass", "(", "type", "(", "string", ")", ",", "six", ".", "string_types", ")", ":", "if", "six", ".", "PY3", ":", "if", "isinstance", "(", "string", ",", "bytes", ")", ":", "string", "=", "six", ".", "text_type", "(", "string", ",", "encoding", ",", "errors", ")", "else", ":", "string", "=", "six", ".", "text_type", "(", "string", ")", "elif", "hasattr", "(", "string", ",", "\"__unicode__\"", ")", ":", "string", "=", "six", ".", "text_type", "(", "string", ")", "else", ":", "string", "=", "six", ".", "text_type", "(", "bytes", "(", "string", ")", ",", "encoding", ",", "errors", ")", "else", ":", "string", "=", "string", ".", "decode", "(", "encoding", ",", "errors", ")", "except", "UnicodeDecodeError", ":", "string", "=", "\" \"", ".", "join", "(", "to_text", "(", "arg", ",", "encoding", ",", "errors", ")", "for", "arg", "in", "string", ")", "return", "string" ]
Force a value to a text-type. :param string: Some input that can be converted to a unicode representation. :type string: str or bytes unicode :param encoding: The encoding to use for conversions, defaults to "utf-8" :param encoding: str, optional :return: The unicode representation of the string :rtype: str
[ "Force", "a", "value", "to", "a", "text", "-", "type", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/misc.py#L434-L467
train
pypa/pipenv
pipenv/vendor/vistir/misc.py
divide
def divide(n, iterable): """ split an iterable into n groups, per https://more-itertools.readthedocs.io/en/latest/api.html#grouping :param int n: Number of unique groups :param iter iterable: An iterable to split up :return: a list of new iterables derived from the original iterable :rtype: list """ seq = tuple(iterable) q, r = divmod(len(seq), n) ret = [] for i in range(n): start = (i * q) + (i if i < r else r) stop = ((i + 1) * q) + (i + 1 if i + 1 < r else r) ret.append(iter(seq[start:stop])) return ret
python
def divide(n, iterable): """ split an iterable into n groups, per https://more-itertools.readthedocs.io/en/latest/api.html#grouping :param int n: Number of unique groups :param iter iterable: An iterable to split up :return: a list of new iterables derived from the original iterable :rtype: list """ seq = tuple(iterable) q, r = divmod(len(seq), n) ret = [] for i in range(n): start = (i * q) + (i if i < r else r) stop = ((i + 1) * q) + (i + 1 if i + 1 < r else r) ret.append(iter(seq[start:stop])) return ret
[ "def", "divide", "(", "n", ",", "iterable", ")", ":", "seq", "=", "tuple", "(", "iterable", ")", "q", ",", "r", "=", "divmod", "(", "len", "(", "seq", ")", ",", "n", ")", "ret", "=", "[", "]", "for", "i", "in", "range", "(", "n", ")", ":", "start", "=", "(", "i", "*", "q", ")", "+", "(", "i", "if", "i", "<", "r", "else", "r", ")", "stop", "=", "(", "(", "i", "+", "1", ")", "*", "q", ")", "+", "(", "i", "+", "1", "if", "i", "+", "1", "<", "r", "else", "r", ")", "ret", ".", "append", "(", "iter", "(", "seq", "[", "start", ":", "stop", "]", ")", ")", "return", "ret" ]
split an iterable into n groups, per https://more-itertools.readthedocs.io/en/latest/api.html#grouping :param int n: Number of unique groups :param iter iterable: An iterable to split up :return: a list of new iterables derived from the original iterable :rtype: list
[ "split", "an", "iterable", "into", "n", "groups", "per", "https", ":", "//", "more", "-", "itertools", ".", "readthedocs", ".", "io", "/", "en", "/", "latest", "/", "api", ".", "html#grouping" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/misc.py#L470-L489
train
pypa/pipenv
pipenv/vendor/vistir/misc.py
getpreferredencoding
def getpreferredencoding(): """Determine the proper output encoding for terminal rendering""" # Borrowed from Invoke # (see https://github.com/pyinvoke/invoke/blob/93af29d/invoke/runners.py#L881) _encoding = locale.getpreferredencoding(False) if six.PY2 and not sys.platform == "win32": _default_encoding = locale.getdefaultlocale()[1] if _default_encoding is not None: _encoding = _default_encoding return _encoding
python
def getpreferredencoding(): """Determine the proper output encoding for terminal rendering""" # Borrowed from Invoke # (see https://github.com/pyinvoke/invoke/blob/93af29d/invoke/runners.py#L881) _encoding = locale.getpreferredencoding(False) if six.PY2 and not sys.platform == "win32": _default_encoding = locale.getdefaultlocale()[1] if _default_encoding is not None: _encoding = _default_encoding return _encoding
[ "def", "getpreferredencoding", "(", ")", ":", "# Borrowed from Invoke", "# (see https://github.com/pyinvoke/invoke/blob/93af29d/invoke/runners.py#L881)", "_encoding", "=", "locale", ".", "getpreferredencoding", "(", "False", ")", "if", "six", ".", "PY2", "and", "not", "sys", ".", "platform", "==", "\"win32\"", ":", "_default_encoding", "=", "locale", ".", "getdefaultlocale", "(", ")", "[", "1", "]", "if", "_default_encoding", "is", "not", "None", ":", "_encoding", "=", "_default_encoding", "return", "_encoding" ]
Determine the proper output encoding for terminal rendering
[ "Determine", "the", "proper", "output", "encoding", "for", "terminal", "rendering" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/misc.py#L522-L532
train
pypa/pipenv
pipenv/vendor/vistir/misc.py
decode_for_output
def decode_for_output(output, target_stream=None, translation_map=None): """Given a string, decode it for output to a terminal :param str output: A string to print to a terminal :param target_stream: A stream to write to, we will encode to target this stream if possible. :param dict translation_map: A mapping of unicode character ordinals to replacement strings. :return: A re-encoded string using the preferred encoding :rtype: str """ if not isinstance(output, six.string_types): return output encoding = None if target_stream is not None: encoding = getattr(target_stream, "encoding", None) encoding = get_output_encoding(encoding) try: output = _encode(output, encoding=encoding, translation_map=translation_map) except (UnicodeDecodeError, UnicodeEncodeError): output = to_native_string(output) output = _encode( output, encoding=encoding, errors="replace", translation_map=translation_map ) return to_text(output, encoding=encoding, errors="replace")
python
def decode_for_output(output, target_stream=None, translation_map=None): """Given a string, decode it for output to a terminal :param str output: A string to print to a terminal :param target_stream: A stream to write to, we will encode to target this stream if possible. :param dict translation_map: A mapping of unicode character ordinals to replacement strings. :return: A re-encoded string using the preferred encoding :rtype: str """ if not isinstance(output, six.string_types): return output encoding = None if target_stream is not None: encoding = getattr(target_stream, "encoding", None) encoding = get_output_encoding(encoding) try: output = _encode(output, encoding=encoding, translation_map=translation_map) except (UnicodeDecodeError, UnicodeEncodeError): output = to_native_string(output) output = _encode( output, encoding=encoding, errors="replace", translation_map=translation_map ) return to_text(output, encoding=encoding, errors="replace")
[ "def", "decode_for_output", "(", "output", ",", "target_stream", "=", "None", ",", "translation_map", "=", "None", ")", ":", "if", "not", "isinstance", "(", "output", ",", "six", ".", "string_types", ")", ":", "return", "output", "encoding", "=", "None", "if", "target_stream", "is", "not", "None", ":", "encoding", "=", "getattr", "(", "target_stream", ",", "\"encoding\"", ",", "None", ")", "encoding", "=", "get_output_encoding", "(", "encoding", ")", "try", ":", "output", "=", "_encode", "(", "output", ",", "encoding", "=", "encoding", ",", "translation_map", "=", "translation_map", ")", "except", "(", "UnicodeDecodeError", ",", "UnicodeEncodeError", ")", ":", "output", "=", "to_native_string", "(", "output", ")", "output", "=", "_encode", "(", "output", ",", "encoding", "=", "encoding", ",", "errors", "=", "\"replace\"", ",", "translation_map", "=", "translation_map", ")", "return", "to_text", "(", "output", ",", "encoding", "=", "encoding", ",", "errors", "=", "\"replace\"", ")" ]
Given a string, decode it for output to a terminal :param str output: A string to print to a terminal :param target_stream: A stream to write to, we will encode to target this stream if possible. :param dict translation_map: A mapping of unicode character ordinals to replacement strings. :return: A re-encoded string using the preferred encoding :rtype: str
[ "Given", "a", "string", "decode", "it", "for", "output", "to", "a", "terminal" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/misc.py#L574-L597
train
pypa/pipenv
pipenv/vendor/vistir/misc.py
get_canonical_encoding_name
def get_canonical_encoding_name(name): # type: (str) -> str """ Given an encoding name, get the canonical name from a codec lookup. :param str name: The name of the codec to lookup :return: The canonical version of the codec name :rtype: str """ import codecs try: codec = codecs.lookup(name) except LookupError: return name else: return codec.name
python
def get_canonical_encoding_name(name): # type: (str) -> str """ Given an encoding name, get the canonical name from a codec lookup. :param str name: The name of the codec to lookup :return: The canonical version of the codec name :rtype: str """ import codecs try: codec = codecs.lookup(name) except LookupError: return name else: return codec.name
[ "def", "get_canonical_encoding_name", "(", "name", ")", ":", "# type: (str) -> str", "import", "codecs", "try", ":", "codec", "=", "codecs", ".", "lookup", "(", "name", ")", "except", "LookupError", ":", "return", "name", "else", ":", "return", "codec", ".", "name" ]
Given an encoding name, get the canonical name from a codec lookup. :param str name: The name of the codec to lookup :return: The canonical version of the codec name :rtype: str
[ "Given", "an", "encoding", "name", "get", "the", "canonical", "name", "from", "a", "codec", "lookup", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/misc.py#L600-L617
train
pypa/pipenv
pipenv/vendor/vistir/misc.py
get_wrapped_stream
def get_wrapped_stream(stream): """ Given a stream, wrap it in a `StreamWrapper` instance and return the wrapped stream. :param stream: A stream instance to wrap :returns: A new, wrapped stream :rtype: :class:`StreamWrapper` """ if stream is None: raise TypeError("must provide a stream to wrap") encoding = getattr(stream, "encoding", None) encoding = get_output_encoding(encoding) return StreamWrapper(stream, encoding, "replace", line_buffering=True)
python
def get_wrapped_stream(stream): """ Given a stream, wrap it in a `StreamWrapper` instance and return the wrapped stream. :param stream: A stream instance to wrap :returns: A new, wrapped stream :rtype: :class:`StreamWrapper` """ if stream is None: raise TypeError("must provide a stream to wrap") encoding = getattr(stream, "encoding", None) encoding = get_output_encoding(encoding) return StreamWrapper(stream, encoding, "replace", line_buffering=True)
[ "def", "get_wrapped_stream", "(", "stream", ")", ":", "if", "stream", "is", "None", ":", "raise", "TypeError", "(", "\"must provide a stream to wrap\"", ")", "encoding", "=", "getattr", "(", "stream", ",", "\"encoding\"", ",", "None", ")", "encoding", "=", "get_output_encoding", "(", "encoding", ")", "return", "StreamWrapper", "(", "stream", ",", "encoding", ",", "\"replace\"", ",", "line_buffering", "=", "True", ")" ]
Given a stream, wrap it in a `StreamWrapper` instance and return the wrapped stream. :param stream: A stream instance to wrap :returns: A new, wrapped stream :rtype: :class:`StreamWrapper`
[ "Given", "a", "stream", "wrap", "it", "in", "a", "StreamWrapper", "instance", "and", "return", "the", "wrapped", "stream", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/misc.py#L620-L633
train
pypa/pipenv
pipenv/vendor/urllib3/util/connection.py
is_connection_dropped
def is_connection_dropped(conn): # Platform-specific """ Returns True if the connection is dropped and should be closed. :param conn: :class:`httplib.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us. """ sock = getattr(conn, 'sock', False) if sock is False: # Platform-specific: AppEngine return False if sock is None: # Connection already closed (such as by httplib). return True try: # Returns True if readable, which here means it's been dropped return wait_for_read(sock, timeout=0.0) except NoWayToWaitForSocketError: # Platform-specific: AppEngine return False
python
def is_connection_dropped(conn): # Platform-specific """ Returns True if the connection is dropped and should be closed. :param conn: :class:`httplib.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us. """ sock = getattr(conn, 'sock', False) if sock is False: # Platform-specific: AppEngine return False if sock is None: # Connection already closed (such as by httplib). return True try: # Returns True if readable, which here means it's been dropped return wait_for_read(sock, timeout=0.0) except NoWayToWaitForSocketError: # Platform-specific: AppEngine return False
[ "def", "is_connection_dropped", "(", "conn", ")", ":", "# Platform-specific", "sock", "=", "getattr", "(", "conn", ",", "'sock'", ",", "False", ")", "if", "sock", "is", "False", ":", "# Platform-specific: AppEngine", "return", "False", "if", "sock", "is", "None", ":", "# Connection already closed (such as by httplib).", "return", "True", "try", ":", "# Returns True if readable, which here means it's been dropped", "return", "wait_for_read", "(", "sock", ",", "timeout", "=", "0.0", ")", "except", "NoWayToWaitForSocketError", ":", "# Platform-specific: AppEngine", "return", "False" ]
Returns True if the connection is dropped and should be closed. :param conn: :class:`httplib.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us.
[ "Returns", "True", "if", "the", "connection", "is", "dropped", "and", "should", "be", "closed", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/connection.py#L7-L26
train
pypa/pipenv
pipenv/vendor/urllib3/util/connection.py
create_connection
def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, socket_options=None): """Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default. """ host, port = address if host.startswith('['): host = host.strip('[]') err = None # Using the value from allowed_gai_family() in the context of getaddrinfo lets # us select whether to work with IPv4 DNS records, IPv6 records, or both. # The original create_connection function always returns all records. family = allowed_gai_family() for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket.socket(af, socktype, proto) # If provided, set socket level options before connecting. _set_socket_options(sock, socket_options) if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(timeout) if source_address: sock.bind(source_address) sock.connect(sa) return sock except socket.error as e: err = e if sock is not None: sock.close() sock = None if err is not None: raise err raise socket.error("getaddrinfo returns an empty list")
python
def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, socket_options=None): """Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default. """ host, port = address if host.startswith('['): host = host.strip('[]') err = None # Using the value from allowed_gai_family() in the context of getaddrinfo lets # us select whether to work with IPv4 DNS records, IPv6 records, or both. # The original create_connection function always returns all records. family = allowed_gai_family() for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket.socket(af, socktype, proto) # If provided, set socket level options before connecting. _set_socket_options(sock, socket_options) if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(timeout) if source_address: sock.bind(source_address) sock.connect(sa) return sock except socket.error as e: err = e if sock is not None: sock.close() sock = None if err is not None: raise err raise socket.error("getaddrinfo returns an empty list")
[ "def", "create_connection", "(", "address", ",", "timeout", "=", "socket", ".", "_GLOBAL_DEFAULT_TIMEOUT", ",", "source_address", "=", "None", ",", "socket_options", "=", "None", ")", ":", "host", ",", "port", "=", "address", "if", "host", ".", "startswith", "(", "'['", ")", ":", "host", "=", "host", ".", "strip", "(", "'[]'", ")", "err", "=", "None", "# Using the value from allowed_gai_family() in the context of getaddrinfo lets", "# us select whether to work with IPv4 DNS records, IPv6 records, or both.", "# The original create_connection function always returns all records.", "family", "=", "allowed_gai_family", "(", ")", "for", "res", "in", "socket", ".", "getaddrinfo", "(", "host", ",", "port", ",", "family", ",", "socket", ".", "SOCK_STREAM", ")", ":", "af", ",", "socktype", ",", "proto", ",", "canonname", ",", "sa", "=", "res", "sock", "=", "None", "try", ":", "sock", "=", "socket", ".", "socket", "(", "af", ",", "socktype", ",", "proto", ")", "# If provided, set socket level options before connecting.", "_set_socket_options", "(", "sock", ",", "socket_options", ")", "if", "timeout", "is", "not", "socket", ".", "_GLOBAL_DEFAULT_TIMEOUT", ":", "sock", ".", "settimeout", "(", "timeout", ")", "if", "source_address", ":", "sock", ".", "bind", "(", "source_address", ")", "sock", ".", "connect", "(", "sa", ")", "return", "sock", "except", "socket", ".", "error", "as", "e", ":", "err", "=", "e", "if", "sock", "is", "not", "None", ":", "sock", ".", "close", "(", ")", "sock", "=", "None", "if", "err", "is", "not", "None", ":", "raise", "err", "raise", "socket", ".", "error", "(", "\"getaddrinfo returns an empty list\"", ")" ]
Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default.
[ "Connect", "to", "*", "address", "*", "and", "return", "the", "socket", "object", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/connection.py#L33-L82
train
pypa/pipenv
pipenv/vendor/urllib3/util/connection.py
_has_ipv6
def _has_ipv6(host): """ Returns True if the system can bind an IPv6 address. """ sock = None has_ipv6 = False # App Engine doesn't support IPV6 sockets and actually has a quota on the # number of sockets that can be used, so just early out here instead of # creating a socket needlessly. # See https://github.com/urllib3/urllib3/issues/1446 if _appengine_environ.is_appengine_sandbox(): return False if socket.has_ipv6: # has_ipv6 returns true if cPython was compiled with IPv6 support. # It does not tell us if the system has IPv6 support enabled. To # determine that we must bind to an IPv6 address. # https://github.com/shazow/urllib3/pull/611 # https://bugs.python.org/issue658327 try: sock = socket.socket(socket.AF_INET6) sock.bind((host, 0)) has_ipv6 = True except Exception: pass if sock: sock.close() return has_ipv6
python
def _has_ipv6(host): """ Returns True if the system can bind an IPv6 address. """ sock = None has_ipv6 = False # App Engine doesn't support IPV6 sockets and actually has a quota on the # number of sockets that can be used, so just early out here instead of # creating a socket needlessly. # See https://github.com/urllib3/urllib3/issues/1446 if _appengine_environ.is_appengine_sandbox(): return False if socket.has_ipv6: # has_ipv6 returns true if cPython was compiled with IPv6 support. # It does not tell us if the system has IPv6 support enabled. To # determine that we must bind to an IPv6 address. # https://github.com/shazow/urllib3/pull/611 # https://bugs.python.org/issue658327 try: sock = socket.socket(socket.AF_INET6) sock.bind((host, 0)) has_ipv6 = True except Exception: pass if sock: sock.close() return has_ipv6
[ "def", "_has_ipv6", "(", "host", ")", ":", "sock", "=", "None", "has_ipv6", "=", "False", "# App Engine doesn't support IPV6 sockets and actually has a quota on the", "# number of sockets that can be used, so just early out here instead of", "# creating a socket needlessly.", "# See https://github.com/urllib3/urllib3/issues/1446", "if", "_appengine_environ", ".", "is_appengine_sandbox", "(", ")", ":", "return", "False", "if", "socket", ".", "has_ipv6", ":", "# has_ipv6 returns true if cPython was compiled with IPv6 support.", "# It does not tell us if the system has IPv6 support enabled. To", "# determine that we must bind to an IPv6 address.", "# https://github.com/shazow/urllib3/pull/611", "# https://bugs.python.org/issue658327", "try", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET6", ")", "sock", ".", "bind", "(", "(", "host", ",", "0", ")", ")", "has_ipv6", "=", "True", "except", "Exception", ":", "pass", "if", "sock", ":", "sock", ".", "close", "(", ")", "return", "has_ipv6" ]
Returns True if the system can bind an IPv6 address.
[ "Returns", "True", "if", "the", "system", "can", "bind", "an", "IPv6", "address", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/connection.py#L104-L131
train
pypa/pipenv
pipenv/vendor/packaging/version.py
_parse_local_version
def _parse_local_version(local): """ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve"). """ if local is not None: return tuple( part.lower() if not part.isdigit() else int(part) for part in _local_version_separators.split(local) )
python
def _parse_local_version(local): """ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve"). """ if local is not None: return tuple( part.lower() if not part.isdigit() else int(part) for part in _local_version_separators.split(local) )
[ "def", "_parse_local_version", "(", "local", ")", ":", "if", "local", "is", "not", "None", ":", "return", "tuple", "(", "part", ".", "lower", "(", ")", "if", "not", "part", ".", "isdigit", "(", ")", "else", "int", "(", "part", ")", "for", "part", "in", "_local_version_separators", ".", "split", "(", "local", ")", ")" ]
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
[ "Takes", "a", "string", "like", "abc", ".", "1", ".", "twelve", "and", "turns", "it", "into", "(", "abc", "1", "twelve", ")", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/packaging/version.py#L367-L375
train
pypa/pipenv
pipenv/vendor/requests/_internal_utils.py
unicode_is_ascii
def unicode_is_ascii(u_string): """Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool """ assert isinstance(u_string, str) try: u_string.encode('ascii') return True except UnicodeEncodeError: return False
python
def unicode_is_ascii(u_string): """Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool """ assert isinstance(u_string, str) try: u_string.encode('ascii') return True except UnicodeEncodeError: return False
[ "def", "unicode_is_ascii", "(", "u_string", ")", ":", "assert", "isinstance", "(", "u_string", ",", "str", ")", "try", ":", "u_string", ".", "encode", "(", "'ascii'", ")", "return", "True", "except", "UnicodeEncodeError", ":", "return", "False" ]
Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool
[ "Determine", "if", "unicode", "string", "only", "contains", "ASCII", "characters", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/_internal_utils.py#L30-L42
train
pypa/pipenv
pipenv/patched/notpip/_internal/cli/cmdoptions.py
raise_option_error
def raise_option_error(parser, option, msg): """ Raise an option parsing error using parser.error(). Args: parser: an OptionParser instance. option: an Option instance. msg: the error text. """ msg = '{} error: {}'.format(option, msg) msg = textwrap.fill(' '.join(msg.split())) parser.error(msg)
python
def raise_option_error(parser, option, msg): """ Raise an option parsing error using parser.error(). Args: parser: an OptionParser instance. option: an Option instance. msg: the error text. """ msg = '{} error: {}'.format(option, msg) msg = textwrap.fill(' '.join(msg.split())) parser.error(msg)
[ "def", "raise_option_error", "(", "parser", ",", "option", ",", "msg", ")", ":", "msg", "=", "'{} error: {}'", ".", "format", "(", "option", ",", "msg", ")", "msg", "=", "textwrap", ".", "fill", "(", "' '", ".", "join", "(", "msg", ".", "split", "(", ")", ")", ")", "parser", ".", "error", "(", "msg", ")" ]
Raise an option parsing error using parser.error(). Args: parser: an OptionParser instance. option: an Option instance. msg: the error text.
[ "Raise", "an", "option", "parsing", "error", "using", "parser", ".", "error", "()", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L32-L43
train
pypa/pipenv
pipenv/patched/notpip/_internal/cli/cmdoptions.py
make_option_group
def make_option_group(group, parser): # type: (Dict[str, Any], ConfigOptionParser) -> OptionGroup """ Return an OptionGroup object group -- assumed to be dict with 'name' and 'options' keys parser -- an optparse Parser """ option_group = OptionGroup(parser, group['name']) for option in group['options']: option_group.add_option(option()) return option_group
python
def make_option_group(group, parser): # type: (Dict[str, Any], ConfigOptionParser) -> OptionGroup """ Return an OptionGroup object group -- assumed to be dict with 'name' and 'options' keys parser -- an optparse Parser """ option_group = OptionGroup(parser, group['name']) for option in group['options']: option_group.add_option(option()) return option_group
[ "def", "make_option_group", "(", "group", ",", "parser", ")", ":", "# type: (Dict[str, Any], ConfigOptionParser) -> OptionGroup", "option_group", "=", "OptionGroup", "(", "parser", ",", "group", "[", "'name'", "]", ")", "for", "option", "in", "group", "[", "'options'", "]", ":", "option_group", ".", "add_option", "(", "option", "(", ")", ")", "return", "option_group" ]
Return an OptionGroup object group -- assumed to be dict with 'name' and 'options' keys parser -- an optparse Parser
[ "Return", "an", "OptionGroup", "object", "group", "--", "assumed", "to", "be", "dict", "with", "name", "and", "options", "keys", "parser", "--", "an", "optparse", "Parser" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L46-L56
train
pypa/pipenv
pipenv/patched/notpip/_internal/cli/cmdoptions.py
check_install_build_global
def check_install_build_global(options, check_options=None): # type: (Values, Optional[Values]) -> None """Disable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options. """ if check_options is None: check_options = options def getname(n): return getattr(check_options, n, None) names = ["build_options", "global_options", "install_options"] if any(map(getname, names)): control = options.format_control control.disallow_binaries() warnings.warn( 'Disabling all use of wheels due to the use of --build-options ' '/ --global-options / --install-options.', stacklevel=2, )
python
def check_install_build_global(options, check_options=None): # type: (Values, Optional[Values]) -> None """Disable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options. """ if check_options is None: check_options = options def getname(n): return getattr(check_options, n, None) names = ["build_options", "global_options", "install_options"] if any(map(getname, names)): control = options.format_control control.disallow_binaries() warnings.warn( 'Disabling all use of wheels due to the use of --build-options ' '/ --global-options / --install-options.', stacklevel=2, )
[ "def", "check_install_build_global", "(", "options", ",", "check_options", "=", "None", ")", ":", "# type: (Values, Optional[Values]) -> None", "if", "check_options", "is", "None", ":", "check_options", "=", "options", "def", "getname", "(", "n", ")", ":", "return", "getattr", "(", "check_options", ",", "n", ",", "None", ")", "names", "=", "[", "\"build_options\"", ",", "\"global_options\"", ",", "\"install_options\"", "]", "if", "any", "(", "map", "(", "getname", ",", "names", ")", ")", ":", "control", "=", "options", ".", "format_control", "control", ".", "disallow_binaries", "(", ")", "warnings", ".", "warn", "(", "'Disabling all use of wheels due to the use of --build-options '", "'/ --global-options / --install-options.'", ",", "stacklevel", "=", "2", ",", ")" ]
Disable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options.
[ "Disable", "wheels", "if", "per", "-", "setup", ".", "py", "call", "options", "are", "set", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L59-L79
train
pypa/pipenv
pipenv/patched/notpip/_internal/cli/cmdoptions.py
check_dist_restriction
def check_dist_restriction(options, check_target=False): # type: (Values, bool) -> None """Function for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used. """ dist_restriction_set = any([ options.python_version, options.platform, options.abi, options.implementation, ]) binary_only = FormatControl(set(), {':all:'}) sdist_dependencies_allowed = ( options.format_control != binary_only and not options.ignore_dependencies ) # Installations or downloads using dist restrictions must not combine # source distributions and dist-specific wheels, as they are not # gauranteed to be locally compatible. if dist_restriction_set and sdist_dependencies_allowed: raise CommandError( "When restricting platform and interpreter constraints using " "--python-version, --platform, --abi, or --implementation, " "either --no-deps must be set, or --only-binary=:all: must be " "set and --no-binary must not be set (or must be set to " ":none:)." ) if check_target: if dist_restriction_set and not options.target_dir: raise CommandError( "Can not use any platform or abi specific options unless " "installing via '--target'" )
python
def check_dist_restriction(options, check_target=False): # type: (Values, bool) -> None """Function for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used. """ dist_restriction_set = any([ options.python_version, options.platform, options.abi, options.implementation, ]) binary_only = FormatControl(set(), {':all:'}) sdist_dependencies_allowed = ( options.format_control != binary_only and not options.ignore_dependencies ) # Installations or downloads using dist restrictions must not combine # source distributions and dist-specific wheels, as they are not # gauranteed to be locally compatible. if dist_restriction_set and sdist_dependencies_allowed: raise CommandError( "When restricting platform and interpreter constraints using " "--python-version, --platform, --abi, or --implementation, " "either --no-deps must be set, or --only-binary=:all: must be " "set and --no-binary must not be set (or must be set to " ":none:)." ) if check_target: if dist_restriction_set and not options.target_dir: raise CommandError( "Can not use any platform or abi specific options unless " "installing via '--target'" )
[ "def", "check_dist_restriction", "(", "options", ",", "check_target", "=", "False", ")", ":", "# type: (Values, bool) -> None", "dist_restriction_set", "=", "any", "(", "[", "options", ".", "python_version", ",", "options", ".", "platform", ",", "options", ".", "abi", ",", "options", ".", "implementation", ",", "]", ")", "binary_only", "=", "FormatControl", "(", "set", "(", ")", ",", "{", "':all:'", "}", ")", "sdist_dependencies_allowed", "=", "(", "options", ".", "format_control", "!=", "binary_only", "and", "not", "options", ".", "ignore_dependencies", ")", "# Installations or downloads using dist restrictions must not combine", "# source distributions and dist-specific wheels, as they are not", "# gauranteed to be locally compatible.", "if", "dist_restriction_set", "and", "sdist_dependencies_allowed", ":", "raise", "CommandError", "(", "\"When restricting platform and interpreter constraints using \"", "\"--python-version, --platform, --abi, or --implementation, \"", "\"either --no-deps must be set, or --only-binary=:all: must be \"", "\"set and --no-binary must not be set (or must be set to \"", "\":none:).\"", ")", "if", "check_target", ":", "if", "dist_restriction_set", "and", "not", "options", ".", "target_dir", ":", "raise", "CommandError", "(", "\"Can not use any platform or abi specific options unless \"", "\"installing via '--target'\"", ")" ]
Function for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used.
[ "Function", "for", "determining", "if", "custom", "platform", "options", "are", "allowed", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L82-L119
train
pypa/pipenv
pipenv/patched/notpip/_internal/cli/cmdoptions.py
no_cache_dir_callback
def no_cache_dir_callback(option, opt, value, parser): """ Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir option. """ # The value argument will be None if --no-cache-dir is passed via the # command-line, since the option doesn't accept arguments. However, # the value can be non-None if the option is triggered e.g. by an # environment variable, like PIP_NO_CACHE_DIR=true. if value is not None: # Then parse the string value to get argument error-checking. try: strtobool(value) except ValueError as exc: raise_option_error(parser, option=option, msg=str(exc)) # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool() # converted to 0 (like "false" or "no") caused cache_dir to be disabled # rather than enabled (logic would say the latter). Thus, we disable # the cache directory not just on values that parse to True, but (for # backwards compatibility reasons) also on values that parse to False. # In other words, always set it to False if the option is provided in # some (valid) form. parser.values.cache_dir = False
python
def no_cache_dir_callback(option, opt, value, parser): """ Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir option. """ # The value argument will be None if --no-cache-dir is passed via the # command-line, since the option doesn't accept arguments. However, # the value can be non-None if the option is triggered e.g. by an # environment variable, like PIP_NO_CACHE_DIR=true. if value is not None: # Then parse the string value to get argument error-checking. try: strtobool(value) except ValueError as exc: raise_option_error(parser, option=option, msg=str(exc)) # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool() # converted to 0 (like "false" or "no") caused cache_dir to be disabled # rather than enabled (logic would say the latter). Thus, we disable # the cache directory not just on values that parse to True, but (for # backwards compatibility reasons) also on values that parse to False. # In other words, always set it to False if the option is provided in # some (valid) form. parser.values.cache_dir = False
[ "def", "no_cache_dir_callback", "(", "option", ",", "opt", ",", "value", ",", "parser", ")", ":", "# The value argument will be None if --no-cache-dir is passed via the", "# command-line, since the option doesn't accept arguments. However,", "# the value can be non-None if the option is triggered e.g. by an", "# environment variable, like PIP_NO_CACHE_DIR=true.", "if", "value", "is", "not", "None", ":", "# Then parse the string value to get argument error-checking.", "try", ":", "strtobool", "(", "value", ")", "except", "ValueError", "as", "exc", ":", "raise_option_error", "(", "parser", ",", "option", "=", "option", ",", "msg", "=", "str", "(", "exc", ")", ")", "# Originally, setting PIP_NO_CACHE_DIR to a value that strtobool()", "# converted to 0 (like \"false\" or \"no\") caused cache_dir to be disabled", "# rather than enabled (logic would say the latter). Thus, we disable", "# the cache directory not just on values that parse to True, but (for", "# backwards compatibility reasons) also on values that parse to False.", "# In other words, always set it to False if the option is provided in", "# some (valid) form.", "parser", ".", "values", ".", "cache_dir", "=", "False" ]
Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir option.
[ "Process", "a", "value", "provided", "for", "the", "--", "no", "-", "cache", "-", "dir", "option", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L546-L570
train
pypa/pipenv
pipenv/patched/notpip/_internal/cli/cmdoptions.py
no_use_pep517_callback
def no_use_pep517_callback(option, opt, value, parser): """ Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option. """ # Since --no-use-pep517 doesn't accept arguments, the value argument # will be None if --no-use-pep517 is passed via the command-line. # However, the value can be non-None if the option is triggered e.g. # by an environment variable, for example "PIP_NO_USE_PEP517=true". if value is not None: msg = """A value was passed for --no-use-pep517, probably using either the PIP_NO_USE_PEP517 environment variable or the "no-use-pep517" config file option. Use an appropriate value of the PIP_USE_PEP517 environment variable or the "use-pep517" config file option instead. """ raise_option_error(parser, option=option, msg=msg) # Otherwise, --no-use-pep517 was passed via the command-line. parser.values.use_pep517 = False
python
def no_use_pep517_callback(option, opt, value, parser): """ Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option. """ # Since --no-use-pep517 doesn't accept arguments, the value argument # will be None if --no-use-pep517 is passed via the command-line. # However, the value can be non-None if the option is triggered e.g. # by an environment variable, for example "PIP_NO_USE_PEP517=true". if value is not None: msg = """A value was passed for --no-use-pep517, probably using either the PIP_NO_USE_PEP517 environment variable or the "no-use-pep517" config file option. Use an appropriate value of the PIP_USE_PEP517 environment variable or the "use-pep517" config file option instead. """ raise_option_error(parser, option=option, msg=msg) # Otherwise, --no-use-pep517 was passed via the command-line. parser.values.use_pep517 = False
[ "def", "no_use_pep517_callback", "(", "option", ",", "opt", ",", "value", ",", "parser", ")", ":", "# Since --no-use-pep517 doesn't accept arguments, the value argument", "# will be None if --no-use-pep517 is passed via the command-line.", "# However, the value can be non-None if the option is triggered e.g.", "# by an environment variable, for example \"PIP_NO_USE_PEP517=true\".", "if", "value", "is", "not", "None", ":", "msg", "=", "\"\"\"A value was passed for --no-use-pep517,\n probably using either the PIP_NO_USE_PEP517 environment variable\n or the \"no-use-pep517\" config file option. Use an appropriate value\n of the PIP_USE_PEP517 environment variable or the \"use-pep517\"\n config file option instead.\n \"\"\"", "raise_option_error", "(", "parser", ",", "option", "=", "option", ",", "msg", "=", "msg", ")", "# Otherwise, --no-use-pep517 was passed via the command-line.", "parser", ".", "values", ".", "use_pep517", "=", "False" ]
Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option.
[ "Process", "a", "value", "provided", "for", "the", "--", "no", "-", "use", "-", "pep517", "option", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L623-L643
train
pypa/pipenv
pipenv/patched/notpip/_internal/cli/cmdoptions.py
_merge_hash
def _merge_hash(option, opt_str, value, parser): # type: (Option, str, str, OptionParser) -> None """Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.""" if not parser.values.hashes: parser.values.hashes = {} # type: ignore try: algo, digest = value.split(':', 1) except ValueError: parser.error('Arguments to %s must be a hash name ' 'followed by a value, like --hash=sha256:abcde...' % opt_str) if algo not in STRONG_HASHES: parser.error('Allowed hash algorithms for %s are %s.' % (opt_str, ', '.join(STRONG_HASHES))) parser.values.hashes.setdefault(algo, []).append(digest)
python
def _merge_hash(option, opt_str, value, parser): # type: (Option, str, str, OptionParser) -> None """Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.""" if not parser.values.hashes: parser.values.hashes = {} # type: ignore try: algo, digest = value.split(':', 1) except ValueError: parser.error('Arguments to %s must be a hash name ' 'followed by a value, like --hash=sha256:abcde...' % opt_str) if algo not in STRONG_HASHES: parser.error('Allowed hash algorithms for %s are %s.' % (opt_str, ', '.join(STRONG_HASHES))) parser.values.hashes.setdefault(algo, []).append(digest)
[ "def", "_merge_hash", "(", "option", ",", "opt_str", ",", "value", ",", "parser", ")", ":", "# type: (Option, str, str, OptionParser) -> None", "if", "not", "parser", ".", "values", ".", "hashes", ":", "parser", ".", "values", ".", "hashes", "=", "{", "}", "# type: ignore", "try", ":", "algo", ",", "digest", "=", "value", ".", "split", "(", "':'", ",", "1", ")", "except", "ValueError", ":", "parser", ".", "error", "(", "'Arguments to %s must be a hash name '", "'followed by a value, like --hash=sha256:abcde...'", "%", "opt_str", ")", "if", "algo", "not", "in", "STRONG_HASHES", ":", "parser", ".", "error", "(", "'Allowed hash algorithms for %s are %s.'", "%", "(", "opt_str", ",", "', '", ".", "join", "(", "STRONG_HASHES", ")", ")", ")", "parser", ".", "values", ".", "hashes", ".", "setdefault", "(", "algo", ",", "[", "]", ")", ".", "append", "(", "digest", ")" ]
Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.
[ "Given", "a", "value", "spelled", "algo", ":", "digest", "append", "the", "digest", "to", "a", "list", "pointed", "to", "in", "a", "dict", "by", "the", "algo", "name", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L727-L742
train
pypa/pipenv
pipenv/vendor/requirementslib/models/pipfile.py
PipfileLoader.populate_source
def populate_source(cls, source): """Derive missing values of source from the existing fields.""" # Only URL pararemter is mandatory, let the KeyError be thrown. if "name" not in source: source["name"] = get_url_name(source["url"]) if "verify_ssl" not in source: source["verify_ssl"] = "https://" in source["url"] if not isinstance(source["verify_ssl"], bool): source["verify_ssl"] = source["verify_ssl"].lower() == "true" return source
python
def populate_source(cls, source): """Derive missing values of source from the existing fields.""" # Only URL pararemter is mandatory, let the KeyError be thrown. if "name" not in source: source["name"] = get_url_name(source["url"]) if "verify_ssl" not in source: source["verify_ssl"] = "https://" in source["url"] if not isinstance(source["verify_ssl"], bool): source["verify_ssl"] = source["verify_ssl"].lower() == "true" return source
[ "def", "populate_source", "(", "cls", ",", "source", ")", ":", "# Only URL pararemter is mandatory, let the KeyError be thrown.", "if", "\"name\"", "not", "in", "source", ":", "source", "[", "\"name\"", "]", "=", "get_url_name", "(", "source", "[", "\"url\"", "]", ")", "if", "\"verify_ssl\"", "not", "in", "source", ":", "source", "[", "\"verify_ssl\"", "]", "=", "\"https://\"", "in", "source", "[", "\"url\"", "]", "if", "not", "isinstance", "(", "source", "[", "\"verify_ssl\"", "]", ",", "bool", ")", ":", "source", "[", "\"verify_ssl\"", "]", "=", "source", "[", "\"verify_ssl\"", "]", ".", "lower", "(", ")", "==", "\"true\"", "return", "source" ]
Derive missing values of source from the existing fields.
[ "Derive", "missing", "values", "of", "source", "from", "the", "existing", "fields", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/pipfile.py#L111-L120
train
pypa/pipenv
pipenv/vendor/passa/internals/utils.py
get_pinned_version
def get_pinned_version(ireq): """Get the pinned version of an InstallRequirement. An InstallRequirement is considered pinned if: - Is not editable - It has exactly one specifier - That specifier is "==" - The version does not contain a wildcard Examples: django==1.8 # pinned django>1.8 # NOT pinned django~=1.8 # NOT pinned django==1.* # NOT pinned Raises `TypeError` if the input is not a valid InstallRequirement, or `ValueError` if the InstallRequirement is not pinned. """ try: specifier = ireq.specifier except AttributeError: raise TypeError("Expected InstallRequirement, not {}".format( type(ireq).__name__, )) if ireq.editable: raise ValueError("InstallRequirement is editable") if not specifier: raise ValueError("InstallRequirement has no version specification") if len(specifier._specs) != 1: raise ValueError("InstallRequirement has multiple specifications") op, version = next(iter(specifier._specs))._spec if op not in ('==', '===') or version.endswith('.*'): raise ValueError("InstallRequirement not pinned (is {0!r})".format( op + version, )) return version
python
def get_pinned_version(ireq): """Get the pinned version of an InstallRequirement. An InstallRequirement is considered pinned if: - Is not editable - It has exactly one specifier - That specifier is "==" - The version does not contain a wildcard Examples: django==1.8 # pinned django>1.8 # NOT pinned django~=1.8 # NOT pinned django==1.* # NOT pinned Raises `TypeError` if the input is not a valid InstallRequirement, or `ValueError` if the InstallRequirement is not pinned. """ try: specifier = ireq.specifier except AttributeError: raise TypeError("Expected InstallRequirement, not {}".format( type(ireq).__name__, )) if ireq.editable: raise ValueError("InstallRequirement is editable") if not specifier: raise ValueError("InstallRequirement has no version specification") if len(specifier._specs) != 1: raise ValueError("InstallRequirement has multiple specifications") op, version = next(iter(specifier._specs))._spec if op not in ('==', '===') or version.endswith('.*'): raise ValueError("InstallRequirement not pinned (is {0!r})".format( op + version, )) return version
[ "def", "get_pinned_version", "(", "ireq", ")", ":", "try", ":", "specifier", "=", "ireq", ".", "specifier", "except", "AttributeError", ":", "raise", "TypeError", "(", "\"Expected InstallRequirement, not {}\"", ".", "format", "(", "type", "(", "ireq", ")", ".", "__name__", ",", ")", ")", "if", "ireq", ".", "editable", ":", "raise", "ValueError", "(", "\"InstallRequirement is editable\"", ")", "if", "not", "specifier", ":", "raise", "ValueError", "(", "\"InstallRequirement has no version specification\"", ")", "if", "len", "(", "specifier", ".", "_specs", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"InstallRequirement has multiple specifications\"", ")", "op", ",", "version", "=", "next", "(", "iter", "(", "specifier", ".", "_specs", ")", ")", ".", "_spec", "if", "op", "not", "in", "(", "'=='", ",", "'==='", ")", "or", "version", ".", "endswith", "(", "'.*'", ")", ":", "raise", "ValueError", "(", "\"InstallRequirement not pinned (is {0!r})\"", ".", "format", "(", "op", "+", "version", ",", ")", ")", "return", "version" ]
Get the pinned version of an InstallRequirement. An InstallRequirement is considered pinned if: - Is not editable - It has exactly one specifier - That specifier is "==" - The version does not contain a wildcard Examples: django==1.8 # pinned django>1.8 # NOT pinned django~=1.8 # NOT pinned django==1.* # NOT pinned Raises `TypeError` if the input is not a valid InstallRequirement, or `ValueError` if the InstallRequirement is not pinned.
[ "Get", "the", "pinned", "version", "of", "an", "InstallRequirement", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/utils.py#L20-L59
train
pypa/pipenv
pipenv/vendor/passa/internals/utils.py
strip_extras
def strip_extras(requirement): """Returns a new requirement object with extras removed. """ line = requirement.as_line() new = type(requirement).from_line(line) new.extras = None return new
python
def strip_extras(requirement): """Returns a new requirement object with extras removed. """ line = requirement.as_line() new = type(requirement).from_line(line) new.extras = None return new
[ "def", "strip_extras", "(", "requirement", ")", ":", "line", "=", "requirement", ".", "as_line", "(", ")", "new", "=", "type", "(", "requirement", ")", ".", "from_line", "(", "line", ")", "new", ".", "extras", "=", "None", "return", "new" ]
Returns a new requirement object with extras removed.
[ "Returns", "a", "new", "requirement", "object", "with", "extras", "removed", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/utils.py#L112-L118
train
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
_subst_vars
def _subst_vars(path, local_vars): """In the string `path`, replace tokens like {some.thing} with the corresponding value from the map `local_vars`. If there is no corresponding value, leave the token unchanged. """ def _replacer(matchobj): name = matchobj.group(1) if name in local_vars: return local_vars[name] elif name in os.environ: return os.environ[name] return matchobj.group(0) return _VAR_REPL.sub(_replacer, path)
python
def _subst_vars(path, local_vars): """In the string `path`, replace tokens like {some.thing} with the corresponding value from the map `local_vars`. If there is no corresponding value, leave the token unchanged. """ def _replacer(matchobj): name = matchobj.group(1) if name in local_vars: return local_vars[name] elif name in os.environ: return os.environ[name] return matchobj.group(0) return _VAR_REPL.sub(_replacer, path)
[ "def", "_subst_vars", "(", "path", ",", "local_vars", ")", ":", "def", "_replacer", "(", "matchobj", ")", ":", "name", "=", "matchobj", ".", "group", "(", "1", ")", "if", "name", "in", "local_vars", ":", "return", "local_vars", "[", "name", "]", "elif", "name", "in", "os", ".", "environ", ":", "return", "os", ".", "environ", "[", "name", "]", "return", "matchobj", ".", "group", "(", "0", ")", "return", "_VAR_REPL", ".", "sub", "(", "_replacer", ",", "path", ")" ]
In the string `path`, replace tokens like {some.thing} with the corresponding value from the map `local_vars`. If there is no corresponding value, leave the token unchanged.
[ "In", "the", "string", "path", "replace", "tokens", "like", "{", "some", ".", "thing", "}", "with", "the", "corresponding", "value", "from", "the", "map", "local_vars", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L133-L146
train
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
get_makefile_filename
def get_makefile_filename(): """Return the path of the Makefile.""" if _PYTHON_BUILD: return os.path.join(_PROJECT_BASE, "Makefile") if hasattr(sys, 'abiflags'): config_dir_name = 'config-%s%s' % (_PY_VERSION_SHORT, sys.abiflags) else: config_dir_name = 'config' return os.path.join(get_path('stdlib'), config_dir_name, 'Makefile')
python
def get_makefile_filename(): """Return the path of the Makefile.""" if _PYTHON_BUILD: return os.path.join(_PROJECT_BASE, "Makefile") if hasattr(sys, 'abiflags'): config_dir_name = 'config-%s%s' % (_PY_VERSION_SHORT, sys.abiflags) else: config_dir_name = 'config' return os.path.join(get_path('stdlib'), config_dir_name, 'Makefile')
[ "def", "get_makefile_filename", "(", ")", ":", "if", "_PYTHON_BUILD", ":", "return", "os", ".", "path", ".", "join", "(", "_PROJECT_BASE", ",", "\"Makefile\"", ")", "if", "hasattr", "(", "sys", ",", "'abiflags'", ")", ":", "config_dir_name", "=", "'config-%s%s'", "%", "(", "_PY_VERSION_SHORT", ",", "sys", ".", "abiflags", ")", "else", ":", "config_dir_name", "=", "'config'", "return", "os", ".", "path", ".", "join", "(", "get_path", "(", "'stdlib'", ")", ",", "config_dir_name", ",", "'Makefile'", ")" ]
Return the path of the Makefile.
[ "Return", "the", "path", "of", "the", "Makefile", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L333-L341
train
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
_init_posix
def _init_posix(vars): """Initialize the module as appropriate for POSIX systems.""" # load the installed Makefile: makefile = get_makefile_filename() try: _parse_makefile(makefile, vars) except IOError as e: msg = "invalid Python installation: unable to open %s" % makefile if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # load the installed pyconfig.h: config_h = get_config_h_filename() try: with open(config_h) as f: parse_config_h(f, vars) except IOError as e: msg = "invalid Python installation: unable to open %s" % config_h if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # On AIX, there are wrong paths to the linker scripts in the Makefile # -- these paths are relative to the Python source, but when installed # the scripts are in another directory. if _PYTHON_BUILD: vars['LDSHARED'] = vars['BLDSHARED']
python
def _init_posix(vars): """Initialize the module as appropriate for POSIX systems.""" # load the installed Makefile: makefile = get_makefile_filename() try: _parse_makefile(makefile, vars) except IOError as e: msg = "invalid Python installation: unable to open %s" % makefile if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # load the installed pyconfig.h: config_h = get_config_h_filename() try: with open(config_h) as f: parse_config_h(f, vars) except IOError as e: msg = "invalid Python installation: unable to open %s" % config_h if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # On AIX, there are wrong paths to the linker scripts in the Makefile # -- these paths are relative to the Python source, but when installed # the scripts are in another directory. if _PYTHON_BUILD: vars['LDSHARED'] = vars['BLDSHARED']
[ "def", "_init_posix", "(", "vars", ")", ":", "# load the installed Makefile:", "makefile", "=", "get_makefile_filename", "(", ")", "try", ":", "_parse_makefile", "(", "makefile", ",", "vars", ")", "except", "IOError", "as", "e", ":", "msg", "=", "\"invalid Python installation: unable to open %s\"", "%", "makefile", "if", "hasattr", "(", "e", ",", "\"strerror\"", ")", ":", "msg", "=", "msg", "+", "\" (%s)\"", "%", "e", ".", "strerror", "raise", "IOError", "(", "msg", ")", "# load the installed pyconfig.h:", "config_h", "=", "get_config_h_filename", "(", ")", "try", ":", "with", "open", "(", "config_h", ")", "as", "f", ":", "parse_config_h", "(", "f", ",", "vars", ")", "except", "IOError", "as", "e", ":", "msg", "=", "\"invalid Python installation: unable to open %s\"", "%", "config_h", "if", "hasattr", "(", "e", ",", "\"strerror\"", ")", ":", "msg", "=", "msg", "+", "\" (%s)\"", "%", "e", ".", "strerror", "raise", "IOError", "(", "msg", ")", "# On AIX, there are wrong paths to the linker scripts in the Makefile", "# -- these paths are relative to the Python source, but when installed", "# the scripts are in another directory.", "if", "_PYTHON_BUILD", ":", "vars", "[", "'LDSHARED'", "]", "=", "vars", "[", "'BLDSHARED'", "]" ]
Initialize the module as appropriate for POSIX systems.
[ "Initialize", "the", "module", "as", "appropriate", "for", "POSIX", "systems", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L344-L369
train
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
_init_non_posix
def _init_non_posix(vars): """Initialize the module as appropriate for NT""" # set basic install directories vars['LIBDEST'] = get_path('stdlib') vars['BINLIBDEST'] = get_path('platstdlib') vars['INCLUDEPY'] = get_path('include') vars['SO'] = '.pyd' vars['EXE'] = '.exe' vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
python
def _init_non_posix(vars): """Initialize the module as appropriate for NT""" # set basic install directories vars['LIBDEST'] = get_path('stdlib') vars['BINLIBDEST'] = get_path('platstdlib') vars['INCLUDEPY'] = get_path('include') vars['SO'] = '.pyd' vars['EXE'] = '.exe' vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
[ "def", "_init_non_posix", "(", "vars", ")", ":", "# set basic install directories", "vars", "[", "'LIBDEST'", "]", "=", "get_path", "(", "'stdlib'", ")", "vars", "[", "'BINLIBDEST'", "]", "=", "get_path", "(", "'platstdlib'", ")", "vars", "[", "'INCLUDEPY'", "]", "=", "get_path", "(", "'include'", ")", "vars", "[", "'SO'", "]", "=", "'.pyd'", "vars", "[", "'EXE'", "]", "=", "'.exe'", "vars", "[", "'VERSION'", "]", "=", "_PY_VERSION_SHORT_NO_DOT", "vars", "[", "'BINDIR'", "]", "=", "os", ".", "path", ".", "dirname", "(", "_safe_realpath", "(", "sys", ".", "executable", ")", ")" ]
Initialize the module as appropriate for NT
[ "Initialize", "the", "module", "as", "appropriate", "for", "NT" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L372-L381
train
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
parse_config_h
def parse_config_h(fp, vars=None): """Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ if vars is None: vars = {} define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n") undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n") while True: line = fp.readline() if not line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = int(v) except ValueError: pass vars[n] = v else: m = undef_rx.match(line) if m: vars[m.group(1)] = 0 return vars
python
def parse_config_h(fp, vars=None): """Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ if vars is None: vars = {} define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n") undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n") while True: line = fp.readline() if not line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = int(v) except ValueError: pass vars[n] = v else: m = undef_rx.match(line) if m: vars[m.group(1)] = 0 return vars
[ "def", "parse_config_h", "(", "fp", ",", "vars", "=", "None", ")", ":", "if", "vars", "is", "None", ":", "vars", "=", "{", "}", "define_rx", "=", "re", ".", "compile", "(", "\"#define ([A-Z][A-Za-z0-9_]+) (.*)\\n\"", ")", "undef_rx", "=", "re", ".", "compile", "(", "\"/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\\n\"", ")", "while", "True", ":", "line", "=", "fp", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "m", "=", "define_rx", ".", "match", "(", "line", ")", "if", "m", ":", "n", ",", "v", "=", "m", ".", "group", "(", "1", ",", "2", ")", "try", ":", "v", "=", "int", "(", "v", ")", "except", "ValueError", ":", "pass", "vars", "[", "n", "]", "=", "v", "else", ":", "m", "=", "undef_rx", ".", "match", "(", "line", ")", "if", "m", ":", "vars", "[", "m", ".", "group", "(", "1", ")", "]", "=", "0", "return", "vars" ]
Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary.
[ "Parse", "a", "config", ".", "h", "-", "style", "file", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L388-L416
train
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
get_config_h_filename
def get_config_h_filename(): """Return the path of pyconfig.h.""" if _PYTHON_BUILD: if os.name == "nt": inc_dir = os.path.join(_PROJECT_BASE, "PC") else: inc_dir = _PROJECT_BASE else: inc_dir = get_path('platinclude') return os.path.join(inc_dir, 'pyconfig.h')
python
def get_config_h_filename(): """Return the path of pyconfig.h.""" if _PYTHON_BUILD: if os.name == "nt": inc_dir = os.path.join(_PROJECT_BASE, "PC") else: inc_dir = _PROJECT_BASE else: inc_dir = get_path('platinclude') return os.path.join(inc_dir, 'pyconfig.h')
[ "def", "get_config_h_filename", "(", ")", ":", "if", "_PYTHON_BUILD", ":", "if", "os", ".", "name", "==", "\"nt\"", ":", "inc_dir", "=", "os", ".", "path", ".", "join", "(", "_PROJECT_BASE", ",", "\"PC\"", ")", "else", ":", "inc_dir", "=", "_PROJECT_BASE", "else", ":", "inc_dir", "=", "get_path", "(", "'platinclude'", ")", "return", "os", ".", "path", ".", "join", "(", "inc_dir", ",", "'pyconfig.h'", ")" ]
Return the path of pyconfig.h.
[ "Return", "the", "path", "of", "pyconfig", ".", "h", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L419-L428
train
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
get_paths
def get_paths(scheme=_get_default_scheme(), vars=None, expand=True): """Return a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform. """ _ensure_cfg_read() if expand: return _expand_vars(scheme, vars) else: return dict(_SCHEMES.items(scheme))
python
def get_paths(scheme=_get_default_scheme(), vars=None, expand=True): """Return a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform. """ _ensure_cfg_read() if expand: return _expand_vars(scheme, vars) else: return dict(_SCHEMES.items(scheme))
[ "def", "get_paths", "(", "scheme", "=", "_get_default_scheme", "(", ")", ",", "vars", "=", "None", ",", "expand", "=", "True", ")", ":", "_ensure_cfg_read", "(", ")", "if", "expand", ":", "return", "_expand_vars", "(", "scheme", ",", "vars", ")", "else", ":", "return", "dict", "(", "_SCHEMES", ".", "items", "(", "scheme", ")", ")" ]
Return a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform.
[ "Return", "a", "mapping", "containing", "an", "install", "scheme", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L442-L452
train
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
get_path
def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True): """Return a path corresponding to the scheme. ``scheme`` is the install scheme name. """ return get_paths(scheme, vars, expand)[name]
python
def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True): """Return a path corresponding to the scheme. ``scheme`` is the install scheme name. """ return get_paths(scheme, vars, expand)[name]
[ "def", "get_path", "(", "name", ",", "scheme", "=", "_get_default_scheme", "(", ")", ",", "vars", "=", "None", ",", "expand", "=", "True", ")", ":", "return", "get_paths", "(", "scheme", ",", "vars", ",", "expand", ")", "[", "name", "]" ]
Return a path corresponding to the scheme. ``scheme`` is the install scheme name.
[ "Return", "a", "path", "corresponding", "to", "the", "scheme", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L455-L460
train
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
_main
def _main(): """Display all information sysconfig detains.""" print('Platform: "%s"' % get_platform()) print('Python version: "%s"' % get_python_version()) print('Current installation scheme: "%s"' % _get_default_scheme()) print() _print_dict('Paths', get_paths()) print() _print_dict('Variables', get_config_vars())
python
def _main(): """Display all information sysconfig detains.""" print('Platform: "%s"' % get_platform()) print('Python version: "%s"' % get_python_version()) print('Current installation scheme: "%s"' % _get_default_scheme()) print() _print_dict('Paths', get_paths()) print() _print_dict('Variables', get_config_vars())
[ "def", "_main", "(", ")", ":", "print", "(", "'Platform: \"%s\"'", "%", "get_platform", "(", ")", ")", "print", "(", "'Python version: \"%s\"'", "%", "get_python_version", "(", ")", ")", "print", "(", "'Current installation scheme: \"%s\"'", "%", "_get_default_scheme", "(", ")", ")", "print", "(", ")", "_print_dict", "(", "'Paths'", ",", "get_paths", "(", ")", ")", "print", "(", ")", "_print_dict", "(", "'Variables'", ",", "get_config_vars", "(", ")", ")" ]
Display all information sysconfig detains.
[ "Display", "all", "information", "sysconfig", "detains", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L776-L784
train
pypa/pipenv
pipenv/vendor/tomlkit/source.py
Source.inc
def inc(self, exception=None): # type: (Optional[ParseError.__class__]) -> bool """ Increments the parser if the end of the input has not been reached. Returns whether or not it was able to advance. """ try: self._idx, self._current = next(self._chars) return True except StopIteration: self._idx = len(self) self._current = self.EOF if exception: raise self.parse_error(exception) return False
python
def inc(self, exception=None): # type: (Optional[ParseError.__class__]) -> bool """ Increments the parser if the end of the input has not been reached. Returns whether or not it was able to advance. """ try: self._idx, self._current = next(self._chars) return True except StopIteration: self._idx = len(self) self._current = self.EOF if exception: raise self.parse_error(exception) return False
[ "def", "inc", "(", "self", ",", "exception", "=", "None", ")", ":", "# type: (Optional[ParseError.__class__]) -> bool", "try", ":", "self", ".", "_idx", ",", "self", ".", "_current", "=", "next", "(", "self", ".", "_chars", ")", "return", "True", "except", "StopIteration", ":", "self", ".", "_idx", "=", "len", "(", "self", ")", "self", ".", "_current", "=", "self", ".", "EOF", "if", "exception", ":", "raise", "self", ".", "parse_error", "(", "exception", ")", "return", "False" ]
Increments the parser if the end of the input has not been reached. Returns whether or not it was able to advance.
[ "Increments", "the", "parser", "if", "the", "end", "of", "the", "input", "has", "not", "been", "reached", ".", "Returns", "whether", "or", "not", "it", "was", "able", "to", "advance", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/source.py#L117-L132
train
pypa/pipenv
pipenv/vendor/tomlkit/source.py
Source.inc_n
def inc_n(self, n, exception=None): # type: (int, Exception) -> bool """ Increments the parser by n characters if the end of the input has not been reached. """ for _ in range(n): if not self.inc(exception=exception): return False return True
python
def inc_n(self, n, exception=None): # type: (int, Exception) -> bool """ Increments the parser by n characters if the end of the input has not been reached. """ for _ in range(n): if not self.inc(exception=exception): return False return True
[ "def", "inc_n", "(", "self", ",", "n", ",", "exception", "=", "None", ")", ":", "# type: (int, Exception) -> bool", "for", "_", "in", "range", "(", "n", ")", ":", "if", "not", "self", ".", "inc", "(", "exception", "=", "exception", ")", ":", "return", "False", "return", "True" ]
Increments the parser by n characters if the end of the input has not been reached.
[ "Increments", "the", "parser", "by", "n", "characters", "if", "the", "end", "of", "the", "input", "has", "not", "been", "reached", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/source.py#L134-L143
train
pypa/pipenv
pipenv/vendor/tomlkit/source.py
Source.consume
def consume(self, chars, min=0, max=-1): """ Consume chars until min/max is satisfied is valid. """ while self.current in chars and max != 0: min -= 1 max -= 1 if not self.inc(): break # failed to consume minimum number of characters if min > 0: self.parse_error(UnexpectedCharError)
python
def consume(self, chars, min=0, max=-1): """ Consume chars until min/max is satisfied is valid. """ while self.current in chars and max != 0: min -= 1 max -= 1 if not self.inc(): break # failed to consume minimum number of characters if min > 0: self.parse_error(UnexpectedCharError)
[ "def", "consume", "(", "self", ",", "chars", ",", "min", "=", "0", ",", "max", "=", "-", "1", ")", ":", "while", "self", ".", "current", "in", "chars", "and", "max", "!=", "0", ":", "min", "-=", "1", "max", "-=", "1", "if", "not", "self", ".", "inc", "(", ")", ":", "break", "# failed to consume minimum number of characters", "if", "min", ">", "0", ":", "self", ".", "parse_error", "(", "UnexpectedCharError", ")" ]
Consume chars until min/max is satisfied is valid.
[ "Consume", "chars", "until", "min", "/", "max", "is", "satisfied", "is", "valid", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/source.py#L145-L157
train
pypa/pipenv
pipenv/vendor/tomlkit/source.py
Source.parse_error
def parse_error( self, exception=ParseError, *args ): # type: (ParseError.__class__, ...) -> ParseError """ Creates a generic "parse error" at the current position. """ line, col = self._to_linecol() return exception(line, col, *args)
python
def parse_error( self, exception=ParseError, *args ): # type: (ParseError.__class__, ...) -> ParseError """ Creates a generic "parse error" at the current position. """ line, col = self._to_linecol() return exception(line, col, *args)
[ "def", "parse_error", "(", "self", ",", "exception", "=", "ParseError", ",", "*", "args", ")", ":", "# type: (ParseError.__class__, ...) -> ParseError", "line", ",", "col", "=", "self", ".", "_to_linecol", "(", ")", "return", "exception", "(", "line", ",", "col", ",", "*", "args", ")" ]
Creates a generic "parse error" at the current position.
[ "Creates", "a", "generic", "parse", "error", "at", "the", "current", "position", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/source.py#L171-L179
train
pypa/pipenv
pipenv/patched/notpip/_internal/commands/__init__.py
get_summaries
def get_summaries(ordered=True): """Yields sorted (command name, command summary) tuples.""" if ordered: cmditems = _sort_commands(commands_dict, commands_order) else: cmditems = commands_dict.items() for name, command_class in cmditems: yield (name, command_class.summary)
python
def get_summaries(ordered=True): """Yields sorted (command name, command summary) tuples.""" if ordered: cmditems = _sort_commands(commands_dict, commands_order) else: cmditems = commands_dict.items() for name, command_class in cmditems: yield (name, command_class.summary)
[ "def", "get_summaries", "(", "ordered", "=", "True", ")", ":", "if", "ordered", ":", "cmditems", "=", "_sort_commands", "(", "commands_dict", ",", "commands_order", ")", "else", ":", "cmditems", "=", "commands_dict", ".", "items", "(", ")", "for", "name", ",", "command_class", "in", "cmditems", ":", "yield", "(", "name", ",", "command_class", ".", "summary", ")" ]
Yields sorted (command name, command summary) tuples.
[ "Yields", "sorted", "(", "command", "name", "command", "summary", ")", "tuples", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/commands/__init__.py#L45-L54
train
pypa/pipenv
pipenv/patched/notpip/_internal/commands/__init__.py
get_similar_commands
def get_similar_commands(name): """Command name auto-correct.""" from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return False
python
def get_similar_commands(name): """Command name auto-correct.""" from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return False
[ "def", "get_similar_commands", "(", "name", ")", ":", "from", "difflib", "import", "get_close_matches", "name", "=", "name", ".", "lower", "(", ")", "close_commands", "=", "get_close_matches", "(", "name", ",", "commands_dict", ".", "keys", "(", ")", ")", "if", "close_commands", ":", "return", "close_commands", "[", "0", "]", "else", ":", "return", "False" ]
Command name auto-correct.
[ "Command", "name", "auto", "-", "correct", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/commands/__init__.py#L57-L68
train
pypa/pipenv
pipenv/vendor/jinja2/ext.py
Extension.bind
def bind(self, environment): """Create a copy of this extension bound to another environment.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.environment = environment return rv
python
def bind(self, environment): """Create a copy of this extension bound to another environment.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.environment = environment return rv
[ "def", "bind", "(", "self", ",", "environment", ")", ":", "rv", "=", "object", ".", "__new__", "(", "self", ".", "__class__", ")", "rv", ".", "__dict__", ".", "update", "(", "self", ".", "__dict__", ")", "rv", ".", "environment", "=", "environment", "return", "rv" ]
Create a copy of this extension bound to another environment.
[ "Create", "a", "copy", "of", "this", "extension", "bound", "to", "another", "environment", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/ext.py#L75-L80
train
pypa/pipenv
pipenv/vendor/jinja2/ext.py
Extension.attr
def attr(self, name, lineno=None): """Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno) """ return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
python
def attr(self, name, lineno=None): """Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno) """ return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
[ "def", "attr", "(", "self", ",", "name", ",", "lineno", "=", "None", ")", ":", "return", "nodes", ".", "ExtensionAttribute", "(", "self", ".", "identifier", ",", "name", ",", "lineno", "=", "lineno", ")" ]
Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno)
[ "Return", "an", "attribute", "node", "for", "the", "current", "extension", ".", "This", "is", "useful", "to", "pass", "constants", "on", "extensions", "to", "generated", "template", "code", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/ext.py#L109-L117
train
pypa/pipenv
pipenv/vendor/jinja2/ext.py
Extension.call_method
def call_method(self, name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None): """Call a method of the extension. This is a shortcut for :meth:`attr` + :class:`jinja2.nodes.Call`. """ if args is None: args = [] if kwargs is None: kwargs = [] return nodes.Call(self.attr(name, lineno=lineno), args, kwargs, dyn_args, dyn_kwargs, lineno=lineno)
python
def call_method(self, name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None): """Call a method of the extension. This is a shortcut for :meth:`attr` + :class:`jinja2.nodes.Call`. """ if args is None: args = [] if kwargs is None: kwargs = [] return nodes.Call(self.attr(name, lineno=lineno), args, kwargs, dyn_args, dyn_kwargs, lineno=lineno)
[ "def", "call_method", "(", "self", ",", "name", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "dyn_args", "=", "None", ",", "dyn_kwargs", "=", "None", ",", "lineno", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "[", "]", "if", "kwargs", "is", "None", ":", "kwargs", "=", "[", "]", "return", "nodes", ".", "Call", "(", "self", ".", "attr", "(", "name", ",", "lineno", "=", "lineno", ")", ",", "args", ",", "kwargs", ",", "dyn_args", ",", "dyn_kwargs", ",", "lineno", "=", "lineno", ")" ]
Call a method of the extension. This is a shortcut for :meth:`attr` + :class:`jinja2.nodes.Call`.
[ "Call", "a", "method", "of", "the", "extension", ".", "This", "is", "a", "shortcut", "for", ":", "meth", ":", "attr", "+", ":", "class", ":", "jinja2", ".", "nodes", ".", "Call", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/ext.py#L119-L129
train
pypa/pipenv
pipenv/vendor/jinja2/ext.py
InternationalizationExtension.parse
def parse(self, parser): """Parse a translatable tag.""" lineno = next(parser.stream).lineno num_called_num = False # find all the variables referenced. Additionally a variable can be # defined in the body of the trans block too, but this is checked at # a later state. plural_expr = None plural_expr_assignment = None variables = {} trimmed = None while parser.stream.current.type != 'block_end': if variables: parser.stream.expect('comma') # skip colon for python compatibility if parser.stream.skip_if('colon'): break name = parser.stream.expect('name') if name.value in variables: parser.fail('translatable variable %r defined twice.' % name.value, name.lineno, exc=TemplateAssertionError) # expressions if parser.stream.current.type == 'assign': next(parser.stream) variables[name.value] = var = parser.parse_expression() elif trimmed is None and name.value in ('trimmed', 'notrimmed'): trimmed = name.value == 'trimmed' continue else: variables[name.value] = var = nodes.Name(name.value, 'load') if plural_expr is None: if isinstance(var, nodes.Call): plural_expr = nodes.Name('_trans', 'load') variables[name.value] = plural_expr plural_expr_assignment = nodes.Assign( nodes.Name('_trans', 'store'), var) else: plural_expr = var num_called_num = name.value == 'num' parser.stream.expect('block_end') plural = None have_plural = False referenced = set() # now parse until endtrans or pluralize singular_names, singular = self._parse_block(parser, True) if singular_names: referenced.update(singular_names) if plural_expr is None: plural_expr = nodes.Name(singular_names[0], 'load') num_called_num = singular_names[0] == 'num' # if we have a pluralize block, we parse that too if parser.stream.current.test('name:pluralize'): have_plural = True next(parser.stream) if parser.stream.current.type != 'block_end': name = parser.stream.expect('name') if name.value not in variables: parser.fail('unknown variable %r for pluralization' % name.value, name.lineno, exc=TemplateAssertionError) plural_expr = variables[name.value] num_called_num = name.value == 'num' parser.stream.expect('block_end') plural_names, plural = self._parse_block(parser, False) next(parser.stream) referenced.update(plural_names) else: next(parser.stream) # register free names as simple name expressions for var in referenced: if var not in variables: variables[var] = nodes.Name(var, 'load') if not have_plural: plural_expr = None elif plural_expr is None: parser.fail('pluralize without variables', lineno) if trimmed is None: trimmed = self.environment.policies['ext.i18n.trimmed'] if trimmed: singular = self._trim_whitespace(singular) if plural: plural = self._trim_whitespace(plural) node = self._make_node(singular, plural, variables, plural_expr, bool(referenced), num_called_num and have_plural) node.set_lineno(lineno) if plural_expr_assignment is not None: return [plural_expr_assignment, node] else: return node
python
def parse(self, parser): """Parse a translatable tag.""" lineno = next(parser.stream).lineno num_called_num = False # find all the variables referenced. Additionally a variable can be # defined in the body of the trans block too, but this is checked at # a later state. plural_expr = None plural_expr_assignment = None variables = {} trimmed = None while parser.stream.current.type != 'block_end': if variables: parser.stream.expect('comma') # skip colon for python compatibility if parser.stream.skip_if('colon'): break name = parser.stream.expect('name') if name.value in variables: parser.fail('translatable variable %r defined twice.' % name.value, name.lineno, exc=TemplateAssertionError) # expressions if parser.stream.current.type == 'assign': next(parser.stream) variables[name.value] = var = parser.parse_expression() elif trimmed is None and name.value in ('trimmed', 'notrimmed'): trimmed = name.value == 'trimmed' continue else: variables[name.value] = var = nodes.Name(name.value, 'load') if plural_expr is None: if isinstance(var, nodes.Call): plural_expr = nodes.Name('_trans', 'load') variables[name.value] = plural_expr plural_expr_assignment = nodes.Assign( nodes.Name('_trans', 'store'), var) else: plural_expr = var num_called_num = name.value == 'num' parser.stream.expect('block_end') plural = None have_plural = False referenced = set() # now parse until endtrans or pluralize singular_names, singular = self._parse_block(parser, True) if singular_names: referenced.update(singular_names) if plural_expr is None: plural_expr = nodes.Name(singular_names[0], 'load') num_called_num = singular_names[0] == 'num' # if we have a pluralize block, we parse that too if parser.stream.current.test('name:pluralize'): have_plural = True next(parser.stream) if parser.stream.current.type != 'block_end': name = parser.stream.expect('name') if name.value not in variables: parser.fail('unknown variable %r for pluralization' % name.value, name.lineno, exc=TemplateAssertionError) plural_expr = variables[name.value] num_called_num = name.value == 'num' parser.stream.expect('block_end') plural_names, plural = self._parse_block(parser, False) next(parser.stream) referenced.update(plural_names) else: next(parser.stream) # register free names as simple name expressions for var in referenced: if var not in variables: variables[var] = nodes.Name(var, 'load') if not have_plural: plural_expr = None elif plural_expr is None: parser.fail('pluralize without variables', lineno) if trimmed is None: trimmed = self.environment.policies['ext.i18n.trimmed'] if trimmed: singular = self._trim_whitespace(singular) if plural: plural = self._trim_whitespace(plural) node = self._make_node(singular, plural, variables, plural_expr, bool(referenced), num_called_num and have_plural) node.set_lineno(lineno) if plural_expr_assignment is not None: return [plural_expr_assignment, node] else: return node
[ "def", "parse", "(", "self", ",", "parser", ")", ":", "lineno", "=", "next", "(", "parser", ".", "stream", ")", ".", "lineno", "num_called_num", "=", "False", "# find all the variables referenced. Additionally a variable can be", "# defined in the body of the trans block too, but this is checked at", "# a later state.", "plural_expr", "=", "None", "plural_expr_assignment", "=", "None", "variables", "=", "{", "}", "trimmed", "=", "None", "while", "parser", ".", "stream", ".", "current", ".", "type", "!=", "'block_end'", ":", "if", "variables", ":", "parser", ".", "stream", ".", "expect", "(", "'comma'", ")", "# skip colon for python compatibility", "if", "parser", ".", "stream", ".", "skip_if", "(", "'colon'", ")", ":", "break", "name", "=", "parser", ".", "stream", ".", "expect", "(", "'name'", ")", "if", "name", ".", "value", "in", "variables", ":", "parser", ".", "fail", "(", "'translatable variable %r defined twice.'", "%", "name", ".", "value", ",", "name", ".", "lineno", ",", "exc", "=", "TemplateAssertionError", ")", "# expressions", "if", "parser", ".", "stream", ".", "current", ".", "type", "==", "'assign'", ":", "next", "(", "parser", ".", "stream", ")", "variables", "[", "name", ".", "value", "]", "=", "var", "=", "parser", ".", "parse_expression", "(", ")", "elif", "trimmed", "is", "None", "and", "name", ".", "value", "in", "(", "'trimmed'", ",", "'notrimmed'", ")", ":", "trimmed", "=", "name", ".", "value", "==", "'trimmed'", "continue", "else", ":", "variables", "[", "name", ".", "value", "]", "=", "var", "=", "nodes", ".", "Name", "(", "name", ".", "value", ",", "'load'", ")", "if", "plural_expr", "is", "None", ":", "if", "isinstance", "(", "var", ",", "nodes", ".", "Call", ")", ":", "plural_expr", "=", "nodes", ".", "Name", "(", "'_trans'", ",", "'load'", ")", "variables", "[", "name", ".", "value", "]", "=", "plural_expr", "plural_expr_assignment", "=", "nodes", ".", "Assign", "(", "nodes", ".", "Name", "(", "'_trans'", ",", "'store'", ")", ",", "var", ")", "else", ":", "plural_expr", "=", "var", "num_called_num", "=", "name", ".", "value", "==", "'num'", "parser", ".", "stream", ".", "expect", "(", "'block_end'", ")", "plural", "=", "None", "have_plural", "=", "False", "referenced", "=", "set", "(", ")", "# now parse until endtrans or pluralize", "singular_names", ",", "singular", "=", "self", ".", "_parse_block", "(", "parser", ",", "True", ")", "if", "singular_names", ":", "referenced", ".", "update", "(", "singular_names", ")", "if", "plural_expr", "is", "None", ":", "plural_expr", "=", "nodes", ".", "Name", "(", "singular_names", "[", "0", "]", ",", "'load'", ")", "num_called_num", "=", "singular_names", "[", "0", "]", "==", "'num'", "# if we have a pluralize block, we parse that too", "if", "parser", ".", "stream", ".", "current", ".", "test", "(", "'name:pluralize'", ")", ":", "have_plural", "=", "True", "next", "(", "parser", ".", "stream", ")", "if", "parser", ".", "stream", ".", "current", ".", "type", "!=", "'block_end'", ":", "name", "=", "parser", ".", "stream", ".", "expect", "(", "'name'", ")", "if", "name", ".", "value", "not", "in", "variables", ":", "parser", ".", "fail", "(", "'unknown variable %r for pluralization'", "%", "name", ".", "value", ",", "name", ".", "lineno", ",", "exc", "=", "TemplateAssertionError", ")", "plural_expr", "=", "variables", "[", "name", ".", "value", "]", "num_called_num", "=", "name", ".", "value", "==", "'num'", "parser", ".", "stream", ".", "expect", "(", "'block_end'", ")", "plural_names", ",", "plural", "=", "self", ".", "_parse_block", "(", "parser", ",", "False", ")", "next", "(", "parser", ".", "stream", ")", "referenced", ".", "update", "(", "plural_names", ")", "else", ":", "next", "(", "parser", ".", "stream", ")", "# register free names as simple name expressions", "for", "var", "in", "referenced", ":", "if", "var", "not", "in", "variables", ":", "variables", "[", "var", "]", "=", "nodes", ".", "Name", "(", "var", ",", "'load'", ")", "if", "not", "have_plural", ":", "plural_expr", "=", "None", "elif", "plural_expr", "is", "None", ":", "parser", ".", "fail", "(", "'pluralize without variables'", ",", "lineno", ")", "if", "trimmed", "is", "None", ":", "trimmed", "=", "self", ".", "environment", ".", "policies", "[", "'ext.i18n.trimmed'", "]", "if", "trimmed", ":", "singular", "=", "self", ".", "_trim_whitespace", "(", "singular", ")", "if", "plural", ":", "plural", "=", "self", ".", "_trim_whitespace", "(", "plural", ")", "node", "=", "self", ".", "_make_node", "(", "singular", ",", "plural", ",", "variables", ",", "plural_expr", ",", "bool", "(", "referenced", ")", ",", "num_called_num", "and", "have_plural", ")", "node", ".", "set_lineno", "(", "lineno", ")", "if", "plural_expr_assignment", "is", "not", "None", ":", "return", "[", "plural_expr_assignment", ",", "node", "]", "else", ":", "return", "node" ]
Parse a translatable tag.
[ "Parse", "a", "translatable", "tag", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/ext.py#L217-L320
train
pypa/pipenv
pipenv/vendor/jinja2/ext.py
InternationalizationExtension._parse_block
def _parse_block(self, parser, allow_pluralize): """Parse until the next block tag with a given name.""" referenced = [] buf = [] while 1: if parser.stream.current.type == 'data': buf.append(parser.stream.current.value.replace('%', '%%')) next(parser.stream) elif parser.stream.current.type == 'variable_begin': next(parser.stream) name = parser.stream.expect('name').value referenced.append(name) buf.append('%%(%s)s' % name) parser.stream.expect('variable_end') elif parser.stream.current.type == 'block_begin': next(parser.stream) if parser.stream.current.test('name:endtrans'): break elif parser.stream.current.test('name:pluralize'): if allow_pluralize: break parser.fail('a translatable section can have only one ' 'pluralize section') parser.fail('control structures in translatable sections are ' 'not allowed') elif parser.stream.eos: parser.fail('unclosed translation block') else: assert False, 'internal parser error' return referenced, concat(buf)
python
def _parse_block(self, parser, allow_pluralize): """Parse until the next block tag with a given name.""" referenced = [] buf = [] while 1: if parser.stream.current.type == 'data': buf.append(parser.stream.current.value.replace('%', '%%')) next(parser.stream) elif parser.stream.current.type == 'variable_begin': next(parser.stream) name = parser.stream.expect('name').value referenced.append(name) buf.append('%%(%s)s' % name) parser.stream.expect('variable_end') elif parser.stream.current.type == 'block_begin': next(parser.stream) if parser.stream.current.test('name:endtrans'): break elif parser.stream.current.test('name:pluralize'): if allow_pluralize: break parser.fail('a translatable section can have only one ' 'pluralize section') parser.fail('control structures in translatable sections are ' 'not allowed') elif parser.stream.eos: parser.fail('unclosed translation block') else: assert False, 'internal parser error' return referenced, concat(buf)
[ "def", "_parse_block", "(", "self", ",", "parser", ",", "allow_pluralize", ")", ":", "referenced", "=", "[", "]", "buf", "=", "[", "]", "while", "1", ":", "if", "parser", ".", "stream", ".", "current", ".", "type", "==", "'data'", ":", "buf", ".", "append", "(", "parser", ".", "stream", ".", "current", ".", "value", ".", "replace", "(", "'%'", ",", "'%%'", ")", ")", "next", "(", "parser", ".", "stream", ")", "elif", "parser", ".", "stream", ".", "current", ".", "type", "==", "'variable_begin'", ":", "next", "(", "parser", ".", "stream", ")", "name", "=", "parser", ".", "stream", ".", "expect", "(", "'name'", ")", ".", "value", "referenced", ".", "append", "(", "name", ")", "buf", ".", "append", "(", "'%%(%s)s'", "%", "name", ")", "parser", ".", "stream", ".", "expect", "(", "'variable_end'", ")", "elif", "parser", ".", "stream", ".", "current", ".", "type", "==", "'block_begin'", ":", "next", "(", "parser", ".", "stream", ")", "if", "parser", ".", "stream", ".", "current", ".", "test", "(", "'name:endtrans'", ")", ":", "break", "elif", "parser", ".", "stream", ".", "current", ".", "test", "(", "'name:pluralize'", ")", ":", "if", "allow_pluralize", ":", "break", "parser", ".", "fail", "(", "'a translatable section can have only one '", "'pluralize section'", ")", "parser", ".", "fail", "(", "'control structures in translatable sections are '", "'not allowed'", ")", "elif", "parser", ".", "stream", ".", "eos", ":", "parser", ".", "fail", "(", "'unclosed translation block'", ")", "else", ":", "assert", "False", ",", "'internal parser error'", "return", "referenced", ",", "concat", "(", "buf", ")" ]
Parse until the next block tag with a given name.
[ "Parse", "until", "the", "next", "block", "tag", "with", "a", "given", "name", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/ext.py#L325-L355
train
pypa/pipenv
pipenv/vendor/jinja2/ext.py
InternationalizationExtension._make_node
def _make_node(self, singular, plural, variables, plural_expr, vars_referenced, num_called_num): """Generates a useful node from the data provided.""" # no variables referenced? no need to escape for old style # gettext invocations only if there are vars. if not vars_referenced and not self.environment.newstyle_gettext: singular = singular.replace('%%', '%') if plural: plural = plural.replace('%%', '%') # singular only: if plural_expr is None: gettext = nodes.Name('gettext', 'load') node = nodes.Call(gettext, [nodes.Const(singular)], [], None, None) # singular and plural else: ngettext = nodes.Name('ngettext', 'load') node = nodes.Call(ngettext, [ nodes.Const(singular), nodes.Const(plural), plural_expr ], [], None, None) # in case newstyle gettext is used, the method is powerful # enough to handle the variable expansion and autoescape # handling itself if self.environment.newstyle_gettext: for key, value in iteritems(variables): # the function adds that later anyways in case num was # called num, so just skip it. if num_called_num and key == 'num': continue node.kwargs.append(nodes.Keyword(key, value)) # otherwise do that here else: # mark the return value as safe if we are in an # environment with autoescaping turned on node = nodes.MarkSafeIfAutoescape(node) if variables: node = nodes.Mod(node, nodes.Dict([ nodes.Pair(nodes.Const(key), value) for key, value in variables.items() ])) return nodes.Output([node])
python
def _make_node(self, singular, plural, variables, plural_expr, vars_referenced, num_called_num): """Generates a useful node from the data provided.""" # no variables referenced? no need to escape for old style # gettext invocations only if there are vars. if not vars_referenced and not self.environment.newstyle_gettext: singular = singular.replace('%%', '%') if plural: plural = plural.replace('%%', '%') # singular only: if plural_expr is None: gettext = nodes.Name('gettext', 'load') node = nodes.Call(gettext, [nodes.Const(singular)], [], None, None) # singular and plural else: ngettext = nodes.Name('ngettext', 'load') node = nodes.Call(ngettext, [ nodes.Const(singular), nodes.Const(plural), plural_expr ], [], None, None) # in case newstyle gettext is used, the method is powerful # enough to handle the variable expansion and autoescape # handling itself if self.environment.newstyle_gettext: for key, value in iteritems(variables): # the function adds that later anyways in case num was # called num, so just skip it. if num_called_num and key == 'num': continue node.kwargs.append(nodes.Keyword(key, value)) # otherwise do that here else: # mark the return value as safe if we are in an # environment with autoescaping turned on node = nodes.MarkSafeIfAutoescape(node) if variables: node = nodes.Mod(node, nodes.Dict([ nodes.Pair(nodes.Const(key), value) for key, value in variables.items() ])) return nodes.Output([node])
[ "def", "_make_node", "(", "self", ",", "singular", ",", "plural", ",", "variables", ",", "plural_expr", ",", "vars_referenced", ",", "num_called_num", ")", ":", "# no variables referenced? no need to escape for old style", "# gettext invocations only if there are vars.", "if", "not", "vars_referenced", "and", "not", "self", ".", "environment", ".", "newstyle_gettext", ":", "singular", "=", "singular", ".", "replace", "(", "'%%'", ",", "'%'", ")", "if", "plural", ":", "plural", "=", "plural", ".", "replace", "(", "'%%'", ",", "'%'", ")", "# singular only:", "if", "plural_expr", "is", "None", ":", "gettext", "=", "nodes", ".", "Name", "(", "'gettext'", ",", "'load'", ")", "node", "=", "nodes", ".", "Call", "(", "gettext", ",", "[", "nodes", ".", "Const", "(", "singular", ")", "]", ",", "[", "]", ",", "None", ",", "None", ")", "# singular and plural", "else", ":", "ngettext", "=", "nodes", ".", "Name", "(", "'ngettext'", ",", "'load'", ")", "node", "=", "nodes", ".", "Call", "(", "ngettext", ",", "[", "nodes", ".", "Const", "(", "singular", ")", ",", "nodes", ".", "Const", "(", "plural", ")", ",", "plural_expr", "]", ",", "[", "]", ",", "None", ",", "None", ")", "# in case newstyle gettext is used, the method is powerful", "# enough to handle the variable expansion and autoescape", "# handling itself", "if", "self", ".", "environment", ".", "newstyle_gettext", ":", "for", "key", ",", "value", "in", "iteritems", "(", "variables", ")", ":", "# the function adds that later anyways in case num was", "# called num, so just skip it.", "if", "num_called_num", "and", "key", "==", "'num'", ":", "continue", "node", ".", "kwargs", ".", "append", "(", "nodes", ".", "Keyword", "(", "key", ",", "value", ")", ")", "# otherwise do that here", "else", ":", "# mark the return value as safe if we are in an", "# environment with autoescaping turned on", "node", "=", "nodes", ".", "MarkSafeIfAutoescape", "(", "node", ")", "if", "variables", ":", "node", "=", "nodes", ".", "Mod", "(", "node", ",", "nodes", ".", "Dict", "(", "[", "nodes", ".", "Pair", "(", "nodes", ".", "Const", "(", "key", ")", ",", "value", ")", "for", "key", ",", "value", "in", "variables", ".", "items", "(", ")", "]", ")", ")", "return", "nodes", ".", "Output", "(", "[", "node", "]", ")" ]
Generates a useful node from the data provided.
[ "Generates", "a", "useful", "node", "from", "the", "data", "provided", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/ext.py#L357-L403
train
pypa/pipenv
pipenv/vendor/dotenv/__init__.py
get_cli_string
def get_cli_string(path=None, action=None, key=None, value=None, quote=None): """Returns a string suitable for running as a shell script. Useful for converting a arguments passed to a fabric task to be passed to a `local` or `run` command. """ command = ['dotenv'] if quote: command.append('-q %s' % quote) if path: command.append('-f %s' % path) if action: command.append(action) if key: command.append(key) if value: if ' ' in value: command.append('"%s"' % value) else: command.append(value) return ' '.join(command).strip()
python
def get_cli_string(path=None, action=None, key=None, value=None, quote=None): """Returns a string suitable for running as a shell script. Useful for converting a arguments passed to a fabric task to be passed to a `local` or `run` command. """ command = ['dotenv'] if quote: command.append('-q %s' % quote) if path: command.append('-f %s' % path) if action: command.append(action) if key: command.append(key) if value: if ' ' in value: command.append('"%s"' % value) else: command.append(value) return ' '.join(command).strip()
[ "def", "get_cli_string", "(", "path", "=", "None", ",", "action", "=", "None", ",", "key", "=", "None", ",", "value", "=", "None", ",", "quote", "=", "None", ")", ":", "command", "=", "[", "'dotenv'", "]", "if", "quote", ":", "command", ".", "append", "(", "'-q %s'", "%", "quote", ")", "if", "path", ":", "command", ".", "append", "(", "'-f %s'", "%", "path", ")", "if", "action", ":", "command", ".", "append", "(", "action", ")", "if", "key", ":", "command", ".", "append", "(", "key", ")", "if", "value", ":", "if", "' '", "in", "value", ":", "command", ".", "append", "(", "'\"%s\"'", "%", "value", ")", "else", ":", "command", ".", "append", "(", "value", ")", "return", "' '", ".", "join", "(", "command", ")", ".", "strip", "(", ")" ]
Returns a string suitable for running as a shell script. Useful for converting a arguments passed to a fabric task to be passed to a `local` or `run` command.
[ "Returns", "a", "string", "suitable", "for", "running", "as", "a", "shell", "script", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/__init__.py#L9-L30
train
pypa/pipenv
pipenv/vendor/requests/sessions.py
merge_hooks
def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): """Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. """ if session_hooks is None or session_hooks.get('response') == []: return request_hooks if request_hooks is None or request_hooks.get('response') == []: return session_hooks return merge_setting(request_hooks, session_hooks, dict_class)
python
def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): """Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. """ if session_hooks is None or session_hooks.get('response') == []: return request_hooks if request_hooks is None or request_hooks.get('response') == []: return session_hooks return merge_setting(request_hooks, session_hooks, dict_class)
[ "def", "merge_hooks", "(", "request_hooks", ",", "session_hooks", ",", "dict_class", "=", "OrderedDict", ")", ":", "if", "session_hooks", "is", "None", "or", "session_hooks", ".", "get", "(", "'response'", ")", "==", "[", "]", ":", "return", "request_hooks", "if", "request_hooks", "is", "None", "or", "request_hooks", ".", "get", "(", "'response'", ")", "==", "[", "]", ":", "return", "session_hooks", "return", "merge_setting", "(", "request_hooks", ",", "session_hooks", ",", "dict_class", ")" ]
Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely.
[ "Properly", "merges", "both", "requests", "and", "session", "hooks", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L80-L92
train
pypa/pipenv
pipenv/vendor/requests/sessions.py
SessionRedirectMixin.get_redirect_target
def get_redirect_target(self, resp): """Receives a Response. Returns a redirect URI or ``None``""" # Due to the nature of how requests processes redirects this method will # be called at least once upon the original response and at least twice # on each subsequent redirect response (if any). # If a custom mixin is used to handle this logic, it may be advantageous # to cache the redirect location onto the response object as a private # attribute. if resp.is_redirect: location = resp.headers['location'] # Currently the underlying http module on py3 decode headers # in latin1, but empirical evidence suggests that latin1 is very # rarely used with non-ASCII characters in HTTP headers. # It is more likely to get UTF8 header rather than latin1. # This causes incorrect handling of UTF8 encoded location headers. # To solve this, we re-encode the location in latin1. if is_py3: location = location.encode('latin1') return to_native_string(location, 'utf8') return None
python
def get_redirect_target(self, resp): """Receives a Response. Returns a redirect URI or ``None``""" # Due to the nature of how requests processes redirects this method will # be called at least once upon the original response and at least twice # on each subsequent redirect response (if any). # If a custom mixin is used to handle this logic, it may be advantageous # to cache the redirect location onto the response object as a private # attribute. if resp.is_redirect: location = resp.headers['location'] # Currently the underlying http module on py3 decode headers # in latin1, but empirical evidence suggests that latin1 is very # rarely used with non-ASCII characters in HTTP headers. # It is more likely to get UTF8 header rather than latin1. # This causes incorrect handling of UTF8 encoded location headers. # To solve this, we re-encode the location in latin1. if is_py3: location = location.encode('latin1') return to_native_string(location, 'utf8') return None
[ "def", "get_redirect_target", "(", "self", ",", "resp", ")", ":", "# Due to the nature of how requests processes redirects this method will", "# be called at least once upon the original response and at least twice", "# on each subsequent redirect response (if any).", "# If a custom mixin is used to handle this logic, it may be advantageous", "# to cache the redirect location onto the response object as a private", "# attribute.", "if", "resp", ".", "is_redirect", ":", "location", "=", "resp", ".", "headers", "[", "'location'", "]", "# Currently the underlying http module on py3 decode headers", "# in latin1, but empirical evidence suggests that latin1 is very", "# rarely used with non-ASCII characters in HTTP headers.", "# It is more likely to get UTF8 header rather than latin1.", "# This causes incorrect handling of UTF8 encoded location headers.", "# To solve this, we re-encode the location in latin1.", "if", "is_py3", ":", "location", "=", "location", ".", "encode", "(", "'latin1'", ")", "return", "to_native_string", "(", "location", ",", "'utf8'", ")", "return", "None" ]
Receives a Response. Returns a redirect URI or ``None``
[ "Receives", "a", "Response", ".", "Returns", "a", "redirect", "URI", "or", "None" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L97-L116
train
pypa/pipenv
pipenv/vendor/requests/sessions.py
SessionRedirectMixin.should_strip_auth
def should_strip_auth(self, old_url, new_url): """Decide whether Authorization header should be removed when redirecting""" old_parsed = urlparse(old_url) new_parsed = urlparse(new_url) if old_parsed.hostname != new_parsed.hostname: return True # Special case: allow http -> https redirect when using the standard # ports. This isn't specified by RFC 7235, but is kept to avoid # breaking backwards compatibility with older versions of requests # that allowed any redirects on the same host. if (old_parsed.scheme == 'http' and old_parsed.port in (80, None) and new_parsed.scheme == 'https' and new_parsed.port in (443, None)): return False # Handle default port usage corresponding to scheme. changed_port = old_parsed.port != new_parsed.port changed_scheme = old_parsed.scheme != new_parsed.scheme default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) if (not changed_scheme and old_parsed.port in default_port and new_parsed.port in default_port): return False # Standard case: root URI must match return changed_port or changed_scheme
python
def should_strip_auth(self, old_url, new_url): """Decide whether Authorization header should be removed when redirecting""" old_parsed = urlparse(old_url) new_parsed = urlparse(new_url) if old_parsed.hostname != new_parsed.hostname: return True # Special case: allow http -> https redirect when using the standard # ports. This isn't specified by RFC 7235, but is kept to avoid # breaking backwards compatibility with older versions of requests # that allowed any redirects on the same host. if (old_parsed.scheme == 'http' and old_parsed.port in (80, None) and new_parsed.scheme == 'https' and new_parsed.port in (443, None)): return False # Handle default port usage corresponding to scheme. changed_port = old_parsed.port != new_parsed.port changed_scheme = old_parsed.scheme != new_parsed.scheme default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) if (not changed_scheme and old_parsed.port in default_port and new_parsed.port in default_port): return False # Standard case: root URI must match return changed_port or changed_scheme
[ "def", "should_strip_auth", "(", "self", ",", "old_url", ",", "new_url", ")", ":", "old_parsed", "=", "urlparse", "(", "old_url", ")", "new_parsed", "=", "urlparse", "(", "new_url", ")", "if", "old_parsed", ".", "hostname", "!=", "new_parsed", ".", "hostname", ":", "return", "True", "# Special case: allow http -> https redirect when using the standard", "# ports. This isn't specified by RFC 7235, but is kept to avoid", "# breaking backwards compatibility with older versions of requests", "# that allowed any redirects on the same host.", "if", "(", "old_parsed", ".", "scheme", "==", "'http'", "and", "old_parsed", ".", "port", "in", "(", "80", ",", "None", ")", "and", "new_parsed", ".", "scheme", "==", "'https'", "and", "new_parsed", ".", "port", "in", "(", "443", ",", "None", ")", ")", ":", "return", "False", "# Handle default port usage corresponding to scheme.", "changed_port", "=", "old_parsed", ".", "port", "!=", "new_parsed", ".", "port", "changed_scheme", "=", "old_parsed", ".", "scheme", "!=", "new_parsed", ".", "scheme", "default_port", "=", "(", "DEFAULT_PORTS", ".", "get", "(", "old_parsed", ".", "scheme", ",", "None", ")", ",", "None", ")", "if", "(", "not", "changed_scheme", "and", "old_parsed", ".", "port", "in", "default_port", "and", "new_parsed", ".", "port", "in", "default_port", ")", ":", "return", "False", "# Standard case: root URI must match", "return", "changed_port", "or", "changed_scheme" ]
Decide whether Authorization header should be removed when redirecting
[ "Decide", "whether", "Authorization", "header", "should", "be", "removed", "when", "redirecting" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L118-L141
train
pypa/pipenv
pipenv/vendor/requests/sessions.py
SessionRedirectMixin.rebuild_auth
def rebuild_auth(self, prepared_request, response): """When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. """ headers = prepared_request.headers url = prepared_request.url if 'Authorization' in headers and self.should_strip_auth(response.request.url, url): # If we get redirected to a new host, we should strip out any # authentication headers. del headers['Authorization'] # .netrc might have more auth for us on our new host. new_auth = get_netrc_auth(url) if self.trust_env else None if new_auth is not None: prepared_request.prepare_auth(new_auth) return
python
def rebuild_auth(self, prepared_request, response): """When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. """ headers = prepared_request.headers url = prepared_request.url if 'Authorization' in headers and self.should_strip_auth(response.request.url, url): # If we get redirected to a new host, we should strip out any # authentication headers. del headers['Authorization'] # .netrc might have more auth for us on our new host. new_auth = get_netrc_auth(url) if self.trust_env else None if new_auth is not None: prepared_request.prepare_auth(new_auth) return
[ "def", "rebuild_auth", "(", "self", ",", "prepared_request", ",", "response", ")", ":", "headers", "=", "prepared_request", ".", "headers", "url", "=", "prepared_request", ".", "url", "if", "'Authorization'", "in", "headers", "and", "self", ".", "should_strip_auth", "(", "response", ".", "request", ".", "url", ",", "url", ")", ":", "# If we get redirected to a new host, we should strip out any", "# authentication headers.", "del", "headers", "[", "'Authorization'", "]", "# .netrc might have more auth for us on our new host.", "new_auth", "=", "get_netrc_auth", "(", "url", ")", "if", "self", ".", "trust_env", "else", "None", "if", "new_auth", "is", "not", "None", ":", "prepared_request", ".", "prepare_auth", "(", "new_auth", ")", "return" ]
When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.
[ "When", "being", "redirected", "we", "may", "want", "to", "strip", "authentication", "from", "the", "request", "to", "avoid", "leaking", "credentials", ".", "This", "method", "intelligently", "removes", "and", "reapplies", "authentication", "where", "possible", "to", "avoid", "credential", "loss", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L256-L274
train
pypa/pipenv
pipenv/vendor/requests/sessions.py
SessionRedirectMixin.rebuild_proxies
def rebuild_proxies(self, prepared_request, proxies): """This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict """ proxies = proxies if proxies is not None else {} headers = prepared_request.headers url = prepared_request.url scheme = urlparse(url).scheme new_proxies = proxies.copy() no_proxy = proxies.get('no_proxy') bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy) if self.trust_env and not bypass_proxy: environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) proxy = environ_proxies.get(scheme, environ_proxies.get('all')) if proxy: new_proxies.setdefault(scheme, proxy) if 'Proxy-Authorization' in headers: del headers['Proxy-Authorization'] try: username, password = get_auth_from_url(new_proxies[scheme]) except KeyError: username, password = None, None if username and password: headers['Proxy-Authorization'] = _basic_auth_str(username, password) return new_proxies
python
def rebuild_proxies(self, prepared_request, proxies): """This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict """ proxies = proxies if proxies is not None else {} headers = prepared_request.headers url = prepared_request.url scheme = urlparse(url).scheme new_proxies = proxies.copy() no_proxy = proxies.get('no_proxy') bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy) if self.trust_env and not bypass_proxy: environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) proxy = environ_proxies.get(scheme, environ_proxies.get('all')) if proxy: new_proxies.setdefault(scheme, proxy) if 'Proxy-Authorization' in headers: del headers['Proxy-Authorization'] try: username, password = get_auth_from_url(new_proxies[scheme]) except KeyError: username, password = None, None if username and password: headers['Proxy-Authorization'] = _basic_auth_str(username, password) return new_proxies
[ "def", "rebuild_proxies", "(", "self", ",", "prepared_request", ",", "proxies", ")", ":", "proxies", "=", "proxies", "if", "proxies", "is", "not", "None", "else", "{", "}", "headers", "=", "prepared_request", ".", "headers", "url", "=", "prepared_request", ".", "url", "scheme", "=", "urlparse", "(", "url", ")", ".", "scheme", "new_proxies", "=", "proxies", ".", "copy", "(", ")", "no_proxy", "=", "proxies", ".", "get", "(", "'no_proxy'", ")", "bypass_proxy", "=", "should_bypass_proxies", "(", "url", ",", "no_proxy", "=", "no_proxy", ")", "if", "self", ".", "trust_env", "and", "not", "bypass_proxy", ":", "environ_proxies", "=", "get_environ_proxies", "(", "url", ",", "no_proxy", "=", "no_proxy", ")", "proxy", "=", "environ_proxies", ".", "get", "(", "scheme", ",", "environ_proxies", ".", "get", "(", "'all'", ")", ")", "if", "proxy", ":", "new_proxies", ".", "setdefault", "(", "scheme", ",", "proxy", ")", "if", "'Proxy-Authorization'", "in", "headers", ":", "del", "headers", "[", "'Proxy-Authorization'", "]", "try", ":", "username", ",", "password", "=", "get_auth_from_url", "(", "new_proxies", "[", "scheme", "]", ")", "except", "KeyError", ":", "username", ",", "password", "=", "None", ",", "None", "if", "username", "and", "password", ":", "headers", "[", "'Proxy-Authorization'", "]", "=", "_basic_auth_str", "(", "username", ",", "password", ")", "return", "new_proxies" ]
This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict
[ "This", "method", "re", "-", "evaluates", "the", "proxy", "configuration", "by", "considering", "the", "environment", "variables", ".", "If", "we", "are", "redirected", "to", "a", "URL", "covered", "by", "NO_PROXY", "we", "strip", "the", "proxy", "configuration", ".", "Otherwise", "we", "set", "missing", "proxy", "keys", "for", "this", "URL", "(", "in", "case", "they", "were", "stripped", "by", "a", "previous", "redirect", ")", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L276-L315
train
pypa/pipenv
pipenv/vendor/requests/sessions.py
Session.prepare_request
def prepare_request(self, request): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest """ cookies = request.cookies or {} # Bootstrap CookieJar. if not isinstance(cookies, cookielib.CookieJar): cookies = cookiejar_from_dict(cookies) # Merge with session cookies merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies) # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: auth = get_netrc_auth(request.url) p = PreparedRequest() p.prepare( method=request.method.upper(), url=request.url, files=request.files, data=request.data, json=request.json, headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict), params=merge_setting(request.params, self.params), auth=merge_setting(auth, self.auth), cookies=merged_cookies, hooks=merge_hooks(request.hooks, self.hooks), ) return p
python
def prepare_request(self, request): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest """ cookies = request.cookies or {} # Bootstrap CookieJar. if not isinstance(cookies, cookielib.CookieJar): cookies = cookiejar_from_dict(cookies) # Merge with session cookies merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies) # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: auth = get_netrc_auth(request.url) p = PreparedRequest() p.prepare( method=request.method.upper(), url=request.url, files=request.files, data=request.data, json=request.json, headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict), params=merge_setting(request.params, self.params), auth=merge_setting(auth, self.auth), cookies=merged_cookies, hooks=merge_hooks(request.hooks, self.hooks), ) return p
[ "def", "prepare_request", "(", "self", ",", "request", ")", ":", "cookies", "=", "request", ".", "cookies", "or", "{", "}", "# Bootstrap CookieJar.", "if", "not", "isinstance", "(", "cookies", ",", "cookielib", ".", "CookieJar", ")", ":", "cookies", "=", "cookiejar_from_dict", "(", "cookies", ")", "# Merge with session cookies", "merged_cookies", "=", "merge_cookies", "(", "merge_cookies", "(", "RequestsCookieJar", "(", ")", ",", "self", ".", "cookies", ")", ",", "cookies", ")", "# Set environment's basic authentication if not explicitly set.", "auth", "=", "request", ".", "auth", "if", "self", ".", "trust_env", "and", "not", "auth", "and", "not", "self", ".", "auth", ":", "auth", "=", "get_netrc_auth", "(", "request", ".", "url", ")", "p", "=", "PreparedRequest", "(", ")", "p", ".", "prepare", "(", "method", "=", "request", ".", "method", ".", "upper", "(", ")", ",", "url", "=", "request", ".", "url", ",", "files", "=", "request", ".", "files", ",", "data", "=", "request", ".", "data", ",", "json", "=", "request", ".", "json", ",", "headers", "=", "merge_setting", "(", "request", ".", "headers", ",", "self", ".", "headers", ",", "dict_class", "=", "CaseInsensitiveDict", ")", ",", "params", "=", "merge_setting", "(", "request", ".", "params", ",", "self", ".", "params", ")", ",", "auth", "=", "merge_setting", "(", "auth", ",", "self", ".", "auth", ")", ",", "cookies", "=", "merged_cookies", ",", "hooks", "=", "merge_hooks", "(", "request", ".", "hooks", ",", "self", ".", "hooks", ")", ",", ")", "return", "p" ]
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest
[ "Constructs", "a", ":", "class", ":", "PreparedRequest", "<PreparedRequest", ">", "for", "transmission", "and", "returns", "it", ".", "The", ":", "class", ":", "PreparedRequest", "has", "settings", "merged", "from", "the", ":", "class", ":", "Request", "<Request", ">", "instance", "and", "those", "of", "the", ":", "class", ":", "Session", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L426-L464
train
pypa/pipenv
pipenv/vendor/requests/sessions.py
Session.request
def request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None): """Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response """ # Create the Request. req = Request( method=method.upper(), url=url, headers=headers, files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=cookies, hooks=hooks, ) prep = self.prepare_request(req) proxies = proxies or {} settings = self.merge_environment_settings( prep.url, proxies, stream, verify, cert ) # Send the request. send_kwargs = { 'timeout': timeout, 'allow_redirects': allow_redirects, } send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) return resp
python
def request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None): """Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response """ # Create the Request. req = Request( method=method.upper(), url=url, headers=headers, files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=cookies, hooks=hooks, ) prep = self.prepare_request(req) proxies = proxies or {} settings = self.merge_environment_settings( prep.url, proxies, stream, verify, cert ) # Send the request. send_kwargs = { 'timeout': timeout, 'allow_redirects': allow_redirects, } send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) return resp
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "params", "=", "None", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "cookies", "=", "None", ",", "files", "=", "None", ",", "auth", "=", "None", ",", "timeout", "=", "None", ",", "allow_redirects", "=", "True", ",", "proxies", "=", "None", ",", "hooks", "=", "None", ",", "stream", "=", "None", ",", "verify", "=", "None", ",", "cert", "=", "None", ",", "json", "=", "None", ")", ":", "# Create the Request.", "req", "=", "Request", "(", "method", "=", "method", ".", "upper", "(", ")", ",", "url", "=", "url", ",", "headers", "=", "headers", ",", "files", "=", "files", ",", "data", "=", "data", "or", "{", "}", ",", "json", "=", "json", ",", "params", "=", "params", "or", "{", "}", ",", "auth", "=", "auth", ",", "cookies", "=", "cookies", ",", "hooks", "=", "hooks", ",", ")", "prep", "=", "self", ".", "prepare_request", "(", "req", ")", "proxies", "=", "proxies", "or", "{", "}", "settings", "=", "self", ".", "merge_environment_settings", "(", "prep", ".", "url", ",", "proxies", ",", "stream", ",", "verify", ",", "cert", ")", "# Send the request.", "send_kwargs", "=", "{", "'timeout'", ":", "timeout", ",", "'allow_redirects'", ":", "allow_redirects", ",", "}", "send_kwargs", ".", "update", "(", "settings", ")", "resp", "=", "self", ".", "send", "(", "prep", ",", "*", "*", "send_kwargs", ")", "return", "resp" ]
Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response
[ "Constructs", "a", ":", "class", ":", "Request", "<Request", ">", "prepares", "it", "and", "sends", "it", ".", "Returns", ":", "class", ":", "Response", "<Response", ">", "object", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L466-L535
train
pypa/pipenv
pipenv/vendor/requests/sessions.py
Session.get
def get(self, url, **kwargs): r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('GET', url, **kwargs)
python
def get(self, url, **kwargs): r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('GET', url, **kwargs)
[ "def", "get", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "True", ")", "return", "self", ".", "request", "(", "'GET'", ",", "url", ",", "*", "*", "kwargs", ")" ]
r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
[ "r", "Sends", "a", "GET", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L537-L546
train
pypa/pipenv
pipenv/vendor/requests/sessions.py
Session.options
def options(self, url, **kwargs): r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('OPTIONS', url, **kwargs)
python
def options(self, url, **kwargs): r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('OPTIONS', url, **kwargs)
[ "def", "options", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "True", ")", "return", "self", ".", "request", "(", "'OPTIONS'", ",", "url", ",", "*", "*", "kwargs", ")" ]
r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
[ "r", "Sends", "a", "OPTIONS", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L548-L557
train
pypa/pipenv
pipenv/vendor/requests/sessions.py
Session.head
def head(self, url, **kwargs): r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', False) return self.request('HEAD', url, **kwargs)
python
def head(self, url, **kwargs): r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', False) return self.request('HEAD', url, **kwargs)
[ "def", "head", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "False", ")", "return", "self", ".", "request", "(", "'HEAD'", ",", "url", ",", "*", "*", "kwargs", ")" ]
r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
[ "r", "Sends", "a", "HEAD", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L559-L568
train
pypa/pipenv
pipenv/vendor/requests/sessions.py
Session.send
def send(self, request, **kwargs): """Send a given PreparedRequest. :rtype: requests.Response """ # Set defaults that the hooks can utilize to ensure they always have # the correct parameters to reproduce the previous request. kwargs.setdefault('stream', self.stream) kwargs.setdefault('verify', self.verify) kwargs.setdefault('cert', self.cert) kwargs.setdefault('proxies', self.proxies) # It's possible that users might accidentally send a Request object. # Guard against that specific failure case. if isinstance(request, Request): raise ValueError('You can only send PreparedRequests.') # Set up variables needed for resolve_redirects and dispatching of hooks allow_redirects = kwargs.pop('allow_redirects', True) stream = kwargs.get('stream') hooks = request.hooks # Get the appropriate adapter to use adapter = self.get_adapter(url=request.url) # Start time (approximately) of the request start = preferred_clock() # Send the request r = adapter.send(request, **kwargs) # Total elapsed time of the request (approximately) elapsed = preferred_clock() - start r.elapsed = timedelta(seconds=elapsed) # Response manipulation hooks r = dispatch_hook('response', hooks, r, **kwargs) # Persist cookies if r.history: # If the hooks create history then we want those cookies too for resp in r.history: extract_cookies_to_jar(self.cookies, resp.request, resp.raw) extract_cookies_to_jar(self.cookies, request, r.raw) # Redirect resolving generator. gen = self.resolve_redirects(r, request, **kwargs) # Resolve redirects if allowed. history = [resp for resp in gen] if allow_redirects else [] # Shuffle things around if there's history. if history: # Insert the first (original) request at the start history.insert(0, r) # Get the last request made r = history.pop() r.history = history # If redirects aren't being followed, store the response on the Request for Response.next(). if not allow_redirects: try: r._next = next(self.resolve_redirects(r, request, yield_requests=True, **kwargs)) except StopIteration: pass if not stream: r.content return r
python
def send(self, request, **kwargs): """Send a given PreparedRequest. :rtype: requests.Response """ # Set defaults that the hooks can utilize to ensure they always have # the correct parameters to reproduce the previous request. kwargs.setdefault('stream', self.stream) kwargs.setdefault('verify', self.verify) kwargs.setdefault('cert', self.cert) kwargs.setdefault('proxies', self.proxies) # It's possible that users might accidentally send a Request object. # Guard against that specific failure case. if isinstance(request, Request): raise ValueError('You can only send PreparedRequests.') # Set up variables needed for resolve_redirects and dispatching of hooks allow_redirects = kwargs.pop('allow_redirects', True) stream = kwargs.get('stream') hooks = request.hooks # Get the appropriate adapter to use adapter = self.get_adapter(url=request.url) # Start time (approximately) of the request start = preferred_clock() # Send the request r = adapter.send(request, **kwargs) # Total elapsed time of the request (approximately) elapsed = preferred_clock() - start r.elapsed = timedelta(seconds=elapsed) # Response manipulation hooks r = dispatch_hook('response', hooks, r, **kwargs) # Persist cookies if r.history: # If the hooks create history then we want those cookies too for resp in r.history: extract_cookies_to_jar(self.cookies, resp.request, resp.raw) extract_cookies_to_jar(self.cookies, request, r.raw) # Redirect resolving generator. gen = self.resolve_redirects(r, request, **kwargs) # Resolve redirects if allowed. history = [resp for resp in gen] if allow_redirects else [] # Shuffle things around if there's history. if history: # Insert the first (original) request at the start history.insert(0, r) # Get the last request made r = history.pop() r.history = history # If redirects aren't being followed, store the response on the Request for Response.next(). if not allow_redirects: try: r._next = next(self.resolve_redirects(r, request, yield_requests=True, **kwargs)) except StopIteration: pass if not stream: r.content return r
[ "def", "send", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "# Set defaults that the hooks can utilize to ensure they always have", "# the correct parameters to reproduce the previous request.", "kwargs", ".", "setdefault", "(", "'stream'", ",", "self", ".", "stream", ")", "kwargs", ".", "setdefault", "(", "'verify'", ",", "self", ".", "verify", ")", "kwargs", ".", "setdefault", "(", "'cert'", ",", "self", ".", "cert", ")", "kwargs", ".", "setdefault", "(", "'proxies'", ",", "self", ".", "proxies", ")", "# It's possible that users might accidentally send a Request object.", "# Guard against that specific failure case.", "if", "isinstance", "(", "request", ",", "Request", ")", ":", "raise", "ValueError", "(", "'You can only send PreparedRequests.'", ")", "# Set up variables needed for resolve_redirects and dispatching of hooks", "allow_redirects", "=", "kwargs", ".", "pop", "(", "'allow_redirects'", ",", "True", ")", "stream", "=", "kwargs", ".", "get", "(", "'stream'", ")", "hooks", "=", "request", ".", "hooks", "# Get the appropriate adapter to use", "adapter", "=", "self", ".", "get_adapter", "(", "url", "=", "request", ".", "url", ")", "# Start time (approximately) of the request", "start", "=", "preferred_clock", "(", ")", "# Send the request", "r", "=", "adapter", ".", "send", "(", "request", ",", "*", "*", "kwargs", ")", "# Total elapsed time of the request (approximately)", "elapsed", "=", "preferred_clock", "(", ")", "-", "start", "r", ".", "elapsed", "=", "timedelta", "(", "seconds", "=", "elapsed", ")", "# Response manipulation hooks", "r", "=", "dispatch_hook", "(", "'response'", ",", "hooks", ",", "r", ",", "*", "*", "kwargs", ")", "# Persist cookies", "if", "r", ".", "history", ":", "# If the hooks create history then we want those cookies too", "for", "resp", "in", "r", ".", "history", ":", "extract_cookies_to_jar", "(", "self", ".", "cookies", ",", "resp", ".", "request", ",", "resp", ".", "raw", ")", "extract_cookies_to_jar", "(", "self", ".", "cookies", ",", "request", ",", "r", ".", "raw", ")", "# Redirect resolving generator.", "gen", "=", "self", ".", "resolve_redirects", "(", "r", ",", "request", ",", "*", "*", "kwargs", ")", "# Resolve redirects if allowed.", "history", "=", "[", "resp", "for", "resp", "in", "gen", "]", "if", "allow_redirects", "else", "[", "]", "# Shuffle things around if there's history.", "if", "history", ":", "# Insert the first (original) request at the start", "history", ".", "insert", "(", "0", ",", "r", ")", "# Get the last request made", "r", "=", "history", ".", "pop", "(", ")", "r", ".", "history", "=", "history", "# If redirects aren't being followed, store the response on the Request for Response.next().", "if", "not", "allow_redirects", ":", "try", ":", "r", ".", "_next", "=", "next", "(", "self", ".", "resolve_redirects", "(", "r", ",", "request", ",", "yield_requests", "=", "True", ",", "*", "*", "kwargs", ")", ")", "except", "StopIteration", ":", "pass", "if", "not", "stream", ":", "r", ".", "content", "return", "r" ]
Send a given PreparedRequest. :rtype: requests.Response
[ "Send", "a", "given", "PreparedRequest", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L617-L688
train
pypa/pipenv
pipenv/vendor/requests/sessions.py
Session.merge_environment_settings
def merge_environment_settings(self, url, proxies, stream, verify, cert): """ Check the environment and merge it with some settings. :rtype: dict """ # Gather clues from the surrounding environment. if self.trust_env: # Set environment's proxies. no_proxy = proxies.get('no_proxy') if proxies is not None else None env_proxies = get_environ_proxies(url, no_proxy=no_proxy) for (k, v) in env_proxies.items(): proxies.setdefault(k, v) # Look for requests environment configuration and be compatible # with cURL. if verify is True or verify is None: verify = (os.environ.get('REQUESTS_CA_BUNDLE') or os.environ.get('CURL_CA_BUNDLE')) # Merge all the kwargs. proxies = merge_setting(proxies, self.proxies) stream = merge_setting(stream, self.stream) verify = merge_setting(verify, self.verify) cert = merge_setting(cert, self.cert) return {'verify': verify, 'proxies': proxies, 'stream': stream, 'cert': cert}
python
def merge_environment_settings(self, url, proxies, stream, verify, cert): """ Check the environment and merge it with some settings. :rtype: dict """ # Gather clues from the surrounding environment. if self.trust_env: # Set environment's proxies. no_proxy = proxies.get('no_proxy') if proxies is not None else None env_proxies = get_environ_proxies(url, no_proxy=no_proxy) for (k, v) in env_proxies.items(): proxies.setdefault(k, v) # Look for requests environment configuration and be compatible # with cURL. if verify is True or verify is None: verify = (os.environ.get('REQUESTS_CA_BUNDLE') or os.environ.get('CURL_CA_BUNDLE')) # Merge all the kwargs. proxies = merge_setting(proxies, self.proxies) stream = merge_setting(stream, self.stream) verify = merge_setting(verify, self.verify) cert = merge_setting(cert, self.cert) return {'verify': verify, 'proxies': proxies, 'stream': stream, 'cert': cert}
[ "def", "merge_environment_settings", "(", "self", ",", "url", ",", "proxies", ",", "stream", ",", "verify", ",", "cert", ")", ":", "# Gather clues from the surrounding environment.", "if", "self", ".", "trust_env", ":", "# Set environment's proxies.", "no_proxy", "=", "proxies", ".", "get", "(", "'no_proxy'", ")", "if", "proxies", "is", "not", "None", "else", "None", "env_proxies", "=", "get_environ_proxies", "(", "url", ",", "no_proxy", "=", "no_proxy", ")", "for", "(", "k", ",", "v", ")", "in", "env_proxies", ".", "items", "(", ")", ":", "proxies", ".", "setdefault", "(", "k", ",", "v", ")", "# Look for requests environment configuration and be compatible", "# with cURL.", "if", "verify", "is", "True", "or", "verify", "is", "None", ":", "verify", "=", "(", "os", ".", "environ", ".", "get", "(", "'REQUESTS_CA_BUNDLE'", ")", "or", "os", ".", "environ", ".", "get", "(", "'CURL_CA_BUNDLE'", ")", ")", "# Merge all the kwargs.", "proxies", "=", "merge_setting", "(", "proxies", ",", "self", ".", "proxies", ")", "stream", "=", "merge_setting", "(", "stream", ",", "self", ".", "stream", ")", "verify", "=", "merge_setting", "(", "verify", ",", "self", ".", "verify", ")", "cert", "=", "merge_setting", "(", "cert", ",", "self", ".", "cert", ")", "return", "{", "'verify'", ":", "verify", ",", "'proxies'", ":", "proxies", ",", "'stream'", ":", "stream", ",", "'cert'", ":", "cert", "}" ]
Check the environment and merge it with some settings. :rtype: dict
[ "Check", "the", "environment", "and", "merge", "it", "with", "some", "settings", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L690-L717
train
pypa/pipenv
pipenv/vendor/requests/sessions.py
Session.get_adapter
def get_adapter(self, url): """ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter """ for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix.lower()): return adapter # Nothing matches :-/ raise InvalidSchema("No connection adapters were found for '%s'" % url)
python
def get_adapter(self, url): """ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter """ for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix.lower()): return adapter # Nothing matches :-/ raise InvalidSchema("No connection adapters were found for '%s'" % url)
[ "def", "get_adapter", "(", "self", ",", "url", ")", ":", "for", "(", "prefix", ",", "adapter", ")", "in", "self", ".", "adapters", ".", "items", "(", ")", ":", "if", "url", ".", "lower", "(", ")", ".", "startswith", "(", "prefix", ".", "lower", "(", ")", ")", ":", "return", "adapter", "# Nothing matches :-/", "raise", "InvalidSchema", "(", "\"No connection adapters were found for '%s'\"", "%", "url", ")" ]
Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter
[ "Returns", "the", "appropriate", "connection", "adapter", "for", "the", "given", "URL", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L719-L731
train
pypa/pipenv
pipenv/vendor/requests/sessions.py
Session.mount
def mount(self, prefix, adapter): """Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. """ self.adapters[prefix] = adapter keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] for key in keys_to_move: self.adapters[key] = self.adapters.pop(key)
python
def mount(self, prefix, adapter): """Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. """ self.adapters[prefix] = adapter keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] for key in keys_to_move: self.adapters[key] = self.adapters.pop(key)
[ "def", "mount", "(", "self", ",", "prefix", ",", "adapter", ")", ":", "self", ".", "adapters", "[", "prefix", "]", "=", "adapter", "keys_to_move", "=", "[", "k", "for", "k", "in", "self", ".", "adapters", "if", "len", "(", "k", ")", "<", "len", "(", "prefix", ")", "]", "for", "key", "in", "keys_to_move", ":", "self", ".", "adapters", "[", "key", "]", "=", "self", ".", "adapters", ".", "pop", "(", "key", ")" ]
Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length.
[ "Registers", "a", "connection", "adapter", "to", "a", "prefix", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L738-L747
train
pypa/pipenv
pipenv/patched/notpip/_internal/utils/compat.py
console_to_str
def console_to_str(data): # type: (bytes) -> Text """Return a string, safe for output, of subprocess output. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors. """ # First, get the encoding we assume. This is the preferred # encoding for the locale, unless that is not found, or # it is ASCII, in which case assume UTF-8 encoding = locale.getpreferredencoding() if (not encoding) or codecs.lookup(encoding).name == "ascii": encoding = "utf-8" # Now try to decode the data - if we fail, warn the user and # decode with replacement. try: decoded_data = data.decode(encoding) except UnicodeDecodeError: logger.warning( "Subprocess output does not appear to be encoded as %s", encoding, ) decoded_data = data.decode(encoding, errors=backslashreplace_decode) # Make sure we can print the output, by encoding it to the output # encoding with replacement of unencodable characters, and then # decoding again. # We use stderr's encoding because it's less likely to be # redirected and if we don't find an encoding we skip this # step (on the assumption that output is wrapped by something # that won't fail). # The double getattr is to deal with the possibility that we're # being called in a situation where sys.__stderr__ doesn't exist, # or doesn't have an encoding attribute. Neither of these cases # should occur in normal pip use, but there's no harm in checking # in case people use pip in (unsupported) unusual situations. output_encoding = getattr(getattr(sys, "__stderr__", None), "encoding", None) if output_encoding: output_encoded = decoded_data.encode( output_encoding, errors="backslashreplace" ) decoded_data = output_encoded.decode(output_encoding) return decoded_data
python
def console_to_str(data): # type: (bytes) -> Text """Return a string, safe for output, of subprocess output. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors. """ # First, get the encoding we assume. This is the preferred # encoding for the locale, unless that is not found, or # it is ASCII, in which case assume UTF-8 encoding = locale.getpreferredencoding() if (not encoding) or codecs.lookup(encoding).name == "ascii": encoding = "utf-8" # Now try to decode the data - if we fail, warn the user and # decode with replacement. try: decoded_data = data.decode(encoding) except UnicodeDecodeError: logger.warning( "Subprocess output does not appear to be encoded as %s", encoding, ) decoded_data = data.decode(encoding, errors=backslashreplace_decode) # Make sure we can print the output, by encoding it to the output # encoding with replacement of unencodable characters, and then # decoding again. # We use stderr's encoding because it's less likely to be # redirected and if we don't find an encoding we skip this # step (on the assumption that output is wrapped by something # that won't fail). # The double getattr is to deal with the possibility that we're # being called in a situation where sys.__stderr__ doesn't exist, # or doesn't have an encoding attribute. Neither of these cases # should occur in normal pip use, but there's no harm in checking # in case people use pip in (unsupported) unusual situations. output_encoding = getattr(getattr(sys, "__stderr__", None), "encoding", None) if output_encoding: output_encoded = decoded_data.encode( output_encoding, errors="backslashreplace" ) decoded_data = output_encoded.decode(output_encoding) return decoded_data
[ "def", "console_to_str", "(", "data", ")", ":", "# type: (bytes) -> Text", "# First, get the encoding we assume. This is the preferred", "# encoding for the locale, unless that is not found, or", "# it is ASCII, in which case assume UTF-8", "encoding", "=", "locale", ".", "getpreferredencoding", "(", ")", "if", "(", "not", "encoding", ")", "or", "codecs", ".", "lookup", "(", "encoding", ")", ".", "name", "==", "\"ascii\"", ":", "encoding", "=", "\"utf-8\"", "# Now try to decode the data - if we fail, warn the user and", "# decode with replacement.", "try", ":", "decoded_data", "=", "data", ".", "decode", "(", "encoding", ")", "except", "UnicodeDecodeError", ":", "logger", ".", "warning", "(", "\"Subprocess output does not appear to be encoded as %s\"", ",", "encoding", ",", ")", "decoded_data", "=", "data", ".", "decode", "(", "encoding", ",", "errors", "=", "backslashreplace_decode", ")", "# Make sure we can print the output, by encoding it to the output", "# encoding with replacement of unencodable characters, and then", "# decoding again.", "# We use stderr's encoding because it's less likely to be", "# redirected and if we don't find an encoding we skip this", "# step (on the assumption that output is wrapped by something", "# that won't fail).", "# The double getattr is to deal with the possibility that we're", "# being called in a situation where sys.__stderr__ doesn't exist,", "# or doesn't have an encoding attribute. Neither of these cases", "# should occur in normal pip use, but there's no harm in checking", "# in case people use pip in (unsupported) unusual situations.", "output_encoding", "=", "getattr", "(", "getattr", "(", "sys", ",", "\"__stderr__\"", ",", "None", ")", ",", "\"encoding\"", ",", "None", ")", "if", "output_encoding", ":", "output_encoded", "=", "decoded_data", ".", "encode", "(", "output_encoding", ",", "errors", "=", "\"backslashreplace\"", ")", "decoded_data", "=", "output_encoded", ".", "decode", "(", "output_encoding", ")", "return", "decoded_data" ]
Return a string, safe for output, of subprocess output. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors.
[ "Return", "a", "string", "safe", "for", "output", "of", "subprocess", "output", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/compat.py#L75-L127
train
pypa/pipenv
pipenv/patched/notpip/_internal/utils/compat.py
get_path_uid
def get_path_uid(path): # type: (str) -> int """ Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read. """ if hasattr(os, 'O_NOFOLLOW'): fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) file_uid = os.fstat(fd).st_uid os.close(fd) else: # AIX and Jython # WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW if not os.path.islink(path): # older versions of Jython don't have `os.fstat` file_uid = os.stat(path).st_uid else: # raise OSError for parity with os.O_NOFOLLOW above raise OSError( "%s is a symlink; Will not return uid for symlinks" % path ) return file_uid
python
def get_path_uid(path): # type: (str) -> int """ Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read. """ if hasattr(os, 'O_NOFOLLOW'): fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) file_uid = os.fstat(fd).st_uid os.close(fd) else: # AIX and Jython # WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW if not os.path.islink(path): # older versions of Jython don't have `os.fstat` file_uid = os.stat(path).st_uid else: # raise OSError for parity with os.O_NOFOLLOW above raise OSError( "%s is a symlink; Will not return uid for symlinks" % path ) return file_uid
[ "def", "get_path_uid", "(", "path", ")", ":", "# type: (str) -> int", "if", "hasattr", "(", "os", ",", "'O_NOFOLLOW'", ")", ":", "fd", "=", "os", ".", "open", "(", "path", ",", "os", ".", "O_RDONLY", "|", "os", ".", "O_NOFOLLOW", ")", "file_uid", "=", "os", ".", "fstat", "(", "fd", ")", ".", "st_uid", "os", ".", "close", "(", "fd", ")", "else", ":", "# AIX and Jython", "# WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW", "if", "not", "os", ".", "path", ".", "islink", "(", "path", ")", ":", "# older versions of Jython don't have `os.fstat`", "file_uid", "=", "os", ".", "stat", "(", "path", ")", ".", "st_uid", "else", ":", "# raise OSError for parity with os.O_NOFOLLOW above", "raise", "OSError", "(", "\"%s is a symlink; Will not return uid for symlinks\"", "%", "path", ")", "return", "file_uid" ]
Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read.
[ "Return", "path", "s", "uid", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/compat.py#L146-L173
train
pypa/pipenv
pipenv/patched/notpip/_internal/utils/compat.py
expanduser
def expanduser(path): # type: (str) -> str """ Expand ~ and ~user constructions. Includes a workaround for https://bugs.python.org/issue14768 """ expanded = os.path.expanduser(path) if path.startswith('~/') and expanded.startswith('//'): expanded = expanded[1:] return expanded
python
def expanduser(path): # type: (str) -> str """ Expand ~ and ~user constructions. Includes a workaround for https://bugs.python.org/issue14768 """ expanded = os.path.expanduser(path) if path.startswith('~/') and expanded.startswith('//'): expanded = expanded[1:] return expanded
[ "def", "expanduser", "(", "path", ")", ":", "# type: (str) -> str", "expanded", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "if", "path", ".", "startswith", "(", "'~/'", ")", "and", "expanded", ".", "startswith", "(", "'//'", ")", ":", "expanded", "=", "expanded", "[", "1", ":", "]", "return", "expanded" ]
Expand ~ and ~user constructions. Includes a workaround for https://bugs.python.org/issue14768
[ "Expand", "~", "and", "~user", "constructions", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/compat.py#L188-L198
train
pypa/pipenv
pipenv/patched/notpip/_internal/utils/compat.py
samefile
def samefile(file1, file2): # type: (str, str) -> bool """Provide an alternative for os.path.samefile on Windows/Python2""" if hasattr(os.path, 'samefile'): return os.path.samefile(file1, file2) else: path1 = os.path.normcase(os.path.abspath(file1)) path2 = os.path.normcase(os.path.abspath(file2)) return path1 == path2
python
def samefile(file1, file2): # type: (str, str) -> bool """Provide an alternative for os.path.samefile on Windows/Python2""" if hasattr(os.path, 'samefile'): return os.path.samefile(file1, file2) else: path1 = os.path.normcase(os.path.abspath(file1)) path2 = os.path.normcase(os.path.abspath(file2)) return path1 == path2
[ "def", "samefile", "(", "file1", ",", "file2", ")", ":", "# type: (str, str) -> bool", "if", "hasattr", "(", "os", ".", "path", ",", "'samefile'", ")", ":", "return", "os", ".", "path", ".", "samefile", "(", "file1", ",", "file2", ")", "else", ":", "path1", "=", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "file1", ")", ")", "path2", "=", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "file2", ")", ")", "return", "path1", "==", "path2" ]
Provide an alternative for os.path.samefile on Windows/Python2
[ "Provide", "an", "alternative", "for", "os", ".", "path", ".", "samefile", "on", "Windows", "/", "Python2" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/compat.py#L214-L222
train
pypa/pipenv
pipenv/resolver.py
Entry.ensure_least_updates_possible
def ensure_least_updates_possible(self): """ Mutate the current entry to ensure that we are making the smallest amount of changes possible to the existing lockfile -- this will keep the old locked versions of packages if they satisfy new constraints. :return: None """ constraints = self.get_constraints() can_use_original = True can_use_updated = True satisfied_by_versions = set() for constraint in constraints: if not constraint.specifier.contains(self.original_version): self.can_use_original = False if not constraint.specifier.contains(self.updated_version): self.can_use_updated = False satisfied_by_value = getattr(constraint, "satisfied_by", None) if satisfied_by_value: satisfied_by = "{0}".format( self.clean_specifier(str(satisfied_by_value.version)) ) satisfied_by_versions.add(satisfied_by) if can_use_original: self.entry_dict = self.lockfile_dict.copy() elif can_use_updated: if len(satisfied_by_versions) == 1: self.entry_dict["version"] = next(iter( sat_by for sat_by in satisfied_by_versions if sat_by ), None) hashes = None if self.lockfile_entry.specifiers == satisfied_by: ireq = self.lockfile_entry.as_ireq() if not self.lockfile_entry.hashes and self.resolver._should_include_hash(ireq): hashes = self.resolver.get_hash(ireq) else: hashes = self.lockfile_entry.hashes else: if self.resolver._should_include_hash(constraint): hashes = self.resolver.get_hash(constraint) if hashes: self.entry_dict["hashes"] = list(hashes) self._entry.hashes = frozenset(hashes) else: # check for any parents, since they depend on this and the current # installed versions are not compatible with the new version, so # we will need to update the top level dependency if possible self.check_flattened_parents()
python
def ensure_least_updates_possible(self): """ Mutate the current entry to ensure that we are making the smallest amount of changes possible to the existing lockfile -- this will keep the old locked versions of packages if they satisfy new constraints. :return: None """ constraints = self.get_constraints() can_use_original = True can_use_updated = True satisfied_by_versions = set() for constraint in constraints: if not constraint.specifier.contains(self.original_version): self.can_use_original = False if not constraint.specifier.contains(self.updated_version): self.can_use_updated = False satisfied_by_value = getattr(constraint, "satisfied_by", None) if satisfied_by_value: satisfied_by = "{0}".format( self.clean_specifier(str(satisfied_by_value.version)) ) satisfied_by_versions.add(satisfied_by) if can_use_original: self.entry_dict = self.lockfile_dict.copy() elif can_use_updated: if len(satisfied_by_versions) == 1: self.entry_dict["version"] = next(iter( sat_by for sat_by in satisfied_by_versions if sat_by ), None) hashes = None if self.lockfile_entry.specifiers == satisfied_by: ireq = self.lockfile_entry.as_ireq() if not self.lockfile_entry.hashes and self.resolver._should_include_hash(ireq): hashes = self.resolver.get_hash(ireq) else: hashes = self.lockfile_entry.hashes else: if self.resolver._should_include_hash(constraint): hashes = self.resolver.get_hash(constraint) if hashes: self.entry_dict["hashes"] = list(hashes) self._entry.hashes = frozenset(hashes) else: # check for any parents, since they depend on this and the current # installed versions are not compatible with the new version, so # we will need to update the top level dependency if possible self.check_flattened_parents()
[ "def", "ensure_least_updates_possible", "(", "self", ")", ":", "constraints", "=", "self", ".", "get_constraints", "(", ")", "can_use_original", "=", "True", "can_use_updated", "=", "True", "satisfied_by_versions", "=", "set", "(", ")", "for", "constraint", "in", "constraints", ":", "if", "not", "constraint", ".", "specifier", ".", "contains", "(", "self", ".", "original_version", ")", ":", "self", ".", "can_use_original", "=", "False", "if", "not", "constraint", ".", "specifier", ".", "contains", "(", "self", ".", "updated_version", ")", ":", "self", ".", "can_use_updated", "=", "False", "satisfied_by_value", "=", "getattr", "(", "constraint", ",", "\"satisfied_by\"", ",", "None", ")", "if", "satisfied_by_value", ":", "satisfied_by", "=", "\"{0}\"", ".", "format", "(", "self", ".", "clean_specifier", "(", "str", "(", "satisfied_by_value", ".", "version", ")", ")", ")", "satisfied_by_versions", ".", "add", "(", "satisfied_by", ")", "if", "can_use_original", ":", "self", ".", "entry_dict", "=", "self", ".", "lockfile_dict", ".", "copy", "(", ")", "elif", "can_use_updated", ":", "if", "len", "(", "satisfied_by_versions", ")", "==", "1", ":", "self", ".", "entry_dict", "[", "\"version\"", "]", "=", "next", "(", "iter", "(", "sat_by", "for", "sat_by", "in", "satisfied_by_versions", "if", "sat_by", ")", ",", "None", ")", "hashes", "=", "None", "if", "self", ".", "lockfile_entry", ".", "specifiers", "==", "satisfied_by", ":", "ireq", "=", "self", ".", "lockfile_entry", ".", "as_ireq", "(", ")", "if", "not", "self", ".", "lockfile_entry", ".", "hashes", "and", "self", ".", "resolver", ".", "_should_include_hash", "(", "ireq", ")", ":", "hashes", "=", "self", ".", "resolver", ".", "get_hash", "(", "ireq", ")", "else", ":", "hashes", "=", "self", ".", "lockfile_entry", ".", "hashes", "else", ":", "if", "self", ".", "resolver", ".", "_should_include_hash", "(", "constraint", ")", ":", "hashes", "=", "self", ".", "resolver", ".", "get_hash", "(", "constraint", ")", "if", "hashes", ":", "self", ".", "entry_dict", "[", "\"hashes\"", "]", "=", "list", "(", "hashes", ")", "self", ".", "_entry", ".", "hashes", "=", "frozenset", "(", "hashes", ")", "else", ":", "# check for any parents, since they depend on this and the current", "# installed versions are not compatible with the new version, so", "# we will need to update the top level dependency if possible", "self", ".", "check_flattened_parents", "(", ")" ]
Mutate the current entry to ensure that we are making the smallest amount of changes possible to the existing lockfile -- this will keep the old locked versions of packages if they satisfy new constraints. :return: None
[ "Mutate", "the", "current", "entry", "to", "ensure", "that", "we", "are", "making", "the", "smallest", "amount", "of", "changes", "possible", "to", "the", "existing", "lockfile", "--", "this", "will", "keep", "the", "old", "locked", "versions", "of", "packages", "if", "they", "satisfy", "new", "constraints", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/resolver.py#L314-L361
train
pypa/pipenv
pipenv/resolver.py
Entry.get_constraints
def get_constraints(self): """ Retrieve all of the relevant constraints, aggregated from the pipfile, resolver, and parent dependencies and their respective conflict resolution where possible. :return: A set of **InstallRequirement** instances representing constraints :rtype: Set """ constraints = { c for c in self.resolver.parsed_constraints if c and c.name == self.entry.name } pipfile_constraint = self.get_pipfile_constraint() if pipfile_constraint: constraints.add(pipfile_constraint) return constraints
python
def get_constraints(self): """ Retrieve all of the relevant constraints, aggregated from the pipfile, resolver, and parent dependencies and their respective conflict resolution where possible. :return: A set of **InstallRequirement** instances representing constraints :rtype: Set """ constraints = { c for c in self.resolver.parsed_constraints if c and c.name == self.entry.name } pipfile_constraint = self.get_pipfile_constraint() if pipfile_constraint: constraints.add(pipfile_constraint) return constraints
[ "def", "get_constraints", "(", "self", ")", ":", "constraints", "=", "{", "c", "for", "c", "in", "self", ".", "resolver", ".", "parsed_constraints", "if", "c", "and", "c", ".", "name", "==", "self", ".", "entry", ".", "name", "}", "pipfile_constraint", "=", "self", ".", "get_pipfile_constraint", "(", ")", "if", "pipfile_constraint", ":", "constraints", ".", "add", "(", "pipfile_constraint", ")", "return", "constraints" ]
Retrieve all of the relevant constraints, aggregated from the pipfile, resolver, and parent dependencies and their respective conflict resolution where possible. :return: A set of **InstallRequirement** instances representing constraints :rtype: Set
[ "Retrieve", "all", "of", "the", "relevant", "constraints", "aggregated", "from", "the", "pipfile", "resolver", "and", "parent", "dependencies", "and", "their", "respective", "conflict", "resolution", "where", "possible", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/resolver.py#L363-L378
train
pypa/pipenv
pipenv/resolver.py
Entry.constraint_from_parent_conflicts
def constraint_from_parent_conflicts(self): """ Given a resolved entry with multiple parent dependencies with different constraints, searches for the resolution that satisfies all of the parent constraints. :return: A new **InstallRequirement** satisfying all parent constraints :raises: :exc:`~pipenv.exceptions.DependencyConflict` if resolution is impossible """ # ensure that we satisfy the parent dependencies of this dep from pipenv.vendor.packaging.specifiers import Specifier parent_dependencies = set() has_mismatch = False can_use_original = True for p in self.parent_deps: # updated dependencies should be satisfied since they were resolved already if p.is_updated: continue # parents with no requirements can't conflict if not p.requirements: continue needed = p.requirements.get("dependencies", []) entry_ref = p.get_dependency(self.name) required = entry_ref.get("required_version", "*") required = self.clean_specifier(required) parent_requires = self.make_requirement(self.name, required) parent_dependencies.add("{0} => {1} ({2})".format(p.name, self.name, required)) if not parent_requires.requirement.specifier.contains(self.original_version): can_use_original = False if not parent_requires.requirement.specifier.contains(self.updated_version): has_mismatch = True if has_mismatch and not can_use_original: from pipenv.exceptions import DependencyConflict msg = ( "Cannot resolve {0} ({1}) due to conflicting parent dependencies: " "\n\t{2}".format( self.name, self.updated_version, "\n\t".join(parent_dependencies) ) ) raise DependencyConflict(msg) elif can_use_original: return self.lockfile_entry.as_ireq() return self.entry.as_ireq()
python
def constraint_from_parent_conflicts(self): """ Given a resolved entry with multiple parent dependencies with different constraints, searches for the resolution that satisfies all of the parent constraints. :return: A new **InstallRequirement** satisfying all parent constraints :raises: :exc:`~pipenv.exceptions.DependencyConflict` if resolution is impossible """ # ensure that we satisfy the parent dependencies of this dep from pipenv.vendor.packaging.specifiers import Specifier parent_dependencies = set() has_mismatch = False can_use_original = True for p in self.parent_deps: # updated dependencies should be satisfied since they were resolved already if p.is_updated: continue # parents with no requirements can't conflict if not p.requirements: continue needed = p.requirements.get("dependencies", []) entry_ref = p.get_dependency(self.name) required = entry_ref.get("required_version", "*") required = self.clean_specifier(required) parent_requires = self.make_requirement(self.name, required) parent_dependencies.add("{0} => {1} ({2})".format(p.name, self.name, required)) if not parent_requires.requirement.specifier.contains(self.original_version): can_use_original = False if not parent_requires.requirement.specifier.contains(self.updated_version): has_mismatch = True if has_mismatch and not can_use_original: from pipenv.exceptions import DependencyConflict msg = ( "Cannot resolve {0} ({1}) due to conflicting parent dependencies: " "\n\t{2}".format( self.name, self.updated_version, "\n\t".join(parent_dependencies) ) ) raise DependencyConflict(msg) elif can_use_original: return self.lockfile_entry.as_ireq() return self.entry.as_ireq()
[ "def", "constraint_from_parent_conflicts", "(", "self", ")", ":", "# ensure that we satisfy the parent dependencies of this dep", "from", "pipenv", ".", "vendor", ".", "packaging", ".", "specifiers", "import", "Specifier", "parent_dependencies", "=", "set", "(", ")", "has_mismatch", "=", "False", "can_use_original", "=", "True", "for", "p", "in", "self", ".", "parent_deps", ":", "# updated dependencies should be satisfied since they were resolved already", "if", "p", ".", "is_updated", ":", "continue", "# parents with no requirements can't conflict", "if", "not", "p", ".", "requirements", ":", "continue", "needed", "=", "p", ".", "requirements", ".", "get", "(", "\"dependencies\"", ",", "[", "]", ")", "entry_ref", "=", "p", ".", "get_dependency", "(", "self", ".", "name", ")", "required", "=", "entry_ref", ".", "get", "(", "\"required_version\"", ",", "\"*\"", ")", "required", "=", "self", ".", "clean_specifier", "(", "required", ")", "parent_requires", "=", "self", ".", "make_requirement", "(", "self", ".", "name", ",", "required", ")", "parent_dependencies", ".", "add", "(", "\"{0} => {1} ({2})\"", ".", "format", "(", "p", ".", "name", ",", "self", ".", "name", ",", "required", ")", ")", "if", "not", "parent_requires", ".", "requirement", ".", "specifier", ".", "contains", "(", "self", ".", "original_version", ")", ":", "can_use_original", "=", "False", "if", "not", "parent_requires", ".", "requirement", ".", "specifier", ".", "contains", "(", "self", ".", "updated_version", ")", ":", "has_mismatch", "=", "True", "if", "has_mismatch", "and", "not", "can_use_original", ":", "from", "pipenv", ".", "exceptions", "import", "DependencyConflict", "msg", "=", "(", "\"Cannot resolve {0} ({1}) due to conflicting parent dependencies: \"", "\"\\n\\t{2}\"", ".", "format", "(", "self", ".", "name", ",", "self", ".", "updated_version", ",", "\"\\n\\t\"", ".", "join", "(", "parent_dependencies", ")", ")", ")", "raise", "DependencyConflict", "(", "msg", ")", "elif", "can_use_original", ":", "return", "self", ".", "lockfile_entry", ".", "as_ireq", "(", ")", "return", "self", ".", "entry", ".", "as_ireq", "(", ")" ]
Given a resolved entry with multiple parent dependencies with different constraints, searches for the resolution that satisfies all of the parent constraints. :return: A new **InstallRequirement** satisfying all parent constraints :raises: :exc:`~pipenv.exceptions.DependencyConflict` if resolution is impossible
[ "Given", "a", "resolved", "entry", "with", "multiple", "parent", "dependencies", "with", "different", "constraints", "searches", "for", "the", "resolution", "that", "satisfies", "all", "of", "the", "parent", "constraints", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/resolver.py#L391-L433
train
pypa/pipenv
pipenv/resolver.py
Entry.validate_constraints
def validate_constraints(self): """ Retrieves the full set of available constraints and iterate over them, validating that they exist and that they are not causing unresolvable conflicts. :return: True if the constraints are satisfied by the resolution provided :raises: :exc:`pipenv.exceptions.DependencyConflict` if the constraints dont exist """ constraints = self.get_constraints() for constraint in constraints: try: constraint.check_if_exists(False) except Exception: from pipenv.exceptions import DependencyConflict msg = ( "Cannot resolve conflicting version {0}{1} while {1}{2} is " "locked.".format( self.name, self.updated_specifier, self.old_name, self.old_specifiers ) ) raise DependencyConflict(msg) return True
python
def validate_constraints(self): """ Retrieves the full set of available constraints and iterate over them, validating that they exist and that they are not causing unresolvable conflicts. :return: True if the constraints are satisfied by the resolution provided :raises: :exc:`pipenv.exceptions.DependencyConflict` if the constraints dont exist """ constraints = self.get_constraints() for constraint in constraints: try: constraint.check_if_exists(False) except Exception: from pipenv.exceptions import DependencyConflict msg = ( "Cannot resolve conflicting version {0}{1} while {1}{2} is " "locked.".format( self.name, self.updated_specifier, self.old_name, self.old_specifiers ) ) raise DependencyConflict(msg) return True
[ "def", "validate_constraints", "(", "self", ")", ":", "constraints", "=", "self", ".", "get_constraints", "(", ")", "for", "constraint", "in", "constraints", ":", "try", ":", "constraint", ".", "check_if_exists", "(", "False", ")", "except", "Exception", ":", "from", "pipenv", ".", "exceptions", "import", "DependencyConflict", "msg", "=", "(", "\"Cannot resolve conflicting version {0}{1} while {1}{2} is \"", "\"locked.\"", ".", "format", "(", "self", ".", "name", ",", "self", ".", "updated_specifier", ",", "self", ".", "old_name", ",", "self", ".", "old_specifiers", ")", ")", "raise", "DependencyConflict", "(", "msg", ")", "return", "True" ]
Retrieves the full set of available constraints and iterate over them, validating that they exist and that they are not causing unresolvable conflicts. :return: True if the constraints are satisfied by the resolution provided :raises: :exc:`pipenv.exceptions.DependencyConflict` if the constraints dont exist
[ "Retrieves", "the", "full", "set", "of", "available", "constraints", "and", "iterate", "over", "them", "validating", "that", "they", "exist", "and", "that", "they", "are", "not", "causing", "unresolvable", "conflicts", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/resolver.py#L435-L456
train
pypa/pipenv
pipenv/vendor/urllib3/contrib/securetransport.py
inject_into_urllib3
def inject_into_urllib3(): """ Monkey-patch urllib3 with SecureTransport-backed SSL-support. """ util.ssl_.SSLContext = SecureTransportContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_SECURETRANSPORT = True util.ssl_.IS_SECURETRANSPORT = True
python
def inject_into_urllib3(): """ Monkey-patch urllib3 with SecureTransport-backed SSL-support. """ util.ssl_.SSLContext = SecureTransportContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_SECURETRANSPORT = True util.ssl_.IS_SECURETRANSPORT = True
[ "def", "inject_into_urllib3", "(", ")", ":", "util", ".", "ssl_", ".", "SSLContext", "=", "SecureTransportContext", "util", ".", "HAS_SNI", "=", "HAS_SNI", "util", ".", "ssl_", ".", "HAS_SNI", "=", "HAS_SNI", "util", ".", "IS_SECURETRANSPORT", "=", "True", "util", ".", "ssl_", ".", "IS_SECURETRANSPORT", "=", "True" ]
Monkey-patch urllib3 with SecureTransport-backed SSL-support.
[ "Monkey", "-", "patch", "urllib3", "with", "SecureTransport", "-", "backed", "SSL", "-", "support", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L154-L162
train
pypa/pipenv
pipenv/vendor/urllib3/contrib/securetransport.py
extract_from_urllib3
def extract_from_urllib3(): """ Undo monkey-patching by :func:`inject_into_urllib3`. """ util.ssl_.SSLContext = orig_util_SSLContext util.HAS_SNI = orig_util_HAS_SNI util.ssl_.HAS_SNI = orig_util_HAS_SNI util.IS_SECURETRANSPORT = False util.ssl_.IS_SECURETRANSPORT = False
python
def extract_from_urllib3(): """ Undo monkey-patching by :func:`inject_into_urllib3`. """ util.ssl_.SSLContext = orig_util_SSLContext util.HAS_SNI = orig_util_HAS_SNI util.ssl_.HAS_SNI = orig_util_HAS_SNI util.IS_SECURETRANSPORT = False util.ssl_.IS_SECURETRANSPORT = False
[ "def", "extract_from_urllib3", "(", ")", ":", "util", ".", "ssl_", ".", "SSLContext", "=", "orig_util_SSLContext", "util", ".", "HAS_SNI", "=", "orig_util_HAS_SNI", "util", ".", "ssl_", ".", "HAS_SNI", "=", "orig_util_HAS_SNI", "util", ".", "IS_SECURETRANSPORT", "=", "False", "util", ".", "ssl_", ".", "IS_SECURETRANSPORT", "=", "False" ]
Undo monkey-patching by :func:`inject_into_urllib3`.
[ "Undo", "monkey", "-", "patching", "by", ":", "func", ":", "inject_into_urllib3", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L165-L173
train
pypa/pipenv
pipenv/vendor/urllib3/contrib/securetransport.py
_read_callback
def _read_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport read callback. This is called by ST to request that data be returned from the socket. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket requested_length = data_length_pointer[0] timeout = wrapped_socket.gettimeout() error = None read_count = 0 try: while read_count < requested_length: if timeout is None or timeout >= 0: if not util.wait_for_read(base_socket, timeout): raise socket.error(errno.EAGAIN, 'timed out') remaining = requested_length - read_count buffer = (ctypes.c_char * remaining).from_address( data_buffer + read_count ) chunk_size = base_socket.recv_into(buffer, remaining) read_count += chunk_size if not chunk_size: if not read_count: return SecurityConst.errSSLClosedGraceful break except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = read_count if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = read_count if read_count != requested_length: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal
python
def _read_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport read callback. This is called by ST to request that data be returned from the socket. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket requested_length = data_length_pointer[0] timeout = wrapped_socket.gettimeout() error = None read_count = 0 try: while read_count < requested_length: if timeout is None or timeout >= 0: if not util.wait_for_read(base_socket, timeout): raise socket.error(errno.EAGAIN, 'timed out') remaining = requested_length - read_count buffer = (ctypes.c_char * remaining).from_address( data_buffer + read_count ) chunk_size = base_socket.recv_into(buffer, remaining) read_count += chunk_size if not chunk_size: if not read_count: return SecurityConst.errSSLClosedGraceful break except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = read_count if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = read_count if read_count != requested_length: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal
[ "def", "_read_callback", "(", "connection_id", ",", "data_buffer", ",", "data_length_pointer", ")", ":", "wrapped_socket", "=", "None", "try", ":", "wrapped_socket", "=", "_connection_refs", ".", "get", "(", "connection_id", ")", "if", "wrapped_socket", "is", "None", ":", "return", "SecurityConst", ".", "errSSLInternal", "base_socket", "=", "wrapped_socket", ".", "socket", "requested_length", "=", "data_length_pointer", "[", "0", "]", "timeout", "=", "wrapped_socket", ".", "gettimeout", "(", ")", "error", "=", "None", "read_count", "=", "0", "try", ":", "while", "read_count", "<", "requested_length", ":", "if", "timeout", "is", "None", "or", "timeout", ">=", "0", ":", "if", "not", "util", ".", "wait_for_read", "(", "base_socket", ",", "timeout", ")", ":", "raise", "socket", ".", "error", "(", "errno", ".", "EAGAIN", ",", "'timed out'", ")", "remaining", "=", "requested_length", "-", "read_count", "buffer", "=", "(", "ctypes", ".", "c_char", "*", "remaining", ")", ".", "from_address", "(", "data_buffer", "+", "read_count", ")", "chunk_size", "=", "base_socket", ".", "recv_into", "(", "buffer", ",", "remaining", ")", "read_count", "+=", "chunk_size", "if", "not", "chunk_size", ":", "if", "not", "read_count", ":", "return", "SecurityConst", ".", "errSSLClosedGraceful", "break", "except", "(", "socket", ".", "error", ")", "as", "e", ":", "error", "=", "e", ".", "errno", "if", "error", "is", "not", "None", "and", "error", "!=", "errno", ".", "EAGAIN", ":", "data_length_pointer", "[", "0", "]", "=", "read_count", "if", "error", "==", "errno", ".", "ECONNRESET", "or", "error", "==", "errno", ".", "EPIPE", ":", "return", "SecurityConst", ".", "errSSLClosedAbort", "raise", "data_length_pointer", "[", "0", "]", "=", "read_count", "if", "read_count", "!=", "requested_length", ":", "return", "SecurityConst", ".", "errSSLWouldBlock", "return", "0", "except", "Exception", "as", "e", ":", "if", "wrapped_socket", "is", "not", "None", ":", "wrapped_socket", ".", "_exception", "=", "e", "return", "SecurityConst", ".", "errSSLInternal" ]
SecureTransport read callback. This is called by ST to request that data be returned from the socket.
[ "SecureTransport", "read", "callback", ".", "This", "is", "called", "by", "ST", "to", "request", "that", "data", "be", "returned", "from", "the", "socket", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L176-L228
train
pypa/pipenv
pipenv/vendor/urllib3/contrib/securetransport.py
_write_callback
def _write_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport write callback. This is called by ST to request that data actually be sent on the network. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket bytes_to_write = data_length_pointer[0] data = ctypes.string_at(data_buffer, bytes_to_write) timeout = wrapped_socket.gettimeout() error = None sent = 0 try: while sent < bytes_to_write: if timeout is None or timeout >= 0: if not util.wait_for_write(base_socket, timeout): raise socket.error(errno.EAGAIN, 'timed out') chunk_sent = base_socket.send(data) sent += chunk_sent # This has some needless copying here, but I'm not sure there's # much value in optimising this data path. data = data[chunk_sent:] except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = sent if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = sent if sent != bytes_to_write: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal
python
def _write_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport write callback. This is called by ST to request that data actually be sent on the network. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket bytes_to_write = data_length_pointer[0] data = ctypes.string_at(data_buffer, bytes_to_write) timeout = wrapped_socket.gettimeout() error = None sent = 0 try: while sent < bytes_to_write: if timeout is None or timeout >= 0: if not util.wait_for_write(base_socket, timeout): raise socket.error(errno.EAGAIN, 'timed out') chunk_sent = base_socket.send(data) sent += chunk_sent # This has some needless copying here, but I'm not sure there's # much value in optimising this data path. data = data[chunk_sent:] except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = sent if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = sent if sent != bytes_to_write: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal
[ "def", "_write_callback", "(", "connection_id", ",", "data_buffer", ",", "data_length_pointer", ")", ":", "wrapped_socket", "=", "None", "try", ":", "wrapped_socket", "=", "_connection_refs", ".", "get", "(", "connection_id", ")", "if", "wrapped_socket", "is", "None", ":", "return", "SecurityConst", ".", "errSSLInternal", "base_socket", "=", "wrapped_socket", ".", "socket", "bytes_to_write", "=", "data_length_pointer", "[", "0", "]", "data", "=", "ctypes", ".", "string_at", "(", "data_buffer", ",", "bytes_to_write", ")", "timeout", "=", "wrapped_socket", ".", "gettimeout", "(", ")", "error", "=", "None", "sent", "=", "0", "try", ":", "while", "sent", "<", "bytes_to_write", ":", "if", "timeout", "is", "None", "or", "timeout", ">=", "0", ":", "if", "not", "util", ".", "wait_for_write", "(", "base_socket", ",", "timeout", ")", ":", "raise", "socket", ".", "error", "(", "errno", ".", "EAGAIN", ",", "'timed out'", ")", "chunk_sent", "=", "base_socket", ".", "send", "(", "data", ")", "sent", "+=", "chunk_sent", "# This has some needless copying here, but I'm not sure there's", "# much value in optimising this data path.", "data", "=", "data", "[", "chunk_sent", ":", "]", "except", "(", "socket", ".", "error", ")", "as", "e", ":", "error", "=", "e", ".", "errno", "if", "error", "is", "not", "None", "and", "error", "!=", "errno", ".", "EAGAIN", ":", "data_length_pointer", "[", "0", "]", "=", "sent", "if", "error", "==", "errno", ".", "ECONNRESET", "or", "error", "==", "errno", ".", "EPIPE", ":", "return", "SecurityConst", ".", "errSSLClosedAbort", "raise", "data_length_pointer", "[", "0", "]", "=", "sent", "if", "sent", "!=", "bytes_to_write", ":", "return", "SecurityConst", ".", "errSSLWouldBlock", "return", "0", "except", "Exception", "as", "e", ":", "if", "wrapped_socket", "is", "not", "None", ":", "wrapped_socket", ".", "_exception", "=", "e", "return", "SecurityConst", ".", "errSSLInternal" ]
SecureTransport write callback. This is called by ST to request that data actually be sent on the network.
[ "SecureTransport", "write", "callback", ".", "This", "is", "called", "by", "ST", "to", "request", "that", "data", "actually", "be", "sent", "on", "the", "network", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L231-L279
train
pypa/pipenv
pipenv/vendor/urllib3/contrib/securetransport.py
WrappedSocket._raise_on_error
def _raise_on_error(self): """ A context manager that can be used to wrap calls that do I/O from SecureTransport. If any of the I/O callbacks hit an exception, this context manager will correctly propagate the exception after the fact. This avoids silently swallowing those exceptions. It also correctly forces the socket closed. """ self._exception = None # We explicitly don't catch around this yield because in the unlikely # event that an exception was hit in the block we don't want to swallow # it. yield if self._exception is not None: exception, self._exception = self._exception, None self.close() raise exception
python
def _raise_on_error(self): """ A context manager that can be used to wrap calls that do I/O from SecureTransport. If any of the I/O callbacks hit an exception, this context manager will correctly propagate the exception after the fact. This avoids silently swallowing those exceptions. It also correctly forces the socket closed. """ self._exception = None # We explicitly don't catch around this yield because in the unlikely # event that an exception was hit in the block we don't want to swallow # it. yield if self._exception is not None: exception, self._exception = self._exception, None self.close() raise exception
[ "def", "_raise_on_error", "(", "self", ")", ":", "self", ".", "_exception", "=", "None", "# We explicitly don't catch around this yield because in the unlikely", "# event that an exception was hit in the block we don't want to swallow", "# it.", "yield", "if", "self", ".", "_exception", "is", "not", "None", ":", "exception", ",", "self", ".", "_exception", "=", "self", ".", "_exception", ",", "None", "self", ".", "close", "(", ")", "raise", "exception" ]
A context manager that can be used to wrap calls that do I/O from SecureTransport. If any of the I/O callbacks hit an exception, this context manager will correctly propagate the exception after the fact. This avoids silently swallowing those exceptions. It also correctly forces the socket closed.
[ "A", "context", "manager", "that", "can", "be", "used", "to", "wrap", "calls", "that", "do", "I", "/", "O", "from", "SecureTransport", ".", "If", "any", "of", "the", "I", "/", "O", "callbacks", "hit", "an", "exception", "this", "context", "manager", "will", "correctly", "propagate", "the", "exception", "after", "the", "fact", ".", "This", "avoids", "silently", "swallowing", "those", "exceptions", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L315-L333
train
pypa/pipenv
pipenv/vendor/urllib3/contrib/securetransport.py
WrappedSocket._set_ciphers
def _set_ciphers(self): """ Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare. """ ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES) result = Security.SSLSetEnabledCiphers( self.context, ciphers, len(CIPHER_SUITES) ) _assert_no_error(result)
python
def _set_ciphers(self): """ Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare. """ ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES) result = Security.SSLSetEnabledCiphers( self.context, ciphers, len(CIPHER_SUITES) ) _assert_no_error(result)
[ "def", "_set_ciphers", "(", "self", ")", ":", "ciphers", "=", "(", "Security", ".", "SSLCipherSuite", "*", "len", "(", "CIPHER_SUITES", ")", ")", "(", "*", "CIPHER_SUITES", ")", "result", "=", "Security", ".", "SSLSetEnabledCiphers", "(", "self", ".", "context", ",", "ciphers", ",", "len", "(", "CIPHER_SUITES", ")", ")", "_assert_no_error", "(", "result", ")" ]
Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare.
[ "Sets", "up", "the", "allowed", "ciphers", ".", "By", "default", "this", "matches", "the", "set", "in", "util", ".", "ssl_", ".", "DEFAULT_CIPHERS", "at", "least", "as", "supported", "by", "macOS", ".", "This", "is", "done", "custom", "and", "doesn", "t", "allow", "changing", "at", "this", "time", "mostly", "because", "parsing", "OpenSSL", "cipher", "strings", "is", "going", "to", "be", "a", "freaking", "nightmare", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L335-L346
train
pypa/pipenv
pipenv/vendor/urllib3/contrib/securetransport.py
WrappedSocket._custom_validate
def _custom_validate(self, verify, trust_bundle): """ Called when we have set custom validation. We do this in two cases: first, when cert validation is entirely disabled; and second, when using a custom trust DB. """ # If we disabled cert validation, just say: cool. if not verify: return # We want data in memory, so load it up. if os.path.isfile(trust_bundle): with open(trust_bundle, 'rb') as f: trust_bundle = f.read() cert_array = None trust = Security.SecTrustRef() try: # Get a CFArray that contains the certs we want. cert_array = _cert_array_from_pem(trust_bundle) # Ok, now the hard part. We want to get the SecTrustRef that ST has # created for this connection, shove our CAs into it, tell ST to # ignore everything else it knows, and then ask if it can build a # chain. This is a buuuunch of code. result = Security.SSLCopyPeerTrust( self.context, ctypes.byref(trust) ) _assert_no_error(result) if not trust: raise ssl.SSLError("Failed to copy trust reference") result = Security.SecTrustSetAnchorCertificates(trust, cert_array) _assert_no_error(result) result = Security.SecTrustSetAnchorCertificatesOnly(trust, True) _assert_no_error(result) trust_result = Security.SecTrustResultType() result = Security.SecTrustEvaluate( trust, ctypes.byref(trust_result) ) _assert_no_error(result) finally: if trust: CoreFoundation.CFRelease(trust) if cert_array is not None: CoreFoundation.CFRelease(cert_array) # Ok, now we can look at what the result was. successes = ( SecurityConst.kSecTrustResultUnspecified, SecurityConst.kSecTrustResultProceed ) if trust_result.value not in successes: raise ssl.SSLError( "certificate verify failed, error code: %d" % trust_result.value )
python
def _custom_validate(self, verify, trust_bundle): """ Called when we have set custom validation. We do this in two cases: first, when cert validation is entirely disabled; and second, when using a custom trust DB. """ # If we disabled cert validation, just say: cool. if not verify: return # We want data in memory, so load it up. if os.path.isfile(trust_bundle): with open(trust_bundle, 'rb') as f: trust_bundle = f.read() cert_array = None trust = Security.SecTrustRef() try: # Get a CFArray that contains the certs we want. cert_array = _cert_array_from_pem(trust_bundle) # Ok, now the hard part. We want to get the SecTrustRef that ST has # created for this connection, shove our CAs into it, tell ST to # ignore everything else it knows, and then ask if it can build a # chain. This is a buuuunch of code. result = Security.SSLCopyPeerTrust( self.context, ctypes.byref(trust) ) _assert_no_error(result) if not trust: raise ssl.SSLError("Failed to copy trust reference") result = Security.SecTrustSetAnchorCertificates(trust, cert_array) _assert_no_error(result) result = Security.SecTrustSetAnchorCertificatesOnly(trust, True) _assert_no_error(result) trust_result = Security.SecTrustResultType() result = Security.SecTrustEvaluate( trust, ctypes.byref(trust_result) ) _assert_no_error(result) finally: if trust: CoreFoundation.CFRelease(trust) if cert_array is not None: CoreFoundation.CFRelease(cert_array) # Ok, now we can look at what the result was. successes = ( SecurityConst.kSecTrustResultUnspecified, SecurityConst.kSecTrustResultProceed ) if trust_result.value not in successes: raise ssl.SSLError( "certificate verify failed, error code: %d" % trust_result.value )
[ "def", "_custom_validate", "(", "self", ",", "verify", ",", "trust_bundle", ")", ":", "# If we disabled cert validation, just say: cool.", "if", "not", "verify", ":", "return", "# We want data in memory, so load it up.", "if", "os", ".", "path", ".", "isfile", "(", "trust_bundle", ")", ":", "with", "open", "(", "trust_bundle", ",", "'rb'", ")", "as", "f", ":", "trust_bundle", "=", "f", ".", "read", "(", ")", "cert_array", "=", "None", "trust", "=", "Security", ".", "SecTrustRef", "(", ")", "try", ":", "# Get a CFArray that contains the certs we want.", "cert_array", "=", "_cert_array_from_pem", "(", "trust_bundle", ")", "# Ok, now the hard part. We want to get the SecTrustRef that ST has", "# created for this connection, shove our CAs into it, tell ST to", "# ignore everything else it knows, and then ask if it can build a", "# chain. This is a buuuunch of code.", "result", "=", "Security", ".", "SSLCopyPeerTrust", "(", "self", ".", "context", ",", "ctypes", ".", "byref", "(", "trust", ")", ")", "_assert_no_error", "(", "result", ")", "if", "not", "trust", ":", "raise", "ssl", ".", "SSLError", "(", "\"Failed to copy trust reference\"", ")", "result", "=", "Security", ".", "SecTrustSetAnchorCertificates", "(", "trust", ",", "cert_array", ")", "_assert_no_error", "(", "result", ")", "result", "=", "Security", ".", "SecTrustSetAnchorCertificatesOnly", "(", "trust", ",", "True", ")", "_assert_no_error", "(", "result", ")", "trust_result", "=", "Security", ".", "SecTrustResultType", "(", ")", "result", "=", "Security", ".", "SecTrustEvaluate", "(", "trust", ",", "ctypes", ".", "byref", "(", "trust_result", ")", ")", "_assert_no_error", "(", "result", ")", "finally", ":", "if", "trust", ":", "CoreFoundation", ".", "CFRelease", "(", "trust", ")", "if", "cert_array", "is", "not", "None", ":", "CoreFoundation", ".", "CFRelease", "(", "cert_array", ")", "# Ok, now we can look at what the result was.", "successes", "=", "(", "SecurityConst", ".", "kSecTrustResultUnspecified", ",", "SecurityConst", ".", "kSecTrustResultProceed", ")", "if", "trust_result", ".", "value", "not", "in", "successes", ":", "raise", "ssl", ".", "SSLError", "(", "\"certificate verify failed, error code: %d\"", "%", "trust_result", ".", "value", ")" ]
Called when we have set custom validation. We do this in two cases: first, when cert validation is entirely disabled; and second, when using a custom trust DB.
[ "Called", "when", "we", "have", "set", "custom", "validation", ".", "We", "do", "this", "in", "two", "cases", ":", "first", "when", "cert", "validation", "is", "entirely", "disabled", ";", "and", "second", "when", "using", "a", "custom", "trust", "DB", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L348-L408
train
pypa/pipenv
pipenv/vendor/urllib3/contrib/securetransport.py
WrappedSocket.handshake
def handshake(self, server_hostname, verify, trust_bundle, min_version, max_version, client_cert, client_key, client_key_passphrase): """ Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code. """ # First, we do the initial bits of connection setup. We need to create # a context, set its I/O funcs, and set the connection reference. self.context = Security.SSLCreateContext( None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType ) result = Security.SSLSetIOFuncs( self.context, _read_callback_pointer, _write_callback_pointer ) _assert_no_error(result) # Here we need to compute the handle to use. We do this by taking the # id of self modulo 2**31 - 1. If this is already in the dictionary, we # just keep incrementing by one until we find a free space. with _connection_ref_lock: handle = id(self) % 2147483647 while handle in _connection_refs: handle = (handle + 1) % 2147483647 _connection_refs[handle] = self result = Security.SSLSetConnection(self.context, handle) _assert_no_error(result) # If we have a server hostname, we should set that too. if server_hostname: if not isinstance(server_hostname, bytes): server_hostname = server_hostname.encode('utf-8') result = Security.SSLSetPeerDomainName( self.context, server_hostname, len(server_hostname) ) _assert_no_error(result) # Setup the ciphers. self._set_ciphers() # Set the minimum and maximum TLS versions. result = Security.SSLSetProtocolVersionMin(self.context, min_version) _assert_no_error(result) result = Security.SSLSetProtocolVersionMax(self.context, max_version) _assert_no_error(result) # If there's a trust DB, we need to use it. We do that by telling # SecureTransport to break on server auth. We also do that if we don't # want to validate the certs at all: we just won't actually do any # authing in that case. if not verify or trust_bundle is not None: result = Security.SSLSetSessionOption( self.context, SecurityConst.kSSLSessionOptionBreakOnServerAuth, True ) _assert_no_error(result) # If there's a client cert, we need to use it. if client_cert: self._keychain, self._keychain_dir = _temporary_keychain() self._client_cert_chain = _load_client_cert_chain( self._keychain, client_cert, client_key ) result = Security.SSLSetCertificate( self.context, self._client_cert_chain ) _assert_no_error(result) while True: with self._raise_on_error(): result = Security.SSLHandshake(self.context) if result == SecurityConst.errSSLWouldBlock: raise socket.timeout("handshake timed out") elif result == SecurityConst.errSSLServerAuthCompleted: self._custom_validate(verify, trust_bundle) continue else: _assert_no_error(result) break
python
def handshake(self, server_hostname, verify, trust_bundle, min_version, max_version, client_cert, client_key, client_key_passphrase): """ Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code. """ # First, we do the initial bits of connection setup. We need to create # a context, set its I/O funcs, and set the connection reference. self.context = Security.SSLCreateContext( None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType ) result = Security.SSLSetIOFuncs( self.context, _read_callback_pointer, _write_callback_pointer ) _assert_no_error(result) # Here we need to compute the handle to use. We do this by taking the # id of self modulo 2**31 - 1. If this is already in the dictionary, we # just keep incrementing by one until we find a free space. with _connection_ref_lock: handle = id(self) % 2147483647 while handle in _connection_refs: handle = (handle + 1) % 2147483647 _connection_refs[handle] = self result = Security.SSLSetConnection(self.context, handle) _assert_no_error(result) # If we have a server hostname, we should set that too. if server_hostname: if not isinstance(server_hostname, bytes): server_hostname = server_hostname.encode('utf-8') result = Security.SSLSetPeerDomainName( self.context, server_hostname, len(server_hostname) ) _assert_no_error(result) # Setup the ciphers. self._set_ciphers() # Set the minimum and maximum TLS versions. result = Security.SSLSetProtocolVersionMin(self.context, min_version) _assert_no_error(result) result = Security.SSLSetProtocolVersionMax(self.context, max_version) _assert_no_error(result) # If there's a trust DB, we need to use it. We do that by telling # SecureTransport to break on server auth. We also do that if we don't # want to validate the certs at all: we just won't actually do any # authing in that case. if not verify or trust_bundle is not None: result = Security.SSLSetSessionOption( self.context, SecurityConst.kSSLSessionOptionBreakOnServerAuth, True ) _assert_no_error(result) # If there's a client cert, we need to use it. if client_cert: self._keychain, self._keychain_dir = _temporary_keychain() self._client_cert_chain = _load_client_cert_chain( self._keychain, client_cert, client_key ) result = Security.SSLSetCertificate( self.context, self._client_cert_chain ) _assert_no_error(result) while True: with self._raise_on_error(): result = Security.SSLHandshake(self.context) if result == SecurityConst.errSSLWouldBlock: raise socket.timeout("handshake timed out") elif result == SecurityConst.errSSLServerAuthCompleted: self._custom_validate(verify, trust_bundle) continue else: _assert_no_error(result) break
[ "def", "handshake", "(", "self", ",", "server_hostname", ",", "verify", ",", "trust_bundle", ",", "min_version", ",", "max_version", ",", "client_cert", ",", "client_key", ",", "client_key_passphrase", ")", ":", "# First, we do the initial bits of connection setup. We need to create", "# a context, set its I/O funcs, and set the connection reference.", "self", ".", "context", "=", "Security", ".", "SSLCreateContext", "(", "None", ",", "SecurityConst", ".", "kSSLClientSide", ",", "SecurityConst", ".", "kSSLStreamType", ")", "result", "=", "Security", ".", "SSLSetIOFuncs", "(", "self", ".", "context", ",", "_read_callback_pointer", ",", "_write_callback_pointer", ")", "_assert_no_error", "(", "result", ")", "# Here we need to compute the handle to use. We do this by taking the", "# id of self modulo 2**31 - 1. If this is already in the dictionary, we", "# just keep incrementing by one until we find a free space.", "with", "_connection_ref_lock", ":", "handle", "=", "id", "(", "self", ")", "%", "2147483647", "while", "handle", "in", "_connection_refs", ":", "handle", "=", "(", "handle", "+", "1", ")", "%", "2147483647", "_connection_refs", "[", "handle", "]", "=", "self", "result", "=", "Security", ".", "SSLSetConnection", "(", "self", ".", "context", ",", "handle", ")", "_assert_no_error", "(", "result", ")", "# If we have a server hostname, we should set that too.", "if", "server_hostname", ":", "if", "not", "isinstance", "(", "server_hostname", ",", "bytes", ")", ":", "server_hostname", "=", "server_hostname", ".", "encode", "(", "'utf-8'", ")", "result", "=", "Security", ".", "SSLSetPeerDomainName", "(", "self", ".", "context", ",", "server_hostname", ",", "len", "(", "server_hostname", ")", ")", "_assert_no_error", "(", "result", ")", "# Setup the ciphers.", "self", ".", "_set_ciphers", "(", ")", "# Set the minimum and maximum TLS versions.", "result", "=", "Security", ".", "SSLSetProtocolVersionMin", "(", "self", ".", "context", ",", "min_version", ")", "_assert_no_error", "(", "result", ")", "result", "=", "Security", ".", "SSLSetProtocolVersionMax", "(", "self", ".", "context", ",", "max_version", ")", "_assert_no_error", "(", "result", ")", "# If there's a trust DB, we need to use it. We do that by telling", "# SecureTransport to break on server auth. We also do that if we don't", "# want to validate the certs at all: we just won't actually do any", "# authing in that case.", "if", "not", "verify", "or", "trust_bundle", "is", "not", "None", ":", "result", "=", "Security", ".", "SSLSetSessionOption", "(", "self", ".", "context", ",", "SecurityConst", ".", "kSSLSessionOptionBreakOnServerAuth", ",", "True", ")", "_assert_no_error", "(", "result", ")", "# If there's a client cert, we need to use it.", "if", "client_cert", ":", "self", ".", "_keychain", ",", "self", ".", "_keychain_dir", "=", "_temporary_keychain", "(", ")", "self", ".", "_client_cert_chain", "=", "_load_client_cert_chain", "(", "self", ".", "_keychain", ",", "client_cert", ",", "client_key", ")", "result", "=", "Security", ".", "SSLSetCertificate", "(", "self", ".", "context", ",", "self", ".", "_client_cert_chain", ")", "_assert_no_error", "(", "result", ")", "while", "True", ":", "with", "self", ".", "_raise_on_error", "(", ")", ":", "result", "=", "Security", ".", "SSLHandshake", "(", "self", ".", "context", ")", "if", "result", "==", "SecurityConst", ".", "errSSLWouldBlock", ":", "raise", "socket", ".", "timeout", "(", "\"handshake timed out\"", ")", "elif", "result", "==", "SecurityConst", ".", "errSSLServerAuthCompleted", ":", "self", ".", "_custom_validate", "(", "verify", ",", "trust_bundle", ")", "continue", "else", ":", "_assert_no_error", "(", "result", ")", "break" ]
Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code.
[ "Actually", "performs", "the", "TLS", "handshake", ".", "This", "is", "run", "automatically", "by", "wrapped", "socket", "and", "shouldn", "t", "be", "needed", "in", "user", "code", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L410-L498
train
pypa/pipenv
pipenv/vendor/jinja2/bccache.py
Bucket.write_bytecode
def write_bytecode(self, f): """Dump the bytecode into the file or file like object passed.""" if self.code is None: raise TypeError('can\'t write empty bucket') f.write(bc_magic) pickle.dump(self.checksum, f, 2) marshal_dump(self.code, f)
python
def write_bytecode(self, f): """Dump the bytecode into the file or file like object passed.""" if self.code is None: raise TypeError('can\'t write empty bucket') f.write(bc_magic) pickle.dump(self.checksum, f, 2) marshal_dump(self.code, f)
[ "def", "write_bytecode", "(", "self", ",", "f", ")", ":", "if", "self", ".", "code", "is", "None", ":", "raise", "TypeError", "(", "'can\\'t write empty bucket'", ")", "f", ".", "write", "(", "bc_magic", ")", "pickle", ".", "dump", "(", "self", ".", "checksum", ",", "f", ",", "2", ")", "marshal_dump", "(", "self", ".", "code", ",", "f", ")" ]
Dump the bytecode into the file or file like object passed.
[ "Dump", "the", "bytecode", "into", "the", "file", "or", "file", "like", "object", "passed", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/bccache.py#L98-L104
train
pypa/pipenv
pipenv/vendor/jinja2/bccache.py
BytecodeCache.get_cache_key
def get_cache_key(self, name, filename=None): """Returns the unique hash key for this template name.""" hash = sha1(name.encode('utf-8')) if filename is not None: filename = '|' + filename if isinstance(filename, text_type): filename = filename.encode('utf-8') hash.update(filename) return hash.hexdigest()
python
def get_cache_key(self, name, filename=None): """Returns the unique hash key for this template name.""" hash = sha1(name.encode('utf-8')) if filename is not None: filename = '|' + filename if isinstance(filename, text_type): filename = filename.encode('utf-8') hash.update(filename) return hash.hexdigest()
[ "def", "get_cache_key", "(", "self", ",", "name", ",", "filename", "=", "None", ")", ":", "hash", "=", "sha1", "(", "name", ".", "encode", "(", "'utf-8'", ")", ")", "if", "filename", "is", "not", "None", ":", "filename", "=", "'|'", "+", "filename", "if", "isinstance", "(", "filename", ",", "text_type", ")", ":", "filename", "=", "filename", ".", "encode", "(", "'utf-8'", ")", "hash", ".", "update", "(", "filename", ")", "return", "hash", ".", "hexdigest", "(", ")" ]
Returns the unique hash key for this template name.
[ "Returns", "the", "unique", "hash", "key", "for", "this", "template", "name", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/bccache.py#L166-L174
train
pypa/pipenv
pipenv/vendor/jinja2/bccache.py
BytecodeCache.get_bucket
def get_bucket(self, environment, name, filename, source): """Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`. """ key = self.get_cache_key(name, filename) checksum = self.get_source_checksum(source) bucket = Bucket(environment, key, checksum) self.load_bytecode(bucket) return bucket
python
def get_bucket(self, environment, name, filename, source): """Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`. """ key = self.get_cache_key(name, filename) checksum = self.get_source_checksum(source) bucket = Bucket(environment, key, checksum) self.load_bytecode(bucket) return bucket
[ "def", "get_bucket", "(", "self", ",", "environment", ",", "name", ",", "filename", ",", "source", ")", ":", "key", "=", "self", ".", "get_cache_key", "(", "name", ",", "filename", ")", "checksum", "=", "self", ".", "get_source_checksum", "(", "source", ")", "bucket", "=", "Bucket", "(", "environment", ",", "key", ",", "checksum", ")", "self", ".", "load_bytecode", "(", "bucket", ")", "return", "bucket" ]
Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`.
[ "Return", "a", "cache", "bucket", "for", "the", "given", "template", ".", "All", "arguments", "are", "mandatory", "but", "filename", "may", "be", "None", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/bccache.py#L180-L188
train
pypa/pipenv
pipenv/patched/notpip/_vendor/webencodings/__init__.py
lookup
def lookup(label): """ Look for an encoding by its label. This is the spec’s `get an encoding <http://encoding.spec.whatwg.org/#concept-encoding-get>`_ algorithm. Supported labels are listed there. :param label: A string. :returns: An :class:`Encoding` object, or :obj:`None` for an unknown label. """ # Only strip ASCII whitespace: U+0009, U+000A, U+000C, U+000D, and U+0020. label = ascii_lower(label.strip('\t\n\f\r ')) name = LABELS.get(label) if name is None: return None encoding = CACHE.get(name) if encoding is None: if name == 'x-user-defined': from .x_user_defined import codec_info else: python_name = PYTHON_NAMES.get(name, name) # Any python_name value that gets to here should be valid. codec_info = codecs.lookup(python_name) encoding = Encoding(name, codec_info) CACHE[name] = encoding return encoding
python
def lookup(label): """ Look for an encoding by its label. This is the spec’s `get an encoding <http://encoding.spec.whatwg.org/#concept-encoding-get>`_ algorithm. Supported labels are listed there. :param label: A string. :returns: An :class:`Encoding` object, or :obj:`None` for an unknown label. """ # Only strip ASCII whitespace: U+0009, U+000A, U+000C, U+000D, and U+0020. label = ascii_lower(label.strip('\t\n\f\r ')) name = LABELS.get(label) if name is None: return None encoding = CACHE.get(name) if encoding is None: if name == 'x-user-defined': from .x_user_defined import codec_info else: python_name = PYTHON_NAMES.get(name, name) # Any python_name value that gets to here should be valid. codec_info = codecs.lookup(python_name) encoding = Encoding(name, codec_info) CACHE[name] = encoding return encoding
[ "def", "lookup", "(", "label", ")", ":", "# Only strip ASCII whitespace: U+0009, U+000A, U+000C, U+000D, and U+0020.", "label", "=", "ascii_lower", "(", "label", ".", "strip", "(", "'\\t\\n\\f\\r '", ")", ")", "name", "=", "LABELS", ".", "get", "(", "label", ")", "if", "name", "is", "None", ":", "return", "None", "encoding", "=", "CACHE", ".", "get", "(", "name", ")", "if", "encoding", "is", "None", ":", "if", "name", "==", "'x-user-defined'", ":", "from", ".", "x_user_defined", "import", "codec_info", "else", ":", "python_name", "=", "PYTHON_NAMES", ".", "get", "(", "name", ",", "name", ")", "# Any python_name value that gets to here should be valid.", "codec_info", "=", "codecs", ".", "lookup", "(", "python_name", ")", "encoding", "=", "Encoding", "(", "name", ",", "codec_info", ")", "CACHE", "[", "name", "]", "=", "encoding", "return", "encoding" ]
Look for an encoding by its label. This is the spec’s `get an encoding <http://encoding.spec.whatwg.org/#concept-encoding-get>`_ algorithm. Supported labels are listed there. :param label: A string. :returns: An :class:`Encoding` object, or :obj:`None` for an unknown label.
[ "Look", "for", "an", "encoding", "by", "its", "label", ".", "This", "is", "the", "spec’s", "get", "an", "encoding", "<http", ":", "//", "encoding", ".", "spec", ".", "whatwg", ".", "org", "/", "#concept", "-", "encoding", "-", "get", ">", "_", "algorithm", ".", "Supported", "labels", "are", "listed", "there", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L61-L88
train
pypa/pipenv
pipenv/patched/notpip/_vendor/webencodings/__init__.py
_get_encoding
def _get_encoding(encoding_or_label): """ Accept either an encoding object or label. :param encoding: An :class:`Encoding` object or a label string. :returns: An :class:`Encoding` object. :raises: :exc:`~exceptions.LookupError` for an unknown label. """ if hasattr(encoding_or_label, 'codec_info'): return encoding_or_label encoding = lookup(encoding_or_label) if encoding is None: raise LookupError('Unknown encoding label: %r' % encoding_or_label) return encoding
python
def _get_encoding(encoding_or_label): """ Accept either an encoding object or label. :param encoding: An :class:`Encoding` object or a label string. :returns: An :class:`Encoding` object. :raises: :exc:`~exceptions.LookupError` for an unknown label. """ if hasattr(encoding_or_label, 'codec_info'): return encoding_or_label encoding = lookup(encoding_or_label) if encoding is None: raise LookupError('Unknown encoding label: %r' % encoding_or_label) return encoding
[ "def", "_get_encoding", "(", "encoding_or_label", ")", ":", "if", "hasattr", "(", "encoding_or_label", ",", "'codec_info'", ")", ":", "return", "encoding_or_label", "encoding", "=", "lookup", "(", "encoding_or_label", ")", "if", "encoding", "is", "None", ":", "raise", "LookupError", "(", "'Unknown encoding label: %r'", "%", "encoding_or_label", ")", "return", "encoding" ]
Accept either an encoding object or label. :param encoding: An :class:`Encoding` object or a label string. :returns: An :class:`Encoding` object. :raises: :exc:`~exceptions.LookupError` for an unknown label.
[ "Accept", "either", "an", "encoding", "object", "or", "label", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L91-L106
train
pypa/pipenv
pipenv/patched/notpip/_vendor/webencodings/__init__.py
decode
def decode(input, fallback_encoding, errors='replace'): """ Decode a single string. :param input: A byte string :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :return: A ``(output, encoding)`` tuple of an Unicode string and an :obj:`Encoding`. """ # Fail early if `encoding` is an invalid label. fallback_encoding = _get_encoding(fallback_encoding) bom_encoding, input = _detect_bom(input) encoding = bom_encoding or fallback_encoding return encoding.codec_info.decode(input, errors)[0], encoding
python
def decode(input, fallback_encoding, errors='replace'): """ Decode a single string. :param input: A byte string :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :return: A ``(output, encoding)`` tuple of an Unicode string and an :obj:`Encoding`. """ # Fail early if `encoding` is an invalid label. fallback_encoding = _get_encoding(fallback_encoding) bom_encoding, input = _detect_bom(input) encoding = bom_encoding or fallback_encoding return encoding.codec_info.decode(input, errors)[0], encoding
[ "def", "decode", "(", "input", ",", "fallback_encoding", ",", "errors", "=", "'replace'", ")", ":", "# Fail early if `encoding` is an invalid label.", "fallback_encoding", "=", "_get_encoding", "(", "fallback_encoding", ")", "bom_encoding", ",", "input", "=", "_detect_bom", "(", "input", ")", "encoding", "=", "bom_encoding", "or", "fallback_encoding", "return", "encoding", ".", "codec_info", ".", "decode", "(", "input", ",", "errors", ")", "[", "0", "]", ",", "encoding" ]
Decode a single string. :param input: A byte string :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :return: A ``(output, encoding)`` tuple of an Unicode string and an :obj:`Encoding`.
[ "Decode", "a", "single", "string", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L139-L158
train
pypa/pipenv
pipenv/patched/notpip/_vendor/webencodings/__init__.py
_detect_bom
def _detect_bom(input): """Return (bom_encoding, input), with any BOM removed from the input.""" if input.startswith(b'\xFF\xFE'): return _UTF16LE, input[2:] if input.startswith(b'\xFE\xFF'): return _UTF16BE, input[2:] if input.startswith(b'\xEF\xBB\xBF'): return UTF8, input[3:] return None, input
python
def _detect_bom(input): """Return (bom_encoding, input), with any BOM removed from the input.""" if input.startswith(b'\xFF\xFE'): return _UTF16LE, input[2:] if input.startswith(b'\xFE\xFF'): return _UTF16BE, input[2:] if input.startswith(b'\xEF\xBB\xBF'): return UTF8, input[3:] return None, input
[ "def", "_detect_bom", "(", "input", ")", ":", "if", "input", ".", "startswith", "(", "b'\\xFF\\xFE'", ")", ":", "return", "_UTF16LE", ",", "input", "[", "2", ":", "]", "if", "input", ".", "startswith", "(", "b'\\xFE\\xFF'", ")", ":", "return", "_UTF16BE", ",", "input", "[", "2", ":", "]", "if", "input", ".", "startswith", "(", "b'\\xEF\\xBB\\xBF'", ")", ":", "return", "UTF8", ",", "input", "[", "3", ":", "]", "return", "None", ",", "input" ]
Return (bom_encoding, input), with any BOM removed from the input.
[ "Return", "(", "bom_encoding", "input", ")", "with", "any", "BOM", "removed", "from", "the", "input", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L161-L169
train
pypa/pipenv
pipenv/patched/notpip/_vendor/webencodings/__init__.py
encode
def encode(input, encoding=UTF8, errors='strict'): """ Encode a single string. :param input: An Unicode string. :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. :return: A byte string. """ return _get_encoding(encoding).codec_info.encode(input, errors)[0]
python
def encode(input, encoding=UTF8, errors='strict'): """ Encode a single string. :param input: An Unicode string. :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. :return: A byte string. """ return _get_encoding(encoding).codec_info.encode(input, errors)[0]
[ "def", "encode", "(", "input", ",", "encoding", "=", "UTF8", ",", "errors", "=", "'strict'", ")", ":", "return", "_get_encoding", "(", "encoding", ")", ".", "codec_info", ".", "encode", "(", "input", ",", "errors", ")", "[", "0", "]" ]
Encode a single string. :param input: An Unicode string. :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. :return: A byte string.
[ "Encode", "a", "single", "string", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L172-L183
train
pypa/pipenv
pipenv/patched/notpip/_vendor/webencodings/__init__.py
iter_decode
def iter_decode(input, fallback_encoding, errors='replace'): """ "Pull"-based decoder. :param input: An iterable of byte strings. The input is first consumed just enough to determine the encoding based on the precense of a BOM, then consumed on demand when the return value is. :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :returns: An ``(output, encoding)`` tuple. :obj:`output` is an iterable of Unicode strings, :obj:`encoding` is the :obj:`Encoding` that is being used. """ decoder = IncrementalDecoder(fallback_encoding, errors) generator = _iter_decode_generator(input, decoder) encoding = next(generator) return generator, encoding
python
def iter_decode(input, fallback_encoding, errors='replace'): """ "Pull"-based decoder. :param input: An iterable of byte strings. The input is first consumed just enough to determine the encoding based on the precense of a BOM, then consumed on demand when the return value is. :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :returns: An ``(output, encoding)`` tuple. :obj:`output` is an iterable of Unicode strings, :obj:`encoding` is the :obj:`Encoding` that is being used. """ decoder = IncrementalDecoder(fallback_encoding, errors) generator = _iter_decode_generator(input, decoder) encoding = next(generator) return generator, encoding
[ "def", "iter_decode", "(", "input", ",", "fallback_encoding", ",", "errors", "=", "'replace'", ")", ":", "decoder", "=", "IncrementalDecoder", "(", "fallback_encoding", ",", "errors", ")", "generator", "=", "_iter_decode_generator", "(", "input", ",", "decoder", ")", "encoding", "=", "next", "(", "generator", ")", "return", "generator", ",", "encoding" ]
"Pull"-based decoder. :param input: An iterable of byte strings. The input is first consumed just enough to determine the encoding based on the precense of a BOM, then consumed on demand when the return value is. :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :returns: An ``(output, encoding)`` tuple. :obj:`output` is an iterable of Unicode strings, :obj:`encoding` is the :obj:`Encoding` that is being used.
[ "Pull", "-", "based", "decoder", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L186-L211
train
pypa/pipenv
pipenv/patched/notpip/_vendor/webencodings/__init__.py
_iter_decode_generator
def _iter_decode_generator(input, decoder): """Return a generator that first yields the :obj:`Encoding`, then yields output chukns as Unicode strings. """ decode = decoder.decode input = iter(input) for chunck in input: output = decode(chunck) if output: assert decoder.encoding is not None yield decoder.encoding yield output break else: # Input exhausted without determining the encoding output = decode(b'', final=True) assert decoder.encoding is not None yield decoder.encoding if output: yield output return for chunck in input: output = decode(chunck) if output: yield output output = decode(b'', final=True) if output: yield output
python
def _iter_decode_generator(input, decoder): """Return a generator that first yields the :obj:`Encoding`, then yields output chukns as Unicode strings. """ decode = decoder.decode input = iter(input) for chunck in input: output = decode(chunck) if output: assert decoder.encoding is not None yield decoder.encoding yield output break else: # Input exhausted without determining the encoding output = decode(b'', final=True) assert decoder.encoding is not None yield decoder.encoding if output: yield output return for chunck in input: output = decode(chunck) if output: yield output output = decode(b'', final=True) if output: yield output
[ "def", "_iter_decode_generator", "(", "input", ",", "decoder", ")", ":", "decode", "=", "decoder", ".", "decode", "input", "=", "iter", "(", "input", ")", "for", "chunck", "in", "input", ":", "output", "=", "decode", "(", "chunck", ")", "if", "output", ":", "assert", "decoder", ".", "encoding", "is", "not", "None", "yield", "decoder", ".", "encoding", "yield", "output", "break", "else", ":", "# Input exhausted without determining the encoding", "output", "=", "decode", "(", "b''", ",", "final", "=", "True", ")", "assert", "decoder", ".", "encoding", "is", "not", "None", "yield", "decoder", ".", "encoding", "if", "output", ":", "yield", "output", "return", "for", "chunck", "in", "input", ":", "output", "=", "decode", "(", "chunck", ")", "if", "output", ":", "yield", "output", "output", "=", "decode", "(", "b''", ",", "final", "=", "True", ")", "if", "output", ":", "yield", "output" ]
Return a generator that first yields the :obj:`Encoding`, then yields output chukns as Unicode strings.
[ "Return", "a", "generator", "that", "first", "yields", "the", ":", "obj", ":", "Encoding", "then", "yields", "output", "chukns", "as", "Unicode", "strings", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L214-L243
train