text
stringlengths
81
112k
“Pull”-based encoder. :param input: An iterable of Unicode strings. :param encoding: An :class:`Encoding` object or a label string. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :returns: An iterable of byt...
Decode one chunk of the input. :param input: A byte string. :param final: Indicate that no more input is available. Must be :obj:`True` if this is the last call. :returns: An Unicode string. def decode(self, input, final=False): """Decode one chunk of the input....
Given a list of Python tuples, create an associated CFDictionary. def _cf_dictionary_from_tuples(tuples): """ Given a list of Python tuples, create an associated CFDictionary. """ dictionary_size = len(tuples) # We need to get the dictionary keys and values out in the same order. keys = (t[0] ...
Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. def _cf_string_to_unicode(value): """ Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me qui...
Checks the return code and throws an exception if there is an error to report def _assert_no_error(error, exception_class=None): """ Checks the return code and throws an exception if there is an error to report """ if error == 0: return cf_error_string = Security.SecCopyErrorMessag...
Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain. def _cert_array_from_pem(pem_bundle): """ Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain. """ # Normalize the...
This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete....
Given a single file, loads all the trust objects from it into arrays and the keychain. Returns a tuple of lists: the first list is a list of identities, the second a list of certs. def _load_items_from_file(keychain, path): """ Given a single file, loads all the trust objects from it into arrays an...
Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain. def _load_client_cert_chain(keychain, *paths): """ Load certificates...
Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code. def get_redirect_location(self): """ Should we redirect ...
Set initial length value for Response content if available. def _init_length(self, request_method): """ Set initial length value for Response content if available. """ length = self.headers.get('content-length') if length is not None: if self.chunked: ...
Set-up the _decoder attribute if necessary. def _init_decoder(self): """ Set-up the _decoder attribute if necessary. """ # Note: content-encoding value should be case-insensitive, per RFC 7230 # Section 3.2 content_encoding = self.headers.get('content-encoding', '').lowe...
Flushes the decoder. Should only be called if the decoder is actually being used. def _flush_decoder(self): """ Flushes the decoder. Should only be called if the decoder is actually being used. """ if self._decoder: buf = self._decoder.decompress(b'') ...
Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool. def _error_catcher(self): """ Catch low-level python exceptions, instead re-raising urlli...
Similar to :meth:`httplib.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full ...
Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. def from_httplib(ResponseCls, r, **response_kw): """ ...
Similar to :meth:`HTTPResponse.read`, but with an additional parameter: ``decode_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param deco...
Returns the URL that was the source of this response. If the request that generated this response redirected, this method will return the final redirect location. def geturl(self): """ Returns the URL that was the source of this response. If the request that generated this respo...
Set Ok (success) finalizer to a spinner. def ok(self, text=u"OK", err=False): """Set Ok (success) finalizer to a spinner.""" # Do not display spin text for ok state self._text = None _text = to_text(text) if text else u"OK" err = err or not self.write_to_stdout self._fr...
Set fail finalizer to a spinner. def fail(self, text=u"FAIL", err=False): """Set fail finalizer to a spinner.""" # Do not display spin text for fail state self._text = None _text = text if text else u"FAIL" err = err or not self.write_to_stdout self._freeze(_text, err=e...
Write error text in the terminal without breaking the spinner. def write_err(self, text): """Write error text in the terminal without breaking the spinner.""" stderr = self.stderr if self.stderr.closed: stderr = sys.stderr stderr.write(decode_output(u"\r", target_stream=stde...
Stop spinner, compose last frame and 'freeze' it. def _freeze(self, final_text, err=False): """Stop spinner, compose last frame and 'freeze' it.""" if not final_text: final_text = "" target = self.stderr if err else self.stdout if target.closed: target = sys.stde...
Like `describe_token` but for token expressions. def describe_token_expr(expr): """Like `describe_token` but for token expressions.""" if ':' in expr: type, value = expr.split(':', 1) if type == 'name': return value else: type = expr return _describe_token_type(type)
Return a lexer which is probably cached. def get_lexer(environment): """Return a lexer which is probably cached.""" key = (environment.block_start_string, environment.block_end_string, environment.variable_start_string, environment.variable_end_string, environment.co...
Calls tokeniter + tokenize and wraps it in a token stream. def tokenize(self, source, name=None, filename=None, state=None): """Calls tokeniter + tokenize and wraps it in a token stream. """ stream = self.tokeniter(source, name, filename, state) return TokenStream(self.wrap(stream, name...
This is called with the stream as returned by `tokenize` and wraps every token in a :class:`Token` and converts the value. def wrap(self, stream, name=None, filename=None): """This is called with the stream as returned by `tokenize` and wraps every token in a :class:`Token` and converts the val...
Load the pyproject.toml file. Parameters: use_pep517 - Has the user requested PEP 517 processing? None means the user hasn't explicitly specified. pyproject_toml - Location of the project's pyproject.toml file setup_py - Location of the project's setup.py file r...
Iterate through CPython versions available for Pipenv to install. def iter_installable_versions(self): """Iterate through CPython versions available for Pipenv to install. """ for name in self._pyenv('install', '--list').out.splitlines(): try: version = Version.parse...
Find a version in pyenv from the version supplied. A ValueError is raised if a matching version cannot be found. def find_version_to_install(self, name): """Find a version in pyenv from the version supplied. A ValueError is raised if a matching version cannot be found. """ ver...
Install the given version with pyenv. The version must be a ``Version`` instance representing a version found in pyenv. A ValueError is raised if the given version does not have a match in pyenv. A PyenvError is raised if the pyenv command fails. def install(self, version): ""...
Parses an editable requirement into: - a requirement name - an URL - extras - editable options Accepted requirements: svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir .[some_extra] def parse_editable(editable_req): # type: (str) -> Tuple[Option...
Returns helpful msg in case requirements file does not exist, or cannot be parsed. :params req: Requirements file path def deduce_helpful_msg(req): # type: (str) -> str """Returns helpful msg in case requirements file does not exist, or cannot be parsed. :params req: Requirements file path ...
Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. def install_req_from_line( name, # type: str comes_from=None, # type: Optional[Union[str, InstallRequirement]] use_pep517=None, # type: Optional[bool] isolated=False, # ty...
Return the file cache path based on the URL. This does not ensure the file exists! def url_to_file_path(url, filecache): """Return the file cache path based on the URL. This does not ensure the file exists! """ key = CacheController.cache_url(url) return filecache._fn(key)
Write the PID in the named PID file. Get the numeric process ID (“PID”) of the current process and write it to the named file as a line of text. def write_pid_to_pidfile(pidfile_path): """ Write the PID in the named PID file. Get the numeric process ID (“PID”) of the current process ...
Remove the named PID file if it exists. Removing a PID file that doesn't already exist puts us in the desired state, so we ignore the condition if the file does not exist. def remove_existing_pidfile(pidfile_path): """ Remove the named PID file if it exists. Removing a PID file th...
Release the lock. Removes the PID file to release the lock, or raises an error if the current process does not hold the lock. def release(self): """ Release the lock. Removes the PID file to release the lock, or raises an error if the current process does not h...
Export the Bazaar repository at the url to the destination location def export(self, location): """ Export the Bazaar repository at the url to the destination location """ # Remove the location to make sure Bazaar can export it correctly if os.path.exists(location): ...
Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory. def search_packages_info(query): """ Gather details from installed distributions. ...
Print the informations from installed distributions found. def print_results(distributions, list_files=False, verbose=False): """ Print the informations from installed distributions found. """ results_printed = False for i, dist in enumerate(distributions): results_printed = True if...
Convenience method that raises `exc` with the message, passed line number or last line number as well as the current name and filename. def fail(self, msg, lineno=None, exc=TemplateSyntaxError): """Convenience method that raises `exc` with the message, passed line number or last line nu...
Called if the parser encounters an unknown tag. Tries to fail with a human readable error message that could help to identify the problem. def fail_unknown_tag(self, name, lineno=None): """Called if the parser encounters an unknown tag. Tries to fail with a human readable error messag...
Like fail_unknown_tag but for end of template situations. def fail_eof(self, end_tokens=None, lineno=None): """Like fail_unknown_tag but for end of template situations.""" stack = list(self._end_token_stack) if end_tokens is not None: stack.append(end_tokens) return self._fa...
Are we at the end of a tuple? def is_tuple_end(self, extra_end_rules=None): """Are we at the end of a tuple?""" if self.stream.current.type in ('variable_end', 'block_end', 'rparen'): return True elif extra_end_rules is not None: return self.stream.current.test_any(extra...
Return a new free identifier as :class:`~jinja2.nodes.InternalName`. def free_identifier(self, lineno=None): """Return a new free identifier as :class:`~jinja2.nodes.InternalName`.""" self._last_identifier += 1 rv = object.__new__(nodes.InternalName) nodes.Node.__init__(rv, 'fi%d' % sel...
Parse a single statement. def parse_statement(self): """Parse a single statement.""" token = self.stream.current if token.type != 'name': self.fail('tag name expected', token.lineno) self._tag_stack.append(token.value) pop_tag = True try: if token...
Parse multiple statements into a list until one of the end tokens is reached. This is used to parse the body of statements as it also parses template data if appropriate. The parser checks first if the current token is a colon and skips it if there is one. Then it checks for the block...
Parse an assign statement. def parse_set(self): """Parse an assign statement.""" lineno = next(self.stream).lineno target = self.parse_assign_target(with_namespace=True) if self.stream.skip_if('assign'): expr = self.parse_tuple() return nodes.Assign(target, expr,...
Parse a for loop. def parse_for(self): """Parse a for loop.""" lineno = self.stream.expect('name:for').lineno target = self.parse_assign_target(extra_end_rules=('name:in',)) self.stream.expect('name:in') iter = self.parse_tuple(with_condexpr=False, ...
Parse an if construct. def parse_if(self): """Parse an if construct.""" node = result = nodes.If(lineno=self.stream.expect('name:if').lineno) while 1: node.test = self.parse_tuple(with_condexpr=False) node.body = self.parse_statements(('name:elif', 'name:else', ...
Parse an assignment target. As Jinja2 allows assignments to tuples, this function can parse all allowed assignment targets. Per default assignments to tuples are parsed, that can be disable however by setting `with_tuple` to `False`. If only assignments to names are wanted `name_only`...
Parse the whole template into a `Template` node. def parse(self): """Parse the whole template into a `Template` node.""" result = nodes.Template(self.subparse(), lineno=1) result.set_environment(self.environment) return result
This returns an abbreviated stack trace with lines that only concern the caller. In other words, the stack trace inside the Pexpect module is not included. def get_trace(self): '''This returns an abbreviated stack trace with lines that only concern the caller. In other words, the stack ...
Parses a URI using the regex given in Appendix B of RFC 3986. (scheme, authority, path, query, fragment) = parse_uri(uri) def parse_uri(uri): """Parses a URI using the regex given in Appendix B of RFC 3986. (scheme, authority, path, query, fragment) = parse_uri(uri) """ groups = URI.match...
Normalize the URL to create a safe key for the cache def _urlnorm(cls, uri): """Normalize the URL to create a safe key for the cache""" (scheme, authority, path, query, fragment) = parse_uri(uri) if not scheme or not authority: raise Exception("Only absolute URIs are allowed. uri = ...
Return a cached response if it exists in the cache, otherwise return False. def cached_request(self, request): """ Return a cached response if it exists in the cache, otherwise return False. """ cache_url = self.cache_url(request.url) logger.debug('Looking up "%s...
Algorithm for caching requests. This assumes a requests Response object. def cache_response(self, request, response, body=None, status_codes=None): """ Algorithm for caching requests. This assumes a requests Response object. """ # From httplib2: Don't cache 206's since...
On a 304 we will get a new set of headers that we want to update our cached value with, assuming we have one. This should only ever be called when we've sent an ETag and gotten a 304 as the response. def update_cached_response(self, request, response): """On a 304 we will get a new set...
Close the file descriptor. Calling this method a second time does nothing, but if the file descriptor was closed elsewhere, :class:`OSError` will be raised. def close (self): """Close the file descriptor. Calling this method a second time does nothing, but if the file descript...
This checks if the file descriptor is still valid. If :func:`os.fstat` does not raise an exception then we assume it is alive. def isalive (self): '''This checks if the file descriptor is still valid. If :func:`os.fstat` does not raise an exception then we assume it is alive. ''' if se...
Read from the file descriptor and return the result as a string. The read_nonblocking method of :class:`SpawnBase` assumes that a call to os.read will not block (timeout parameter is ignored). This is not the case for POSIX file-like objects such as sockets and serial ports. Use :func:...
Jinja2 keeps internal caches for environments and lexers. These are used so that Jinja2 doesn't have to recreate environments and lexers all the time. Normally you don't have to care about that but if you are measuring memory consumption you may want to clean the caches. def clear_caches(): """Jinja2...
Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax.saxutils:escape``). If the `silent` is True the...
Prettyprint an object. Either use the `pretty` library or the builtin `pprint`. def pformat(obj, verbose=False): """Prettyprint an object. Either use the `pretty` library or the builtin `pprint`. """ try: from pretty import pretty return pretty(obj, verbose=verbose) except Imp...
URL escapes a single bytestring or unicode string with the given charset if applicable to URL safe quoting under all rules that need to be considered under all supported Python versions. If non strings are provided they are converted to their unicode representation first. def unicode_urlencode(obj, ch...
Intelligently sets the initial value of autoescaping based on the filename of the template. This is the recommended way to configure autoescaping if you do not want to write a custom function yourself. If you want to enable it for all templates created from strings or for all templates with `.html` an...
Works exactly like :func:`dumps` but is safe for use in ``<script>`` tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the ``|tojson`` filter which will also mark the result as safe. Due to how this function escapes certain characters this...
Return a shallow copy of the instance. def copy(self): """Return a shallow copy of the instance.""" rv = self.__class__(self.capacity) rv._mapping.update(self._mapping) rv._queue = deque(self._queue) return rv
Set `default` if the key is not in the cache otherwise leave unchanged. Return the value of this key. def setdefault(self, key, default=None): """Set `default` if the key is not in the cache otherwise leave unchanged. Return the value of this key. """ self._wlock.acquire() ...
Clear the cache. def clear(self): """Clear the cache.""" self._wlock.acquire() try: self._mapping.clear() self._queue.clear() finally: self._wlock.release()
Return a list of items. def items(self): """Return a list of items.""" result = [(key, self._mapping[key]) for key in list(self._queue)] result.reverse() return result
Hardcoded license URLs. Check when updating if those are still needed def license_fallback(vendor_dir, sdist_name): """Hardcoded license URLs. Check when updating if those are still needed""" libname = libname_from_dir(sdist_name) if libname not in HARDCODED_LICENSE_URLS: raise ValueError('No hardc...
Reconstruct the library name without it's version def libname_from_dir(dirname): """Reconstruct the library name without it's version""" parts = [] for part in dirname.split('-'): if part[0].isdigit(): break parts.append(part) return '-'.join(parts)
Given the (reconstructed) library name, find appropriate destination def license_destination(vendor_dir, libname, filename): """Given the (reconstructed) library name, find appropriate destination""" normal = vendor_dir / libname if normal.is_dir(): return normal / filename lowercase = vendor_d...
Convert Pipfile.lock hash lines into InstallRequirement option format. The option format uses a str-list mapping. Keys are hash algorithms, and the list contains all values of that algorithm. def _convert_hashes(values): """Convert Pipfile.lock hash lines into InstallRequirement option format. The op...
Hack to hide noise generated by `setup.py develop`. There isn't a good way to suppress them now, so let's monky-patch. See https://bugs.python.org/issue25392. def _suppress_distutils_logs(): """Hack to hide noise generated by `setup.py develop`. There isn't a good way to suppress them now, so let's m...
Find this package's .egg-info directory. Due to how sdists are designed, the .egg-info directory cannot be reliably found without running setup.py to aggregate all configurations. This function instead uses some heuristics to locate the egg-info directory that most likely represents this package. ...
Encodes a string into the proper filesystem encoding Borrowed from pip-tools def fs_str(string): """Encodes a string into the proper filesystem encoding Borrowed from pip-tools """ if isinstance(string, str): return string assert not isinstance(string, bytes) return string.encode...
Fetch the string value from a path-like object Returns **None** if there is no string value. def _get_path(path): """ Fetch the string value from a path-like object Returns **None** if there is no string value. """ if isinstance(path, (six.string_types, bytes)): return path path_...
Encode a filesystem path to the proper filesystem encoding :param Union[str, bytes] path: A string-like path :returns: A bytes-encoded filesystem path representation def fs_encode(path): """ Encode a filesystem path to the proper filesystem encoding :param Union[str, bytes] path: A string-like pa...
Decode a filesystem path using the proper filesystem encoding :param path: The filesystem path to decode from bytes or string :return: [description] :rtype: [type] def fs_decode(path): """ Decode a filesystem path using the proper filesystem encoding :param path: The filesystem path to decode...
Build a collection of "traces" for each package. A trace is a list of names that eventually leads to the package. For example, if A and B are root dependencies, A depends on C and D, B depends on C, and C depends on D, the return value would be like:: { None: [], "A": [None...
Check that a timeout attribute is valid. :param value: The timeout value to validate :param name: The name of the timeout attribute to validate. This is used to specify in error messages. :return: The validated and casted version of the given value. :raises ValueError: If it...
Create a copy of the timeout object Timeout properties are stored per-pool but each request needs a fresh Timeout object to ensure each one has its own start/stop configured. :return: a copy of the timeout object :rtype: :class:`Timeout` def clone(self): """ Create a copy of t...
Start the timeout clock, used during a connect() attempt :raises urllib3.exceptions.TimeoutStateError: if you attempt to start a timer that has been started already. def start_connect(self): """ Start the timeout clock, used during a connect() attempt :raises urllib3.exceptions.Ti...
Get the value to use when setting a connection timeout. This will be a positive float or integer, the value None (never timeout), or the default system timeout. :return: Connect timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None def connect_timeout(self): """...
Get the value for the read timeout. This assumes some time has elapsed in the connection timeout and computes the read timeout appropriately. If self.total is set, the read timeout is dependent on the amount of time taken by the connect timeout. If the connection time has not been ...
Establish a new connection via the SOCKS proxy. def _new_conn(self): """ Establish a new connection via the SOCKS proxy. """ extra_kw = {} if self.source_address: extra_kw['source_address'] = self.source_address if self.socket_options: extra_kw['...
Compute and return values (req, editable, comments) for use in FrozenRequirement.from_dist(). def get_requirement_info(dist): # type: (Distribution) -> RequirementInfo """ Compute and return values (req, editable, comments) for use in FrozenRequirement.from_dist(). """ if not dist_is_editab...
Detect /proc filesystem style. This checks the /proc/{pid} directory for possible formats. Returns one of the followings as str: * `stat`: Linux-style, i.e. ``/proc/{pid}/stat``. * `status`: BSD-style, i.e. ``/proc/{pid}/status``. def detect_proc(): """Detect /proc filesystem style. This che...
Try to look up the process tree via the /proc interface. def get_process_mapping(): """Try to look up the process tree via the /proc interface. """ stat_name = detect_proc() self_tty = _get_stat(os.getpid(), stat_name)[0] processes = {} for pid in os.listdir('/proc'): if not pid.isdigit...
Create and return a temporary file. Arguments: 'prefix', 'suffix', 'dir' -- as for mkstemp. 'mode' -- the mode argument to io.open (default "w+b"). 'buffering' -- the buffer size argument to io.open (default -1). 'encoding' -- the encoding argument to io.open (default None) 'newline' -- the newl...
Exit without garbage collection, this speeds up exit by about 10ms for things like bash completion. def fast_exit(code): """Exit without garbage collection, this speeds up exit by about 10ms for things like bash completion. """ sys.stdout.flush() sys.stderr.flush() os._exit(code)
Internal handler for the bash completion support. def _bashcomplete(cmd, prog_name, complete_var=None): """Internal handler for the bash completion support.""" if complete_var is None: complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper() complete_instr = os.environ.get(complete_var...
Context manager that attaches extra information to exceptions that fly. def augment_usage_errors(ctx, param=None): """Context manager that attaches extra information to exceptions that fly. """ try: yield except BadParameter as e: if e.ctx is None: e.ctx = ctx ...
Given a sequence of parameters in the order as should be considered for processing and an iterable of parameters that exist, this returns a list in the correct order as they should be processed. def iter_params_for_processing(invocation_order, declaration_order): """Given a sequence of parameters in the or...
This helper method can be used with the context object to promote it to the current thread local (see :func:`get_current_context`). The default behavior of this is to invoke the cleanup functions which can be disabled by setting `cleanup` to `False`. The cleanup functions are typically ...
The computed command path. This is used for the ``usage`` information on the help page. It's automatically created by combining the info names of the chain of contexts to the root. def command_path(self): """The computed command path. This is used for the ``usage`` information on the...
Finds the outermost context. def find_root(self): """Finds the outermost context.""" node = self while node.parent is not None: node = node.parent return node
Finds the closest object of a given type. def find_object(self, object_type): """Finds the closest object of a given type.""" node = self while node is not None: if isinstance(node.obj, object_type): return node.obj node = node.parent