text
stringlengths
81
112k
Load requests lazily. def _get_requests_session(): """Load requests lazily.""" global requests_session if requests_session is not None: return requests_session import requests requests_session = requests.Session() adapter = requests.adapters.HTTPAdapter( max_retries=environment...
Converts all outline tables to inline tables. def convert_toml_outline_tables(parsed): """Converts all outline tables to inline tables.""" def convert_tomlkit_table(section): for key, value in section._body: if not key: continue if hasattr(value, "keys") and not ...
Take an input command and run it, handling exceptions and error codes and returning its stdout and stderr. :param cmd: The list of command and arguments. :type cmd: list :returns: A 2-tuple of the output and error from the command :rtype: Tuple[str, str] :raises: exceptions.PipenvCmdError def ...
Parse a Python version output returned by `python --version`. Return a dict with three keys: major, minor, and micro. Each value is a string containing a version part. Note: The micro part would be `'0'` if it's missing from the input string. def parse_python_version(output): """Parse a Python versio...
Prepares a string for the shell (on Windows too!) Only for use on grouped arguments (passed as a string to Popen) def escape_grouped_arguments(s): """Prepares a string for the shell (on Windows too!) Only for use on grouped arguments (passed as a string to Popen) """ if s is None: return ...
Resolve dependencies for a pipenv project, acts as a portal to the target environment. Regardless of whether a virtual environment is present or not, this will spawn a subproces which is isolated to the target environment and which will perform dependency resolution. This function reads the output of that...
Given a list of dependencies, return a resolved list of dependencies, using pip-tools -- and their hashes, using the warehouse API / pip. def resolve_deps( deps, which, project, sources=None, python=False, clear=False, pre=False, allow_global=False, req_dir=None ): """Given ...
Converts a Pipfile-formatted dependency to a pip-formatted one. def convert_deps_to_pip(deps, project=None, r=True, include_index=True): """"Converts a Pipfile-formatted dependency to a pip-formatted one.""" from .vendor.requirementslib.models.requirements import Requirement dependencies = [] for dep_...
Check to see if there's a hard requirement for version number provided in the Pipfile. def is_required_version(version, specified_version): """Check to see if there's a hard requirement for version number provided in the Pipfile. """ # Certain packages may be defined with multiple values. if is...
Determine if a path can potentially be installed def is_installable_file(path): """Determine if a path can potentially be installed""" from .vendor.pip_shims.shims import is_installable_dir, is_archive_file from .patched.notpip._internal.utils.packaging import specifiers from ._compat import Path ...
Determine if a package name is for a File dependency. def is_file(package): """Determine if a package name is for a File dependency.""" if hasattr(package, "keys"): return any(key for key in package.keys() if key in ["file", "path"]) if os.path.exists(str(package)): return True for st...
Normalize package name to PEP 423 style standard. def pep423_name(name): """Normalize package name to PEP 423 style standard.""" name = name.lower() if any(i not in name for i in (VCS_LIST + SCHEME_LIST)): return name.replace("_", "-") else: return name
Properly case project name from pypi.org. def proper_case(package_name): """Properly case project name from pypi.org.""" # Hit the simple API. r = _get_requests_session().get( "https://pypi.org/pypi/{0}/json".format(package_name), timeout=0.3, stream=True ) if not r.ok: raise IOErro...
Given an executable name, search the given location for an executable def find_windows_executable(bin_path, exe_name): """Given an executable name, search the given location for an executable""" requested_path = get_windows_path(bin_path, exe_name) if os.path.isfile(requested_path): return requeste...
Canonicalize a list of packages and return a set of canonical names def get_canonical_names(packages): """Canonicalize a list of packages and return a set of canonical names""" from .vendor.packaging.utils import canonicalize_name if not isinstance(packages, Sequence): if not isinstance(packages, ...
Returns the path of a Pipfile in parent directories. def find_requirements(max_depth=3): """Returns the path of a Pipfile in parent directories.""" i = 0 for c, d, f in walk_up(os.getcwd()): i += 1 if i < max_depth: if "requirements.txt": r = os.path.join(c, "req...
Allow the ability to set os.environ temporarily def temp_environ(): """Allow the ability to set os.environ temporarily""" environ = dict(os.environ) try: yield finally: os.environ.clear() os.environ.update(environ)
Allow the ability to set os.environ temporarily def temp_path(): """Allow the ability to set os.environ temporarily""" path = [p for p in sys.path] try: yield finally: sys.path = [p for p in path]
Checks if a given string is an url def is_valid_url(url): """Checks if a given string is an url""" pieces = urlparse(url) return all([pieces.scheme, pieces.netloc])
Downloads file from url to a path with filename def download_file(url, filename): """Downloads file from url to a path with filename""" r = _get_requests_session().get(url, stream=True) if not r.ok: raise IOError("Unable to download file") with open(filename, "wb") as f: f.write(r.cont...
Normalize drive in path so they stay consistent. This currently only affects local drives on Windows, which can be identified with either upper or lower cased drive names. The case is always converted to uppercase because it seems to be preferred. See: <https://github.com/pypa/pipenv/issues/1218> def...
Check if a provided path exists and is readonly. Permissions check is `bool(path.stat & stat.S_IREAD)` or `not os.access(path, os.W_OK)` def is_readonly_path(fn): """Check if a provided path exists and is readonly. Permissions check is `bool(path.stat & stat.S_IREAD)` or `not os.access(path, os.W_OK)` ...
Error handler for shutil.rmtree. Windows source repo folders are read-only by default, so this error handler attempts to set them as writeable and then proceed with deletion. def handle_remove_readonly(func, path, exc): """Error handler for shutil.rmtree. Windows source repo folders are read-only by ...
Call os.path.expandvars if value is a string, otherwise do nothing. def safe_expandvars(value): """Call os.path.expandvars if value is a string, otherwise do nothing. """ if isinstance(value, six.string_types): return os.path.expandvars(value) return value
Take a pipfile entry and normalize its markers Provide a pipfile entry which may have 'markers' as a key or it may have any valid key from `packaging.markers.marker_context.keys()` and standardize the format into {'markers': 'key == "some_value"'}. :param pipfile_entry: A dictionariy of keys and value...
Check if a given path is a virtual environment's root. This is done by checking if the directory contains a Python executable in its bin/Scripts directory. Not technically correct, but good enough for general usage. def is_virtual_environment(path): """Check if a given path is a virtual environment's ...
Set a temporary sys.version_info tuple :param version_tuple: a fake sys.version_info tuple def sys_version(version_tuple): """ Set a temporary sys.version_info tuple :param version_tuple: a fake sys.version_info tuple """ old_version = sys.version_info sys.version_info = version_tuple ...
Given a set and some arbitrary element, add the element(s) to the set def add_to_set(original_set, element): """Given a set and some arbitrary element, add the element(s) to the set""" if not element: return original_set if isinstance(element, Set): original_set |= element elif isinstan...
Compare two urls by scheme, host, and path, ignoring auth :param str url: The initial URL to compare :param str url: Second url to compare to the first :return: Whether the URLs are equal without **auth**, **query**, and **fragment** :rtype: bool >>> is_url_equal("https://user:pass@mydomain.com/so...
Convert a path with possible windows-style separators to a posix-style path (with **/** separators instead of **\\** separators). :param Text path: A path to convert. :return: A converted posix-style path :rtype: Text >>> make_posix("c:/users/user/venvs/some_venv\\Lib\\site-packages") "c:/user...
Given a `pythonfinder.Finder` instance and an optional line, find a corresponding python :param finder: A :class:`pythonfinder.Finder` instance to use for searching :type finder: :class:pythonfinder.Finder` :param str line: A version, path, name, or nothing, defaults to None :return: A path to python ...
Given an input, checks whether the input is a request for python or notself. This can be a version, a python runtime name, or a generic 'python' or 'pythonX.Y' :param str line: A potential request to find python :returns: Whether the line is a python lookup :rtype: bool def is_python_command(line): ...
Retrieve hashes for a specific ``InstallRequirement`` instance. :param ireq: An ``InstallRequirement`` to retrieve hashes for :type ireq: :class:`~pip_shims.InstallRequirement` :return: A set of hashes. :rtype: Set def get_hash(self, ireq, ireq_hashes=None): """ Retriev...
Select a way to obtain process information from the system. * `/proc` is used if supported. * The system `ps` utility is used as a fallback option. def _get_process_mapping(): """Select a way to obtain process information from the system. * `/proc` is used if supported. * The system `ps` utility ...
Iterator to traverse up the tree, yielding `argv[0]` of each process. def _iter_process_command(mapping, pid, max_depth): """Iterator to traverse up the tree, yielding `argv[0]` of each process. """ for _ in range(max_depth): try: proc = mapping[pid] except KeyError: # We've ...
Form shell information from the SHELL environment variable if possible. def _get_login_shell(proc_cmd): """Form shell information from the SHELL environment variable if possible. """ login_shell = os.environ.get('SHELL', '') if login_shell: proc_cmd = login_shell else: proc_cmd = pr...
Get the shell that the supplied pid or os.getpid() is running in. def get_shell(pid=None, max_depth=6): """Get the shell that the supplied pid or os.getpid() is running in. """ pid = str(pid or os.getpid()) mapping = _get_process_mapping() for proc_cmd in _iter_process_command(mapping, pid, max_dep...
Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up...
Initializes a urllib3 PoolManager. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param connections: The number of urllib3 connection pools to cache. :param maxsize: The ma...
Return urllib3 ProxyManager for the given proxy. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The proxy to return a urllib3 ProxyManager for. :param proxy_kw...
Builds a :class:`Response <requests.Response>` object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>` :param req: The :class:`PreparedRequest <PreparedRequest>` used ...
Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of p...
Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections. def close(self): """Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any poo...
Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the ...
Return git+ssh:// formatted URI to git+git@ format def strip_ssh_from_git_uri(uri): # type: (S) -> S """Return git+ssh:// formatted URI to git+git@ format""" if isinstance(uri, six.string_types): if "git+ssh://" in uri: parsed = urlparse(uri) # split the path on the first se...
Cleans VCS uris from pipenv.patched.notpip format def add_ssh_scheme_to_git_uri(uri): # type: (S) -> S """Cleans VCS uris from pipenv.patched.notpip format""" if isinstance(uri, six.string_types): # Add scheme for parsing purposes, this is also what pip does if uri.startswith("git+") and ":...
Determine if dictionary entry from Pipfile is for a vcs dependency. def is_vcs(pipfile_entry): # type: (PipfileType) -> bool """Determine if dictionary entry from Pipfile is for a vcs dependency.""" if isinstance(pipfile_entry, Mapping): return any(key for key in pipfile_entry.keys() if key in VCS_...
Splits on multiple given separators. def multi_split(s, split): # type: (S, Iterable[S]) -> List[S] """Splits on multiple given separators.""" for r in split: s = s.replace(r, "|") return [i for i in s.split("|") if len(i) > 0]
Convert a pipfile entry to a string def convert_entry_to_path(path): # type: (Dict[S, Union[S, bool, Tuple[S], List[S]]]) -> S """Convert a pipfile entry to a string""" if not isinstance(path, Mapping): raise TypeError("expecting a mapping, received {0!r}".format(path)) if not any(key in path...
Determine if a path can potentially be installed def is_installable_file(path): # type: (PipfileType) -> bool """Determine if a path can potentially be installed""" from packaging import specifiers if isinstance(path, Mapping): path = convert_entry_to_path(path) # If the string starts wit...
Retrieve a value from a nested object via a tuple representing the lookup path. >>> root = {'a': {'b': {'c': [[1], [2], [3]]}}} >>> get_path(root, ('a', 'b', 'c', 2, 0)) 3 The path format is intentionally consistent with that of :func:`remap`. One of get_path's chief aims is improved error m...
Return a comparison of actual and expected hash values. Example:: Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde or 123451234512345123451234512345123451234512345 Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef def _hash_co...
Reset the UniversalDetector and all of its probers back to their initial states. This is called by ``__init__``, so you only need to call this directly in between analyses of different documents. def reset(self): """ Reset the UniversalDetector and all of its probers back to their ...
Takes a chunk of a document and feeds it through all of the relevant charset probers. After calling ``feed``, you can check the value of the ``done`` attribute to see if you need to continue feeding the ``UniversalDetector`` more data, or if it has made a prediction (in the ``re...
Stop analyzing the current document and come up with a final prediction. :returns: The ``result`` attribute, a ``dict`` with the keys `encoding`, `confidence`, and `language`. def close(self): """ Stop analyzing the current document and come up with a final ...
Start a bash shell and return a :class:`REPLWrapper` object. def bash(command="bash"): """Start a bash shell and return a :class:`REPLWrapper` object.""" bashrc = os.path.join(os.path.dirname(__file__), 'bashrc.sh') child = pexpect.spawn(command, ['--rcfile', bashrc], echo=False, ...
Send a command to the REPL, wait for and return output. :param str command: The command to send. Trailing newlines are not needed. This should be a complete block of input that will trigger execution; if a continuation prompt is found after sending input, :exc:`ValueError` will be...
Parse hashes from *self.line* and set them on the current object. :returns: Nothing :rtype: None def parse_hashes(self): # type: () -> None """ Parse hashes from *self.line* and set them on the current object. :returns: Nothing :rtype: None """ l...
Parse extras from *self.line* and set them on the current object :returns: Nothing :rtype: None def parse_extras(self): # type: () -> None """ Parse extras from *self.line* and set them on the current object :returns: Nothing :rtype: None """ ext...
Sets ``self.name`` if given a **PEP-508** style URL def get_url(self): # type: () -> STRING_TYPE """Sets ``self.name`` if given a **PEP-508** style URL""" line = self.line try: parsed = URI.parse(line) line = parsed.to_string(escape_password=False, direct=False,...
Generates a 3-tuple of the requisite *name*, *extras* and *url* to generate a :class:`~packaging.requirements.Requirement` out of. :return: A Tuple of an optional name, a Tuple of extras, and an optional URL. :rtype: Tuple[Optional[S], Tuple[Optional[S], ...], Optional[S]] def requirement_info...
This is a safeguard against decoy requirements when a user installs a package whose name coincides with the name of a folder in the cwd, e.g. install *alembic* when there is a folder called *alembic* in the working directory. In this case we first need to check that the given requirement is a v...
This implements a substitute for the forkpty system call. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris. Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to resolve the issue with Python's pty.fork() not supporting Solaris, ...
This makes the pseudo-terminal the controlling tty. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris. def pty_make_controlling_tty(tty_fd): '''This makes the pseudo-terminal the controlling tty. This should be more portable than the pty.fork() functio...
Wraps a function so that it swallows exceptions. def safecall(func): """Wraps a function so that it swallows exceptions.""" def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception: pass return wrapper
Converts a value into a valid string. def make_str(value): """Converts a value into a valid string.""" if isinstance(value, bytes): try: return value.decode(get_filesystem_encoding()) except UnicodeError: return value.decode('utf-8', 'replace') return text_type(value...
Return a condensed version of help string. def make_default_short_help(help, max_length=45): """Return a condensed version of help string.""" words = help.split() total_length = 0 result = [] done = False for word in words: if word[-1:] == '.': done = True new_lengt...
Returns a system stream for byte processing. This essentially returns the stream from the sys module with the given name but it solves some compatibility issues between different Python versions. Primarily this function is necessary for getting binary streams on Python 3. :param name: the name of ...
Returns a system stream for text processing. This usually returns a wrapped stream around a binary stream returned from :func:`get_binary_stream` but it also can take shortcuts on Python 3 for already correctly configured streams. :param name: the name of the stream to open. Valid names are ``'stdin'...
This is similar to how the :class:`File` works but for manual usage. Files are opened non lazy by default. This can open regular files as well as stdin/stdout if ``'-'`` is passed. If stdin/stdout is returned the stream is wrapped so that the context manager will not close the stream accidentally. T...
Formats a filename for user display. The main purpose of this function is to ensure that the filename can be displayed at all. This will decode the filename to unicode if necessary in a way that it will not fail. Optionally, it can shorten the filename to not include the full path to the filename. ...
r"""Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system. To give you an idea, for an app called ``"Foo Bar"``, something like the following folders could be returned: Mac OS X: ``~/Library/Application Support/Foo...
Opens the file if it's not yet open. This call might fail with a :exc:`FileError`. Not handling this error will produce an error that Click shows. def open(self): """Opens the file if it's not yet open. This call might fail with a :exc:`FileError`. Not handling this error will produ...
Version of shlex.split that silently accept incomplete strings. Parameters ---------- line : str The string to split Returns ------- [str] The line split in separated arguments def split_args(line): """Version of shlex.split that silently accept incomplete strings. Pa...
Prompts for confirmation (yes/no question). If the user aborts the input by sending a interrupt signal this function will catch it and raise a :exc:`Abort` exception. .. versionadded:: 4.0 Added the `err` parameter. :param text: the question to ask. :param default: the default for the prom...
This function takes a text and shows it via an environment specific pager on stdout. .. versionchanged:: 3.0 Added the `color` flag. :param text_or_generator: the text to page, or alternatively, a generator emitting the text to page. :param color: controls if the p...
This function creates an iterable context manager that can be used to iterate over something while showing a progress bar. It will either iterate over the `iterable` or `length` items (that are counted up). While iteration happens, this function will print a rendered progress bar to the given `file` (...
Clears the terminal screen. This will have the effect of clearing the whole visible space of the terminal and moving the cursor to the top left. This does not do anything if not connected to a terminal. .. versionadded:: 2.0 def clear(): """Clears the terminal screen. This will have the effect of c...
r"""Edits the given text in the defined editor. If an editor is given (should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is clos...
This function launches the given URL (or filename) in the default viewer application for this file type. If this is an executable, it might launch the executable in a new session. The return value is the exit code of the launched application. Usually, ``0`` indicates success. Examples:: ...
Fetches a single character from the terminal and returns it. This will always return a unicode character and under certain rare circumstances this might return more than one character. The situations which more than one character is returned is when for whatever reason multiple characters end up in th...
This command stops execution and waits for the user to press any key to continue. This is similar to the Windows batch "pause" command. If the program is not run through a terminal, this command will instead do nothing. .. versionadded:: 2.0 .. versionadded:: 4.0 Added the `err` parameter...
A validator that makes an attribute optional. An optional attribute is one which can be set to ``None`` in addition to satisfying the requirements of the sub-validator. :param validator: A validator (or a list of validators) that is used for non-``None`` values. :type validator: callable or :c...
Return a shallow copy of this graph. def copy(self): """Return a shallow copy of this graph. """ other = DirectedGraph() other._vertices = set(self._vertices) other._forwards = {k: set(v) for k, v in self._forwards.items()} other._backwards = {k: set(v) for k, v in self....
Add a new vertex to the graph. def add(self, key): """Add a new vertex to the graph. """ if key in self._vertices: raise ValueError('vertex exists') self._vertices.add(key) self._forwards[key] = set() self._backwards[key] = set()
Remove a vertex from the graph, disconnecting all edges from/to it. def remove(self, key): """Remove a vertex from the graph, disconnecting all edges from/to it. """ self._vertices.remove(key) for f in self._forwards.pop(key): self._backwards[f].remove(key) for t in ...
Connect two existing vertices. Nothing happens if the vertices are already connected. def connect(self, f, t): """Connect two existing vertices. Nothing happens if the vertices are already connected. """ if t not in self._vertices: raise KeyError(t) self._f...
Compare two digests of equal length in constant time. The digests must be of type str/bytes. Returns True if the digests match, and False otherwise. def _const_compare_digest_backport(a, b): """ Compare two digests of equal length in constant time. The digests must be of type str/bytes. Retur...
Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. def assert_fingerprint(cert, fingerprint): """ Checks if given fingerprint matches the supplied...
Resolves the argument to a numeric constant, which can be passed to the wrap_socket function/method from the ssl module. Defaults to :data:`ssl.CERT_NONE`. If given a string it is assumed to be the name of the constant in the :mod:`ssl` module or its abbreviation. (So you can specify `REQUIRED` inst...
like resolve_cert_reqs def resolve_ssl_version(candidate): """ like resolve_cert_reqs """ if candidate is None: return PROTOCOL_SSLv23 if isinstance(candidate, str): res = getattr(ssl, candidate, None) if res is None: res = getattr(ssl, 'PROTOCOL_' + candidate) ...
All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If n...
Detects whether the hostname given is an IP address. :param str hostname: Hostname to examine. :return: True if the hostname is an IP address, False otherwise. def is_ipaddress(hostname): """Detects whether the hostname given is an IP address. :param str hostname: Hostname to examine. :return: Tr...
Formula for computing the current backoff :rtype: float def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ # We want to consider only the last consecutive errors sequence (Ignore redirects). consecutive_errors_len = len(list(tak...
Get the value of Retry-After in seconds. def get_retry_after(self, response): """ Get the value of Retry-After in seconds. """ retry_after = response.getheader("Retry-After") if retry_after is None: return None return self.parse_retry_after(retry_after)
Sleep between retry attempts. This method will respect a server's ``Retry-After`` response header and sleep the duration of the time requested. If that is not present, it will use an exponential backoff. By default, the backoff factor is 0 and this method will return immediately. def s...
Checks if a given HTTP method should be retried upon, depending if it is included on the method whitelist. def _is_method_retryable(self, method): """ Checks if a given HTTP method should be retried upon, depending if it is included on the method whitelist. """ if self.method_wh...
Is this method/status code retryable? (Based on whitelists and control variables such as the number of total retries to allow, whether to respect the Retry-After header, whether this header is present, and whether the returned status code is on the list of status codes to be retried upon...
Are we out of retries? def is_exhausted(self): """ Are we out of retries? """ retry_counts = (self.total, self.connect, self.read, self.redirect, self.status) retry_counts = list(filter(None, retry_counts)) if not retry_counts: return False return min(retry_counts) ...
Return a new Retry object with incremented retry counters. :param response: A response object, or None, if the server did not return a response. :type response: :class:`~urllib3.response.HTTPResponse` :param Exception error: An error encountered during the request, or No...