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=environments.PIPENV_MAX_RETRIES ) requests_session.mount("https://pypi.org/pypi", adapter) return requests_session
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 isinstance(value, tomlkit.items.InlineTable): table = tomlkit.inline_table() table.update(value.value) section[key.key] = table def convert_toml_table(section): for package, value in section.items(): if hasattr(value, "keys") and not isinstance(value, toml.decoder.InlineTableDict): table = toml.TomlDecoder().get_empty_inline_table() table.update(value) section[package] = table is_tomlkit_parsed = isinstance(parsed, tomlkit.container.Container) for section in ("packages", "dev-packages"): table_data = parsed.get(section, {}) if not table_data: continue if is_tomlkit_parsed: convert_tomlkit_table(table_data) else: convert_toml_table(table_data) return parsed
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 run_command(cmd, *args, **kwargs): """ 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 """ from pipenv.vendor import delegator from ._compat import decode_for_output from .cmdparse import Script catch_exceptions = kwargs.pop("catch_exceptions", True) if isinstance(cmd, (six.string_types, list, tuple)): cmd = Script.parse(cmd) if not isinstance(cmd, Script): raise TypeError("Command input must be a string, list or tuple") if "env" not in kwargs: kwargs["env"] = os.environ.copy() kwargs["env"]["PYTHONIOENCODING"] = "UTF-8" try: cmd_string = cmd.cmdify() except TypeError: click_echo("Error turning command into string: {0}".format(cmd), err=True) sys.exit(1) if environments.is_verbose(): click_echo("Running command: $ {0}".format(cmd_string, err=True)) c = delegator.run(cmd_string, *args, **kwargs) return_code = c.return_code if environments.is_verbose(): click_echo("Command output: {0}".format( crayons.blue(decode_for_output(c.out)) ), err=True) if not c.ok and catch_exceptions: raise PipenvCmdError(cmd_string, c.out, c.err, return_code) return c
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 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. """ version_line = output.split("\n", 1)[0] version_pattern = re.compile( r""" ^ # Beginning of line. Python # Literally "Python". \s # Space. (?P<major>\d+) # Major = one or more digits. \. # Dot. (?P<minor>\d+) # Minor = one or more digits. (?: # Unnamed group for dot-micro. \. # Dot. (?P<micro>\d+) # Micro = one or more digit. )? # Micro is optional because pypa/pipenv#1893. .* # Trailing garbage. $ # End of line. """, re.VERBOSE, ) match = version_pattern.match(version_line) if not match: return None return match.groupdict(default="0")
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 None # Additional escaping for windows paths if os.name == "nt": s = "{}".format(s.replace("\\", "\\\\")) return '"' + s.replace("'", "'\\''") + '"'
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 call and mutates the provided lockfile accordingly, returning nothing. :param List[:class:`~requirementslib.Requirement`] deps: A list of dependencies to resolve. :param Callable which: [description] :param project: The pipenv Project instance to use during resolution :param Optional[bool] pre: Whether to resolve pre-release candidates, defaults to False :param Optional[bool] clear: Whether to clear the cache during resolution, defaults to False :param Optional[bool] allow_global: Whether to use *sys.executable* as the python binary, defaults to False :param Optional[str] pypi_mirror: A URL to substitute any time *pypi.org* is encountered, defaults to None :param Optional[bool] dev: Whether to target *dev-packages* or not, defaults to False :param pipfile: A Pipfile section to operate on, defaults to None :type pipfile: Optional[Dict[str, Union[str, Dict[str, bool, List[str]]]]] :param Dict[str, Any] lockfile: A project lockfile to mutate, defaults to None :param bool keep_outdated: Whether to retain outdated dependencies and resolve with them in mind, defaults to False :raises RuntimeError: Raised on resolution failure :return: Nothing :rtype: None def venv_resolve_deps( deps, which, project, pre=False, clear=False, allow_global=False, pypi_mirror=None, dev=False, pipfile=None, lockfile=None, keep_outdated=False ): """ 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 call and mutates the provided lockfile accordingly, returning nothing. :param List[:class:`~requirementslib.Requirement`] deps: A list of dependencies to resolve. :param Callable which: [description] :param project: The pipenv Project instance to use during resolution :param Optional[bool] pre: Whether to resolve pre-release candidates, defaults to False :param Optional[bool] clear: Whether to clear the cache during resolution, defaults to False :param Optional[bool] allow_global: Whether to use *sys.executable* as the python binary, defaults to False :param Optional[str] pypi_mirror: A URL to substitute any time *pypi.org* is encountered, defaults to None :param Optional[bool] dev: Whether to target *dev-packages* or not, defaults to False :param pipfile: A Pipfile section to operate on, defaults to None :type pipfile: Optional[Dict[str, Union[str, Dict[str, bool, List[str]]]]] :param Dict[str, Any] lockfile: A project lockfile to mutate, defaults to None :param bool keep_outdated: Whether to retain outdated dependencies and resolve with them in mind, defaults to False :raises RuntimeError: Raised on resolution failure :return: Nothing :rtype: None """ from .vendor.vistir.misc import fs_str from .vendor.vistir.compat import Path, JSONDecodeError, NamedTemporaryFile from .vendor.vistir.path import create_tracked_tempdir from . import resolver from ._compat import decode_for_output import json results = [] pipfile_section = "dev-packages" if dev else "packages" lockfile_section = "develop" if dev else "default" if not deps: if not project.pipfile_exists: return None deps = project.parsed_pipfile.get(pipfile_section, {}) if not deps: return None if not pipfile: pipfile = getattr(project, pipfile_section, {}) if not lockfile: lockfile = project._lockfile req_dir = create_tracked_tempdir(prefix="pipenv", suffix="requirements") cmd = [ which("python", allow_global=allow_global), Path(resolver.__file__.rstrip("co")).as_posix() ] if pre: cmd.append("--pre") if clear: cmd.append("--clear") if allow_global: cmd.append("--system") if dev: cmd.append("--dev") target_file = NamedTemporaryFile(prefix="resolver", suffix=".json", delete=False) target_file.close() cmd.extend(["--write", make_posix(target_file.name)]) with temp_environ(): os.environ.update({fs_str(k): fs_str(val) for k, val in os.environ.items()}) if pypi_mirror: os.environ["PIPENV_PYPI_MIRROR"] = str(pypi_mirror) os.environ["PIPENV_VERBOSITY"] = str(environments.PIPENV_VERBOSITY) os.environ["PIPENV_REQ_DIR"] = fs_str(req_dir) os.environ["PIP_NO_INPUT"] = fs_str("1") os.environ["PIPENV_SITE_DIR"] = get_pipenv_sitedir() if keep_outdated: os.environ["PIPENV_KEEP_OUTDATED"] = fs_str("1") with create_spinner(text=decode_for_output("Locking...")) as sp: # This conversion is somewhat slow on local and file-type requirements since # we now download those requirements / make temporary folders to perform # dependency resolution on them, so we are including this step inside the # spinner context manager for the UX improvement sp.write(decode_for_output("Building requirements...")) deps = convert_deps_to_pip( deps, project, r=False, include_index=True ) constraints = set(deps) os.environ["PIPENV_PACKAGES"] = str("\n".join(constraints)) sp.write(decode_for_output("Resolving dependencies...")) c = resolve(cmd, sp) results = c.out.strip() sp.green.ok(environments.PIPENV_SPINNER_OK_TEXT.format("Success!")) try: with open(target_file.name, "r") as fh: results = json.load(fh) except (IndexError, JSONDecodeError): click_echo(c.out.strip(), err=True) click_echo(c.err.strip(), err=True) if os.path.exists(target_file.name): os.unlink(target_file.name) raise RuntimeError("There was a problem with locking.") if os.path.exists(target_file.name): os.unlink(target_file.name) if environments.is_verbose(): click_echo(results, err=True) if lockfile_section not in lockfile: lockfile[lockfile_section] = {} prepare_lockfile(results, pipfile, lockfile[lockfile_section])
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 a list of dependencies, return a resolved list of dependencies, using pip-tools -- and their hashes, using the warehouse API / pip. """ index_lookup = {} markers_lookup = {} python_path = which("python", allow_global=allow_global) if not os.environ.get("PIP_SRC"): os.environ["PIP_SRC"] = project.virtualenv_src_location backup_python_path = sys.executable results = [] resolver = None if not deps: return results, resolver # First (proper) attempt: req_dir = req_dir if req_dir else os.environ.get("req_dir", None) if not req_dir: from .vendor.vistir.path import create_tracked_tempdir req_dir = create_tracked_tempdir(prefix="pipenv-", suffix="-requirements") with HackedPythonVersion(python_version=python, python_path=python_path): try: results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( deps, index_lookup, markers_lookup, project, sources, clear, pre, req_dir=req_dir, ) except RuntimeError: # Don't exit here, like usual. results = None # Second (last-resort) attempt: if results is None: with HackedPythonVersion( python_version=".".join([str(s) for s in sys.version_info[:3]]), python_path=backup_python_path, ): try: # Attempt to resolve again, with different Python version information, # particularly for particularly particular packages. results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( deps, index_lookup, markers_lookup, project, sources, clear, pre, req_dir=req_dir, ) except RuntimeError: sys.exit(1) return results, resolver
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_name, dep in deps.items(): if project: project.clear_pipfile_cache() indexes = getattr(project, "pipfile_sources", []) if project is not None else [] new_dep = Requirement.from_pipfile(dep_name, dep) if new_dep.index: include_index = True req = new_dep.as_line(sources=indexes if include_index else None).strip() dependencies.append(req) if not r: return dependencies # Write requirements.txt to tmp directory. from .vendor.vistir.path import create_tracked_tempfile f = create_tracked_tempfile(suffix="-requirements.txt", delete=False) f.write("\n".join(dependencies).encode("utf-8")) f.close() return f.name
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 isinstance(specified_version, dict): specified_version = specified_version.get("version", "") if specified_version.startswith("=="): return version.strip() == specified_version.split("==")[1].strip() return True
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 if hasattr(path, "keys") and any( key for key in path.keys() if key in ["file", "path"] ): path = urlparse(path["file"]).path if "file" in path else path["path"] if not isinstance(path, six.string_types) or path == "*": return False # If the string starts with a valid specifier operator, test if it is a valid # specifier set before making a path object (to avoid breaking windows) if any(path.startswith(spec) for spec in "!=<>~"): try: specifiers.SpecifierSet(path) # If this is not a valid specifier, just move on and try it as a path except specifiers.InvalidSpecifier: pass else: return False if not os.path.exists(os.path.abspath(path)): return False lookup_path = Path(path) absolute_path = "{0}".format(lookup_path.absolute()) if lookup_path.is_dir() and is_installable_dir(absolute_path): return True elif lookup_path.is_file() and is_archive_file(absolute_path): return True return False
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 start in SCHEME_LIST: if str(package).startswith(start): return True return False
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 IOError( "Unable to find package {0} in PyPI repository.".format(package_name) ) r = parse.parse("https://pypi.org/pypi/{name}/json", r.url) good_name = r["name"] return good_name
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 requested_path try: pathext = os.environ["PATHEXT"] except KeyError: pass else: for ext in pathext.split(os.pathsep): path = get_windows_path(bin_path, exe_name + ext.strip().lower()) if os.path.isfile(path): return path return find_executable(exe_name)
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, six.string_types): return packages packages = [packages] return set([canonicalize_name(pkg) for pkg in packages if pkg])
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, "requirements.txt") if os.path.isfile(r): return r raise RuntimeError("No requirements.txt found!")
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.content)
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 normalize_drive(path): """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> """ if os.name != "nt" or not isinstance(path, six.string_types): return path drive, tail = os.path.splitdrive(path) # Only match (lower cased) local drives (e.g. 'c:'), not UNC mounts. if drive.islower() and len(drive) == 2 and drive[1] == ":": return "{}{}".format(drive.upper(), tail) return path
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)` """ if os.path.exists(fn): return (os.stat(fn).st_mode & stat.S_IREAD) or not os.access(fn, os.W_OK) return False
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 default, so this error handler attempts to set them as writeable and then proceed with deletion.""" # Check for read-only attribute default_warning_message = ( "Unable to remove file due to permissions restriction: {!r}" ) # split the initial exception out into its type, exception, and traceback exc_type, exc_exception, exc_tb = exc if is_readonly_path(path): # Apply write permission and call original function set_write_bit(path) try: func(path) except (OSError, IOError) as e: if e.errno in [errno.EACCES, errno.EPERM]: warnings.warn(default_warning_message.format(path), ResourceWarning) return if exc_exception.errno in [errno.EACCES, errno.EPERM]: warnings.warn(default_warning_message.format(path), ResourceWarning) return raise exc
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 values representing a pipfile entry :type pipfile_entry: dict :returns: A normalized dictionary with cleaned marker entries 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 pipfile_entry: A dictionariy of keys and values representing a pipfile entry :type pipfile_entry: dict :returns: A normalized dictionary with cleaned marker entries """ if not isinstance(pipfile_entry, Mapping): raise TypeError("Entry is not a pipfile formatted mapping.") from .vendor.distlib.markers import DEFAULT_CONTEXT as marker_context from .vendor.packaging.markers import Marker from .vendor.vistir.misc import dedup allowed_marker_keys = ["markers"] + [k for k in marker_context.keys()] provided_keys = list(pipfile_entry.keys()) if hasattr(pipfile_entry, "keys") else [] pipfile_markers = [k for k in provided_keys if k in allowed_marker_keys] new_pipfile = dict(pipfile_entry).copy() marker_set = set() if "markers" in new_pipfile: marker = str(Marker(new_pipfile.pop("markers"))) if 'extra' not in marker: marker_set.add(marker) for m in pipfile_markers: entry = "{0}".format(pipfile_entry[m]) if m != "markers": marker_set.add(str(Marker("{0}{1}".format(m, entry)))) new_pipfile.pop(m) if marker_set: new_pipfile["markers"] = str(Marker(" or ".join( "{0}".format(s) if " and " in s else s for s in sorted(dedup(marker_set)) ))).replace('"', "'") return new_pipfile
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 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 False for bindir_name in ('bin', 'Scripts'): for python in path.joinpath(bindir_name).glob('python*'): try: exeness = python.is_file() and os.access(str(python), os.X_OK) except OSError: exeness = False if exeness: return True return False
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 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) else: original_set.add(element) return original_set
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/some/path?some_query", "https://user2:pass2@mydomain.com/some/path") True >>> is_url_equal("https://user:pass@mydomain.com/some/path?some_query", "https://mydomain.com/some?some_query") False 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 **fragment** :rtype: bool >>> is_url_equal("https://user:pass@mydomain.com/some/path?some_query", "https://user2:pass2@mydomain.com/some/path") True >>> is_url_equal("https://user:pass@mydomain.com/some/path?some_query", "https://mydomain.com/some?some_query") False """ if not isinstance(url, six.string_types): raise TypeError("Expected string for url, received {0!r}".format(url)) if not isinstance(other_url, six.string_types): raise TypeError("Expected string for url, received {0!r}".format(other_url)) parsed_url = urllib3_util.parse_url(url) parsed_other_url = urllib3_util.parse_url(other_url) unparsed = parsed_url._replace(auth=None, query=None, fragment=None).url unparsed_other = parsed_other_url._replace(auth=None, query=None, fragment=None).url return unparsed == unparsed_other
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:/users/user/venvs/some_venv/Lib/site-packages" >>> make_posix("c:\\users\\user\\venvs\\some_venv") "c:/users/user/venvs/some_venv" 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:/users/user/venvs/some_venv\\Lib\\site-packages") "c:/users/user/venvs/some_venv/Lib/site-packages" >>> make_posix("c:\\users\\user\\venvs\\some_venv") "c:/users/user/venvs/some_venv" """ if not isinstance(path, six.string_types): raise TypeError("Expected a string for path, received {0!r}...".format(path)) starts_with_sep = path.startswith(os.path.sep) separated = normalize_path(path).split(os.path.sep) if isinstance(separated, (list, tuple)): path = posixpath.join(*separated) if starts_with_sep: path = "/{0}".format(path) return path
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 :rtype: str 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, defaults to None :return: A path to python :rtype: str """ if line and not isinstance(line, six.string_types): raise TypeError( "Invalid python search type: expected string, received {0!r}".format(line) ) if line and os.path.isabs(line): if os.name == "nt": line = posixpath.join(*line.split(os.path.sep)) return line if not finder: from pipenv.vendor.pythonfinder import Finder finder = Finder(global_search=True) if not line: result = next(iter(finder.find_all_python_versions()), None) elif line and line[0].isdigit() or re.match(r'[\d\.]+', line): result = finder.find_python_version(line) else: result = finder.find_python_version(name=line) if not result: result = finder.which(line) if not result and not line.startswith("python"): line = "python{0}".format(line) result = find_python(finder, line) if not result: result = next(iter(finder.find_all_python_versions()), None) if result: if not isinstance(result, six.string_types): return result.path.as_posix() return result return
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): """ 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 """ if not isinstance(line, six.string_types): raise TypeError("Not a valid command to check: {0!r}".format(line)) from pipenv.vendor.pythonfinder.utils import PYTHON_IMPLEMENTATIONS is_version = re.match(r'[\d\.]+', line) if (line.startswith("python") or is_version or any(line.startswith(v) for v in PYTHON_IMPLEMENTATIONS)): return True # we are less sure about this but we can guess if line.startswith("py"): return True return False
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): """ 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 """ # We _ALWAYS MUST PRIORITIZE_ the inclusion of hashes from local sources # PLEASE *DO NOT MODIFY THIS* TO CHECK WHETHER AN IREQ ALREADY HAS A HASH # RESOLVED. The resolver will pull hashes from PyPI and only from PyPI. # The entire purpose of this approach is to include missing hashes. # This fixes a race condition in resolution for missing dependency caches # see pypa/pipenv#3289 if not self._should_include_hash(ireq): return set() elif self._should_include_hash(ireq) and ( not ireq_hashes or ireq.link.scheme == "file" ): if not ireq_hashes: ireq_hashes = set() new_hashes = self.resolver.repository._hash_cache.get_hash(ireq.link) ireq_hashes = add_to_set(ireq_hashes, new_hashes) else: ireq_hashes = set(ireq_hashes) # The _ONLY CASE_ where we flat out set the value is if it isn't present # It's a set, so otherwise we *always* need to do a union update if ireq not in self.hashes: return ireq_hashes else: return self.hashes[ireq] | ireq_hashes
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 is used as a fallback option. """ for impl in (proc, ps): try: mapping = impl.get_process_mapping() except EnvironmentError: continue return mapping raise ShellDetectionFailure('compatible proc fs or ps utility is required')
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: cmd = proc.args[0] except IndexError: # Process has no name? Whatever, ignore it. pass else: yield cmd pid = proc.ppid
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 use this. return _get_login_shell(proc_cmd) name = os.path.basename(proc_cmd).lower() if name in SHELL_NAMES: # The inner-most (non-login) shell. return (name, proc_cmd) return None
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, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. 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 content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. """ raise NotImplementedError
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 maximum number of connections to save in the pool. :param block: Block when no free connections are available. :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager. 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>`. :param connections: The number of urllib3 connection pools to cache. :param maxsize: The maximum number of connections to save in the pool. :param block: Block when no free connections are available. :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager. """ # save these values for pickling self._pool_connections = connections self._pool_maxsize = maxsize self._pool_block = block self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, strict=True, **pool_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 proxy to return a urllib3 ProxyManager for. :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. :returns: ProxyManager :rtype: urllib3.ProxyManager 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 proxy to return a urllib3 ProxyManager for. :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. :returns: ProxyManager :rtype: urllib3.ProxyManager """ if proxy in self.proxy_manager: manager = self.proxy_manager[proxy] elif proxy.lower().startswith('socks'): username, password = get_auth_from_url(proxy) manager = self.proxy_manager[proxy] = SOCKSProxyManager( proxy, username=username, password=password, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs ) else: proxy_headers = self.proxy_headers(proxy) manager = self.proxy_manager[proxy] = proxy_from_url( proxy, proxy_headers=proxy_headers, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs) return manager
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 to generate the response. :param resp: The urllib3 response object. :rtype: requests.Response 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 :class:`PreparedRequest <PreparedRequest>` used to generate the response. :param resp: The urllib3 response object. :rtype: requests.Response """ response = Response() # Fallback to None if there's no status_code, for whatever reason. response.status_code = getattr(resp, 'status', None) # Make headers case-insensitive. response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {})) # Set encoding. response.encoding = get_encoding_from_headers(response.headers) response.raw = resp response.reason = response.raw.reason if isinstance(req.url, bytes): response.url = req.url.decode('utf-8') else: response.url = req.url # Add new cookies from the server. extract_cookies_to_jar(response.cookies, req, resp) # Give the Response some context. response.request = req response.connection = self return response
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 proxies used on this request. :rtype: urllib3.ConnectionPool 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. :param proxies: (optional) A Requests-style dictionary of proxies used on this request. :rtype: urllib3.ConnectionPool """ proxy = select_proxy(url, proxies) if proxy: proxy = prepend_scheme_if_needed(proxy, 'http') proxy_url = parse_url(proxy) if not proxy_url.host: raise InvalidProxyURL("Please check proxy URL. It is malformed" " and could be missing the host.") proxy_manager = self.proxy_manager_for(proxy) conn = proxy_manager.connection_from_url(url) else: # Only scheme should be lower case parsed = urlparse(url) url = parsed.geturl() conn = self.poolmanager.connection_from_url(url) return conn
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 pooled connections. """ self.poolmanager.clear() for proxy in self.proxy_manager.values(): proxy.clear()
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 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. :rtype: str 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 only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. :rtype: str """ proxy = select_proxy(request.url, proxies) scheme = urlparse(request.url).scheme is_proxied_http_request = (proxy and scheme != 'https') using_socks_proxy = False if proxy: proxy_scheme = urlparse(proxy).scheme.lower() using_socks_proxy = proxy_scheme.startswith('socks') url = request.path_url if is_proxied_http_request and not using_socks_proxy: url = urldefragauth(request.url) return url
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 separating / so we can put the first segment # into the 'netloc' section with a : separator path_part, _, path = parsed.path.lstrip("/").partition("/") path = "/{0}".format(path) parsed = parsed._replace( netloc="{0}:{1}".format(parsed.netloc, path_part), path=path ) uri = urlunparse(parsed).replace("git+ssh://", "git+", 1) return uri
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+", "git+ssh://", 1) parsed = urlparse(uri) if ":" in parsed.netloc: netloc, _, path_start = parsed.netloc.rpartition(":") path = "/{0}{1}".format(path_start, parsed.path) uri = urlunparse(parsed._replace(netloc=netloc, path=path)) return uri
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): if not is_valid_url(pipfile_entry) and pipfile_entry.startswith("git+"): pipfile_entry = add_ssh_scheme_to_git_uri(pipfile_entry) parsed_entry = urlsplit(pipfile_entry) return parsed_entry.scheme in VCS_SCHEMES return False
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"]): raise ValueError("missing path-like entry in supplied mapping {0!r}".format(path)) if "file" in path: path = vistir.path.url_to_path(path["file"]) elif "path" in path: path = path["path"] return 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 valid # specifier set before making a path object (to avoid breaking windows) if any(path.startswith(spec) for spec in "!=<>~"): try: specifiers.SpecifierSet(path) # If this is not a valid specifier, just move on and try it as a path except specifiers.InvalidSpecifier: pass else: return False parsed = urlparse(path) is_local = ( not parsed.scheme or parsed.scheme == "file" or (len(parsed.scheme) == 1 and os.name == "nt") ) if parsed.scheme and parsed.scheme == "file": path = vistir.compat.fs_decode(vistir.path.url_to_path(path)) normalized_path = vistir.path.normalize_path(path) if is_local and not os.path.exists(normalized_path): return False is_archive = pip_shims.shims.is_archive_file(normalized_path) is_local_project = os.path.isdir(normalized_path) and is_installable_dir( normalized_path ) if is_local and is_local_project or is_archive: return True if not is_local and pip_shims.shims.is_archive_file(parsed.path): return True return False
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 error messages are not. For instance, ``root['a']['b']['c'][2][1]`` gives back ``IndexError: list index out of range`` What went out of range where? get_path currently raises ``PathAccessError: could not access 2 from path ('a', 'b', 'c', 2, 1), got error: IndexError('list index out of range',)``, a subclass of IndexError and KeyError. You can also pass a default that covers the entire operation, should the lookup fail at any level. Args: root: The target nesting of dictionaries, lists, or other objects supporting ``__getitem__``. path (tuple): A list of strings and integers to be successively looked up within *root*. default: The value to be returned should any ``PathAccessError`` exceptions be raised. 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`. One of get_path's chief aims is improved error messaging. EAFP is great, but the error messages are not. For instance, ``root['a']['b']['c'][2][1]`` gives back ``IndexError: list index out of range`` What went out of range where? get_path currently raises ``PathAccessError: could not access 2 from path ('a', 'b', 'c', 2, 1), got error: IndexError('list index out of range',)``, a subclass of IndexError and KeyError. You can also pass a default that covers the entire operation, should the lookup fail at any level. Args: root: The target nesting of dictionaries, lists, or other objects supporting ``__getitem__``. path (tuple): A list of strings and integers to be successively looked up within *root*. default: The value to be returned should any ``PathAccessError`` exceptions be raised. """ if isinstance(path, six.string_types): path = path.split(".") cur = root try: for seg in path: try: cur = cur[seg] except (KeyError, IndexError) as exc: raise PathAccessError(exc, seg, path) except TypeError as exc: # either string index in a list, or a parent that # doesn't support indexing try: seg = int(seg) cur = cur[seg] except (ValueError, KeyError, IndexError, TypeError): if not getattr(cur, "__iter__", None): exc = TypeError("%r object is not indexable" % type(cur).__name__) raise PathAccessError(exc, seg, path) except PathAccessError: if default is _UNSET: raise return default return cur
Return a comparison of actual and expected hash values. Example:: Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde or 123451234512345123451234512345123451234512345 Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef def _hash_comparison(self): """ Return a comparison of actual and expected hash values. Example:: Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde or 123451234512345123451234512345123451234512345 Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef """ def hash_then_or(hash_name): # For now, all the decent hashes have 6-char names, so we can get # away with hard-coding space literals. return chain([hash_name], repeat(' or')) lines = [] for hash_name, expecteds in iteritems(self.allowed): prefix = hash_then_or(hash_name) lines.extend((' Expected %s %s' % (next(prefix), e)) for e in expecteds) lines.append(' Got %s\n' % self.gots[hash_name].hexdigest()) prefix = ' or' return '\n'.join(lines)
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, 'language': None} self.done = False self._got_data = False self._has_win_bytes = False self._input_state = InputState.PURE_ASCII self._last_char = b'' if self._esc_charset_prober: self._esc_charset_prober.reset() for prober in self._charset_probers: prober.reset()
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 ``result`` attribute). .. note:: You should always call ``close`` when you're done feeding in your document if ``done`` is not already ``True``. 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 it has made a prediction (in the ``result`` attribute). .. note:: You should always call ``close`` when you're done feeding in your document if ``done`` is not already ``True``. """ if self.done: return if not len(byte_str): return if not isinstance(byte_str, bytearray): byte_str = bytearray(byte_str) # First check for known BOMs, since these are guaranteed to be correct if not self._got_data: # If the data starts with BOM, we know it is UTF if byte_str.startswith(codecs.BOM_UTF8): # EF BB BF UTF-8 with BOM self.result = {'encoding': "UTF-8-SIG", 'confidence': 1.0, 'language': ''} elif byte_str.startswith((codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)): # FF FE 00 00 UTF-32, little-endian BOM # 00 00 FE FF UTF-32, big-endian BOM self.result = {'encoding': "UTF-32", 'confidence': 1.0, 'language': ''} elif byte_str.startswith(b'\xFE\xFF\x00\x00'): # FE FF 00 00 UCS-4, unusual octet order BOM (3412) self.result = {'encoding': "X-ISO-10646-UCS-4-3412", 'confidence': 1.0, 'language': ''} elif byte_str.startswith(b'\x00\x00\xFF\xFE'): # 00 00 FF FE UCS-4, unusual octet order BOM (2143) self.result = {'encoding': "X-ISO-10646-UCS-4-2143", 'confidence': 1.0, 'language': ''} elif byte_str.startswith((codecs.BOM_LE, codecs.BOM_BE)): # FF FE UTF-16, little endian BOM # FE FF UTF-16, big endian BOM self.result = {'encoding': "UTF-16", 'confidence': 1.0, 'language': ''} self._got_data = True if self.result['encoding'] is not None: self.done = True return # If none of those matched and we've only see ASCII so far, check # for high bytes and escape sequences if self._input_state == InputState.PURE_ASCII: if self.HIGH_BYTE_DETECTOR.search(byte_str): self._input_state = InputState.HIGH_BYTE elif self._input_state == InputState.PURE_ASCII and \ self.ESC_DETECTOR.search(self._last_char + byte_str): self._input_state = InputState.ESC_ASCII self._last_char = byte_str[-1:] # If we've seen escape sequences, use the EscCharSetProber, which # uses a simple state machine to check for known escape sequences in # HZ and ISO-2022 encodings, since those are the only encodings that # use such sequences. if self._input_state == InputState.ESC_ASCII: if not self._esc_charset_prober: self._esc_charset_prober = EscCharSetProber(self.lang_filter) if self._esc_charset_prober.feed(byte_str) == ProbingState.FOUND_IT: self.result = {'encoding': self._esc_charset_prober.charset_name, 'confidence': self._esc_charset_prober.get_confidence(), 'language': self._esc_charset_prober.language} self.done = True # If we've seen high bytes (i.e., those with values greater than 127), # we need to do more complicated checks using all our multi-byte and # single-byte probers that are left. The single-byte probers # use character bigram distributions to determine the encoding, whereas # the multi-byte probers use a combination of character unigram and # bigram distributions. elif self._input_state == InputState.HIGH_BYTE: if not self._charset_probers: self._charset_probers = [MBCSGroupProber(self.lang_filter)] # If we're checking non-CJK encodings, use single-byte prober if self.lang_filter & LanguageFilter.NON_CJK: self._charset_probers.append(SBCSGroupProber()) self._charset_probers.append(Latin1Prober()) for prober in self._charset_probers: if prober.feed(byte_str) == ProbingState.FOUND_IT: self.result = {'encoding': prober.charset_name, 'confidence': prober.get_confidence(), 'language': prober.language} self.done = True break if self.WIN_BYTE_DETECTOR.search(byte_str): self._has_win_bytes = True
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 prediction. :returns: The ``result`` attribute, a ``dict`` with the keys `encoding`, `confidence`, and `language`. """ # Don't bother with checks if we're already done if self.done: return self.result self.done = True if not self._got_data: self.logger.debug('no data received!') # Default to ASCII if it is all we've seen so far elif self._input_state == InputState.PURE_ASCII: self.result = {'encoding': 'ascii', 'confidence': 1.0, 'language': ''} # If we have seen non-ASCII, return the best that met MINIMUM_THRESHOLD elif self._input_state == InputState.HIGH_BYTE: prober_confidence = None max_prober_confidence = 0.0 max_prober = None for prober in self._charset_probers: if not prober: continue prober_confidence = prober.get_confidence() if prober_confidence > max_prober_confidence: max_prober_confidence = prober_confidence max_prober = prober if max_prober and (max_prober_confidence > self.MINIMUM_THRESHOLD): charset_name = max_prober.charset_name lower_charset_name = max_prober.charset_name.lower() confidence = max_prober.get_confidence() # Use Windows encoding name instead of ISO-8859 if we saw any # extra Windows-specific bytes if lower_charset_name.startswith('iso-8859'): if self._has_win_bytes: charset_name = self.ISO_WIN_MAP.get(lower_charset_name, charset_name) self.result = {'encoding': charset_name, 'confidence': confidence, 'language': max_prober.language} # Log all prober confidences if none met MINIMUM_THRESHOLD if self.logger.getEffectiveLevel() == logging.DEBUG: if self.result['encoding'] is None: self.logger.debug('no probers hit minimum threshold') for group_prober in self._charset_probers: if not group_prober: continue if isinstance(group_prober, CharSetGroupProber): for prober in group_prober.probers: self.logger.debug('%s %s confidence = %s', prober.charset_name, prober.language, prober.get_confidence()) else: self.logger.debug('%s %s confidence = %s', prober.charset_name, prober.language, prober.get_confidence()) return self.result
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 PS1 will be in the output. To avoid # replwrap seeing that as the next prompt, we'll embed the marker characters # for invisible characters in the prompt; these show up when inspecting the # environment variable, but not when bash displays the prompt. ps1 = PEXPECT_PROMPT[:5] + u'\\[\\]' + PEXPECT_PROMPT[5:] ps2 = PEXPECT_CONTINUATION_PROMPT[:5] + u'\\[\\]' + PEXPECT_CONTINUATION_PROMPT[5:] prompt_change = u"PS1='{0}' PS2='{1}' PROMPT_COMMAND=''".format(ps1, ps2) return REPLWrapper(child, u'\\$', prompt_change, extra_init_cmd="export PAGER=cat")
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 raised. :param int timeout: How long to wait for the next prompt. -1 means the default from the :class:`pexpect.spawn` object (default 30 seconds). None means to wait indefinitely. 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 after sending input, :exc:`ValueError` will be raised. :param int timeout: How long to wait for the next prompt. -1 means the default from the :class:`pexpect.spawn` object (default 30 seconds). None means to wait indefinitely. """ # Split up multiline commands and feed them in bit-by-bit cmdlines = command.splitlines() # splitlines ignores trailing newlines - add it back in manually if command.endswith('\n'): cmdlines.append('') if not cmdlines: raise ValueError("No command was given") res = [] self.child.sendline(cmdlines[0]) for line in cmdlines[1:]: self._expect_prompt(timeout=timeout) res.append(self.child.before) self.child.sendline(line) # Command was fully submitted, now wait for the next prompt if self._expect_prompt(timeout=timeout) == 1: # We got the continuation prompt - command was incomplete self.child.kill(signal.SIGINT) self._expect_prompt(timeout=1) raise ValueError("Continuation prompt found - input was incomplete:\n" + command) return u''.join(res + [self.child.before])
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) uri = URI.parse(line) name = uri.name if name: self._name = name if uri.host and uri.path and uri.scheme: self.line = uri.to_string( escape_password=False, direct=False, strip_ssh=uri.is_implicit_ssh ) else: self.line, extras = pip_shims.shims._strip_extras(self.line) else: self.line, extras = pip_shims.shims._strip_extras(self.line) extras_set = set() # type: Set[STRING_TYPE] if extras is not None: extras_set = set(parse_extras(extras)) if self._name: self._name, name_extras = pip_shims.shims._strip_extras(self._name) if name_extras: name_extras = set(parse_extras(name_extras)) extras_set |= name_extras if extras_set is not None: self.extras = tuple(sorted(extras_set))
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: pass else: self._parsed_url = parsed return line if self.vcs is not None and self.line.startswith("{0}+".format(self.vcs)): _, _, _parseable = self.line.partition("+") parsed = urllib_parse.urlparse(add_ssh_scheme_to_git_uri(_parseable)) line, _ = split_ref_from_uri(line) else: parsed = urllib_parse.urlparse(add_ssh_scheme_to_git_uri(line)) if "@" in self.line and parsed.scheme == "": name, _, url = self.line.partition("@") if self._name is None: url = url.strip() self._name = name.strip() if is_valid_url(url): self.is_direct_url = True line = url.strip() parsed = urllib_parse.urlparse(line) url_path = parsed.path if "@" in url_path: url_path, _, _ = url_path.rpartition("@") parsed = parsed._replace(path=url_path) self._parsed_url = parsed return line
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(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 of extras, and an optional URL. :rtype: Tuple[Optional[S], Tuple[Optional[S], ...], Optional[S]] """ # Direct URLs can be converted to packaging requirements directly, but # only if they are `file://` (with only two slashes) name = None # type: Optional[S] extras = () # type: Tuple[Optional[S], ...] url = None # type: Optional[STRING_TYPE] # if self.is_direct_url: if self._name: name = canonicalize_name(self._name) if self.is_file or self.is_url or self.is_path or self.is_file_url or self.is_vcs: url = "" if self.is_vcs: url = self.url if self.url else self.uri if self.is_direct_url: url = self.link.url_without_fragment else: if self.link: url = self.link.url_without_fragment elif self.url: url = self.url if self.ref: url = "{0}@{1}".format(url, self.ref) else: url = self.uri if self.link and name is None: self._name = self.link.egg_fragment if self._name: name = canonicalize_name(self._name) return name, extras, url
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 valid URL, VCS requirement, or installable filesystem path before deciding to treat it as a file requirement over a named requirement. 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. In this case we first need to check that the given requirement is a valid URL, VCS requirement, or installable filesystem path before deciding to treat it as a file requirement over a named requirement. """ line = self.line if is_file_url(line): link = create_link(line) line = link.url_without_fragment line, _ = split_ref_from_uri(line) if ( is_vcs(line) or ( is_valid_url(line) and (not is_file_url(line) or is_installable_file(line)) ) or is_installable_file(line) ): return True return False
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, particularly ssh. Based on patch to posixmodule.c authored by Noah Spurrier:: http://mail.python.org/pipermail/python-dev/2003-May/035281.html 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 supporting Solaris, particularly ssh. Based on patch to posixmodule.c authored by Noah Spurrier:: http://mail.python.org/pipermail/python-dev/2003-May/035281.html ''' parent_fd, child_fd = os.openpty() if parent_fd < 0 or child_fd < 0: raise OSError("os.openpty() failed") pid = os.fork() if pid == CHILD: # Child. os.close(parent_fd) pty_make_controlling_tty(child_fd) os.dup2(child_fd, STDIN_FILENO) os.dup2(child_fd, STDOUT_FILENO) os.dup2(child_fd, STDERR_FILENO) else: # Parent. os.close(child_fd) return pid, parent_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. 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 # if there was no controlling tty to begin with, such as when # executed by a cron(1) job. try: fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY) os.close(fd) except OSError as err: if err.errno != errno.ENXIO: raise os.setsid() # Verify we are disconnected from controlling tty by attempting to open # it again. We expect that OSError of ENXIO should always be raised. try: fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY) os.close(fd) raise PtyProcessError("OSError of errno.ENXIO should be raised.") except OSError as err: if err.errno != errno.ENXIO: raise # Verify we can open child pty. fd = os.open(child_name, os.O_RDWR) os.close(fd) # Verify we now have a controlling tty. fd = os.open("/dev/tty", os.O_WRONLY) os.close(fd)
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) if total_length + new_length > max_length: result.append('...') done = True else: if result: result.append(' ') result.append(word) if done: break total_length += new_length return ''.join(result)
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 the stream to open. Valid names are ``'stdin'``, ``'stdout'`` and ``'stderr'`` 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 Python 3. :param name: the name of the stream to open. Valid names are ``'stdin'``, ``'stdout'`` and ``'stderr'`` """ opener = binary_streams.get(name) if opener is None: raise TypeError('Unknown standard stream %r' % name) return opener()
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'``, ``'stdout'`` and ``'stderr'`` :param encoding: overrides the detected default encoding. :param errors: overrides the default error mode. 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. :param name: the name of the stream to open. Valid names are ``'stdin'``, ``'stdout'`` and ``'stderr'`` :param encoding: overrides the detected default encoding. :param errors: overrides the default error mode. """ opener = text_streams.get(name) if opener is None: raise TypeError('Unknown standard stream %r' % name) return opener(encoding, errors)
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. This makes it possible to always use the function like this without having to worry to accidentally close a standard stream:: with open_file(filename) as f: ... .. versionadded:: 3.0 :param filename: the name of the file to open (or ``'-'`` for stdin/stdout). :param mode: the mode in which to open the file. :param encoding: the encoding to use. :param errors: the error handling for this file. :param lazy: can be flipped to true to open the file lazily. :param atomic: in atomic mode writes go into a temporary file and it's moved on close. 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/stdout is returned the stream is wrapped so that the context manager will not close the stream accidentally. This makes it possible to always use the function like this without having to worry to accidentally close a standard stream:: with open_file(filename) as f: ... .. versionadded:: 3.0 :param filename: the name of the file to open (or ``'-'`` for stdin/stdout). :param mode: the mode in which to open the file. :param encoding: the encoding to use. :param errors: the error handling for this file. :param lazy: can be flipped to true to open the file lazily. :param atomic: in atomic mode writes go into a temporary file and it's moved on close. """ if lazy: return LazyFile(filename, mode, encoding, errors, atomic=atomic) f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic) if not should_close: f = KeepOpenFile(f) return f
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. :param filename: formats a filename for UI display. This will also convert the filename into unicode without failing. :param shorten: this optionally shortens the filename to strip of the path that leads up to it. 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 to not include the full path to the filename. :param filename: formats a filename for UI display. This will also convert the filename into unicode without failing. :param shorten: this optionally shortens the filename to strip of the path that leads up to it. """ if shorten: filename = os.path.basename(filename) return filename_to_ui(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 Bar`` Mac OS X (POSIX): ``~/.foo-bar`` Unix: ``~/.config/foo-bar`` Unix (POSIX): ``~/.foo-bar`` Win XP (roaming): ``C:\Documents and Settings\<user>\Local Settings\Application Data\Foo Bar`` Win XP (not roaming): ``C:\Documents and Settings\<user>\Application Data\Foo Bar`` Win 7 (roaming): ``C:\Users\<user>\AppData\Roaming\Foo Bar`` Win 7 (not roaming): ``C:\Users\<user>\AppData\Local\Foo Bar`` .. versionadded:: 2.0 :param app_name: the application name. This should be properly capitalized and can contain whitespace. :param roaming: controls if the folder should be roaming or not on Windows. Has no affect otherwise. :param force_posix: if this is set to `True` then on any POSIX system the folder will be stored in the home folder with a leading dot instead of the XDG config home or darwin's application support folder. 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 returned: Mac OS X: ``~/Library/Application Support/Foo Bar`` Mac OS X (POSIX): ``~/.foo-bar`` Unix: ``~/.config/foo-bar`` Unix (POSIX): ``~/.foo-bar`` Win XP (roaming): ``C:\Documents and Settings\<user>\Local Settings\Application Data\Foo Bar`` Win XP (not roaming): ``C:\Documents and Settings\<user>\Application Data\Foo Bar`` Win 7 (roaming): ``C:\Users\<user>\AppData\Roaming\Foo Bar`` Win 7 (not roaming): ``C:\Users\<user>\AppData\Local\Foo Bar`` .. versionadded:: 2.0 :param app_name: the application name. This should be properly capitalized and can contain whitespace. :param roaming: controls if the folder should be roaming or not on Windows. Has no affect otherwise. :param force_posix: if this is set to `True` then on any POSIX system the folder will be stored in the home folder with a leading dot instead of the XDG config home or darwin's application support folder. """ if WIN: key = roaming and 'APPDATA' or 'LOCALAPPDATA' folder = os.environ.get(key) if folder is None: folder = os.path.expanduser('~') return os.path.join(folder, app_name) if force_posix: return os.path.join(os.path.expanduser('~/.' + _posixify(app_name))) if sys.platform == 'darwin': return os.path.join(os.path.expanduser( '~/Library/Application Support'), app_name) return os.path.join( os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')), _posixify(app_name))
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_stream(self.name, self.mode, self.encoding, self.errors, atomic=self.atomic) except (IOError, OSError) as e: from .exceptions import FileError raise FileError(self.name, hint=get_streerror(e)) self._f = rv return rv
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. Parameters ---------- line : str The string to split Returns ------- [str] The line split in separated arguments """ lex = shlex.shlex(line, posix=True) lex.whitespace_split = True lex.commenters = '' res = [] try: while True: res.append(next(lex)) except ValueError: # No closing quotation pass except StopIteration: # End of loop pass if lex.token: res.append(lex.token) return res
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 prompt. :param abort: if this is set to `True` a negative answer aborts the exception by raising :exc:`Abort`. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo. 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 Added the `err` parameter. :param text: the question to ask. :param default: the default for the prompt. :param abort: if this is set to `True` a negative answer aborts the exception by raising :exc:`Abort`. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo. """ prompt = _build_prompt(text, prompt_suffix, show_default, default and 'Y/n' or 'y/N') while 1: try: # Write the prompt separately so that we get nice # coloring through colorama on Windows echo(prompt, nl=False, err=err) value = visible_prompt_func('').lower().strip() except (KeyboardInterrupt, EOFError): raise Abort() if value in ('y', 'yes'): rv = True elif value in ('n', 'no'): rv = False elif value == '': rv = default else: echo('Error: invalid input', err=err) continue break if abort and not rv: raise Abort() return rv
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 pager supports ANSI colors or not. The default is autodetection. 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 emitting the text to page. :param color: controls if the pager supports ANSI colors or not. The default is autodetection. """ color = resolve_color_default(color) if inspect.isgeneratorfunction(text_or_generator): i = text_or_generator() elif isinstance(text_or_generator, string_types): i = [text_or_generator] else: i = iter(text_or_generator) # convert every element of i to a text type if necessary text_generator = (el if isinstance(el, string_types) else text_type(el) for el in i) from ._termui_impl import pager return pager(itertools.chain(text_generator, "\n"), color)
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) and will attempt to calculate remaining time and more. By default, this progress bar will not be rendered if the file is not a terminal. The context manager creates the progress bar. When the context manager is entered the progress bar is already displayed. With every iteration over the progress bar, the iterable passed to the bar is advanced and the bar is updated. When the context manager exits, a newline is printed and the progress bar is finalized on screen. No printing must happen or the progress bar will be unintentionally destroyed. Example usage:: with progressbar(items) as bar: for item in bar: do_something_with(item) Alternatively, if no iterable is specified, one can manually update the progress bar through the `update()` method instead of directly iterating over the progress bar. The update method accepts the number of steps to increment the bar with:: with progressbar(length=chunks.total_bytes) as bar: for chunk in chunks: process_chunk(chunk) bar.update(chunks.bytes) .. versionadded:: 2.0 .. versionadded:: 4.0 Added the `color` parameter. Added a `update` method to the progressbar object. :param iterable: an iterable to iterate over. If not provided the length is required. :param length: the number of items to iterate over. By default the progressbar will attempt to ask the iterator about its length, which might or might not work. If an iterable is also provided this parameter can be used to override the length. If an iterable is not provided the progress bar will iterate over a range of that length. :param label: the label to show next to the progress bar. :param show_eta: enables or disables the estimated time display. This is automatically disabled if the length cannot be determined. :param show_percent: enables or disables the percentage display. The default is `True` if the iterable has a length or `False` if not. :param show_pos: enables or disables the absolute position display. The default is `False`. :param item_show_func: a function called with the current item which can return a string to show the current item next to the progress bar. Note that the current item can be `None`! :param fill_char: the character to use to show the filled part of the progress bar. :param empty_char: the character to use to show the non-filled part of the progress bar. :param bar_template: the format string to use as template for the bar. The parameters in it are ``label`` for the label, ``bar`` for the progress bar and ``info`` for the info section. :param info_sep: the separator between multiple info items (eta etc.) :param width: the width of the progress bar in characters, 0 means full terminal width :param file: the file to write to. If this is not a terminal then only the label is printed. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are included anywhere in the progress bar output which is not the case by default. 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): """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) and will attempt to calculate remaining time and more. By default, this progress bar will not be rendered if the file is not a terminal. The context manager creates the progress bar. When the context manager is entered the progress bar is already displayed. With every iteration over the progress bar, the iterable passed to the bar is advanced and the bar is updated. When the context manager exits, a newline is printed and the progress bar is finalized on screen. No printing must happen or the progress bar will be unintentionally destroyed. Example usage:: with progressbar(items) as bar: for item in bar: do_something_with(item) Alternatively, if no iterable is specified, one can manually update the progress bar through the `update()` method instead of directly iterating over the progress bar. The update method accepts the number of steps to increment the bar with:: with progressbar(length=chunks.total_bytes) as bar: for chunk in chunks: process_chunk(chunk) bar.update(chunks.bytes) .. versionadded:: 2.0 .. versionadded:: 4.0 Added the `color` parameter. Added a `update` method to the progressbar object. :param iterable: an iterable to iterate over. If not provided the length is required. :param length: the number of items to iterate over. By default the progressbar will attempt to ask the iterator about its length, which might or might not work. If an iterable is also provided this parameter can be used to override the length. If an iterable is not provided the progress bar will iterate over a range of that length. :param label: the label to show next to the progress bar. :param show_eta: enables or disables the estimated time display. This is automatically disabled if the length cannot be determined. :param show_percent: enables or disables the percentage display. The default is `True` if the iterable has a length or `False` if not. :param show_pos: enables or disables the absolute position display. The default is `False`. :param item_show_func: a function called with the current item which can return a string to show the current item next to the progress bar. Note that the current item can be `None`! :param fill_char: the character to use to show the filled part of the progress bar. :param empty_char: the character to use to show the non-filled part of the progress bar. :param bar_template: the format string to use as template for the bar. The parameters in it are ``label`` for the label, ``bar`` for the progress bar and ``info`` for the info section. :param info_sep: the separator between multiple info items (eta etc.) :param width: the width of the progress bar in characters, 0 means full terminal width :param file: the file to write to. If this is not a terminal then only the label is printed. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are included anywhere in the progress bar output which is not the case by default. """ from ._termui_impl import ProgressBar color = resolve_color_default(color) return ProgressBar(iterable=iterable, length=length, show_eta=show_eta, show_percent=show_percent, show_pos=show_pos, item_show_func=item_show_func, fill_char=fill_char, empty_char=empty_char, bar_template=bar_template, info_sep=info_sep, file=file, label=label, width=width, color=color)
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 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 # If we're on Windows and we don't have colorama available, then we # clear the screen by shelling out. Otherwise we can use an escape # sequence. if WIN: os.system('cls') else: sys.stdout.write('\033[2J\033[1;1H')
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, `None` is returned. In case a file is edited directly the return value is always `None` and `require_save` and `extension` are ignored. If the editor cannot be opened a :exc:`UsageError` is raised. Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have ``\n`` as newline markers. :param text: the text to edit. :param editor: optionally the editor to use. Defaults to automatic detection. :param env: environment variables to forward to the editor. :param require_save: if this is true, then not saving in the editor will make the return value become `None`. :param extension: the extension to tell the editor about. This defaults to `.txt` but changing this might change syntax highlighting. :param filename: if provided it will edit this file instead of the provided text contents. It will not use a temporary file as an indirection in that case. 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 overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, `None` is returned. In case a file is edited directly the return value is always `None` and `require_save` and `extension` are ignored. If the editor cannot be opened a :exc:`UsageError` is raised. Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have ``\n`` as newline markers. :param text: the text to edit. :param editor: optionally the editor to use. Defaults to automatic detection. :param env: environment variables to forward to the editor. :param require_save: if this is true, then not saving in the editor will make the return value become `None`. :param extension: the extension to tell the editor about. This defaults to `.txt` but changing this might change syntax highlighting. :param filename: if provided it will edit this file instead of the provided text contents. It will not use a temporary file as an indirection in that case. """ from ._termui_impl import Editor editor = Editor(editor=editor, env=env, require_save=require_save, extension=extension) if filename is None: return editor.edit(text) editor.edit_file(filename)
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:: click.launch('https://click.palletsprojects.com/') click.launch('/my/downloaded/file', locate=True) .. versionadded:: 2.0 :param url: URL or filename of the thing to launch. :param wait: waits for the program to stop. :param locate: if this is set to `True` then instead of launching the application associated with the URL it will attempt to launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem. 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`` indicates success. Examples:: click.launch('https://click.palletsprojects.com/') click.launch('/my/downloaded/file', locate=True) .. versionadded:: 2.0 :param url: URL or filename of the thing to launch. :param wait: waits for the program to stop. :param locate: if this is set to `True` then instead of launching the application associated with the URL it will attempt to launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem. """ from ._termui_impl import open_url return open_url(url, wait=wait, locate=locate)
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 or standard input was not actually a terminal. Note that this will always read from the terminal, even if something is piped into the standard input. Note for Windows: in rare cases when typing non-ASCII characters, this function might wait for a second character and then return both at once. This is because certain Unicode characters look like special-key markers. .. versionadded:: 2.0 :param echo: if set to `True`, the character read will also show up on the terminal. The default is to not show it. 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 multiple characters end up in the terminal buffer or standard input was not actually a terminal. Note that this will always read from the terminal, even if something is piped into the standard input. Note for Windows: in rare cases when typing non-ASCII characters, this function might wait for a second character and then return both at once. This is because certain Unicode characters look like special-key markers. .. versionadded:: 2.0 :param echo: if set to `True`, the character read will also show up on the terminal. The default is to not show it. """ f = _getchar if f is None: from ._termui_impl import getchar as f return f(echo)
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. :param info: the info string to print before pausing. :param err: if set to message goes to ``stderr`` instead of ``stdout``, the same as with echo. 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. .. versionadded:: 2.0 .. versionadded:: 4.0 Added the `err` parameter. :param info: the info string to print before pausing. :param err: if set to message goes to ``stderr`` instead of ``stdout``, the same as with echo. """ if not isatty(sys.stdin) or not isatty(sys.stdout): return try: if info: echo(info, nl=False, err=err) try: getchar() except (KeyboardInterrupt, EOFError): pass finally: if info: echo(err=err)
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 :class:`list` of callables. .. versionadded:: 15.1.0 .. versionchanged:: 17.1.0 *validator* can be a list of validators. 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. :type validator: callable or :class:`list` of callables. .. versionadded:: 15.1.0 .. versionchanged:: 17.1.0 *validator* can be a list of validators. """ if isinstance(validator, list): return _OptionalValidator(_AndValidator(validator)) return _OptionalValidator(validator)
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 other
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. 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._forwards[f].add(t) self._backwards[t].add(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. 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 |= l ^ r return result == 0
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 certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. """ fingerprint = fingerprint.replace(':', '').lower() digest_length = len(fingerprint) hashfunc = HASHFUNC_MAP.get(digest_length) if not hashfunc: raise SSLError( 'Fingerprint of invalid length: {0}'.format(fingerprint)) # We need encode() here for py32; works on py2 and p33. fingerprint_bytes = unhexlify(fingerprint.encode()) cert_digest = hashfunc(cert).digest() if not _const_compare_digest(cert_digest, fingerprint_bytes): raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".' .format(fingerprint, hexlify(cert_digest)))
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`. If it's neither `None` nor a string we assume it is already the numeric constant which can directly be passed to wrap_socket. 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 abbreviation. (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. If it's neither `None` nor a string we assume it is already the numeric constant which can directly be passed to wrap_socket. """ if candidate is None: return CERT_NONE if isinstance(candidate, str): res = getattr(ssl, candidate, None) if res is None: res = getattr(ssl, 'CERT_' + candidate) return res return candidate
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 return 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 none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations(). 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 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 none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations(). """ context = ssl_context if context is None: # Note: This branch of code and all the variables in it are no longer # used by urllib3 itself. We should consider deprecating and removing # this code. context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) if ca_certs or ca_cert_dir: try: context.load_verify_locations(ca_certs, ca_cert_dir) except IOError as e: # Platform-specific: Python 2.7 raise SSLError(e) # Py33 raises FileNotFoundError which subclasses OSError # These are not equivalent unless we check the errno attribute except OSError as e: # Platform-specific: Python 3.3 and beyond if e.errno == errno.ENOENT: raise SSLError(e) raise elif getattr(context, 'load_default_certs', None) is not None: # try to load OS default certs; works well on Windows (require Python3.4+) context.load_default_certs() if certfile: context.load_cert_chain(certfile, keyfile) # If we detect server_hostname is an IP address then the SNI # extension should not be used according to RFC3546 Section 3.1 # We shouldn't warn the user if SNI isn't available but we would # not be using SNI anyways due to IP address for server_hostname. if ((server_hostname is not None and not is_ipaddress(server_hostname)) or IS_SECURETRANSPORT): if HAS_SNI and server_hostname is not None: return context.wrap_socket(sock, server_hostname=server_hostname) warnings.warn( 'An HTTPS request has been made, but the SNI (Server Name ' 'Indication) extension to TLS is not available on this platform. ' 'This may cause the server to present an incorrect TLS ' 'certificate, which can cause validation failures. You can upgrade to ' 'a newer version of Python to solve this. For more information, see ' 'https://urllib3.readthedocs.io/en/latest/advanced-usage.html' '#ssl-warnings', SNIMissingWarning ) return context.wrap_socket(sock)
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: True if the hostname is an IP address, False otherwise. """ if six.PY3 and isinstance(hostname, bytes): # IDN A-label bytes are ASCII compatible. hostname = hostname.decode('ascii') families = [socket.AF_INET] if hasattr(socket, 'AF_INET6'): families.append(socket.AF_INET6) for af in families: try: inet_pton(af, hostname) except (socket.error, ValueError, OSError): pass else: return True return False
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(takewhile(lambda x: x.redirect_location is None, reversed(self.history)))) if consecutive_errors_len <= 1: return 0 backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1)) return min(self.BACKOFF_MAX, backoff_value)
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 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 this method will return immediately. """ if response: slept = self.sleep_for_retry(response) if slept: return self._sleep_backoff()
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 aforementioned header) 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 returned status code is on the list of status codes to be retried upon on the presence of the aforementioned header) """ if not self._is_method_retryable(method): return False if self.status_forcelist and status_code in self.status_forcelist: return True return (self.total and self.respect_retry_after_header and has_retry_after and (status_code in self.RETRY_AFTER_STATUS_CODES))
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. :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 None if the response was received successfully. :return: A new ``Retry`` object. 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: :class:`~urllib3.response.HTTPResponse` :param Exception error: An error encountered during the request, or None if the response was received successfully. :return: A new ``Retry`` object. """ if self.total is False and error: # Disabled, indicate to re-raise the error. raise six.reraise(type(error), error, _stacktrace) total = self.total if total is not None: total -= 1 connect = self.connect read = self.read redirect = self.redirect status_count = self.status cause = 'unknown' status = None redirect_location = None if error and self._is_connection_error(error): # Connect retry? if connect is False: raise six.reraise(type(error), error, _stacktrace) elif connect is not None: connect -= 1 elif error and self._is_read_error(error): # Read retry? if read is False or not self._is_method_retryable(method): raise six.reraise(type(error), error, _stacktrace) elif read is not None: read -= 1 elif response and response.get_redirect_location(): # Redirect retry? if redirect is not None: redirect -= 1 cause = 'too many redirects' redirect_location = response.get_redirect_location() status = response.status else: # Incrementing because of a server error like a 500 in # status_forcelist and a the given method is in the whitelist cause = ResponseError.GENERIC_ERROR if response and response.status: if status_count is not None: status_count -= 1 cause = ResponseError.SPECIFIC_ERROR.format( status_code=response.status) status = response.status history = self.history + (RequestHistory(method, url, error, status, redirect_location),) new_retry = self.new( total=total, connect=connect, read=read, redirect=redirect, status=status_count, history=history) if new_retry.is_exhausted(): raise MaxRetryError(_pool, url, error or ResponseError(cause)) log.debug("Incremented Retry for (url='%s'): %r", url, new_retry) return new_retry