INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Take a pipfile entry and normalize its markers
def translate_markers(pipfile_entry): """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 p...
Check if a given path is a virtual environment s root.
def is_virtual_environment(path): """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. """ if not path.is_dir(): return F...
Set a temporary 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 yield sys.version_info = old_version
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 isinstance(element, (list, tuple)): original_set |= set(element) el...
Compare two urls by scheme host and path ignoring auth
def is_url_equal(url, other_url): # type: (str, str) -> bool """ 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 **fragmen...
Convert a path with possible windows - style separators to a posix - style path ( with **/ ** separators instead of ** \\ ** separators ).
def make_posix(path): # type: (str) -> str """ 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:/us...
Given a pythonfinder. Finder instance and an optional line find a corresponding python
def find_python(finder, line=None): """ 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, ...
Given an input checks whether the input is a request for python or notself.
def is_python_command(line): """ 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 :rt...
Retrieve hashes for a specific InstallRequirement instance.
def get_hash(self, ireq, ireq_hashes=None): """ 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 ...
Select a way to obtain process information from the system.
def _get_process_mapping(): """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. """ for impl in (proc, ps): try: mapping = impl.get_process_mapping() except EnvironmentErro...
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 reached the root process. Give up. break try: ...
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 = proc_cmd[1:] return (os.path.basename(proc_cmd).lower(), proc_cmd)
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_depth): if proc_cmd.startswith('-'): # Login shell! Let's u...
Sends PreparedRequest object. Returns Response object.
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request co...
Initializes a urllib3 PoolManager.
def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs): """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>`. ...
Return urllib3 ProxyManager for the given proxy.
def proxy_manager_for(self, proxy, **proxy_kwargs): """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 prox...
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 >
def build_response(self, req, resp): """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 ...
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 >.
def get_connection(self, url, proxies=None): """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. :pa...
Disposes of any internal state.
def close(self): """Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections. """ self.poolmanager.clear() for proxy in self.proxy_manager.values(): proxy.clear()
Obtain the url to use when making the final request.
def request_url(self, request, proxies): """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 o...
Return git + ssh:// formatted URI to git + git
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 separating / so we can put the first segment ...
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 "://" not in uri: uri = uri.replace("git+...
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_LIST) elif isinstance(pipfile_entry, six.string_types): ...
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 for key in ["file", "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 with a valid specifier operator, test if it is a vali...
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 messaging. EAFP is great but the er...
def get_path(root, path, default=_UNSET): """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`. ...
Return a comparison of actual and expected hash values.
def _hash_comparison(self): """ Return a comparison of actual and expected hash values. Example:: Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde or 123451234512345123451234512345123451234512345 Got bcdefbcdefb...
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 initial states. This is called by ``__init__``, so you only need to call this directly in between analyses of different documents. """ self.result = {'encoding': None, 'confidence': 0.0...
Takes a chunk of a document and feeds it through all of the relevant charset probers.
def feed(self, byte_str): """ 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...
Stop analyzing the current document and come up with a final prediction.
def close(self): """ 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`. """ # Don't bother with checks if we're already done ...
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, encoding='utf-8') # If the user runs 'env', the value of ...
Send a command to the REPL wait for and return output.
def run_command(self, command, timeout=-1): """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 a...
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 """ line, hashes = self.split_hashes(self.line) self.hashes = hashes self.line = line
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 """ extras = None if "@" in self.line or self.is_vcs or self.is_url: line = "{0}".format(self.line) ...
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, strip_ref=True) except ValueError: ...
Generates a 3 - tuple of the requisite * name * * extras * and * url * to generate a: class: ~packaging. requirements. Requirement out of.
def requirement_info(self): # type: () -> Tuple[Optional[S], Tuple[Optional[S], ...], Optional[S]] """ 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...
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.
def line_is_installable(self): # type: () -> bool """ 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. ...
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.
def fork_pty(): '''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 s...
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() function. Specifically, this should work on Solaris. ''' child_name = os.ttyname(tty_fd) # Disconnect from controlling tty, if any. Raises OSError of ENXIO...
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_length = result and 1 + len(word) or len(word) ...
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.
def get_binary_stream(name): """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 Pyth...
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.
def get_text_stream(name, encoding=None, errors='strict'): """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. :para...
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.
def open_file(filename, mode='r', encoding=None, errors='strict', lazy=False, atomic=False): """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/s...
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.
def format_filename(filename, shorten=False): """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...
r Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system.
def get_app_dir(app_name, roaming=True, force_posix=False): 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 re...
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 produce an error that Click shows. """ if self._f is not None: return self._f try: rv, self.should_close = open_str...
Version of shlex. split that silently accept incomplete strings.
def split_args(line): """Version of shlex.split that silently accept incomplete strings. Parameters ---------- line : str The string to split Returns ------- [str] The line split in separated arguments """ lex = shlex.shlex(line, posix=True) lex.whitespace_split...
Prompts for confirmation ( yes/ no question ).
def confirm(text, default=False, abort=False, prompt_suffix=': ', show_default=True, err=False): """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 ...
This function takes a text and shows it via an environment specific pager on stdout.
def echo_via_pager(text_or_generator, color=None): """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 emit...
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 ( defaults to stdout ) a...
def progressbar(iterable=None, length=None, label=None, show_eta=True, show_percent=None, show_pos=False, item_show_func=None, fill_char='#', empty_char='-', bar_template='%(label)s [%(bar)s] %(info)s', info_sep=' ', width=36, file=None, color=None): ...
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.
def clear(): """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 """ if not isatty(sys.stdout): return # ...
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 closed without changes N...
def edit(text=None, editor=None, env=None, require_save=True, extension='.txt', filename=None): 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 overr...
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.
def launch(url, wait=False, locate=False): """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...
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 the terminal buffer ...
def getchar(echo=False): """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 ...
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.
def pause(info='Press any key to continue ...', err=False): """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. .. versionadde...
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.
def optional(validator): """ 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...
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._backwards.items()} return oth...
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 self._backwards.pop(key): self._forwards[t].remove(key)
Connect two existing vertices.
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._forwards[f].add(t) self._backwards[t].add(f)
Compare two digests of equal length in constant time.
def _const_compare_digest_backport(a, b): """ 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. """ result = abs(len(a) - len(b)) for l, r in zip(bytearray(a), bytearray(b)): result |=...
Checks if given fingerprint matches the supplied certificate.
def assert_fingerprint(cert, fingerprint): """ 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. """ fingerprint = fingerprint.replace(':...
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 instead of CERT_REQUIRED. ...
def resolve_cert_reqs(candidate): """ 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 abbrevi...
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) return res ...
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.
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None, ca_cert_dir=None): """ All arguments except for server_hostname, ssl_context, and ca_cert_dir ...
Detects whether the hostname given is an IP address.
def is_ipaddress(hostname): """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. """ if six.PY3 and isinstance(hostname, bytes): # IDN A-label bytes are ASCII compatible. ho...
Formula for computing the current backoff
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(takewhile(lambda x: x.redirect_location is None, ...
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.
def sleep(self, response=None): """ 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 ...
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_whitelist and method.upper() not in self.method_whitelist: return False return True
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 on the presence of the aforeme...
def is_retry(self, method, status_code, has_retry_after=False): """ 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 re...
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) < 0
Return a new Retry object with incremented retry counters.
def increment(self, method=None, url=None, response=None, error=None, _pool=None, _stacktrace=None): """ 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:...
Build a response by making a request or using the cache.
def build_response( self, request, response, from_cache=False, cacheable_methods=None ): """ Build a response by making a request or using the cache. This will end up calling send and returning a potentially cached response """ cacheable = cacheable_methods o...
Try to look up the process tree via Linux s/ proc
def get_process_mapping(): """Try to look up the process tree via Linux's /proc """ with open('/proc/{0}/stat'.format(os.getpid())) as f: self_tty = f.read().split()[STAT_TTY] processes = {} for pid in os.listdir('/proc'): if not pid.isdigit(): continue try: ...
Return ( hash length ) for path using hashlib. sha256 ()
def rehash(path, blocksize=1 << 20): # type: (str, int) -> Tuple[str, str] """Return (hash, length) for path using hashlib.sha256()""" h = hashlib.sha256() length = 0 with open(path, 'rb') as f: for block in read_chunks(f, size=blocksize): length += len(block) h.updat...
Replace the Python tag in a wheel file name with a new value.
def replace_python_tag(wheelname, new_tag): # type: (str, str) -> str """Replace the Python tag in a wheel file name with a new value. """ parts = wheelname.split('-') parts[-3] = new_tag return '-'.join(parts)
Determine if any scripts are not on PATH and format a warning.
def message_about_scripts_not_on_PATH(scripts): # type: (Sequence[str]) -> Optional[str] """Determine if any scripts are not on PATH and format a warning. Returns a warning message if one or more scripts are not on PATH, otherwise None. """ if not scripts: return None # Group scrip...
Return the given rows of a RECORD file in sorted order.
def sorted_outrows(outrows): # type: (Iterable[InstalledCSVRow]) -> List[InstalledCSVRow] """ Return the given rows of a RECORD file in sorted order. Each row is a 3-tuple (path, hash, size) and corresponds to a record of a RECORD file (see PEP 376 and PEP 427 for details). For the rows passed...
: param installed: A map from archive RECORD path to installation RECORD path.
def get_csv_rows_for_installed( old_csv_rows, # type: Iterable[List[str]] installed, # type: Dict[str, str] changed, # type: set generated, # type: List[str] lib_dir, # type: str ): # type: (...) -> List[InstalledCSVRow] """ :param installed: A map from archive RECORD path to instal...
Install a wheel
def move_wheel_files( name, # type: str req, # type: Requirement wheeldir, # type: str user=False, # type: bool home=None, # type: Optional[str] root=None, # type: Optional[str] pycompile=True, # type: bool scheme=None, # type: Optional[Mapping[str, str]] isolated=False, # t...
Return the Wheel - Version of an extracted wheel if possible.
def wheel_version(source_dir): # type: (Optional[str]) -> Optional[Tuple[int, ...]] """ Return the Wheel-Version of an extracted wheel, if possible. Otherwise, return None if we couldn't parse / extract it. """ try: dist = [d for d in pkg_resources.find_on_path(None, source_dir)][0] ...
Determine whether the string looks like an egg_info.
def _contains_egg_info( s, _egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)): """Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 """ return bool(_egg_info_re.search(s))
Return whether to build an InstallRequirement object using the ephemeral cache.
def should_use_ephemeral_cache( req, # type: InstallRequirement format_control, # type: FormatControl autobuilding, # type: bool cache_available # type: bool ): # type: (...) -> Optional[bool] """ Return whether to build an InstallRequirement object using the ephemeral cache. :p...
Format command information for logging.
def format_command( command_args, # type: List[str] command_output, # type: str ): # type: (...) -> str """ Format command information for logging. """ text = 'Command arguments: {}\n'.format(command_args) if not command_output: text += 'Command output: None' elif logger.g...
Return the path to the wheel in the temporary build directory.
def get_legacy_build_wheel_path( names, # type: List[str] temp_dir, # type: str req, # type: InstallRequirement command_args, # type: List[str] command_output, # type: str ): # type: (...) -> Optional[str] """ Return the path to the wheel in the temporary build directory. """ ...
Return the lowest index that one of the wheel s file_tag combinations achieves in the supported_tags list e. g. if there are 8 supported tags and one of the file tags is first in the list then return 0. Returns None is the wheel is not supported.
def support_index_min(self, tags=None): # type: (Optional[List[Pep425Tag]]) -> Optional[int] """ Return the lowest index that one of the wheel's file_tag combinations achieves in the supported_tags list e.g. if there are 8 supported tags, and one of the file tags is first in the ...
Is this wheel supported on this system?
def supported(self, tags=None): # type: (Optional[List[Pep425Tag]]) -> bool """Is this wheel supported on this system?""" if tags is None: # for mock tags = pep425tags.get_supported() return bool(set(tags).intersection(self.file_tags))
Build one wheel.
def _build_one(self, req, output_dir, python_tag=None): """Build one wheel. :return: The filename of the built wheel, or None if the build failed. """ # Install build deps into temporary directory (PEP 518) with req.build_env: return self._build_one_inside_env(req, o...
Build one InstallRequirement using the PEP 517 build process.
def _build_one_pep517(self, req, tempd, python_tag=None): """Build one InstallRequirement using the PEP 517 build process. Returns path to wheel if successfully built. Otherwise, returns None. """ assert req.metadata_directory is not None try: req.spin_message = 'Bui...
Build one InstallRequirement using the legacy build process.
def _build_one_legacy(self, req, tempd, python_tag=None): """Build one InstallRequirement using the "legacy" build process. Returns path to wheel if successfully built. Otherwise, returns None. """ base_args = self._base_setup_args(req) spin_message = 'Building wheel for %s (se...
Build wheels.
def build( self, requirements, # type: Iterable[InstallRequirement] session, # type: PipSession autobuilding=False # type: bool ): # type: (...) -> List[InstallRequirement] """Build wheels. :param unpack: If True, replace the sdist we built from with the ...
Get the distutils command for interacting with PyPI configurations.: return: the command.
def _get_pypirc_command(self): """ Get the distutils command for interacting with PyPI configurations. :return: the command. """ from distutils.core import Distribution from distutils.config import PyPIRCCommand d = Distribution() return PyPIRCCommand(d)
Read the PyPI access configuration as supported by distutils getting PyPI to do the actual work. This populates username password realm and url attributes from the configuration.
def read_configuration(self): """ Read the PyPI access configuration as supported by distutils, getting PyPI to do the actual work. This populates ``username``, ``password``, ``realm`` and ``url`` attributes from the configuration. """ # get distutils to do the work ...
Save the PyPI access configuration. You must have set username and password attributes before calling this method.
def save_configuration(self): """ Save the PyPI access configuration. You must have set ``username`` and ``password`` attributes before calling this method. Again, distutils is used to do the actual work. """ self.check_credentials() # get distutils to do the wor...
Check that username and password have been set and raise an exception if not.
def check_credentials(self): """ Check that ``username`` and ``password`` have been set, and raise an exception if not. """ if self.username is None or self.password is None: raise DistlibException('username and password must be set') pm = HTTPPasswordMgr() ...
Register a distribution on PyPI using the provided metadata.
def register(self, metadata): """ Register a distribution on PyPI, using the provided metadata. :param metadata: A :class:`Metadata` instance defining at least a name and version number for the distribution to be registered. :return: The...