text
stringlengths
81
112k
Helper to split the netmask and raise AddressValueError if needed def _split_optional_netmask(address): """Helper to split the netmask and raise AddressValueError if needed""" addr = _compat_str(address).split('/') if len(addr) > 2: raise AddressValueError("Only one '/' permitted in %r" % address) ...
Find a sequence of sorted deduplicated IPv#Address. Args: addresses: a list of IPv#Address objects. Yields: A tuple containing the first and last IP addresses in the sequence. def _find_address_range(addresses): """Find a sequence of sorted deduplicated IPv#Address. Args: add...
Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number. def _count_righthand_zero_bits(number, bits): """Count the number of zero bits on the right...
Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse_addresses_internal([ip1, ip2, ip3, ip4]) -> ...
Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network or IPv6Network objects. Returns: ...
Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may...
Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones def _prefix_from_ip_int(cls, ip_int): ...
Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask def _prefix_from_prefix_string(cls, prefixlen_str): ""...
Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask def _prefix_from_ip_string(cls, ip_str): ...
Tell if self is partly contained in other. def overlaps(self, other): """Tell if self is partly contained in other.""" return self.network_address in other or ( self.broadcast_address in other or ( other.network_address in self or ( other.broadcast_addres...
Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') list(addr1.address_exclude(addr2)) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/...
Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._i...
The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length ...
The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. ...
Make a (netmask, prefix_len) tuple from the given argument. Argument can be: - an integer (the prefix length) - a string representing the prefix length (e.g. "24") - a string representing the prefix netmask (e.g. "255.255.255.0") def _make_netmask(cls, arg): """Make a (netmask,...
Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. def _ip_int_from_string(cls, ip_str): """Turn the...
Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation. def _string_from_ip_int(cls, ip_int): """Turns a 32-bit integer into dotted decimal notation. Args: ...
Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). ...
Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry. def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the add...
Make a (netmask, prefix_len) tuple from the given argument. Argument can be: - an integer (the prefix length) - a string representing the prefix length (e.g. "24") - a string representing the prefix netmask (e.g. "255.255.255.0") def _make_netmask(cls, arg): """Make a (netmask,...
Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: An int, the IPv6 address Raises: AddressValueError: if ip_str isn't a valid IPv6 Address. def _ip_int_from_string(cls, ip_str): """Turn an IPv6 ip_str into an in...
Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF]. def _parse_hextet(cls, hextet_str)...
Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of ...
Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32) def teredo(self): """Tuple of embedded teredo IPs. Returns: Tuple of the (server...
Serializes the input token stream using the specified treewalker :arg input: the token stream to serialize :arg tree: the treewalker to use :arg encoding: the encoding to use :arg serializer_opts: any options to pass to the :py:class:`html5lib.serializer.HTMLSerializer` that gets created ...
Serializes the stream from the treewalker into a string :arg treewalker: the treewalker to serialize :arg encoding: the string encoding to use :returns: the serialized tree Example: >>> from html5lib import parse, getTreeWalker >>> from html5lib.serializer import HTM...
Return the current branch, or None if HEAD isn't at a branch (e.g. detached HEAD). def get_current_branch(self, location): """ Return the current branch, or None if HEAD isn't at a branch (e.g. detached HEAD). """ # git-symbolic-ref exits with empty stdout if "HEAD" is a...
Return (sha_or_none, is_branch), where sha_or_none is a commit hash if the revision names a remote branch or tag, otherwise None. Args: dest: the repository directory. rev: the revision name. def get_revision_sha(self, dest, rev): """ Return (sha_or_none, is_branch)...
Resolve a revision to a new RevOptions object with the SHA1 of the branch, tag, or ref if found. Args: rev_options: a RevOptions object. def resolve_revision(self, dest, url, rev_options): """ Resolve a revision to a new RevOptions object with the SHA1 of the branch, ...
Return whether the current commit hash equals the given name. Args: dest: the repository directory. name: a string name. def is_commit_id_equal(self, dest, name): """ Return whether the current commit hash equals the given name. Args: dest: the repository...
Return URL of the first remote encountered. Raises RemoteNotFoundError if the repository does not have a remote url configured. def get_remote_url(cls, location): """ Return URL of the first remote encountered. Raises RemoteNotFoundError if the repository does not have a remot...
Return the relative path of setup.py to the git repo root. def _get_subdirectory(cls, location): """Return the relative path of setup.py to the git repo root.""" # find the repo root git_dir = cls.run_command(['rev-parse', '--git-dir'], show_stdout=False, cwd=l...
Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'. That's required because although they use SSH they sometimes don't work with a ssh:// scheme (e.g. GitHub). But we need a scheme for parsing. Hence we remove it again afterwards and return it as a stub. def get_url_rev_and_aut...
Make a name consistent regardless of source (environment or file) def _normalize_name(name): # type: (str) -> str """Make a name consistent regardless of source (environment or file) """ name = name.lower().replace('_', '-') if name.startswith('--'): name = name[2:] # only prefer long opts...
Get a value from the configuration. def get_value(self, key): # type: (str) -> Any """Get a value from the configuration. """ try: return self._dictionary[key] except KeyError: raise ConfigurationError("No such key - {}".format(key))
Modify a value in the configuration. def set_value(self, key, value): # type: (str, Any) -> None """Modify a value in the configuration. """ self._ensure_have_load_only() fname, parser = self._get_parser_to_modify() if parser is not None: section, name = _d...
Unset a value in the configuration. def unset_value(self, key): # type: (str) -> None """Unset a value in the configuration. """ self._ensure_have_load_only() if key not in self._config[self.load_only]: raise ConfigurationError("No such key - {}".format(key)) ...
Save the currentin-memory state. def save(self): # type: () -> None """Save the currentin-memory state. """ self._ensure_have_load_only() for fname, parser in self._modified_parsers: logger.info("Writing to %s", fname) # Ensure directory exists. ...
A dictionary representing the loaded configuration. def _dictionary(self): # type: () -> Dict[str, Any] """A dictionary representing the loaded configuration. """ # NOTE: Dictionaries are not populated if not loaded. So, conditionals # are not needed here. retval =...
Loads configuration from configuration files def _load_config_files(self): # type: () -> None """Loads configuration from configuration files """ config_files = dict(self._iter_config_files()) if config_files[kinds.ENV][0:1] == [os.devnull]: logger.debug( ...
Loads configuration from environment variables def _load_environment_vars(self): # type: () -> None """Loads configuration from environment variables """ self._config[kinds.ENV_VAR].update( self._normalized_keys(":env:", self._get_environ_vars()) )
Normalizes items to construct a dictionary with normalized keys. This routine is where the names become keys and are made the same regardless of source - configuration files or environment. def _normalized_keys(self, section, items): # type: (str, Iterable[Tuple[str, Any]]) -> Dict[str, Any] ...
Returns a generator with all environmental vars with prefix PIP_ def _get_environ_vars(self): # type: () -> Iterable[Tuple[str, str]] """Returns a generator with all environmental vars with prefix PIP_""" for key, val in os.environ.items(): should_be_yielded = ( key....
Yields variant and configuration files associated with it. This should be treated like items of a dictionary. def _iter_config_files(self): # type: () -> Iterable[Tuple[Kind, List[str]]] """Yields variant and configuration files associated with it. This should be treated like items of...
Helper to make sure the command got the right number of arguments def _get_n_args(self, args, example, n): """Helper to make sure the command got the right number of arguments """ if len(args) != n: msg = ( 'Got unexpected number of arguments, expected {}. ' ...
Encode into a cmd-executable string. This re-implements CreateProcess's quoting logic to turn a list of arguments into one single string for the shell to interpret. * All double quotes are escaped with a backslash. * Existing backslashes before a quote are doubled, so they are all ...
Return a case-normalized absolute variable-expanded path. :param str path: The non-normalized path :return: A normalized, expanded, case-normalized path :rtype: str def normalize_path(path): # type: (AnyStr) -> AnyStr """ Return a case-normalized absolute variable-expanded path. :param st...
Convert the supplied local path to a file uri. :param str path: A string pointing to or representing a local path :return: A `file://` uri for the same location :rtype: str >>> path_to_url("/home/user/code/myrepo/myfile.zip") 'file:///home/user/code/myrepo/myfile.zip' def path_to_url(path): #...
Convert a valid file url to a local filesystem path Follows logic taken from pip's equivalent function def url_to_path(url): # type: (str) -> ByteString """ Convert a valid file url to a local filesystem path Follows logic taken from pip's equivalent function """ from .misc import to_byte...
Checks if a given string is an url def is_valid_url(url): """Checks if a given string is an url""" from .misc import to_text if not url: return url pieces = urllib_parse.urlparse(to_text(url)) return all([pieces.scheme, pieces.netloc])
Returns true if the given url is a file url def is_file_url(url): """Returns true if the given url is a file url""" from .misc import to_text if not url: return False if not isinstance(url, six.string_types): try: url = getattr(url, "url") except AttributeError: ...
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)` ...
Recursively creates the target directory and all of its parents if they do not already exist. Fails silently if they do. :param str newdir: The directory path to ensure :raises: OSError if a file is encountered along the way def mkdir_p(newdir, mode=0o777): """Recursively creates the target directory...
Decorator to ensure `mkdir_p` is called to the function's return value. def ensure_mkdir_p(mode=0o777): """Decorator to ensure `mkdir_p` is called to the function's return value. """ def decorator(f): @functools.wraps(f) def decorated(*args, **kwargs): path = f(*args, **kwargs)...
Create a tracked temporary directory. This uses `TemporaryDirectory`, but does not remove the directory when the return value goes out of scope, instead registers a handler to cleanup on program exit. The return value is the path to the created directory. def create_tracked_tempdir(*args, **kwargs): ...
Set read-write permissions for the current user on the target path. Fail silently if the path doesn't exist. :param str fn: The target filename or path :return: None def set_write_bit(fn): # type: (str) -> None """ Set read-write permissions for the current user on the target path. Fail sile...
Stand-in for :func:`~shutil.rmtree` with additional error-handling. This version of `rmtree` handles read-only paths, especially in the case of index files written by certain source control systems. :param str directory: The target directory to remove :param bool ignore_errors: Whether to ignore error...
Retry with backoff up to 1 second to delete files from a directory. :param str path: The path to crawl to delete files from :return: A list of remaining paths or None :rtype: Optional[List[str]] def _wait_for_files(path): """ Retry with backoff up to 1 second to delete files from a directory. ...
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. :param function func: The caller function :param str path: The target path for removal :param Exception exc: The raised exc...
Checks to see if a pathlib `Path` object is a unc path or not def check_for_unc_path(path): """ Checks to see if a pathlib `Path` object is a unc path or not""" if ( os.name == "nt" and len(path.drive) > 2 and not path.drive[0].isalpha() and path.drive[1] != ":" ): r...
Convert `path` to be relative. Given a vague relative path, return the path relative to the given location. :param str path: The location of a target path :param str relative_to: The starting path to build against, optional :returns: A relative posix-style path with a leading `./` This perfor...
Checks whether a given file-like object is closed. :param obj: The file-like object to check. def is_fp_closed(obj): """ Checks whether a given file-like object is closed. :param obj: The file-like object to check. """ try: # Check `isclosed()` first, in case Python3 ...
Asserts whether all headers have been successfully parsed. Extracts encountered errors from the result of parsing headers. Only works on Python 3. :param headers: Headers to verify. :type headers: `httplib.HTTPMessage`. :raises urllib3.exceptions.HeaderParsingError: If parsing errors are ...
Checks whether the request of a response has been a HEAD-request. Handles the quirks of AppEngine. :param conn: :type conn: :class:`httplib.HTTPResponse` def is_response_to_head(response): """ Checks whether the request of a response has been a HEAD-request. Handles the quirks of AppEngine. ...
This calculates the Levenshtein distance between a and b. def levenshtein_distance(self, a, b): '''This calculates the Levenshtein distance between a and b. ''' n, m = len(a), len(b) if n > m: a,b = b,a n,m = m,n current = range(n+1) for i in ran...
This facilitates using communication timeouts to perform synchronization as quickly as possible, while supporting high latency connections with a tunable worst case performance. Fast connections should be read almost immediately. Worst case performance for this method is timeout_multipli...
This attempts to find the prompt. Basically, press enter and record the response; press enter again and record the response; if the two responses are similar then assume we are at the original prompt. This can be a slow function. Worst case with the default sync_multiplier can take 12 se...
This logs the user into the given server. It uses 'original_prompt' to try to find the prompt right after login. When it finds the prompt it immediately tries to reset the prompt to something more easily matched. The default 'original_prompt' is very optimistic and is easily foo...
Sends exit to the remote shell. If there are stopped jobs then this automatically sends exit twice. def logout (self): '''Sends exit to the remote shell. If there are stopped jobs then this automatically sends exit twice. ''' self.sendline("exit") index = self.expect([...
Match the next shell prompt. This is little more than a short-cut to the :meth:`~pexpect.spawn.expect` method. Note that if you called :meth:`login` with ``auto_prompt_reset=False``, then before calling :meth:`prompt` you must set the :attr:`PROMPT` attribute to a regex that it will use...
This sets the remote prompt to something more unique than ``#`` or ``$``. This makes it easier for the :meth:`prompt` method to match the shell prompt unambiguously. This method is called automatically by the :meth:`login` method, but you may want to call it manually if you somehow reset the ...
Return a string representing the user agent. def user_agent(): """ Return a string representing the user agent. """ data = { "installer": {"name": "pip", "version": pipenv.patched.notpip.__version__}, "python": platform.python_version(), "implementation": { "name": p...
Convert a file: URL to a path. def url_to_path(url): # type: (str) -> str """ Convert a file: URL to a path. """ assert url.startswith('file:'), ( "You can only turn file: urls into filenames (not %r)" % url) _, netloc, path, _, _ = urllib_parse.urlsplit(url) # if we have a UNC pa...
Convert a path to a file: URL. The path will be made absolute and have quoted path parts. def path_to_url(path): # type: (Union[str, Text]) -> str """ Convert a path to a file: URL. The path will be made absolute and have quoted path parts. """ path = os.path.normpath(os.path.abspath(path...
Return True if `name` is a considered as an archive file. def is_archive_file(name): # type: (str) -> bool """Return True if `name` is a considered as an archive file.""" ext = splitext(name)[1].lower() if ext in ARCHIVE_EXTENSIONS: return True return False
Return whether a file:// Link points to a directory. ``link`` must not have any other scheme but file://. Call is_file_url() first. def is_dir_url(link): # type: (Link) -> bool """Return whether a file:// Link points to a directory. ``link`` must not have any other scheme but file://. Call is_fil...
Unpack link into location. If download_dir is provided and link points to a file, make a copy of the link file inside download_dir. def unpack_file_url( link, # type: Link location, # type: str download_dir=None, # type: Optional[str] hashes=None # type: Optional[Hashes] ): # type: (.....
Copy distribution files in `link_path` to `location`. Invoked when user requests to install a local directory. E.g.: pip install . pip install ~/dev/git-repos/python-prompt-toolkit def _copy_dist_from_dir(link_path, location): """Copy distribution files in `link_path` to `location`. Invo...
Unpack link. If link is a VCS link: if only_download, export into download_dir and ignore location else unpack into location for other types of link: - unpack into location - if download_dir, copy the file into download_dir - if only_download, mark location fo...
Check download_dir for previously downloaded file with correct hash If a correct file is found return its path else None def _check_download_dir(link, download_dir, hashes): # type: (Link, str, Hashes) -> Optional[str] """ Check download_dir for previously downloaded file with correct hash If a...
Create a pool key out of a request context dictionary. According to RFC 3986, both the scheme and host are case-insensitive. Therefore, this function normalizes both before constructing the pool key for an HTTPS request. If you wish to change this behaviour, provide alternate callables to ``key_fn_by_s...
Create a new :class:`ConnectionPool` based on host, port, scheme, and any additional pool keyword arguments. If ``request_context`` is provided, it is provided as keyword arguments to the pool class used. This method is used to actually create the connection pools handed out by :meth:`c...
Get a :class:`ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is provided, it is merged with the instance's ``connection_pool_kw`` variable and used t...
Get a :class:`ConnectionPool` based on the request context. ``request_context`` must at least contain the ``scheme`` key and its value must be a key in ``key_fn_by_scheme`` instance variable. def connection_from_context(self, request_context): """ Get a :class:`ConnectionPool` based on...
Get a :class:`ConnectionPool` based on the provided pool key. ``pool_key`` should be a namedtuple that only contains immutable objects. At a minimum it must have the ``scheme``, ``host``, and ``port`` fields. def connection_from_pool_key(self, pool_key, request_context=None): """ ...
Similar to :func:`urllib3.connectionpool.connection_from_url`. If ``pool_kwargs`` is not provided and a new pool needs to be constructed, ``self.connection_pool_kw`` is used to initialize the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs`` is provided, it is used inst...
Merge a dictionary of override values for self.connection_pool_kw. This does not modify self.connection_pool_kw and returns a new dict. Any keys in the override dictionary with a value of ``None`` are removed from the merged dictionary. def _merge_pool_kwargs(self, override): """ ...
Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``. The given ``url`` parameter must be absolute, such that an appropriate :class:`urllib3.connectionpool.ConnectionPool` can be cho...
Sets headers needed by proxies: specifically, the Accept and Host headers. Only sets headers not provided by the user. def _set_proxy_headers(self, url, headers=None): """ Sets headers needed by proxies: specifically, the Accept and Host headers. Only sets headers not provided by the us...
Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute. def urlopen(self, method, url, redirect=True, **kw): "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute." u = parse_url(url) if u.scheme == "http": # For proxied HTTPS requests, httplib sets the necessar...
Returns a set of all variables in the AST that will be looked up from the context at runtime. Because at compile time it's not known which variables will be used depending on the path the execution takes at runtime, all variables are returned. >>> from jinja2 import Environment, meta >>> env = Env...
Finds all the referenced templates from the AST. This will return an iterator over all the hardcoded template extensions, inclusions and imports. If dynamic inheritance or inclusion is used, `None` will be yielded. >>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env...
Remember all undeclared identifiers. def enter_frame(self, frame): """Remember all undeclared identifiers.""" CodeGenerator.enter_frame(self, frame) for _, (action, param) in iteritems(frame.symbols.loads): if action == 'resolve': self.undeclared_identifiers.add(para...
Parse a marker string and return a dictionary containing a marker expression. The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in the expression grammar, or strings. A string contained in quotes is to be interpreted as a literal string, and a string not contained in quotes is a ...
Parse a requirement passed in as a string. Return a Container whose attributes contain the various parts of the requirement. def parse_requirement(req): """ Parse a requirement passed in as a string. Return a Container whose attributes contain the various parts of the requirement. """ remaining...
Return 'pathname' as a name that will work on the native filesystem. The path is split on '/' and put back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local convention before we ca...
Return the default base location for distlib caches. If the directory does not exist, it is created. Use the suffix provided for the base directory, and default to '.distlib' if it isn't provided. On Windows, if LOCALAPPDATA is defined in the environment, then it is assumed to be a directory, and will ...
Convert an absolute path to a directory name for use in a cache. The algorithm used is: #. On Windows, any ``':'`` in the drive is replaced with ``'---'``. #. Any occurrence of ``os.sep`` is replaced with ``'--'``. #. ``'.cache'`` is appended. def path_to_cache_dir(path): """ Convert an absol...
Extract name, version, python version from a filename (no extension) Return name, version, pyver or None def split_filename(filename, project_name=None): """ Extract name, version, python version from a filename (no extension) Return name, version, pyver or None """ result = None pyver = ...
A utility method used to get name and version from a string. From e.g. a Provides-Dist value. :param p: A value in a form 'foo (1.0)' :return: The name and version as a tuple. def parse_name_and_version(p): """ A utility method used to get name and version from a string. From e.g. a Provides...