partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
path_is_known_executable
Returns whether a given path is a known executable from known executable extensions or has the executable bit toggled. :param path: The path to the target executable. :type path: :class:`~vistir.compat.Path` :return: True if the path has chmod +x, or is a readable, known executable extension. :rtype: bool
pipenv/vendor/pythonfinder/utils.py
def path_is_known_executable(path): # type: (vistir.compat.Path) -> bool """ Returns whether a given path is a known executable from known executable extensions or has the executable bit toggled. :param path: The path to the target executable. :type path: :class:`~vistir.compat.Path` :return: True if the path has chmod +x, or is a readable, known executable extension. :rtype: bool """ return ( path_is_executable(path) or os.access(str(path), os.R_OK) and path.suffix in KNOWN_EXTS )
def path_is_known_executable(path): # type: (vistir.compat.Path) -> bool """ Returns whether a given path is a known executable from known executable extensions or has the executable bit toggled. :param path: The path to the target executable. :type path: :class:`~vistir.compat.Path` :return: True if the path has chmod +x, or is a readable, known executable extension. :rtype: bool """ return ( path_is_executable(path) or os.access(str(path), os.R_OK) and path.suffix in KNOWN_EXTS )
[ "Returns", "whether", "a", "given", "path", "is", "a", "known", "executable", "from", "known", "executable", "extensions", "or", "has", "the", "executable", "bit", "toggled", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pythonfinder/utils.py#L181-L197
[ "def", "path_is_known_executable", "(", "path", ")", ":", "# type: (vistir.compat.Path) -> bool", "return", "(", "path_is_executable", "(", "path", ")", "or", "os", ".", "access", "(", "str", "(", "path", ")", ",", "os", ".", "R_OK", ")", "and", "path", ".",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
looks_like_python
Determine whether the supplied filename looks like a possible name of python. :param str name: The name of the provided file. :return: Whether the provided name looks like python. :rtype: bool
pipenv/vendor/pythonfinder/utils.py
def looks_like_python(name): # type: (str) -> bool """ Determine whether the supplied filename looks like a possible name of python. :param str name: The name of the provided file. :return: Whether the provided name looks like python. :rtype: bool """ if not any(name.lower().startswith(py_name) for py_name in PYTHON_IMPLEMENTATIONS): return False match = RE_MATCHER.match(name) if match: return any(fnmatch(name, rule) for rule in MATCH_RULES) return False
def looks_like_python(name): # type: (str) -> bool """ Determine whether the supplied filename looks like a possible name of python. :param str name: The name of the provided file. :return: Whether the provided name looks like python. :rtype: bool """ if not any(name.lower().startswith(py_name) for py_name in PYTHON_IMPLEMENTATIONS): return False match = RE_MATCHER.match(name) if match: return any(fnmatch(name, rule) for rule in MATCH_RULES) return False
[ "Determine", "whether", "the", "supplied", "filename", "looks", "like", "a", "possible", "name", "of", "python", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pythonfinder/utils.py#L201-L216
[ "def", "looks_like_python", "(", "name", ")", ":", "# type: (str) -> bool", "if", "not", "any", "(", "name", ".", "lower", "(", ")", ".", "startswith", "(", "py_name", ")", "for", "py_name", "in", "PYTHON_IMPLEMENTATIONS", ")", ":", "return", "False", "match...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ensure_path
Given a path (either a string or a Path object), expand variables and return a Path object. :param path: A string or a :class:`~pathlib.Path` object. :type path: str or :class:`~pathlib.Path` :return: A fully expanded Path object. :rtype: :class:`~pathlib.Path`
pipenv/vendor/pythonfinder/utils.py
def ensure_path(path): # type: (Union[vistir.compat.Path, str]) -> vistir.compat.Path """ Given a path (either a string or a Path object), expand variables and return a Path object. :param path: A string or a :class:`~pathlib.Path` object. :type path: str or :class:`~pathlib.Path` :return: A fully expanded Path object. :rtype: :class:`~pathlib.Path` """ if isinstance(path, vistir.compat.Path): return path path = vistir.compat.Path(os.path.expandvars(path)) return path.absolute()
def ensure_path(path): # type: (Union[vistir.compat.Path, str]) -> vistir.compat.Path """ Given a path (either a string or a Path object), expand variables and return a Path object. :param path: A string or a :class:`~pathlib.Path` object. :type path: str or :class:`~pathlib.Path` :return: A fully expanded Path object. :rtype: :class:`~pathlib.Path` """ if isinstance(path, vistir.compat.Path): return path path = vistir.compat.Path(os.path.expandvars(path)) return path.absolute()
[ "Given", "a", "path", "(", "either", "a", "string", "or", "a", "Path", "object", ")", "expand", "variables", "and", "return", "a", "Path", "object", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pythonfinder/utils.py#L235-L249
[ "def", "ensure_path", "(", "path", ")", ":", "# type: (Union[vistir.compat.Path, str]) -> vistir.compat.Path", "if", "isinstance", "(", "path", ",", "vistir", ".", "compat", ".", "Path", ")", ":", "return", "path", "path", "=", "vistir", ".", "compat", ".", "Pat...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
filter_pythons
Return all valid pythons in a given path
pipenv/vendor/pythonfinder/utils.py
def filter_pythons(path): # type: (Union[str, vistir.compat.Path]) -> Iterable """Return all valid pythons in a given path""" if not isinstance(path, vistir.compat.Path): path = vistir.compat.Path(str(path)) if not path.is_dir(): return path if path_is_python(path) else None return filter(path_is_python, path.iterdir())
def filter_pythons(path): # type: (Union[str, vistir.compat.Path]) -> Iterable """Return all valid pythons in a given path""" if not isinstance(path, vistir.compat.Path): path = vistir.compat.Path(str(path)) if not path.is_dir(): return path if path_is_python(path) else None return filter(path_is_python, path.iterdir())
[ "Return", "all", "valid", "pythons", "in", "a", "given", "path" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pythonfinder/utils.py#L270-L277
[ "def", "filter_pythons", "(", "path", ")", ":", "# type: (Union[str, vistir.compat.Path]) -> Iterable", "if", "not", "isinstance", "(", "path", ",", "vistir", ".", "compat", ".", "Path", ")", ":", "path", "=", "vistir", ".", "compat", ".", "Path", "(", "str", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
expand_paths
Recursively expand a list or :class:`~pythonfinder.models.path.PathEntry` instance :param Union[Sequence, PathEntry] path: The path or list of paths to expand :param bool only_python: Whether to filter to include only python paths, default True :returns: An iterator over the expanded set of path entries :rtype: Iterator[PathEntry]
pipenv/vendor/pythonfinder/utils.py
def expand_paths(path, only_python=True): # type: (Union[Sequence, PathEntry], bool) -> Iterator """ Recursively expand a list or :class:`~pythonfinder.models.path.PathEntry` instance :param Union[Sequence, PathEntry] path: The path or list of paths to expand :param bool only_python: Whether to filter to include only python paths, default True :returns: An iterator over the expanded set of path entries :rtype: Iterator[PathEntry] """ if path is not None and ( isinstance(path, Sequence) and not getattr(path.__class__, "__name__", "") == "PathEntry" ): for p in unnest(path): if p is None: continue for expanded in itertools.chain.from_iterable( expand_paths(p, only_python=only_python) ): yield expanded elif path is not None and path.is_dir: for p in path.children.values(): if p is not None and p.is_python and p.as_python is not None: for sub_path in itertools.chain.from_iterable( expand_paths(p, only_python=only_python) ): yield sub_path else: if path is not None and path.is_python and path.as_python is not None: yield path
def expand_paths(path, only_python=True): # type: (Union[Sequence, PathEntry], bool) -> Iterator """ Recursively expand a list or :class:`~pythonfinder.models.path.PathEntry` instance :param Union[Sequence, PathEntry] path: The path or list of paths to expand :param bool only_python: Whether to filter to include only python paths, default True :returns: An iterator over the expanded set of path entries :rtype: Iterator[PathEntry] """ if path is not None and ( isinstance(path, Sequence) and not getattr(path.__class__, "__name__", "") == "PathEntry" ): for p in unnest(path): if p is None: continue for expanded in itertools.chain.from_iterable( expand_paths(p, only_python=only_python) ): yield expanded elif path is not None and path.is_dir: for p in path.children.values(): if p is not None and p.is_python and p.as_python is not None: for sub_path in itertools.chain.from_iterable( expand_paths(p, only_python=only_python) ): yield sub_path else: if path is not None and path.is_python and path.as_python is not None: yield path
[ "Recursively", "expand", "a", "list", "or", ":", "class", ":", "~pythonfinder", ".", "models", ".", "path", ".", "PathEntry", "instance" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pythonfinder/utils.py#L334-L365
[ "def", "expand_paths", "(", "path", ",", "only_python", "=", "True", ")", ":", "# type: (Union[Sequence, PathEntry], bool) -> Iterator", "if", "path", "is", "not", "None", "and", "(", "isinstance", "(", "path", ",", "Sequence", ")", "and", "not", "getattr", "(",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Cache._get_cache_path_parts
Get parts of part that must be os.path.joined with cache_dir
pipenv/patched/notpip/_internal/cache.py
def _get_cache_path_parts(self, link): # type: (Link) -> List[str] """Get parts of part that must be os.path.joined with cache_dir """ # We want to generate an url to use as our cache key, we don't want to # just re-use the URL because it might have other items in the fragment # and we don't care about those. key_parts = [link.url_without_fragment] if link.hash_name is not None and link.hash is not None: key_parts.append("=".join([link.hash_name, link.hash])) key_url = "#".join(key_parts) # Encode our key url with sha224, we'll use this because it has similar # security properties to sha256, but with a shorter total output (and # thus less secure). However the differences don't make a lot of # difference for our use case here. hashed = hashlib.sha224(key_url.encode()).hexdigest() # We want to nest the directories some to prevent having a ton of top # level directories where we might run out of sub directories on some # FS. parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]] return parts
def _get_cache_path_parts(self, link): # type: (Link) -> List[str] """Get parts of part that must be os.path.joined with cache_dir """ # We want to generate an url to use as our cache key, we don't want to # just re-use the URL because it might have other items in the fragment # and we don't care about those. key_parts = [link.url_without_fragment] if link.hash_name is not None and link.hash is not None: key_parts.append("=".join([link.hash_name, link.hash])) key_url = "#".join(key_parts) # Encode our key url with sha224, we'll use this because it has similar # security properties to sha256, but with a shorter total output (and # thus less secure). However the differences don't make a lot of # difference for our use case here. hashed = hashlib.sha224(key_url.encode()).hexdigest() # We want to nest the directories some to prevent having a ton of top # level directories where we might run out of sub directories on some # FS. parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]] return parts
[ "Get", "parts", "of", "part", "that", "must", "be", "os", ".", "path", ".", "joined", "with", "cache_dir" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cache.py#L46-L70
[ "def", "_get_cache_path_parts", "(", "self", ",", "link", ")", ":", "# type: (Link) -> List[str]", "# We want to generate an url to use as our cache key, we don't want to", "# just re-use the URL because it might have other items in the fragment", "# and we don't care about those.", "key_par...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
SimpleWheelCache.get_path_for_link
Return a directory to store cached wheels for link Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited. :param link: The link of the sdist for which this will cache wheels.
pipenv/patched/notpip/_internal/cache.py
def get_path_for_link(self, link): # type: (Link) -> str """Return a directory to store cached wheels for link Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited. :param link: The link of the sdist for which this will cache wheels. """ parts = self._get_cache_path_parts(link) # Store wheels within the root cache_dir return os.path.join(self.cache_dir, "wheels", *parts)
def get_path_for_link(self, link): # type: (Link) -> str """Return a directory to store cached wheels for link Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited. :param link: The link of the sdist for which this will cache wheels. """ parts = self._get_cache_path_parts(link) # Store wheels within the root cache_dir return os.path.join(self.cache_dir, "wheels", *parts)
[ "Return", "a", "directory", "to", "store", "cached", "wheels", "for", "link" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cache.py#L132-L151
[ "def", "get_path_for_link", "(", "self", ",", "link", ")", ":", "# type: (Link) -> str", "parts", "=", "self", ".", "_get_cache_path_parts", "(", "link", ")", "# Store wheels within the root cache_dir", "return", "os", ".", "path", ".", "join", "(", "self", ".", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Link.is_artifact
Determines if this points to an actual artifact (e.g. a tarball) or if it points to an "abstract" thing like a path or a VCS location.
pipenv/patched/notpip/_internal/models/link.py
def is_artifact(self): # type: () -> bool """ Determines if this points to an actual artifact (e.g. a tarball) or if it points to an "abstract" thing like a path or a VCS location. """ from pipenv.patched.notpip._internal.vcs import vcs if self.scheme in vcs.all_schemes: return False return True
def is_artifact(self): # type: () -> bool """ Determines if this points to an actual artifact (e.g. a tarball) or if it points to an "abstract" thing like a path or a VCS location. """ from pipenv.patched.notpip._internal.vcs import vcs if self.scheme in vcs.all_schemes: return False return True
[ "Determines", "if", "this", "points", "to", "an", "actual", "artifact", "(", "e", ".", "g", ".", "a", "tarball", ")", "or", "if", "it", "points", "to", "an", "abstract", "thing", "like", "a", "path", "or", "a", "VCS", "location", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/models/link.py#L152-L163
[ "def", "is_artifact", "(", "self", ")", ":", "# type: () -> bool", "from", "pipenv", ".", "patched", ".", "notpip", ".", "_internal", ".", "vcs", "import", "vcs", "if", "self", ".", "scheme", "in", "vcs", ".", "all_schemes", ":", "return", "False", "return...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_get_dependencies_from_cache
Retrieves dependencies for the requirement from the dependency cache.
pipenv/vendor/passa/internals/dependencies.py
def _get_dependencies_from_cache(ireq): """Retrieves dependencies for the requirement from the dependency cache. """ if os.environ.get("PASSA_IGNORE_LOCAL_CACHE"): return if ireq.editable: return try: deps = DEPENDENCY_CACHE[ireq] pyrq = REQUIRES_PYTHON_CACHE[ireq] except KeyError: return # Preserving sanity: Run through the cache and make sure every entry if # valid. If this fails, something is wrong with the cache. Drop it. try: packaging.specifiers.SpecifierSet(pyrq) ireq_name = packaging.utils.canonicalize_name(ireq.name) if any(_is_cache_broken(line, ireq_name) for line in deps): broken = True else: broken = False except Exception: broken = True if broken: print("dropping broken cache for {0}".format(ireq.name)) del DEPENDENCY_CACHE[ireq] del REQUIRES_PYTHON_CACHE[ireq] return return deps, pyrq
def _get_dependencies_from_cache(ireq): """Retrieves dependencies for the requirement from the dependency cache. """ if os.environ.get("PASSA_IGNORE_LOCAL_CACHE"): return if ireq.editable: return try: deps = DEPENDENCY_CACHE[ireq] pyrq = REQUIRES_PYTHON_CACHE[ireq] except KeyError: return # Preserving sanity: Run through the cache and make sure every entry if # valid. If this fails, something is wrong with the cache. Drop it. try: packaging.specifiers.SpecifierSet(pyrq) ireq_name = packaging.utils.canonicalize_name(ireq.name) if any(_is_cache_broken(line, ireq_name) for line in deps): broken = True else: broken = False except Exception: broken = True if broken: print("dropping broken cache for {0}".format(ireq.name)) del DEPENDENCY_CACHE[ireq] del REQUIRES_PYTHON_CACHE[ireq] return return deps, pyrq
[ "Retrieves", "dependencies", "for", "the", "requirement", "from", "the", "dependency", "cache", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/dependencies.py#L49-L80
[ "def", "_get_dependencies_from_cache", "(", "ireq", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "\"PASSA_IGNORE_LOCAL_CACHE\"", ")", ":", "return", "if", "ireq", ".", "editable", ":", "return", "try", ":", "deps", "=", "DEPENDENCY_CACHE", "[", "ir...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_get_dependencies_from_json
Retrieves dependencies for the install requirement from the JSON API. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None
pipenv/vendor/passa/internals/dependencies.py
def _get_dependencies_from_json(ireq, sources): """Retrieves dependencies for the install requirement from the JSON API. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None """ if os.environ.get("PASSA_IGNORE_JSON_API"): return # It is technically possible to parse extras out of the JSON API's # requirement format, but it is such a chore let's just use the simple API. if ireq.extras: return try: version = get_pinned_version(ireq) except ValueError: return url_prefixes = [ proc_url[:-7] # Strip "/simple". for proc_url in ( raw_url.rstrip("/") for raw_url in (source.get("url", "") for source in sources) ) if proc_url.endswith("/simple") ] session = requests.session() for prefix in url_prefixes: url = "{prefix}/pypi/{name}/{version}/json".format( prefix=prefix, name=packaging.utils.canonicalize_name(ireq.name), version=version, ) try: dependencies = _get_dependencies_from_json_url(url, session) if dependencies is not None: return dependencies except Exception as e: print("unable to read dependencies via {0} ({1})".format(url, e)) session.close() return
def _get_dependencies_from_json(ireq, sources): """Retrieves dependencies for the install requirement from the JSON API. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None """ if os.environ.get("PASSA_IGNORE_JSON_API"): return # It is technically possible to parse extras out of the JSON API's # requirement format, but it is such a chore let's just use the simple API. if ireq.extras: return try: version = get_pinned_version(ireq) except ValueError: return url_prefixes = [ proc_url[:-7] # Strip "/simple". for proc_url in ( raw_url.rstrip("/") for raw_url in (source.get("url", "") for source in sources) ) if proc_url.endswith("/simple") ] session = requests.session() for prefix in url_prefixes: url = "{prefix}/pypi/{name}/{version}/json".format( prefix=prefix, name=packaging.utils.canonicalize_name(ireq.name), version=version, ) try: dependencies = _get_dependencies_from_json_url(url, session) if dependencies is not None: return dependencies except Exception as e: print("unable to read dependencies via {0} ({1})".format(url, e)) session.close() return
[ "Retrieves", "dependencies", "for", "the", "install", "requirement", "from", "the", "JSON", "API", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/dependencies.py#L113-L158
[ "def", "_get_dependencies_from_json", "(", "ireq", ",", "sources", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "\"PASSA_IGNORE_JSON_API\"", ")", ":", "return", "# It is technically possible to parse extras out of the JSON API's", "# requirement format, but it is su...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_read_requirements
Read wheel metadata to know what it depends on. The `run_requires` attribute contains a list of dict or str specifying requirements. For dicts, it may contain an "extra" key to specify these requirements are for a specific extra. Unfortunately, not all fields are specificed like this (I don't know why); some are specified with markers. So we jump though these terrible hoops to know exactly what we need. The extra extraction is not comprehensive. Tt assumes the marker is NEVER something like `extra == "foo" and extra == "bar"`. I guess this never makes sense anyway? Markers are just terrible.
pipenv/vendor/passa/internals/dependencies.py
def _read_requirements(metadata, extras): """Read wheel metadata to know what it depends on. The `run_requires` attribute contains a list of dict or str specifying requirements. For dicts, it may contain an "extra" key to specify these requirements are for a specific extra. Unfortunately, not all fields are specificed like this (I don't know why); some are specified with markers. So we jump though these terrible hoops to know exactly what we need. The extra extraction is not comprehensive. Tt assumes the marker is NEVER something like `extra == "foo" and extra == "bar"`. I guess this never makes sense anyway? Markers are just terrible. """ extras = extras or () requirements = [] for entry in metadata.run_requires: if isinstance(entry, six.text_type): entry = {"requires": [entry]} extra = None else: extra = entry.get("extra") if extra is not None and extra not in extras: continue for line in entry.get("requires", []): r = requirementslib.Requirement.from_line(line) if r.markers: contained = get_contained_extras(r.markers) if (contained and not any(e in contained for e in extras)): continue marker = get_without_extra(r.markers) r.markers = str(marker) if marker else None line = r.as_line(include_hashes=False) requirements.append(line) return requirements
def _read_requirements(metadata, extras): """Read wheel metadata to know what it depends on. The `run_requires` attribute contains a list of dict or str specifying requirements. For dicts, it may contain an "extra" key to specify these requirements are for a specific extra. Unfortunately, not all fields are specificed like this (I don't know why); some are specified with markers. So we jump though these terrible hoops to know exactly what we need. The extra extraction is not comprehensive. Tt assumes the marker is NEVER something like `extra == "foo" and extra == "bar"`. I guess this never makes sense anyway? Markers are just terrible. """ extras = extras or () requirements = [] for entry in metadata.run_requires: if isinstance(entry, six.text_type): entry = {"requires": [entry]} extra = None else: extra = entry.get("extra") if extra is not None and extra not in extras: continue for line in entry.get("requires", []): r = requirementslib.Requirement.from_line(line) if r.markers: contained = get_contained_extras(r.markers) if (contained and not any(e in contained for e in extras)): continue marker = get_without_extra(r.markers) r.markers = str(marker) if marker else None line = r.as_line(include_hashes=False) requirements.append(line) return requirements
[ "Read", "wheel", "metadata", "to", "know", "what", "it", "depends", "on", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/dependencies.py#L161-L194
[ "def", "_read_requirements", "(", "metadata", ",", "extras", ")", ":", "extras", "=", "extras", "or", "(", ")", "requirements", "=", "[", "]", "for", "entry", "in", "metadata", ".", "run_requires", ":", "if", "isinstance", "(", "entry", ",", "six", ".", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_read_requires_python
Read wheel metadata to know the value of Requires-Python. This is surprisingly poorly supported in Distlib. This function tries several ways to get this information: * Metadata 2.0: metadata.dictionary.get("requires_python") is not None * Metadata 2.1: metadata._legacy.get("Requires-Python") is not None * Metadata 1.2: metadata._legacy.get("Requires-Python") != "UNKNOWN"
pipenv/vendor/passa/internals/dependencies.py
def _read_requires_python(metadata): """Read wheel metadata to know the value of Requires-Python. This is surprisingly poorly supported in Distlib. This function tries several ways to get this information: * Metadata 2.0: metadata.dictionary.get("requires_python") is not None * Metadata 2.1: metadata._legacy.get("Requires-Python") is not None * Metadata 1.2: metadata._legacy.get("Requires-Python") != "UNKNOWN" """ # TODO: Support more metadata formats. value = metadata.dictionary.get("requires_python") if value is not None: return value if metadata._legacy: value = metadata._legacy.get("Requires-Python") if value is not None and value != "UNKNOWN": return value return ""
def _read_requires_python(metadata): """Read wheel metadata to know the value of Requires-Python. This is surprisingly poorly supported in Distlib. This function tries several ways to get this information: * Metadata 2.0: metadata.dictionary.get("requires_python") is not None * Metadata 2.1: metadata._legacy.get("Requires-Python") is not None * Metadata 1.2: metadata._legacy.get("Requires-Python") != "UNKNOWN" """ # TODO: Support more metadata formats. value = metadata.dictionary.get("requires_python") if value is not None: return value if metadata._legacy: value = metadata._legacy.get("Requires-Python") if value is not None and value != "UNKNOWN": return value return ""
[ "Read", "wheel", "metadata", "to", "know", "the", "value", "of", "Requires", "-", "Python", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/dependencies.py#L197-L215
[ "def", "_read_requires_python", "(", "metadata", ")", ":", "# TODO: Support more metadata formats.", "value", "=", "metadata", ".", "dictionary", ".", "get", "(", "\"requires_python\"", ")", "if", "value", "is", "not", "None", ":", "return", "value", "if", "metada...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_get_dependencies_from_pip
Retrieves dependencies for the requirement from pipenv.patched.notpip internals. The current strategy is to try the followings in order, returning the first successful result. 1. Try to build a wheel out of the ireq, and read metadata out of it. 2. Read metadata out of the egg-info directory if it is present.
pipenv/vendor/passa/internals/dependencies.py
def _get_dependencies_from_pip(ireq, sources): """Retrieves dependencies for the requirement from pipenv.patched.notpip internals. The current strategy is to try the followings in order, returning the first successful result. 1. Try to build a wheel out of the ireq, and read metadata out of it. 2. Read metadata out of the egg-info directory if it is present. """ extras = ireq.extras or () try: wheel = build_wheel(ireq, sources) except WheelBuildError: # XXX: This depends on a side effect of `build_wheel`. This block is # reached when it fails to build an sdist, where the sdist would have # been downloaded, extracted into `ireq.source_dir`, and partially # built (hopefully containing .egg-info). metadata = read_sdist_metadata(ireq) if not metadata: raise else: metadata = wheel.metadata requirements = _read_requirements(metadata, extras) requires_python = _read_requires_python(metadata) return requirements, requires_python
def _get_dependencies_from_pip(ireq, sources): """Retrieves dependencies for the requirement from pipenv.patched.notpip internals. The current strategy is to try the followings in order, returning the first successful result. 1. Try to build a wheel out of the ireq, and read metadata out of it. 2. Read metadata out of the egg-info directory if it is present. """ extras = ireq.extras or () try: wheel = build_wheel(ireq, sources) except WheelBuildError: # XXX: This depends on a side effect of `build_wheel`. This block is # reached when it fails to build an sdist, where the sdist would have # been downloaded, extracted into `ireq.source_dir`, and partially # built (hopefully containing .egg-info). metadata = read_sdist_metadata(ireq) if not metadata: raise else: metadata = wheel.metadata requirements = _read_requirements(metadata, extras) requires_python = _read_requires_python(metadata) return requirements, requires_python
[ "Retrieves", "dependencies", "for", "the", "requirement", "from", "pipenv", ".", "patched", ".", "notpip", "internals", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/dependencies.py#L218-L242
[ "def", "_get_dependencies_from_pip", "(", "ireq", ",", "sources", ")", ":", "extras", "=", "ireq", ".", "extras", "or", "(", ")", "try", ":", "wheel", "=", "build_wheel", "(", "ireq", ",", "sources", ")", "except", "WheelBuildError", ":", "# XXX: This depend...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_dependencies
Get all dependencies for a given install requirement. :param requirement: A requirement :param sources: Pipfile-formatted sources :type sources: list[dict]
pipenv/vendor/passa/internals/dependencies.py
def get_dependencies(requirement, sources): """Get all dependencies for a given install requirement. :param requirement: A requirement :param sources: Pipfile-formatted sources :type sources: list[dict] """ getters = [ _get_dependencies_from_cache, _cached(_get_dependencies_from_json, sources=sources), _cached(_get_dependencies_from_pip, sources=sources), ] ireq = requirement.as_ireq() last_exc = None for getter in getters: try: result = getter(ireq) except Exception as e: last_exc = sys.exc_info() continue if result is not None: deps, pyreq = result reqs = [requirementslib.Requirement.from_line(d) for d in deps] return reqs, pyreq if last_exc: six.reraise(*last_exc) raise RuntimeError("failed to get dependencies for {}".format( requirement.as_line(), ))
def get_dependencies(requirement, sources): """Get all dependencies for a given install requirement. :param requirement: A requirement :param sources: Pipfile-formatted sources :type sources: list[dict] """ getters = [ _get_dependencies_from_cache, _cached(_get_dependencies_from_json, sources=sources), _cached(_get_dependencies_from_pip, sources=sources), ] ireq = requirement.as_ireq() last_exc = None for getter in getters: try: result = getter(ireq) except Exception as e: last_exc = sys.exc_info() continue if result is not None: deps, pyreq = result reqs = [requirementslib.Requirement.from_line(d) for d in deps] return reqs, pyreq if last_exc: six.reraise(*last_exc) raise RuntimeError("failed to get dependencies for {}".format( requirement.as_line(), ))
[ "Get", "all", "dependencies", "for", "a", "given", "install", "requirement", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/dependencies.py#L245-L273
[ "def", "get_dependencies", "(", "requirement", ",", "sources", ")", ":", "getters", "=", "[", "_get_dependencies_from_cache", ",", "_cached", "(", "_get_dependencies_from_json", ",", "sources", "=", "sources", ")", ",", "_cached", "(", "_get_dependencies_from_pip", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
format_header_param
Helper function to format and quote a single header parameter. Particularly useful for header parameters which might contain non-ASCII values, like file names. This follows RFC 2231, as suggested by RFC 2388 Section 4.4. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as a unicode string.
pipenv/vendor/urllib3/fields.py
def format_header_param(name, value): """ Helper function to format and quote a single header parameter. Particularly useful for header parameters which might contain non-ASCII values, like file names. This follows RFC 2231, as suggested by RFC 2388 Section 4.4. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as a unicode string. """ if not any(ch in value for ch in '"\\\r\n'): result = '%s="%s"' % (name, value) try: result.encode('ascii') except (UnicodeEncodeError, UnicodeDecodeError): pass else: return result if not six.PY3 and isinstance(value, six.text_type): # Python 2: value = value.encode('utf-8') value = email.utils.encode_rfc2231(value, 'utf-8') value = '%s*=%s' % (name, value) return value
def format_header_param(name, value): """ Helper function to format and quote a single header parameter. Particularly useful for header parameters which might contain non-ASCII values, like file names. This follows RFC 2231, as suggested by RFC 2388 Section 4.4. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as a unicode string. """ if not any(ch in value for ch in '"\\\r\n'): result = '%s="%s"' % (name, value) try: result.encode('ascii') except (UnicodeEncodeError, UnicodeDecodeError): pass else: return result if not six.PY3 and isinstance(value, six.text_type): # Python 2: value = value.encode('utf-8') value = email.utils.encode_rfc2231(value, 'utf-8') value = '%s*=%s' % (name, value) return value
[ "Helper", "function", "to", "format", "and", "quote", "a", "single", "header", "parameter", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/fields.py#L22-L47
[ "def", "format_header_param", "(", "name", ",", "value", ")", ":", "if", "not", "any", "(", "ch", "in", "value", "for", "ch", "in", "'\"\\\\\\r\\n'", ")", ":", "result", "=", "'%s=\"%s\"'", "%", "(", "name", ",", "value", ")", "try", ":", "result", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
RequestField.from_tuples
A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters. Supports constructing :class:`~urllib3.fields.RequestField` from parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', Field names and filenames must be unicode.
pipenv/vendor/urllib3/fields.py
def from_tuples(cls, fieldname, value): """ A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters. Supports constructing :class:`~urllib3.fields.RequestField` from parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', Field names and filenames must be unicode. """ if isinstance(value, tuple): if len(value) == 3: filename, data, content_type = value else: filename, data = value content_type = guess_content_type(filename) else: filename = None content_type = None data = value request_param = cls(fieldname, data, filename=filename) request_param.make_multipart(content_type=content_type) return request_param
def from_tuples(cls, fieldname, value): """ A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters. Supports constructing :class:`~urllib3.fields.RequestField` from parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', Field names and filenames must be unicode. """ if isinstance(value, tuple): if len(value) == 3: filename, data, content_type = value else: filename, data = value content_type = guess_content_type(filename) else: filename = None content_type = None data = value request_param = cls(fieldname, data, filename=filename) request_param.make_multipart(content_type=content_type) return request_param
[ "A", ":", "class", ":", "~urllib3", ".", "fields", ".", "RequestField", "factory", "from", "old", "-", "style", "tuple", "parameters", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/fields.py#L72-L103
[ "def", "from_tuples", "(", "cls", ",", "fieldname", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "tuple", ")", ":", "if", "len", "(", "value", ")", "==", "3", ":", "filename", ",", "data", ",", "content_type", "=", "value", "else", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
RequestField._render_parts
Helper function to format and quote a single header. Useful for single headers that are composed of multiple items. E.g., 'Content-Disposition' fields. :param header_parts: A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format as `k1="v1"; k2="v2"; ...`.
pipenv/vendor/urllib3/fields.py
def _render_parts(self, header_parts): """ Helper function to format and quote a single header. Useful for single headers that are composed of multiple items. E.g., 'Content-Disposition' fields. :param header_parts: A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format as `k1="v1"; k2="v2"; ...`. """ parts = [] iterable = header_parts if isinstance(header_parts, dict): iterable = header_parts.items() for name, value in iterable: if value is not None: parts.append(self._render_part(name, value)) return '; '.join(parts)
def _render_parts(self, header_parts): """ Helper function to format and quote a single header. Useful for single headers that are composed of multiple items. E.g., 'Content-Disposition' fields. :param header_parts: A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format as `k1="v1"; k2="v2"; ...`. """ parts = [] iterable = header_parts if isinstance(header_parts, dict): iterable = header_parts.items() for name, value in iterable: if value is not None: parts.append(self._render_part(name, value)) return '; '.join(parts)
[ "Helper", "function", "to", "format", "and", "quote", "a", "single", "header", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/fields.py#L116-L136
[ "def", "_render_parts", "(", "self", ",", "header_parts", ")", ":", "parts", "=", "[", "]", "iterable", "=", "header_parts", "if", "isinstance", "(", "header_parts", ",", "dict", ")", ":", "iterable", "=", "header_parts", ".", "items", "(", ")", "for", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
RequestField.render_headers
Renders the headers for this request field.
pipenv/vendor/urllib3/fields.py
def render_headers(self): """ Renders the headers for this request field. """ lines = [] sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location'] for sort_key in sort_keys: if self.headers.get(sort_key, False): lines.append('%s: %s' % (sort_key, self.headers[sort_key])) for header_name, header_value in self.headers.items(): if header_name not in sort_keys: if header_value: lines.append('%s: %s' % (header_name, header_value)) lines.append('\r\n') return '\r\n'.join(lines)
def render_headers(self): """ Renders the headers for this request field. """ lines = [] sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location'] for sort_key in sort_keys: if self.headers.get(sort_key, False): lines.append('%s: %s' % (sort_key, self.headers[sort_key])) for header_name, header_value in self.headers.items(): if header_name not in sort_keys: if header_value: lines.append('%s: %s' % (header_name, header_value)) lines.append('\r\n') return '\r\n'.join(lines)
[ "Renders", "the", "headers", "for", "this", "request", "field", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/fields.py#L138-L155
[ "def", "render_headers", "(", "self", ")", ":", "lines", "=", "[", "]", "sort_keys", "=", "[", "'Content-Disposition'", ",", "'Content-Type'", ",", "'Content-Location'", "]", "for", "sort_key", "in", "sort_keys", ":", "if", "self", ".", "headers", ".", "get"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
RequestField.make_multipart
Makes this request field into a multipart request field. This method overrides "Content-Disposition", "Content-Type" and "Content-Location" headers to the request parameter. :param content_type: The 'Content-Type' of the request body. :param content_location: The 'Content-Location' of the request body.
pipenv/vendor/urllib3/fields.py
def make_multipart(self, content_disposition=None, content_type=None, content_location=None): """ Makes this request field into a multipart request field. This method overrides "Content-Disposition", "Content-Type" and "Content-Location" headers to the request parameter. :param content_type: The 'Content-Type' of the request body. :param content_location: The 'Content-Location' of the request body. """ self.headers['Content-Disposition'] = content_disposition or 'form-data' self.headers['Content-Disposition'] += '; '.join([ '', self._render_parts( (('name', self._name), ('filename', self._filename)) ) ]) self.headers['Content-Type'] = content_type self.headers['Content-Location'] = content_location
def make_multipart(self, content_disposition=None, content_type=None, content_location=None): """ Makes this request field into a multipart request field. This method overrides "Content-Disposition", "Content-Type" and "Content-Location" headers to the request parameter. :param content_type: The 'Content-Type' of the request body. :param content_location: The 'Content-Location' of the request body. """ self.headers['Content-Disposition'] = content_disposition or 'form-data' self.headers['Content-Disposition'] += '; '.join([ '', self._render_parts( (('name', self._name), ('filename', self._filename)) ) ]) self.headers['Content-Type'] = content_type self.headers['Content-Location'] = content_location
[ "Makes", "this", "request", "field", "into", "a", "multipart", "request", "field", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/fields.py#L157-L178
[ "def", "make_multipart", "(", "self", ",", "content_disposition", "=", "None", ",", "content_type", "=", "None", ",", "content_location", "=", "None", ")", ":", "self", ".", "headers", "[", "'Content-Disposition'", "]", "=", "content_disposition", "or", "'form-d...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TreeWalker.emptyTag
Generates an EmptyTag token :arg namespace: the namespace of the token--can be ``None`` :arg name: the name of the element :arg attrs: the attributes of the element as a dict :arg hasChildren: whether or not to yield a SerializationError because this tag shouldn't have children :returns: EmptyTag token
pipenv/patched/notpip/_vendor/html5lib/treewalkers/base.py
def emptyTag(self, namespace, name, attrs, hasChildren=False): """Generates an EmptyTag token :arg namespace: the namespace of the token--can be ``None`` :arg name: the name of the element :arg attrs: the attributes of the element as a dict :arg hasChildren: whether or not to yield a SerializationError because this tag shouldn't have children :returns: EmptyTag token """ yield {"type": "EmptyTag", "name": name, "namespace": namespace, "data": attrs} if hasChildren: yield self.error("Void element has children")
def emptyTag(self, namespace, name, attrs, hasChildren=False): """Generates an EmptyTag token :arg namespace: the namespace of the token--can be ``None`` :arg name: the name of the element :arg attrs: the attributes of the element as a dict :arg hasChildren: whether or not to yield a SerializationError because this tag shouldn't have children :returns: EmptyTag token """ yield {"type": "EmptyTag", "name": name, "namespace": namespace, "data": attrs} if hasChildren: yield self.error("Void element has children")
[ "Generates", "an", "EmptyTag", "token" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treewalkers/base.py#L48-L67
[ "def", "emptyTag", "(", "self", ",", "namespace", ",", "name", ",", "attrs", ",", "hasChildren", "=", "False", ")", ":", "yield", "{", "\"type\"", ":", "\"EmptyTag\"", ",", "\"name\"", ":", "name", ",", "\"namespace\"", ":", "namespace", ",", "\"data\"", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TreeWalker.text
Generates SpaceCharacters and Characters tokens Depending on what's in the data, this generates one or more ``SpaceCharacters`` and ``Characters`` tokens. For example: >>> from html5lib.treewalkers.base import TreeWalker >>> # Give it an empty tree just so it instantiates >>> walker = TreeWalker([]) >>> list(walker.text('')) [] >>> list(walker.text(' ')) [{u'data': ' ', u'type': u'SpaceCharacters'}] >>> list(walker.text(' abc ')) # doctest: +NORMALIZE_WHITESPACE [{u'data': ' ', u'type': u'SpaceCharacters'}, {u'data': u'abc', u'type': u'Characters'}, {u'data': u' ', u'type': u'SpaceCharacters'}] :arg data: the text data :returns: one or more ``SpaceCharacters`` and ``Characters`` tokens
pipenv/patched/notpip/_vendor/html5lib/treewalkers/base.py
def text(self, data): """Generates SpaceCharacters and Characters tokens Depending on what's in the data, this generates one or more ``SpaceCharacters`` and ``Characters`` tokens. For example: >>> from html5lib.treewalkers.base import TreeWalker >>> # Give it an empty tree just so it instantiates >>> walker = TreeWalker([]) >>> list(walker.text('')) [] >>> list(walker.text(' ')) [{u'data': ' ', u'type': u'SpaceCharacters'}] >>> list(walker.text(' abc ')) # doctest: +NORMALIZE_WHITESPACE [{u'data': ' ', u'type': u'SpaceCharacters'}, {u'data': u'abc', u'type': u'Characters'}, {u'data': u' ', u'type': u'SpaceCharacters'}] :arg data: the text data :returns: one or more ``SpaceCharacters`` and ``Characters`` tokens """ data = data middle = data.lstrip(spaceCharacters) left = data[:len(data) - len(middle)] if left: yield {"type": "SpaceCharacters", "data": left} data = middle middle = data.rstrip(spaceCharacters) right = data[len(middle):] if middle: yield {"type": "Characters", "data": middle} if right: yield {"type": "SpaceCharacters", "data": right}
def text(self, data): """Generates SpaceCharacters and Characters tokens Depending on what's in the data, this generates one or more ``SpaceCharacters`` and ``Characters`` tokens. For example: >>> from html5lib.treewalkers.base import TreeWalker >>> # Give it an empty tree just so it instantiates >>> walker = TreeWalker([]) >>> list(walker.text('')) [] >>> list(walker.text(' ')) [{u'data': ' ', u'type': u'SpaceCharacters'}] >>> list(walker.text(' abc ')) # doctest: +NORMALIZE_WHITESPACE [{u'data': ' ', u'type': u'SpaceCharacters'}, {u'data': u'abc', u'type': u'Characters'}, {u'data': u' ', u'type': u'SpaceCharacters'}] :arg data: the text data :returns: one or more ``SpaceCharacters`` and ``Characters`` tokens """ data = data middle = data.lstrip(spaceCharacters) left = data[:len(data) - len(middle)] if left: yield {"type": "SpaceCharacters", "data": left} data = middle middle = data.rstrip(spaceCharacters) right = data[len(middle):] if middle: yield {"type": "Characters", "data": middle} if right: yield {"type": "SpaceCharacters", "data": right}
[ "Generates", "SpaceCharacters", "and", "Characters", "tokens" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treewalkers/base.py#L100-L136
[ "def", "text", "(", "self", ",", "data", ")", ":", "data", "=", "data", "middle", "=", "data", ".", "lstrip", "(", "spaceCharacters", ")", "left", "=", "data", "[", ":", "len", "(", "data", ")", "-", "len", "(", "middle", ")", "]", "if", "left", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_get_activate_script
Returns the string to activate a virtualenv. This is POSIX-only at the moment since the compat (pexpect-based) shell does not work elsewhere anyway.
pipenv/shells.py
def _get_activate_script(cmd, venv): """Returns the string to activate a virtualenv. This is POSIX-only at the moment since the compat (pexpect-based) shell does not work elsewhere anyway. """ # Suffix and source command for other shells. # Support for fish shell. if "fish" in cmd: suffix = ".fish" command = "source" # Support for csh shell. elif "csh" in cmd: suffix = ".csh" command = "source" else: suffix = "" command = "." # Escape any spaces located within the virtualenv path to allow # for proper activation. venv_location = str(venv).replace(" ", r"\ ") # The leading space can make history cleaner in some shells. return " {2} {0}/bin/activate{1}".format(venv_location, suffix, command)
def _get_activate_script(cmd, venv): """Returns the string to activate a virtualenv. This is POSIX-only at the moment since the compat (pexpect-based) shell does not work elsewhere anyway. """ # Suffix and source command for other shells. # Support for fish shell. if "fish" in cmd: suffix = ".fish" command = "source" # Support for csh shell. elif "csh" in cmd: suffix = ".csh" command = "source" else: suffix = "" command = "." # Escape any spaces located within the virtualenv path to allow # for proper activation. venv_location = str(venv).replace(" ", r"\ ") # The leading space can make history cleaner in some shells. return " {2} {0}/bin/activate{1}".format(venv_location, suffix, command)
[ "Returns", "the", "string", "to", "activate", "a", "virtualenv", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/shells.py#L32-L54
[ "def", "_get_activate_script", "(", "cmd", ",", "venv", ")", ":", "# Suffix and source command for other shells.", "# Support for fish shell.", "if", "\"fish\"", "in", "cmd", ":", "suffix", "=", "\".fish\"", "command", "=", "\"source\"", "# Support for csh shell.", "elif"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Wheel.filename
Build and return a filename from the various components.
pipenv/vendor/distlib/wheel.py
def filename(self): """ Build and return a filename from the various components. """ if self.buildver: buildver = '-' + self.buildver else: buildver = '' pyver = '.'.join(self.pyver) abi = '.'.join(self.abi) arch = '.'.join(self.arch) # replace - with _ as a local version separator version = self.version.replace('-', '_') return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver, pyver, abi, arch)
def filename(self): """ Build and return a filename from the various components. """ if self.buildver: buildver = '-' + self.buildver else: buildver = '' pyver = '.'.join(self.pyver) abi = '.'.join(self.abi) arch = '.'.join(self.arch) # replace - with _ as a local version separator version = self.version.replace('-', '_') return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver, pyver, abi, arch)
[ "Build", "and", "return", "a", "filename", "from", "the", "various", "components", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/wheel.py#L186-L200
[ "def", "filename", "(", "self", ")", ":", "if", "self", ".", "buildver", ":", "buildver", "=", "'-'", "+", "self", ".", "buildver", "else", ":", "buildver", "=", "''", "pyver", "=", "'.'", ".", "join", "(", "self", ".", "pyver", ")", "abi", "=", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Wheel.build
Build a wheel from files in specified paths, and use any specified tags when determining the name of the wheel.
pipenv/vendor/distlib/wheel.py
def build(self, paths, tags=None, wheel_version=None): """ Build a wheel from files in specified paths, and use any specified tags when determining the name of the wheel. """ if tags is None: tags = {} libkey = list(filter(lambda o: o in paths, ('purelib', 'platlib')))[0] if libkey == 'platlib': is_pure = 'false' default_pyver = [IMPVER] default_abi = [ABI] default_arch = [ARCH] else: is_pure = 'true' default_pyver = [PYVER] default_abi = ['none'] default_arch = ['any'] self.pyver = tags.get('pyver', default_pyver) self.abi = tags.get('abi', default_abi) self.arch = tags.get('arch', default_arch) libdir = paths[libkey] name_ver = '%s-%s' % (self.name, self.version) data_dir = '%s.data' % name_ver info_dir = '%s.dist-info' % name_ver archive_paths = [] # First, stuff which is not in site-packages for key in ('data', 'headers', 'scripts'): if key not in paths: continue path = paths[key] if os.path.isdir(path): for root, dirs, files in os.walk(path): for fn in files: p = fsdecode(os.path.join(root, fn)) rp = os.path.relpath(p, path) ap = to_posix(os.path.join(data_dir, key, rp)) archive_paths.append((ap, p)) if key == 'scripts' and not p.endswith('.exe'): with open(p, 'rb') as f: data = f.read() data = self.process_shebang(data) with open(p, 'wb') as f: f.write(data) # Now, stuff which is in site-packages, other than the # distinfo stuff. path = libdir distinfo = None for root, dirs, files in os.walk(path): if root == path: # At the top level only, save distinfo for later # and skip it for now for i, dn in enumerate(dirs): dn = fsdecode(dn) if dn.endswith('.dist-info'): distinfo = os.path.join(root, dn) del dirs[i] break assert distinfo, '.dist-info directory expected, not found' for fn in files: # comment out next suite to leave .pyc files in if fsdecode(fn).endswith(('.pyc', '.pyo')): continue p = os.path.join(root, fn) rp = to_posix(os.path.relpath(p, path)) archive_paths.append((rp, p)) # Now distinfo. Assumed to be flat, i.e. os.listdir is enough. files = os.listdir(distinfo) for fn in files: if fn not in ('RECORD', 'INSTALLER', 'SHARED', 'WHEEL'): p = fsdecode(os.path.join(distinfo, fn)) ap = to_posix(os.path.join(info_dir, fn)) archive_paths.append((ap, p)) wheel_metadata = [ 'Wheel-Version: %d.%d' % (wheel_version or self.wheel_version), 'Generator: distlib %s' % __version__, 'Root-Is-Purelib: %s' % is_pure, ] for pyver, abi, arch in self.tags: wheel_metadata.append('Tag: %s-%s-%s' % (pyver, abi, arch)) p = os.path.join(distinfo, 'WHEEL') with open(p, 'w') as f: f.write('\n'.join(wheel_metadata)) ap = to_posix(os.path.join(info_dir, 'WHEEL')) archive_paths.append((ap, p)) # Now, at last, RECORD. # Paths in here are archive paths - nothing else makes sense. self.write_records((distinfo, info_dir), libdir, archive_paths) # Now, ready to build the zip file pathname = os.path.join(self.dirname, self.filename) self.build_zip(pathname, archive_paths) return pathname
def build(self, paths, tags=None, wheel_version=None): """ Build a wheel from files in specified paths, and use any specified tags when determining the name of the wheel. """ if tags is None: tags = {} libkey = list(filter(lambda o: o in paths, ('purelib', 'platlib')))[0] if libkey == 'platlib': is_pure = 'false' default_pyver = [IMPVER] default_abi = [ABI] default_arch = [ARCH] else: is_pure = 'true' default_pyver = [PYVER] default_abi = ['none'] default_arch = ['any'] self.pyver = tags.get('pyver', default_pyver) self.abi = tags.get('abi', default_abi) self.arch = tags.get('arch', default_arch) libdir = paths[libkey] name_ver = '%s-%s' % (self.name, self.version) data_dir = '%s.data' % name_ver info_dir = '%s.dist-info' % name_ver archive_paths = [] # First, stuff which is not in site-packages for key in ('data', 'headers', 'scripts'): if key not in paths: continue path = paths[key] if os.path.isdir(path): for root, dirs, files in os.walk(path): for fn in files: p = fsdecode(os.path.join(root, fn)) rp = os.path.relpath(p, path) ap = to_posix(os.path.join(data_dir, key, rp)) archive_paths.append((ap, p)) if key == 'scripts' and not p.endswith('.exe'): with open(p, 'rb') as f: data = f.read() data = self.process_shebang(data) with open(p, 'wb') as f: f.write(data) # Now, stuff which is in site-packages, other than the # distinfo stuff. path = libdir distinfo = None for root, dirs, files in os.walk(path): if root == path: # At the top level only, save distinfo for later # and skip it for now for i, dn in enumerate(dirs): dn = fsdecode(dn) if dn.endswith('.dist-info'): distinfo = os.path.join(root, dn) del dirs[i] break assert distinfo, '.dist-info directory expected, not found' for fn in files: # comment out next suite to leave .pyc files in if fsdecode(fn).endswith(('.pyc', '.pyo')): continue p = os.path.join(root, fn) rp = to_posix(os.path.relpath(p, path)) archive_paths.append((rp, p)) # Now distinfo. Assumed to be flat, i.e. os.listdir is enough. files = os.listdir(distinfo) for fn in files: if fn not in ('RECORD', 'INSTALLER', 'SHARED', 'WHEEL'): p = fsdecode(os.path.join(distinfo, fn)) ap = to_posix(os.path.join(info_dir, fn)) archive_paths.append((ap, p)) wheel_metadata = [ 'Wheel-Version: %d.%d' % (wheel_version or self.wheel_version), 'Generator: distlib %s' % __version__, 'Root-Is-Purelib: %s' % is_pure, ] for pyver, abi, arch in self.tags: wheel_metadata.append('Tag: %s-%s-%s' % (pyver, abi, arch)) p = os.path.join(distinfo, 'WHEEL') with open(p, 'w') as f: f.write('\n'.join(wheel_metadata)) ap = to_posix(os.path.join(info_dir, 'WHEEL')) archive_paths.append((ap, p)) # Now, at last, RECORD. # Paths in here are archive paths - nothing else makes sense. self.write_records((distinfo, info_dir), libdir, archive_paths) # Now, ready to build the zip file pathname = os.path.join(self.dirname, self.filename) self.build_zip(pathname, archive_paths) return pathname
[ "Build", "a", "wheel", "from", "files", "in", "specified", "paths", "and", "use", "any", "specified", "tags", "when", "determining", "the", "name", "of", "the", "wheel", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/wheel.py#L332-L434
[ "def", "build", "(", "self", ",", "paths", ",", "tags", "=", "None", ",", "wheel_version", "=", "None", ")", ":", "if", "tags", "is", "None", ":", "tags", "=", "{", "}", "libkey", "=", "list", "(", "filter", "(", "lambda", "o", ":", "o", "in", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Wheel.install
Install a wheel to the specified paths. If kwarg ``warner`` is specified, it should be a callable, which will be called with two tuples indicating the wheel version of this software and the wheel version in the file, if there is a discrepancy in the versions. This can be used to issue any warnings to raise any exceptions. If kwarg ``lib_only`` is True, only the purelib/platlib files are installed, and the headers, scripts, data and dist-info metadata are not written. If kwarg ``bytecode_hashed_invalidation`` is True, written bytecode will try to use file-hash based invalidation (PEP-552) on supported interpreter versions (CPython 2.7+). The return value is a :class:`InstalledDistribution` instance unless ``options.lib_only`` is True, in which case the return value is ``None``.
pipenv/vendor/distlib/wheel.py
def install(self, paths, maker, **kwargs): """ Install a wheel to the specified paths. If kwarg ``warner`` is specified, it should be a callable, which will be called with two tuples indicating the wheel version of this software and the wheel version in the file, if there is a discrepancy in the versions. This can be used to issue any warnings to raise any exceptions. If kwarg ``lib_only`` is True, only the purelib/platlib files are installed, and the headers, scripts, data and dist-info metadata are not written. If kwarg ``bytecode_hashed_invalidation`` is True, written bytecode will try to use file-hash based invalidation (PEP-552) on supported interpreter versions (CPython 2.7+). The return value is a :class:`InstalledDistribution` instance unless ``options.lib_only`` is True, in which case the return value is ``None``. """ dry_run = maker.dry_run warner = kwargs.get('warner') lib_only = kwargs.get('lib_only', False) bc_hashed_invalidation = kwargs.get('bytecode_hashed_invalidation', False) pathname = os.path.join(self.dirname, self.filename) name_ver = '%s-%s' % (self.name, self.version) data_dir = '%s.data' % name_ver info_dir = '%s.dist-info' % name_ver metadata_name = posixpath.join(info_dir, METADATA_FILENAME) wheel_metadata_name = posixpath.join(info_dir, 'WHEEL') record_name = posixpath.join(info_dir, 'RECORD') wrapper = codecs.getreader('utf-8') with ZipFile(pathname, 'r') as zf: with zf.open(wheel_metadata_name) as bwf: wf = wrapper(bwf) message = message_from_file(wf) wv = message['Wheel-Version'].split('.', 1) file_version = tuple([int(i) for i in wv]) if (file_version != self.wheel_version) and warner: warner(self.wheel_version, file_version) if message['Root-Is-Purelib'] == 'true': libdir = paths['purelib'] else: libdir = paths['platlib'] records = {} with zf.open(record_name) as bf: with CSVReader(stream=bf) as reader: for row in reader: p = row[0] records[p] = row data_pfx = posixpath.join(data_dir, '') info_pfx = posixpath.join(info_dir, '') script_pfx = posixpath.join(data_dir, 'scripts', '') # make a new instance rather than a copy of maker's, # as we mutate it fileop = FileOperator(dry_run=dry_run) fileop.record = True # so we can rollback if needed bc = not sys.dont_write_bytecode # Double negatives. Lovely! outfiles = [] # for RECORD writing # for script copying/shebang processing workdir = tempfile.mkdtemp() # set target dir later # we default add_launchers to False, as the # Python Launcher should be used instead maker.source_dir = workdir maker.target_dir = None try: for zinfo in zf.infolist(): arcname = zinfo.filename if isinstance(arcname, text_type): u_arcname = arcname else: u_arcname = arcname.decode('utf-8') # The signature file won't be in RECORD, # and we don't currently don't do anything with it if u_arcname.endswith('/RECORD.jws'): continue row = records[u_arcname] if row[2] and str(zinfo.file_size) != row[2]: raise DistlibException('size mismatch for ' '%s' % u_arcname) if row[1]: kind, value = row[1].split('=', 1) with zf.open(arcname) as bf: data = bf.read() _, digest = self.get_hash(data, kind) if digest != value: raise DistlibException('digest mismatch for ' '%s' % arcname) if lib_only and u_arcname.startswith((info_pfx, data_pfx)): logger.debug('lib_only: skipping %s', u_arcname) continue is_script = (u_arcname.startswith(script_pfx) and not u_arcname.endswith('.exe')) if u_arcname.startswith(data_pfx): _, where, rp = u_arcname.split('/', 2) outfile = os.path.join(paths[where], convert_path(rp)) else: # meant for site-packages. if u_arcname in (wheel_metadata_name, record_name): continue outfile = os.path.join(libdir, convert_path(u_arcname)) if not is_script: with zf.open(arcname) as bf: fileop.copy_stream(bf, outfile) outfiles.append(outfile) # Double check the digest of the written file if not dry_run and row[1]: with open(outfile, 'rb') as bf: data = bf.read() _, newdigest = self.get_hash(data, kind) if newdigest != digest: raise DistlibException('digest mismatch ' 'on write for ' '%s' % outfile) if bc and outfile.endswith('.py'): try: pyc = fileop.byte_compile(outfile, hashed_invalidation=bc_hashed_invalidation) outfiles.append(pyc) except Exception: # Don't give up if byte-compilation fails, # but log it and perhaps warn the user logger.warning('Byte-compilation failed', exc_info=True) else: fn = os.path.basename(convert_path(arcname)) workname = os.path.join(workdir, fn) with zf.open(arcname) as bf: fileop.copy_stream(bf, workname) dn, fn = os.path.split(outfile) maker.target_dir = dn filenames = maker.make(fn) fileop.set_executable_mode(filenames) outfiles.extend(filenames) if lib_only: logger.debug('lib_only: returning None') dist = None else: # Generate scripts # Try to get pydist.json so we can see if there are # any commands to generate. If this fails (e.g. because # of a legacy wheel), log a warning but don't give up. commands = None file_version = self.info['Wheel-Version'] if file_version == '1.0': # Use legacy info ep = posixpath.join(info_dir, 'entry_points.txt') try: with zf.open(ep) as bwf: epdata = read_exports(bwf) commands = {} for key in ('console', 'gui'): k = '%s_scripts' % key if k in epdata: commands['wrap_%s' % key] = d = {} for v in epdata[k].values(): s = '%s:%s' % (v.prefix, v.suffix) if v.flags: s += ' %s' % v.flags d[v.name] = s except Exception: logger.warning('Unable to read legacy script ' 'metadata, so cannot generate ' 'scripts') else: try: with zf.open(metadata_name) as bwf: wf = wrapper(bwf) commands = json.load(wf).get('extensions') if commands: commands = commands.get('python.commands') except Exception: logger.warning('Unable to read JSON metadata, so ' 'cannot generate scripts') if commands: console_scripts = commands.get('wrap_console', {}) gui_scripts = commands.get('wrap_gui', {}) if console_scripts or gui_scripts: script_dir = paths.get('scripts', '') if not os.path.isdir(script_dir): raise ValueError('Valid script path not ' 'specified') maker.target_dir = script_dir for k, v in console_scripts.items(): script = '%s = %s' % (k, v) filenames = maker.make(script) fileop.set_executable_mode(filenames) if gui_scripts: options = {'gui': True } for k, v in gui_scripts.items(): script = '%s = %s' % (k, v) filenames = maker.make(script, options) fileop.set_executable_mode(filenames) p = os.path.join(libdir, info_dir) dist = InstalledDistribution(p) # Write SHARED paths = dict(paths) # don't change passed in dict del paths['purelib'] del paths['platlib'] paths['lib'] = libdir p = dist.write_shared_locations(paths, dry_run) if p: outfiles.append(p) # Write RECORD dist.write_installed_files(outfiles, paths['prefix'], dry_run) return dist except Exception: # pragma: no cover logger.exception('installation failed.') fileop.rollback() raise finally: shutil.rmtree(workdir)
def install(self, paths, maker, **kwargs): """ Install a wheel to the specified paths. If kwarg ``warner`` is specified, it should be a callable, which will be called with two tuples indicating the wheel version of this software and the wheel version in the file, if there is a discrepancy in the versions. This can be used to issue any warnings to raise any exceptions. If kwarg ``lib_only`` is True, only the purelib/platlib files are installed, and the headers, scripts, data and dist-info metadata are not written. If kwarg ``bytecode_hashed_invalidation`` is True, written bytecode will try to use file-hash based invalidation (PEP-552) on supported interpreter versions (CPython 2.7+). The return value is a :class:`InstalledDistribution` instance unless ``options.lib_only`` is True, in which case the return value is ``None``. """ dry_run = maker.dry_run warner = kwargs.get('warner') lib_only = kwargs.get('lib_only', False) bc_hashed_invalidation = kwargs.get('bytecode_hashed_invalidation', False) pathname = os.path.join(self.dirname, self.filename) name_ver = '%s-%s' % (self.name, self.version) data_dir = '%s.data' % name_ver info_dir = '%s.dist-info' % name_ver metadata_name = posixpath.join(info_dir, METADATA_FILENAME) wheel_metadata_name = posixpath.join(info_dir, 'WHEEL') record_name = posixpath.join(info_dir, 'RECORD') wrapper = codecs.getreader('utf-8') with ZipFile(pathname, 'r') as zf: with zf.open(wheel_metadata_name) as bwf: wf = wrapper(bwf) message = message_from_file(wf) wv = message['Wheel-Version'].split('.', 1) file_version = tuple([int(i) for i in wv]) if (file_version != self.wheel_version) and warner: warner(self.wheel_version, file_version) if message['Root-Is-Purelib'] == 'true': libdir = paths['purelib'] else: libdir = paths['platlib'] records = {} with zf.open(record_name) as bf: with CSVReader(stream=bf) as reader: for row in reader: p = row[0] records[p] = row data_pfx = posixpath.join(data_dir, '') info_pfx = posixpath.join(info_dir, '') script_pfx = posixpath.join(data_dir, 'scripts', '') # make a new instance rather than a copy of maker's, # as we mutate it fileop = FileOperator(dry_run=dry_run) fileop.record = True # so we can rollback if needed bc = not sys.dont_write_bytecode # Double negatives. Lovely! outfiles = [] # for RECORD writing # for script copying/shebang processing workdir = tempfile.mkdtemp() # set target dir later # we default add_launchers to False, as the # Python Launcher should be used instead maker.source_dir = workdir maker.target_dir = None try: for zinfo in zf.infolist(): arcname = zinfo.filename if isinstance(arcname, text_type): u_arcname = arcname else: u_arcname = arcname.decode('utf-8') # The signature file won't be in RECORD, # and we don't currently don't do anything with it if u_arcname.endswith('/RECORD.jws'): continue row = records[u_arcname] if row[2] and str(zinfo.file_size) != row[2]: raise DistlibException('size mismatch for ' '%s' % u_arcname) if row[1]: kind, value = row[1].split('=', 1) with zf.open(arcname) as bf: data = bf.read() _, digest = self.get_hash(data, kind) if digest != value: raise DistlibException('digest mismatch for ' '%s' % arcname) if lib_only and u_arcname.startswith((info_pfx, data_pfx)): logger.debug('lib_only: skipping %s', u_arcname) continue is_script = (u_arcname.startswith(script_pfx) and not u_arcname.endswith('.exe')) if u_arcname.startswith(data_pfx): _, where, rp = u_arcname.split('/', 2) outfile = os.path.join(paths[where], convert_path(rp)) else: # meant for site-packages. if u_arcname in (wheel_metadata_name, record_name): continue outfile = os.path.join(libdir, convert_path(u_arcname)) if not is_script: with zf.open(arcname) as bf: fileop.copy_stream(bf, outfile) outfiles.append(outfile) # Double check the digest of the written file if not dry_run and row[1]: with open(outfile, 'rb') as bf: data = bf.read() _, newdigest = self.get_hash(data, kind) if newdigest != digest: raise DistlibException('digest mismatch ' 'on write for ' '%s' % outfile) if bc and outfile.endswith('.py'): try: pyc = fileop.byte_compile(outfile, hashed_invalidation=bc_hashed_invalidation) outfiles.append(pyc) except Exception: # Don't give up if byte-compilation fails, # but log it and perhaps warn the user logger.warning('Byte-compilation failed', exc_info=True) else: fn = os.path.basename(convert_path(arcname)) workname = os.path.join(workdir, fn) with zf.open(arcname) as bf: fileop.copy_stream(bf, workname) dn, fn = os.path.split(outfile) maker.target_dir = dn filenames = maker.make(fn) fileop.set_executable_mode(filenames) outfiles.extend(filenames) if lib_only: logger.debug('lib_only: returning None') dist = None else: # Generate scripts # Try to get pydist.json so we can see if there are # any commands to generate. If this fails (e.g. because # of a legacy wheel), log a warning but don't give up. commands = None file_version = self.info['Wheel-Version'] if file_version == '1.0': # Use legacy info ep = posixpath.join(info_dir, 'entry_points.txt') try: with zf.open(ep) as bwf: epdata = read_exports(bwf) commands = {} for key in ('console', 'gui'): k = '%s_scripts' % key if k in epdata: commands['wrap_%s' % key] = d = {} for v in epdata[k].values(): s = '%s:%s' % (v.prefix, v.suffix) if v.flags: s += ' %s' % v.flags d[v.name] = s except Exception: logger.warning('Unable to read legacy script ' 'metadata, so cannot generate ' 'scripts') else: try: with zf.open(metadata_name) as bwf: wf = wrapper(bwf) commands = json.load(wf).get('extensions') if commands: commands = commands.get('python.commands') except Exception: logger.warning('Unable to read JSON metadata, so ' 'cannot generate scripts') if commands: console_scripts = commands.get('wrap_console', {}) gui_scripts = commands.get('wrap_gui', {}) if console_scripts or gui_scripts: script_dir = paths.get('scripts', '') if not os.path.isdir(script_dir): raise ValueError('Valid script path not ' 'specified') maker.target_dir = script_dir for k, v in console_scripts.items(): script = '%s = %s' % (k, v) filenames = maker.make(script) fileop.set_executable_mode(filenames) if gui_scripts: options = {'gui': True } for k, v in gui_scripts.items(): script = '%s = %s' % (k, v) filenames = maker.make(script, options) fileop.set_executable_mode(filenames) p = os.path.join(libdir, info_dir) dist = InstalledDistribution(p) # Write SHARED paths = dict(paths) # don't change passed in dict del paths['purelib'] del paths['platlib'] paths['lib'] = libdir p = dist.write_shared_locations(paths, dry_run) if p: outfiles.append(p) # Write RECORD dist.write_installed_files(outfiles, paths['prefix'], dry_run) return dist except Exception: # pragma: no cover logger.exception('installation failed.') fileop.rollback() raise finally: shutil.rmtree(workdir)
[ "Install", "a", "wheel", "to", "the", "specified", "paths", ".", "If", "kwarg", "warner", "is", "specified", "it", "should", "be", "a", "callable", "which", "will", "be", "called", "with", "two", "tuples", "indicating", "the", "wheel", "version", "of", "th...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/wheel.py#L436-L666
[ "def", "install", "(", "self", ",", "paths", ",", "maker", ",", "*", "*", "kwargs", ")", ":", "dry_run", "=", "maker", ".", "dry_run", "warner", "=", "kwargs", ".", "get", "(", "'warner'", ")", "lib_only", "=", "kwargs", ".", "get", "(", "'lib_only'"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Wheel.update
Update the contents of a wheel in a generic way. The modifier should be a callable which expects a dictionary argument: its keys are archive-entry paths, and its values are absolute filesystem paths where the contents the corresponding archive entries can be found. The modifier is free to change the contents of the files pointed to, add new entries and remove entries, before returning. This method will extract the entire contents of the wheel to a temporary location, call the modifier, and then use the passed (and possibly updated) dictionary to write a new wheel. If ``dest_dir`` is specified, the new wheel is written there -- otherwise, the original wheel is overwritten. The modifier should return True if it updated the wheel, else False. This method returns the same value the modifier returns.
pipenv/vendor/distlib/wheel.py
def update(self, modifier, dest_dir=None, **kwargs): """ Update the contents of a wheel in a generic way. The modifier should be a callable which expects a dictionary argument: its keys are archive-entry paths, and its values are absolute filesystem paths where the contents the corresponding archive entries can be found. The modifier is free to change the contents of the files pointed to, add new entries and remove entries, before returning. This method will extract the entire contents of the wheel to a temporary location, call the modifier, and then use the passed (and possibly updated) dictionary to write a new wheel. If ``dest_dir`` is specified, the new wheel is written there -- otherwise, the original wheel is overwritten. The modifier should return True if it updated the wheel, else False. This method returns the same value the modifier returns. """ def get_version(path_map, info_dir): version = path = None key = '%s/%s' % (info_dir, METADATA_FILENAME) if key not in path_map: key = '%s/PKG-INFO' % info_dir if key in path_map: path = path_map[key] version = Metadata(path=path).version return version, path def update_version(version, path): updated = None try: v = NormalizedVersion(version) i = version.find('-') if i < 0: updated = '%s+1' % version else: parts = [int(s) for s in version[i + 1:].split('.')] parts[-1] += 1 updated = '%s+%s' % (version[:i], '.'.join(str(i) for i in parts)) except UnsupportedVersionError: logger.debug('Cannot update non-compliant (PEP-440) ' 'version %r', version) if updated: md = Metadata(path=path) md.version = updated legacy = not path.endswith(METADATA_FILENAME) md.write(path=path, legacy=legacy) logger.debug('Version updated from %r to %r', version, updated) pathname = os.path.join(self.dirname, self.filename) name_ver = '%s-%s' % (self.name, self.version) info_dir = '%s.dist-info' % name_ver record_name = posixpath.join(info_dir, 'RECORD') with tempdir() as workdir: with ZipFile(pathname, 'r') as zf: path_map = {} for zinfo in zf.infolist(): arcname = zinfo.filename if isinstance(arcname, text_type): u_arcname = arcname else: u_arcname = arcname.decode('utf-8') if u_arcname == record_name: continue if '..' in u_arcname: raise DistlibException('invalid entry in ' 'wheel: %r' % u_arcname) zf.extract(zinfo, workdir) path = os.path.join(workdir, convert_path(u_arcname)) path_map[u_arcname] = path # Remember the version. original_version, _ = get_version(path_map, info_dir) # Files extracted. Call the modifier. modified = modifier(path_map, **kwargs) if modified: # Something changed - need to build a new wheel. current_version, path = get_version(path_map, info_dir) if current_version and (current_version == original_version): # Add or update local version to signify changes. update_version(current_version, path) # Decide where the new wheel goes. if dest_dir is None: fd, newpath = tempfile.mkstemp(suffix='.whl', prefix='wheel-update-', dir=workdir) os.close(fd) else: if not os.path.isdir(dest_dir): raise DistlibException('Not a directory: %r' % dest_dir) newpath = os.path.join(dest_dir, self.filename) archive_paths = list(path_map.items()) distinfo = os.path.join(workdir, info_dir) info = distinfo, info_dir self.write_records(info, workdir, archive_paths) self.build_zip(newpath, archive_paths) if dest_dir is None: shutil.copyfile(newpath, pathname) return modified
def update(self, modifier, dest_dir=None, **kwargs): """ Update the contents of a wheel in a generic way. The modifier should be a callable which expects a dictionary argument: its keys are archive-entry paths, and its values are absolute filesystem paths where the contents the corresponding archive entries can be found. The modifier is free to change the contents of the files pointed to, add new entries and remove entries, before returning. This method will extract the entire contents of the wheel to a temporary location, call the modifier, and then use the passed (and possibly updated) dictionary to write a new wheel. If ``dest_dir`` is specified, the new wheel is written there -- otherwise, the original wheel is overwritten. The modifier should return True if it updated the wheel, else False. This method returns the same value the modifier returns. """ def get_version(path_map, info_dir): version = path = None key = '%s/%s' % (info_dir, METADATA_FILENAME) if key not in path_map: key = '%s/PKG-INFO' % info_dir if key in path_map: path = path_map[key] version = Metadata(path=path).version return version, path def update_version(version, path): updated = None try: v = NormalizedVersion(version) i = version.find('-') if i < 0: updated = '%s+1' % version else: parts = [int(s) for s in version[i + 1:].split('.')] parts[-1] += 1 updated = '%s+%s' % (version[:i], '.'.join(str(i) for i in parts)) except UnsupportedVersionError: logger.debug('Cannot update non-compliant (PEP-440) ' 'version %r', version) if updated: md = Metadata(path=path) md.version = updated legacy = not path.endswith(METADATA_FILENAME) md.write(path=path, legacy=legacy) logger.debug('Version updated from %r to %r', version, updated) pathname = os.path.join(self.dirname, self.filename) name_ver = '%s-%s' % (self.name, self.version) info_dir = '%s.dist-info' % name_ver record_name = posixpath.join(info_dir, 'RECORD') with tempdir() as workdir: with ZipFile(pathname, 'r') as zf: path_map = {} for zinfo in zf.infolist(): arcname = zinfo.filename if isinstance(arcname, text_type): u_arcname = arcname else: u_arcname = arcname.decode('utf-8') if u_arcname == record_name: continue if '..' in u_arcname: raise DistlibException('invalid entry in ' 'wheel: %r' % u_arcname) zf.extract(zinfo, workdir) path = os.path.join(workdir, convert_path(u_arcname)) path_map[u_arcname] = path # Remember the version. original_version, _ = get_version(path_map, info_dir) # Files extracted. Call the modifier. modified = modifier(path_map, **kwargs) if modified: # Something changed - need to build a new wheel. current_version, path = get_version(path_map, info_dir) if current_version and (current_version == original_version): # Add or update local version to signify changes. update_version(current_version, path) # Decide where the new wheel goes. if dest_dir is None: fd, newpath = tempfile.mkstemp(suffix='.whl', prefix='wheel-update-', dir=workdir) os.close(fd) else: if not os.path.isdir(dest_dir): raise DistlibException('Not a directory: %r' % dest_dir) newpath = os.path.join(dest_dir, self.filename) archive_paths = list(path_map.items()) distinfo = os.path.join(workdir, info_dir) info = distinfo, info_dir self.write_records(info, workdir, archive_paths) self.build_zip(newpath, archive_paths) if dest_dir is None: shutil.copyfile(newpath, pathname) return modified
[ "Update", "the", "contents", "of", "a", "wheel", "in", "a", "generic", "way", ".", "The", "modifier", "should", "be", "a", "callable", "which", "expects", "a", "dictionary", "argument", ":", "its", "keys", "are", "archive", "-", "entry", "paths", "and", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/wheel.py#L810-L909
[ "def", "update", "(", "self", ",", "modifier", ",", "dest_dir", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "get_version", "(", "path_map", ",", "info_dir", ")", ":", "version", "=", "path", "=", "None", "key", "=", "'%s/%s'", "%", "(", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
load_dot_env
Loads .env file into sys.environ.
pipenv/core.py
def load_dot_env(): """Loads .env file into sys.environ.""" if not environments.PIPENV_DONT_LOAD_ENV: # If the project doesn't exist yet, check current directory for a .env file project_directory = project.project_directory or "." dotenv_file = environments.PIPENV_DOTENV_LOCATION or os.sep.join( [project_directory, ".env"] ) if os.path.isfile(dotenv_file): click.echo( crayons.normal(fix_utf8("Loading .env environment variables…"), bold=True), err=True, ) else: if environments.PIPENV_DOTENV_LOCATION: click.echo( "{0}: file {1}={2} does not exist!!\n{3}".format( crayons.red("Warning", bold=True), crayons.normal("PIPENV_DOTENV_LOCATION", bold=True), crayons.normal(environments.PIPENV_DOTENV_LOCATION, bold=True), crayons.red("Not loading environment variables.", bold=True), ), err=True, ) dotenv.load_dotenv(dotenv_file, override=True)
def load_dot_env(): """Loads .env file into sys.environ.""" if not environments.PIPENV_DONT_LOAD_ENV: # If the project doesn't exist yet, check current directory for a .env file project_directory = project.project_directory or "." dotenv_file = environments.PIPENV_DOTENV_LOCATION or os.sep.join( [project_directory, ".env"] ) if os.path.isfile(dotenv_file): click.echo( crayons.normal(fix_utf8("Loading .env environment variables…"), bold=True), err=True, ) else: if environments.PIPENV_DOTENV_LOCATION: click.echo( "{0}: file {1}={2} does not exist!!\n{3}".format( crayons.red("Warning", bold=True), crayons.normal("PIPENV_DOTENV_LOCATION", bold=True), crayons.normal(environments.PIPENV_DOTENV_LOCATION, bold=True), crayons.red("Not loading environment variables.", bold=True), ), err=True, ) dotenv.load_dotenv(dotenv_file, override=True)
[ "Loads", ".", "env", "file", "into", "sys", ".", "environ", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L131-L156
[ "def", "load_dot_env", "(", ")", ":", "if", "not", "environments", ".", "PIPENV_DONT_LOAD_ENV", ":", "# If the project doesn't exist yet, check current directory for a .env file", "project_directory", "=", "project", ".", "project_directory", "or", "\".\"", "dotenv_file", "="...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
add_to_path
Adds a given path to the PATH.
pipenv/core.py
def add_to_path(p): """Adds a given path to the PATH.""" if p not in os.environ["PATH"]: os.environ["PATH"] = "{0}{1}{2}".format(p, os.pathsep, os.environ["PATH"])
def add_to_path(p): """Adds a given path to the PATH.""" if p not in os.environ["PATH"]: os.environ["PATH"] = "{0}{1}{2}".format(p, os.pathsep, os.environ["PATH"])
[ "Adds", "a", "given", "path", "to", "the", "PATH", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L159-L162
[ "def", "add_to_path", "(", "p", ")", ":", "if", "p", "not", "in", "os", ".", "environ", "[", "\"PATH\"", "]", ":", "os", ".", "environ", "[", "\"PATH\"", "]", "=", "\"{0}{1}{2}\"", ".", "format", "(", "p", ",", "os", ".", "pathsep", ",", "os", "....
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
cleanup_virtualenv
Removes the virtualenv directory from the system.
pipenv/core.py
def cleanup_virtualenv(bare=True): """Removes the virtualenv directory from the system.""" if not bare: click.echo(crayons.red("Environment creation aborted.")) try: # Delete the virtualenv. vistir.path.rmtree(project.virtualenv_location) except OSError as e: click.echo( "{0} An error occurred while removing {1}!".format( crayons.red("Error: ", bold=True), crayons.green(project.virtualenv_location), ), err=True, ) click.echo(crayons.blue(e), err=True)
def cleanup_virtualenv(bare=True): """Removes the virtualenv directory from the system.""" if not bare: click.echo(crayons.red("Environment creation aborted.")) try: # Delete the virtualenv. vistir.path.rmtree(project.virtualenv_location) except OSError as e: click.echo( "{0} An error occurred while removing {1}!".format( crayons.red("Error: ", bold=True), crayons.green(project.virtualenv_location), ), err=True, ) click.echo(crayons.blue(e), err=True)
[ "Removes", "the", "virtualenv", "directory", "from", "the", "system", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L165-L180
[ "def", "cleanup_virtualenv", "(", "bare", "=", "True", ")", ":", "if", "not", "bare", ":", "click", ".", "echo", "(", "crayons", ".", "red", "(", "\"Environment creation aborted.\"", ")", ")", "try", ":", "# Delete the virtualenv.", "vistir", ".", "path", "....
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ensure_pipfile
Creates a Pipfile for the project, if it doesn't exist.
pipenv/core.py
def ensure_pipfile(validate=True, skip_requirements=False, system=False): """Creates a Pipfile for the project, if it doesn't exist.""" from .environments import PIPENV_VIRTUALENV # Assert Pipfile exists. python = which("python") if not (USING_DEFAULT_PYTHON or system) else None if project.pipfile_is_empty: # Show an error message and exit if system is passed and no pipfile exists if system and not PIPENV_VIRTUALENV: raise exceptions.PipenvOptionsError( "--system", "--system is intended to be used for pre-existing Pipfile " "installation, not installation of specific packages. Aborting." ) # If there's a requirements file, but no Pipfile… if project.requirements_exists and not skip_requirements: click.echo( crayons.normal( fix_utf8("requirements.txt found, instead of Pipfile! Converting…"), bold=True, ) ) # Create a Pipfile… project.create_pipfile(python=python) with create_spinner("Importing requirements...") as sp: # Import requirements.txt. try: import_requirements() except Exception: sp.fail(environments.PIPENV_SPINNER_FAIL_TEXT.format("Failed...")) else: sp.ok(environments.PIPENV_SPINNER_OK_TEXT.format("Success!")) # Warn the user of side-effects. click.echo( u"{0}: Your {1} now contains pinned versions, if your {2} did. \n" "We recommend updating your {1} to specify the {3} version, instead." "".format( crayons.red("Warning", bold=True), crayons.normal("Pipfile", bold=True), crayons.normal("requirements.txt", bold=True), crayons.normal('"*"', bold=True), ) ) else: click.echo( crayons.normal(fix_utf8("Creating a Pipfile for this project…"), bold=True), err=True, ) # Create the pipfile if it doesn't exist. project.create_pipfile(python=python) # Validate the Pipfile's contents. if validate and project.virtualenv_exists and not PIPENV_SKIP_VALIDATION: # Ensure that Pipfile is using proper casing. p = project.parsed_pipfile changed = project.ensure_proper_casing() # Write changes out to disk. if changed: click.echo( crayons.normal(u"Fixing package names in Pipfile…", bold=True), err=True ) project.write_toml(p)
def ensure_pipfile(validate=True, skip_requirements=False, system=False): """Creates a Pipfile for the project, if it doesn't exist.""" from .environments import PIPENV_VIRTUALENV # Assert Pipfile exists. python = which("python") if not (USING_DEFAULT_PYTHON or system) else None if project.pipfile_is_empty: # Show an error message and exit if system is passed and no pipfile exists if system and not PIPENV_VIRTUALENV: raise exceptions.PipenvOptionsError( "--system", "--system is intended to be used for pre-existing Pipfile " "installation, not installation of specific packages. Aborting." ) # If there's a requirements file, but no Pipfile… if project.requirements_exists and not skip_requirements: click.echo( crayons.normal( fix_utf8("requirements.txt found, instead of Pipfile! Converting…"), bold=True, ) ) # Create a Pipfile… project.create_pipfile(python=python) with create_spinner("Importing requirements...") as sp: # Import requirements.txt. try: import_requirements() except Exception: sp.fail(environments.PIPENV_SPINNER_FAIL_TEXT.format("Failed...")) else: sp.ok(environments.PIPENV_SPINNER_OK_TEXT.format("Success!")) # Warn the user of side-effects. click.echo( u"{0}: Your {1} now contains pinned versions, if your {2} did. \n" "We recommend updating your {1} to specify the {3} version, instead." "".format( crayons.red("Warning", bold=True), crayons.normal("Pipfile", bold=True), crayons.normal("requirements.txt", bold=True), crayons.normal('"*"', bold=True), ) ) else: click.echo( crayons.normal(fix_utf8("Creating a Pipfile for this project…"), bold=True), err=True, ) # Create the pipfile if it doesn't exist. project.create_pipfile(python=python) # Validate the Pipfile's contents. if validate and project.virtualenv_exists and not PIPENV_SKIP_VALIDATION: # Ensure that Pipfile is using proper casing. p = project.parsed_pipfile changed = project.ensure_proper_casing() # Write changes out to disk. if changed: click.echo( crayons.normal(u"Fixing package names in Pipfile…", bold=True), err=True ) project.write_toml(p)
[ "Creates", "a", "Pipfile", "for", "the", "project", "if", "it", "doesn", "t", "exist", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L255-L315
[ "def", "ensure_pipfile", "(", "validate", "=", "True", ",", "skip_requirements", "=", "False", ",", "system", "=", "False", ")", ":", "from", ".", "environments", "import", "PIPENV_VIRTUALENV", "# Assert Pipfile exists.", "python", "=", "which", "(", "\"python\"",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
find_a_system_python
Find a Python installation from a given line. This tries to parse the line in various of ways: * Looks like an absolute path? Use it directly. * Looks like a py.exe call? Use py.exe to get the executable. * Starts with "py" something? Looks like a python command. Try to find it in PATH, and use it directly. * Search for "python" and "pythonX.Y" executables in PATH to find a match. * Nothing fits, return None.
pipenv/core.py
def find_a_system_python(line): """Find a Python installation from a given line. This tries to parse the line in various of ways: * Looks like an absolute path? Use it directly. * Looks like a py.exe call? Use py.exe to get the executable. * Starts with "py" something? Looks like a python command. Try to find it in PATH, and use it directly. * Search for "python" and "pythonX.Y" executables in PATH to find a match. * Nothing fits, return None. """ from .vendor.pythonfinder import Finder finder = Finder(system=False, global_search=True) if not line: return next(iter(finder.find_all_python_versions()), None) # Use the windows finder executable if (line.startswith("py ") or line.startswith("py.exe ")) and os.name == "nt": line = line.split(" ", 1)[1].lstrip("-") python_entry = find_python(finder, line) return python_entry
def find_a_system_python(line): """Find a Python installation from a given line. This tries to parse the line in various of ways: * Looks like an absolute path? Use it directly. * Looks like a py.exe call? Use py.exe to get the executable. * Starts with "py" something? Looks like a python command. Try to find it in PATH, and use it directly. * Search for "python" and "pythonX.Y" executables in PATH to find a match. * Nothing fits, return None. """ from .vendor.pythonfinder import Finder finder = Finder(system=False, global_search=True) if not line: return next(iter(finder.find_all_python_versions()), None) # Use the windows finder executable if (line.startswith("py ") or line.startswith("py.exe ")) and os.name == "nt": line = line.split(" ", 1)[1].lstrip("-") python_entry = find_python(finder, line) return python_entry
[ "Find", "a", "Python", "installation", "from", "a", "given", "line", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L318-L339
[ "def", "find_a_system_python", "(", "line", ")", ":", "from", ".", "vendor", ".", "pythonfinder", "import", "Finder", "finder", "=", "Finder", "(", "system", "=", "False", ",", "global_search", "=", "True", ")", "if", "not", "line", ":", "return", "next", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ensure_virtualenv
Creates a virtualenv, if one doesn't exist.
pipenv/core.py
def ensure_virtualenv(three=None, python=None, site_packages=False, pypi_mirror=None): """Creates a virtualenv, if one doesn't exist.""" from .environments import PIPENV_USE_SYSTEM def abort(): sys.exit(1) global USING_DEFAULT_PYTHON if not project.virtualenv_exists: try: # Ensure environment variables are set properly. ensure_environment() # Ensure Python is available. python = ensure_python(three=three, python=python) if python is not None and not isinstance(python, six.string_types): python = python.path.as_posix() # Create the virtualenv. # Abort if --system (or running in a virtualenv). if PIPENV_USE_SYSTEM: click.echo( crayons.red( "You are attempting to re–create a virtualenv that " "Pipenv did not create. Aborting." ) ) sys.exit(1) do_create_virtualenv( python=python, site_packages=site_packages, pypi_mirror=pypi_mirror ) except KeyboardInterrupt: # If interrupted, cleanup the virtualenv. cleanup_virtualenv(bare=False) sys.exit(1) # If --three, --two, or --python were passed… elif (python) or (three is not None) or (site_packages is not False): USING_DEFAULT_PYTHON = False # Ensure python is installed before deleting existing virtual env python = ensure_python(three=three, python=python) if python is not None and not isinstance(python, six.string_types): python = python.path.as_posix() click.echo(crayons.red("Virtualenv already exists!"), err=True) # If VIRTUAL_ENV is set, there is a possibility that we are # going to remove the active virtualenv that the user cares # about, so confirm first. if "VIRTUAL_ENV" in os.environ: if not ( PIPENV_YES or click.confirm("Remove existing virtualenv?", default=True) ): abort() click.echo( crayons.normal(fix_utf8("Removing existing virtualenv…"), bold=True), err=True ) # Remove the virtualenv. cleanup_virtualenv(bare=True) # Call this function again. ensure_virtualenv( three=three, python=python, site_packages=site_packages, pypi_mirror=pypi_mirror, )
def ensure_virtualenv(three=None, python=None, site_packages=False, pypi_mirror=None): """Creates a virtualenv, if one doesn't exist.""" from .environments import PIPENV_USE_SYSTEM def abort(): sys.exit(1) global USING_DEFAULT_PYTHON if not project.virtualenv_exists: try: # Ensure environment variables are set properly. ensure_environment() # Ensure Python is available. python = ensure_python(three=three, python=python) if python is not None and not isinstance(python, six.string_types): python = python.path.as_posix() # Create the virtualenv. # Abort if --system (or running in a virtualenv). if PIPENV_USE_SYSTEM: click.echo( crayons.red( "You are attempting to re–create a virtualenv that " "Pipenv did not create. Aborting." ) ) sys.exit(1) do_create_virtualenv( python=python, site_packages=site_packages, pypi_mirror=pypi_mirror ) except KeyboardInterrupt: # If interrupted, cleanup the virtualenv. cleanup_virtualenv(bare=False) sys.exit(1) # If --three, --two, or --python were passed… elif (python) or (three is not None) or (site_packages is not False): USING_DEFAULT_PYTHON = False # Ensure python is installed before deleting existing virtual env python = ensure_python(three=three, python=python) if python is not None and not isinstance(python, six.string_types): python = python.path.as_posix() click.echo(crayons.red("Virtualenv already exists!"), err=True) # If VIRTUAL_ENV is set, there is a possibility that we are # going to remove the active virtualenv that the user cares # about, so confirm first. if "VIRTUAL_ENV" in os.environ: if not ( PIPENV_YES or click.confirm("Remove existing virtualenv?", default=True) ): abort() click.echo( crayons.normal(fix_utf8("Removing existing virtualenv…"), bold=True), err=True ) # Remove the virtualenv. cleanup_virtualenv(bare=True) # Call this function again. ensure_virtualenv( three=three, python=python, site_packages=site_packages, pypi_mirror=pypi_mirror, )
[ "Creates", "a", "virtualenv", "if", "one", "doesn", "t", "exist", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L455-L516
[ "def", "ensure_virtualenv", "(", "three", "=", "None", ",", "python", "=", "None", ",", "site_packages", "=", "False", ",", "pypi_mirror", "=", "None", ")", ":", "from", ".", "environments", "import", "PIPENV_USE_SYSTEM", "def", "abort", "(", ")", ":", "sy...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ensure_project
Ensures both Pipfile and virtualenv exist for the project.
pipenv/core.py
def ensure_project( three=None, python=None, validate=True, system=False, warn=True, site_packages=False, deploy=False, skip_requirements=False, pypi_mirror=None, clear=False, ): """Ensures both Pipfile and virtualenv exist for the project.""" from .environments import PIPENV_USE_SYSTEM # Clear the caches, if appropriate. if clear: print("clearing") sys.exit(1) # Automatically use an activated virtualenv. if PIPENV_USE_SYSTEM: system = True if not project.pipfile_exists and deploy: raise exceptions.PipfileNotFound # Fail if working under / if not project.name: click.echo( "{0}: Pipenv is not intended to work under the root directory, " "please choose another path.".format(crayons.red("ERROR")), err=True ) sys.exit(1) # Skip virtualenv creation when --system was used. if not system: ensure_virtualenv( three=three, python=python, site_packages=site_packages, pypi_mirror=pypi_mirror, ) if warn: # Warn users if they are using the wrong version of Python. if project.required_python_version: path_to_python = which("python") or which("py") if path_to_python and project.required_python_version not in ( python_version(path_to_python) or "" ): click.echo( "{0}: Your Pipfile requires {1} {2}, " "but you are using {3} ({4}).".format( crayons.red("Warning", bold=True), crayons.normal("python_version", bold=True), crayons.blue(project.required_python_version), crayons.blue(python_version(path_to_python)), crayons.green(shorten_path(path_to_python)), ), err=True, ) click.echo( " {0} and rebuilding the virtual environment " "may resolve the issue.".format(crayons.green("$ pipenv --rm")), err=True, ) if not deploy: click.echo( " {0} will surely fail." "".format(crayons.red("$ pipenv check")), err=True, ) else: raise exceptions.DeployException # Ensure the Pipfile exists. ensure_pipfile( validate=validate, skip_requirements=skip_requirements, system=system )
def ensure_project( three=None, python=None, validate=True, system=False, warn=True, site_packages=False, deploy=False, skip_requirements=False, pypi_mirror=None, clear=False, ): """Ensures both Pipfile and virtualenv exist for the project.""" from .environments import PIPENV_USE_SYSTEM # Clear the caches, if appropriate. if clear: print("clearing") sys.exit(1) # Automatically use an activated virtualenv. if PIPENV_USE_SYSTEM: system = True if not project.pipfile_exists and deploy: raise exceptions.PipfileNotFound # Fail if working under / if not project.name: click.echo( "{0}: Pipenv is not intended to work under the root directory, " "please choose another path.".format(crayons.red("ERROR")), err=True ) sys.exit(1) # Skip virtualenv creation when --system was used. if not system: ensure_virtualenv( three=three, python=python, site_packages=site_packages, pypi_mirror=pypi_mirror, ) if warn: # Warn users if they are using the wrong version of Python. if project.required_python_version: path_to_python = which("python") or which("py") if path_to_python and project.required_python_version not in ( python_version(path_to_python) or "" ): click.echo( "{0}: Your Pipfile requires {1} {2}, " "but you are using {3} ({4}).".format( crayons.red("Warning", bold=True), crayons.normal("python_version", bold=True), crayons.blue(project.required_python_version), crayons.blue(python_version(path_to_python)), crayons.green(shorten_path(path_to_python)), ), err=True, ) click.echo( " {0} and rebuilding the virtual environment " "may resolve the issue.".format(crayons.green("$ pipenv --rm")), err=True, ) if not deploy: click.echo( " {0} will surely fail." "".format(crayons.red("$ pipenv check")), err=True, ) else: raise exceptions.DeployException # Ensure the Pipfile exists. ensure_pipfile( validate=validate, skip_requirements=skip_requirements, system=system )
[ "Ensures", "both", "Pipfile", "and", "virtualenv", "exist", "for", "the", "project", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L519-L594
[ "def", "ensure_project", "(", "three", "=", "None", ",", "python", "=", "None", ",", "validate", "=", "True", ",", "system", "=", "False", ",", "warn", "=", "True", ",", "site_packages", "=", "False", ",", "deploy", "=", "False", ",", "skip_requirements"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
shorten_path
Returns a visually shorter representation of a given system path.
pipenv/core.py
def shorten_path(location, bold=False): """Returns a visually shorter representation of a given system path.""" original = location short = os.sep.join( [s[0] if len(s) > (len("2long4")) else s for s in location.split(os.sep)] ) short = short.split(os.sep) short[-1] = original.split(os.sep)[-1] if bold: short[-1] = str(crayons.normal(short[-1], bold=True)) return os.sep.join(short)
def shorten_path(location, bold=False): """Returns a visually shorter representation of a given system path.""" original = location short = os.sep.join( [s[0] if len(s) > (len("2long4")) else s for s in location.split(os.sep)] ) short = short.split(os.sep) short[-1] = original.split(os.sep)[-1] if bold: short[-1] = str(crayons.normal(short[-1], bold=True)) return os.sep.join(short)
[ "Returns", "a", "visually", "shorter", "representation", "of", "a", "given", "system", "path", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L597-L607
[ "def", "shorten_path", "(", "location", ",", "bold", "=", "False", ")", ":", "original", "=", "location", "short", "=", "os", ".", "sep", ".", "join", "(", "[", "s", "[", "0", "]", "if", "len", "(", "s", ")", ">", "(", "len", "(", "\"2long4\"", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_where
Executes the where functionality.
pipenv/core.py
def do_where(virtualenv=False, bare=True): """Executes the where functionality.""" if not virtualenv: if not project.pipfile_exists: click.echo( "No Pipfile present at project home. Consider running " "{0} first to automatically generate a Pipfile for you." "".format(crayons.green("`pipenv install`")), err=True, ) return location = project.pipfile_location # Shorten the virtual display of the path to the virtualenv. if not bare: location = shorten_path(location) click.echo( "Pipfile found at {0}.\n Considering this to be the project home." "".format(crayons.green(location)), err=True, ) else: click.echo(project.project_directory) else: location = project.virtualenv_location if not bare: click.echo( "Virtualenv location: {0}".format(crayons.green(location)), err=True ) else: click.echo(location)
def do_where(virtualenv=False, bare=True): """Executes the where functionality.""" if not virtualenv: if not project.pipfile_exists: click.echo( "No Pipfile present at project home. Consider running " "{0} first to automatically generate a Pipfile for you." "".format(crayons.green("`pipenv install`")), err=True, ) return location = project.pipfile_location # Shorten the virtual display of the path to the virtualenv. if not bare: location = shorten_path(location) click.echo( "Pipfile found at {0}.\n Considering this to be the project home." "".format(crayons.green(location)), err=True, ) else: click.echo(project.project_directory) else: location = project.virtualenv_location if not bare: click.echo( "Virtualenv location: {0}".format(crayons.green(location)), err=True ) else: click.echo(location)
[ "Executes", "the", "where", "functionality", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L611-L640
[ "def", "do_where", "(", "virtualenv", "=", "False", ",", "bare", "=", "True", ")", ":", "if", "not", "virtualenv", ":", "if", "not", "project", ".", "pipfile_exists", ":", "click", ".", "echo", "(", "\"No Pipfile present at project home. Consider running \"", "\...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_install_dependencies
Executes the install functionality. If requirements is True, simply spits out a requirements format to stdout.
pipenv/core.py
def do_install_dependencies( dev=False, only=False, bare=False, requirements=False, allow_global=False, ignore_hashes=False, skip_lock=False, concurrent=True, requirements_dir=None, pypi_mirror=False, ): """" Executes the install functionality. If requirements is True, simply spits out a requirements format to stdout. """ from six.moves import queue if requirements: bare = True blocking = not concurrent # Load the lockfile if it exists, or if only is being used (e.g. lock is being used). if skip_lock or only or not project.lockfile_exists: if not bare: click.echo( crayons.normal(fix_utf8("Installing dependencies from Pipfile…"), bold=True) ) # skip_lock should completely bypass the lockfile (broken in 4dac1676) lockfile = project.get_or_create_lockfile(from_pipfile=True) else: lockfile = project.get_or_create_lockfile() if not bare: click.echo( crayons.normal( fix_utf8("Installing dependencies from Pipfile.lock ({0})…".format( lockfile["_meta"].get("hash", {}).get("sha256")[-6:] )), bold=True, ) ) # Allow pip to resolve dependencies when in skip-lock mode. no_deps = not skip_lock deps_list = list(lockfile.get_requirements(dev=dev, only=requirements)) if requirements: index_args = prepare_pip_source_args(project.sources) index_args = " ".join(index_args).replace(" -", "\n-") deps = [ req.as_line(sources=False, include_hashes=False) for req in deps_list ] # Output only default dependencies click.echo(index_args) click.echo( "\n".join(sorted(deps)) ) sys.exit(0) procs = queue.Queue(maxsize=PIPENV_MAX_SUBPROCESS) failed_deps_queue = queue.Queue() if skip_lock: ignore_hashes = True install_kwargs = { "no_deps": no_deps, "ignore_hashes": ignore_hashes, "allow_global": allow_global, "blocking": blocking, "pypi_mirror": pypi_mirror } if concurrent: install_kwargs["nprocs"] = PIPENV_MAX_SUBPROCESS else: install_kwargs["nprocs"] = 1 # with project.environment.activated(): batch_install( deps_list, procs, failed_deps_queue, requirements_dir, **install_kwargs ) if not procs.empty(): _cleanup_procs(procs, concurrent, failed_deps_queue) # Iterate over the hopefully-poorly-packaged dependencies… if not failed_deps_queue.empty(): click.echo( crayons.normal(fix_utf8("Installing initially failed dependencies…"), bold=True) ) retry_list = [] while not failed_deps_queue.empty(): failed_dep = failed_deps_queue.get() retry_list.append(failed_dep) install_kwargs.update({ "nprocs": 1, "retry": False, "blocking": True, }) batch_install( retry_list, procs, failed_deps_queue, requirements_dir, **install_kwargs ) if not procs.empty(): _cleanup_procs(procs, False, failed_deps_queue, retry=False)
def do_install_dependencies( dev=False, only=False, bare=False, requirements=False, allow_global=False, ignore_hashes=False, skip_lock=False, concurrent=True, requirements_dir=None, pypi_mirror=False, ): """" Executes the install functionality. If requirements is True, simply spits out a requirements format to stdout. """ from six.moves import queue if requirements: bare = True blocking = not concurrent # Load the lockfile if it exists, or if only is being used (e.g. lock is being used). if skip_lock or only or not project.lockfile_exists: if not bare: click.echo( crayons.normal(fix_utf8("Installing dependencies from Pipfile…"), bold=True) ) # skip_lock should completely bypass the lockfile (broken in 4dac1676) lockfile = project.get_or_create_lockfile(from_pipfile=True) else: lockfile = project.get_or_create_lockfile() if not bare: click.echo( crayons.normal( fix_utf8("Installing dependencies from Pipfile.lock ({0})…".format( lockfile["_meta"].get("hash", {}).get("sha256")[-6:] )), bold=True, ) ) # Allow pip to resolve dependencies when in skip-lock mode. no_deps = not skip_lock deps_list = list(lockfile.get_requirements(dev=dev, only=requirements)) if requirements: index_args = prepare_pip_source_args(project.sources) index_args = " ".join(index_args).replace(" -", "\n-") deps = [ req.as_line(sources=False, include_hashes=False) for req in deps_list ] # Output only default dependencies click.echo(index_args) click.echo( "\n".join(sorted(deps)) ) sys.exit(0) procs = queue.Queue(maxsize=PIPENV_MAX_SUBPROCESS) failed_deps_queue = queue.Queue() if skip_lock: ignore_hashes = True install_kwargs = { "no_deps": no_deps, "ignore_hashes": ignore_hashes, "allow_global": allow_global, "blocking": blocking, "pypi_mirror": pypi_mirror } if concurrent: install_kwargs["nprocs"] = PIPENV_MAX_SUBPROCESS else: install_kwargs["nprocs"] = 1 # with project.environment.activated(): batch_install( deps_list, procs, failed_deps_queue, requirements_dir, **install_kwargs ) if not procs.empty(): _cleanup_procs(procs, concurrent, failed_deps_queue) # Iterate over the hopefully-poorly-packaged dependencies… if not failed_deps_queue.empty(): click.echo( crayons.normal(fix_utf8("Installing initially failed dependencies…"), bold=True) ) retry_list = [] while not failed_deps_queue.empty(): failed_dep = failed_deps_queue.get() retry_list.append(failed_dep) install_kwargs.update({ "nprocs": 1, "retry": False, "blocking": True, }) batch_install( retry_list, procs, failed_deps_queue, requirements_dir, **install_kwargs ) if not procs.empty(): _cleanup_procs(procs, False, failed_deps_queue, retry=False)
[ "Executes", "the", "install", "functionality", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L759-L856
[ "def", "do_install_dependencies", "(", "dev", "=", "False", ",", "only", "=", "False", ",", "bare", "=", "False", ",", "requirements", "=", "False", ",", "allow_global", "=", "False", ",", "ignore_hashes", "=", "False", ",", "skip_lock", "=", "False", ",",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_create_virtualenv
Creates a virtualenv.
pipenv/core.py
def do_create_virtualenv(python=None, site_packages=False, pypi_mirror=None): """Creates a virtualenv.""" click.echo( crayons.normal(fix_utf8("Creating a virtualenv for this project…"), bold=True), err=True ) click.echo( u"Pipfile: {0}".format(crayons.red(project.pipfile_location, bold=True)), err=True, ) # Default to using sys.executable, if Python wasn't provided. if not python: python = sys.executable click.echo( u"{0} {1} {3} {2}".format( crayons.normal("Using", bold=True), crayons.red(python, bold=True), crayons.normal(fix_utf8("to create virtualenv…"), bold=True), crayons.green("({0})".format(python_version(python))), ), err=True, ) cmd = [ vistir.compat.Path(sys.executable).absolute().as_posix(), "-m", "virtualenv", "--prompt=({0}) ".format(project.name), "--python={0}".format(python), project.get_location_for_virtualenv(), ] # Pass site-packages flag to virtualenv, if desired… if site_packages: click.echo( crayons.normal(fix_utf8("Making site-packages available…"), bold=True), err=True ) cmd.append("--system-site-packages") if pypi_mirror: pip_config = {"PIP_INDEX_URL": vistir.misc.fs_str(pypi_mirror)} else: pip_config = {} # Actually create the virtualenv. nospin = environments.PIPENV_NOSPIN with create_spinner("Creating virtual environment...") as sp: c = vistir.misc.run( cmd, verbose=False, return_object=True, write_to_stdout=False, combine_stderr=False, block=True, nospin=True, env=pip_config, ) click.echo(crayons.blue("{0}".format(c.out)), err=True) if c.returncode != 0: sp.fail(environments.PIPENV_SPINNER_FAIL_TEXT.format("Failed creating virtual environment")) error = c.err if environments.is_verbose() else exceptions.prettify_exc(c.err) raise exceptions.VirtualenvCreationException( extra=[crayons.red("{0}".format(error)),] ) else: sp.green.ok(environments.PIPENV_SPINNER_OK_TEXT.format(u"Successfully created virtual environment!")) # Associate project directory with the environment. # This mimics Pew's "setproject". project_file_name = os.path.join(project.virtualenv_location, ".project") with open(project_file_name, "w") as f: f.write(vistir.misc.fs_str(project.project_directory)) from .environment import Environment sources = project.pipfile_sources project._environment = Environment( prefix=project.get_location_for_virtualenv(), is_venv=True, sources=sources, pipfile=project.parsed_pipfile, project=project ) project._environment.add_dist("pipenv") # Say where the virtualenv is. do_where(virtualenv=True, bare=False)
def do_create_virtualenv(python=None, site_packages=False, pypi_mirror=None): """Creates a virtualenv.""" click.echo( crayons.normal(fix_utf8("Creating a virtualenv for this project…"), bold=True), err=True ) click.echo( u"Pipfile: {0}".format(crayons.red(project.pipfile_location, bold=True)), err=True, ) # Default to using sys.executable, if Python wasn't provided. if not python: python = sys.executable click.echo( u"{0} {1} {3} {2}".format( crayons.normal("Using", bold=True), crayons.red(python, bold=True), crayons.normal(fix_utf8("to create virtualenv…"), bold=True), crayons.green("({0})".format(python_version(python))), ), err=True, ) cmd = [ vistir.compat.Path(sys.executable).absolute().as_posix(), "-m", "virtualenv", "--prompt=({0}) ".format(project.name), "--python={0}".format(python), project.get_location_for_virtualenv(), ] # Pass site-packages flag to virtualenv, if desired… if site_packages: click.echo( crayons.normal(fix_utf8("Making site-packages available…"), bold=True), err=True ) cmd.append("--system-site-packages") if pypi_mirror: pip_config = {"PIP_INDEX_URL": vistir.misc.fs_str(pypi_mirror)} else: pip_config = {} # Actually create the virtualenv. nospin = environments.PIPENV_NOSPIN with create_spinner("Creating virtual environment...") as sp: c = vistir.misc.run( cmd, verbose=False, return_object=True, write_to_stdout=False, combine_stderr=False, block=True, nospin=True, env=pip_config, ) click.echo(crayons.blue("{0}".format(c.out)), err=True) if c.returncode != 0: sp.fail(environments.PIPENV_SPINNER_FAIL_TEXT.format("Failed creating virtual environment")) error = c.err if environments.is_verbose() else exceptions.prettify_exc(c.err) raise exceptions.VirtualenvCreationException( extra=[crayons.red("{0}".format(error)),] ) else: sp.green.ok(environments.PIPENV_SPINNER_OK_TEXT.format(u"Successfully created virtual environment!")) # Associate project directory with the environment. # This mimics Pew's "setproject". project_file_name = os.path.join(project.virtualenv_location, ".project") with open(project_file_name, "w") as f: f.write(vistir.misc.fs_str(project.project_directory)) from .environment import Environment sources = project.pipfile_sources project._environment = Environment( prefix=project.get_location_for_virtualenv(), is_venv=True, sources=sources, pipfile=project.parsed_pipfile, project=project ) project._environment.add_dist("pipenv") # Say where the virtualenv is. do_where(virtualenv=True, bare=False)
[ "Creates", "a", "virtualenv", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L874-L953
[ "def", "do_create_virtualenv", "(", "python", "=", "None", ",", "site_packages", "=", "False", ",", "pypi_mirror", "=", "None", ")", ":", "click", ".", "echo", "(", "crayons", ".", "normal", "(", "fix_utf8", "(", "\"Creating a virtualenv for this project…\"),", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_lock
Executes the freeze functionality.
pipenv/core.py
def do_lock( ctx=None, system=False, clear=False, pre=False, keep_outdated=False, write=True, pypi_mirror=None, ): """Executes the freeze functionality.""" cached_lockfile = {} if not pre: pre = project.settings.get("allow_prereleases") if keep_outdated: if not project.lockfile_exists: raise exceptions.PipenvOptionsError( "--keep-outdated", ctx=ctx, message="Pipfile.lock must exist to use --keep-outdated!" ) cached_lockfile = project.lockfile_content # Create the lockfile. lockfile = project._lockfile # Cleanup lockfile. for section in ("default", "develop"): for k, v in lockfile[section].copy().items(): if not hasattr(v, "keys"): del lockfile[section][k] # Ensure that develop inherits from default. dev_packages = project.dev_packages.copy() dev_packages = overwrite_dev(project.packages, dev_packages) # Resolve dev-package dependencies, with pip-tools. for is_dev in [True, False]: pipfile_section = "dev-packages" if is_dev else "packages" lockfile_section = "develop" if is_dev else "default" if project.pipfile_exists: packages = project.parsed_pipfile.get(pipfile_section, {}) else: packages = getattr(project, pipfile_section.replace("-", "_")) if write: # Alert the user of progress. click.echo( u"{0} {1} {2}".format( crayons.normal(u"Locking"), crayons.red(u"[{0}]".format(pipfile_section.replace("_", "-"))), crayons.normal(fix_utf8("dependencies…")), ), err=True, ) # Mutates the lockfile venv_resolve_deps( packages, which=which, project=project, dev=is_dev, clear=clear, pre=pre, allow_global=system, pypi_mirror=pypi_mirror, pipfile=packages, lockfile=lockfile, keep_outdated=keep_outdated ) # Support for --keep-outdated… if keep_outdated: from pipenv.vendor.packaging.utils import canonicalize_name for section_name, section in ( ("default", project.packages), ("develop", project.dev_packages), ): for package_specified in section.keys(): if not is_pinned(section[package_specified]): canonical_name = canonicalize_name(package_specified) if canonical_name in cached_lockfile[section_name]: lockfile[section_name][canonical_name] = cached_lockfile[ section_name ][canonical_name].copy() for key in ["default", "develop"]: packages = set(cached_lockfile[key].keys()) new_lockfile = set(lockfile[key].keys()) missing = packages - new_lockfile for missing_pkg in missing: lockfile[key][missing_pkg] = cached_lockfile[key][missing_pkg].copy() # Overwrite any develop packages with default packages. lockfile["develop"].update(overwrite_dev(lockfile.get("default", {}), lockfile["develop"])) if write: project.write_lockfile(lockfile) click.echo( "{0}".format( crayons.normal( "Updated Pipfile.lock ({0})!".format( lockfile["_meta"].get("hash", {}).get("sha256")[-6:] ), bold=True, ) ), err=True, ) else: return lockfile
def do_lock( ctx=None, system=False, clear=False, pre=False, keep_outdated=False, write=True, pypi_mirror=None, ): """Executes the freeze functionality.""" cached_lockfile = {} if not pre: pre = project.settings.get("allow_prereleases") if keep_outdated: if not project.lockfile_exists: raise exceptions.PipenvOptionsError( "--keep-outdated", ctx=ctx, message="Pipfile.lock must exist to use --keep-outdated!" ) cached_lockfile = project.lockfile_content # Create the lockfile. lockfile = project._lockfile # Cleanup lockfile. for section in ("default", "develop"): for k, v in lockfile[section].copy().items(): if not hasattr(v, "keys"): del lockfile[section][k] # Ensure that develop inherits from default. dev_packages = project.dev_packages.copy() dev_packages = overwrite_dev(project.packages, dev_packages) # Resolve dev-package dependencies, with pip-tools. for is_dev in [True, False]: pipfile_section = "dev-packages" if is_dev else "packages" lockfile_section = "develop" if is_dev else "default" if project.pipfile_exists: packages = project.parsed_pipfile.get(pipfile_section, {}) else: packages = getattr(project, pipfile_section.replace("-", "_")) if write: # Alert the user of progress. click.echo( u"{0} {1} {2}".format( crayons.normal(u"Locking"), crayons.red(u"[{0}]".format(pipfile_section.replace("_", "-"))), crayons.normal(fix_utf8("dependencies…")), ), err=True, ) # Mutates the lockfile venv_resolve_deps( packages, which=which, project=project, dev=is_dev, clear=clear, pre=pre, allow_global=system, pypi_mirror=pypi_mirror, pipfile=packages, lockfile=lockfile, keep_outdated=keep_outdated ) # Support for --keep-outdated… if keep_outdated: from pipenv.vendor.packaging.utils import canonicalize_name for section_name, section in ( ("default", project.packages), ("develop", project.dev_packages), ): for package_specified in section.keys(): if not is_pinned(section[package_specified]): canonical_name = canonicalize_name(package_specified) if canonical_name in cached_lockfile[section_name]: lockfile[section_name][canonical_name] = cached_lockfile[ section_name ][canonical_name].copy() for key in ["default", "develop"]: packages = set(cached_lockfile[key].keys()) new_lockfile = set(lockfile[key].keys()) missing = packages - new_lockfile for missing_pkg in missing: lockfile[key][missing_pkg] = cached_lockfile[key][missing_pkg].copy() # Overwrite any develop packages with default packages. lockfile["develop"].update(overwrite_dev(lockfile.get("default", {}), lockfile["develop"])) if write: project.write_lockfile(lockfile) click.echo( "{0}".format( crayons.normal( "Updated Pipfile.lock ({0})!".format( lockfile["_meta"].get("hash", {}).get("sha256")[-6:] ), bold=True, ) ), err=True, ) else: return lockfile
[ "Executes", "the", "freeze", "functionality", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L1003-L1105
[ "def", "do_lock", "(", "ctx", "=", "None", ",", "system", "=", "False", ",", "clear", "=", "False", ",", "pre", "=", "False", ",", "keep_outdated", "=", "False", ",", "write", "=", "True", ",", "pypi_mirror", "=", "None", ",", ")", ":", "cached_lockf...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_purge
Executes the purge functionality.
pipenv/core.py
def do_purge(bare=False, downloads=False, allow_global=False): """Executes the purge functionality.""" if downloads: if not bare: click.echo(crayons.normal(fix_utf8("Clearing out downloads directory…"), bold=True)) vistir.path.rmtree(project.download_location) return # Remove comments from the output, if any. installed = set([ pep423_name(pkg.project_name) for pkg in project.environment.get_installed_packages() ]) bad_pkgs = set([pep423_name(pkg) for pkg in BAD_PACKAGES]) # Remove setuptools, pip, etc from targets for removal to_remove = installed - bad_pkgs # Skip purging if there is no packages which needs to be removed if not to_remove: if not bare: click.echo("Found 0 installed package, skip purging.") click.echo(crayons.green("Environment now purged and fresh!")) return installed if not bare: click.echo( fix_utf8("Found {0} installed package(s), purging…".format(len(to_remove))) ) command = "{0} uninstall {1} -y".format( escape_grouped_arguments(which_pip(allow_global=allow_global)), " ".join(to_remove), ) if environments.is_verbose(): click.echo("$ {0}".format(command)) c = delegator.run(command) if c.return_code != 0: raise exceptions.UninstallError(installed, command, c.out + c.err, c.return_code) if not bare: click.echo(crayons.blue(c.out)) click.echo(crayons.green("Environment now purged and fresh!")) return installed
def do_purge(bare=False, downloads=False, allow_global=False): """Executes the purge functionality.""" if downloads: if not bare: click.echo(crayons.normal(fix_utf8("Clearing out downloads directory…"), bold=True)) vistir.path.rmtree(project.download_location) return # Remove comments from the output, if any. installed = set([ pep423_name(pkg.project_name) for pkg in project.environment.get_installed_packages() ]) bad_pkgs = set([pep423_name(pkg) for pkg in BAD_PACKAGES]) # Remove setuptools, pip, etc from targets for removal to_remove = installed - bad_pkgs # Skip purging if there is no packages which needs to be removed if not to_remove: if not bare: click.echo("Found 0 installed package, skip purging.") click.echo(crayons.green("Environment now purged and fresh!")) return installed if not bare: click.echo( fix_utf8("Found {0} installed package(s), purging…".format(len(to_remove))) ) command = "{0} uninstall {1} -y".format( escape_grouped_arguments(which_pip(allow_global=allow_global)), " ".join(to_remove), ) if environments.is_verbose(): click.echo("$ {0}".format(command)) c = delegator.run(command) if c.return_code != 0: raise exceptions.UninstallError(installed, command, c.out + c.err, c.return_code) if not bare: click.echo(crayons.blue(c.out)) click.echo(crayons.green("Environment now purged and fresh!")) return installed
[ "Executes", "the", "purge", "functionality", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L1108-L1149
[ "def", "do_purge", "(", "bare", "=", "False", ",", "downloads", "=", "False", ",", "allow_global", "=", "False", ")", ":", "if", "downloads", ":", "if", "not", "bare", ":", "click", ".", "echo", "(", "crayons", ".", "normal", "(", "fix_utf8", "(", "\...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_init
Executes the init functionality.
pipenv/core.py
def do_init( dev=False, requirements=False, allow_global=False, ignore_pipfile=False, skip_lock=False, system=False, concurrent=True, deploy=False, pre=False, keep_outdated=False, requirements_dir=None, pypi_mirror=None, ): """Executes the init functionality.""" from .environments import ( PIPENV_VIRTUALENV, PIPENV_DEFAULT_PYTHON_VERSION, PIPENV_PYTHON, PIPENV_USE_SYSTEM ) python = None if PIPENV_PYTHON is not None: python = PIPENV_PYTHON elif PIPENV_DEFAULT_PYTHON_VERSION is not None: python = PIPENV_DEFAULT_PYTHON_VERSION if not system and not PIPENV_USE_SYSTEM: if not project.virtualenv_exists: try: do_create_virtualenv(python=python, three=None, pypi_mirror=pypi_mirror) except KeyboardInterrupt: cleanup_virtualenv(bare=False) sys.exit(1) # Ensure the Pipfile exists. if not deploy: ensure_pipfile(system=system) if not requirements_dir: requirements_dir = vistir.path.create_tracked_tempdir( suffix="-requirements", prefix="pipenv-" ) # Write out the lockfile if it doesn't exist, but not if the Pipfile is being ignored if (project.lockfile_exists and not ignore_pipfile) and not skip_lock: old_hash = project.get_lockfile_hash() new_hash = project.calculate_pipfile_hash() if new_hash != old_hash: if deploy: click.echo( crayons.red( "Your Pipfile.lock ({0}) is out of date. Expected: ({1}).".format( old_hash[-6:], new_hash[-6:] ) ) ) raise exceptions.DeployException sys.exit(1) elif (system or allow_global) and not (PIPENV_VIRTUALENV): click.echo( crayons.red(fix_utf8( "Pipfile.lock ({0}) out of date, but installation " "uses {1}… re-building lockfile must happen in " "isolation. Please rebuild lockfile in a virtualenv. " "Continuing anyway…".format( crayons.white(old_hash[-6:]), crayons.white("--system") )), bold=True, ), err=True, ) else: if old_hash: msg = fix_utf8("Pipfile.lock ({0}) out of date, updating to ({1})…") else: msg = fix_utf8("Pipfile.lock is corrupted, replaced with ({1})…") click.echo( crayons.red(msg.format(old_hash[-6:], new_hash[-6:]), bold=True), err=True, ) do_lock( system=system, pre=pre, keep_outdated=keep_outdated, write=True, pypi_mirror=pypi_mirror, ) # Write out the lockfile if it doesn't exist. if not project.lockfile_exists and not skip_lock: # Unless we're in a virtualenv not managed by pipenv, abort if we're # using the system's python. if (system or allow_global) and not (PIPENV_VIRTUALENV): raise exceptions.PipenvOptionsError( "--system", "--system is intended to be used for Pipfile installation, " "not installation of specific packages. Aborting.\n" "See also: --deploy flag." ) else: click.echo( crayons.normal(fix_utf8("Pipfile.lock not found, creating…"), bold=True), err=True, ) do_lock( system=system, pre=pre, keep_outdated=keep_outdated, write=True, pypi_mirror=pypi_mirror, ) do_install_dependencies( dev=dev, requirements=requirements, allow_global=allow_global, skip_lock=skip_lock, concurrent=concurrent, requirements_dir=requirements_dir, pypi_mirror=pypi_mirror, ) # Hint the user what to do to activate the virtualenv. if not allow_global and not deploy and "PIPENV_ACTIVE" not in os.environ: click.echo( "To activate this project's virtualenv, run {0}.\n" "Alternatively, run a command " "inside the virtualenv with {1}.".format( crayons.red("pipenv shell"), crayons.red("pipenv run") ) )
def do_init( dev=False, requirements=False, allow_global=False, ignore_pipfile=False, skip_lock=False, system=False, concurrent=True, deploy=False, pre=False, keep_outdated=False, requirements_dir=None, pypi_mirror=None, ): """Executes the init functionality.""" from .environments import ( PIPENV_VIRTUALENV, PIPENV_DEFAULT_PYTHON_VERSION, PIPENV_PYTHON, PIPENV_USE_SYSTEM ) python = None if PIPENV_PYTHON is not None: python = PIPENV_PYTHON elif PIPENV_DEFAULT_PYTHON_VERSION is not None: python = PIPENV_DEFAULT_PYTHON_VERSION if not system and not PIPENV_USE_SYSTEM: if not project.virtualenv_exists: try: do_create_virtualenv(python=python, three=None, pypi_mirror=pypi_mirror) except KeyboardInterrupt: cleanup_virtualenv(bare=False) sys.exit(1) # Ensure the Pipfile exists. if not deploy: ensure_pipfile(system=system) if not requirements_dir: requirements_dir = vistir.path.create_tracked_tempdir( suffix="-requirements", prefix="pipenv-" ) # Write out the lockfile if it doesn't exist, but not if the Pipfile is being ignored if (project.lockfile_exists and not ignore_pipfile) and not skip_lock: old_hash = project.get_lockfile_hash() new_hash = project.calculate_pipfile_hash() if new_hash != old_hash: if deploy: click.echo( crayons.red( "Your Pipfile.lock ({0}) is out of date. Expected: ({1}).".format( old_hash[-6:], new_hash[-6:] ) ) ) raise exceptions.DeployException sys.exit(1) elif (system or allow_global) and not (PIPENV_VIRTUALENV): click.echo( crayons.red(fix_utf8( "Pipfile.lock ({0}) out of date, but installation " "uses {1}… re-building lockfile must happen in " "isolation. Please rebuild lockfile in a virtualenv. " "Continuing anyway…".format( crayons.white(old_hash[-6:]), crayons.white("--system") )), bold=True, ), err=True, ) else: if old_hash: msg = fix_utf8("Pipfile.lock ({0}) out of date, updating to ({1})…") else: msg = fix_utf8("Pipfile.lock is corrupted, replaced with ({1})…") click.echo( crayons.red(msg.format(old_hash[-6:], new_hash[-6:]), bold=True), err=True, ) do_lock( system=system, pre=pre, keep_outdated=keep_outdated, write=True, pypi_mirror=pypi_mirror, ) # Write out the lockfile if it doesn't exist. if not project.lockfile_exists and not skip_lock: # Unless we're in a virtualenv not managed by pipenv, abort if we're # using the system's python. if (system or allow_global) and not (PIPENV_VIRTUALENV): raise exceptions.PipenvOptionsError( "--system", "--system is intended to be used for Pipfile installation, " "not installation of specific packages. Aborting.\n" "See also: --deploy flag." ) else: click.echo( crayons.normal(fix_utf8("Pipfile.lock not found, creating…"), bold=True), err=True, ) do_lock( system=system, pre=pre, keep_outdated=keep_outdated, write=True, pypi_mirror=pypi_mirror, ) do_install_dependencies( dev=dev, requirements=requirements, allow_global=allow_global, skip_lock=skip_lock, concurrent=concurrent, requirements_dir=requirements_dir, pypi_mirror=pypi_mirror, ) # Hint the user what to do to activate the virtualenv. if not allow_global and not deploy and "PIPENV_ACTIVE" not in os.environ: click.echo( "To activate this project's virtualenv, run {0}.\n" "Alternatively, run a command " "inside the virtualenv with {1}.".format( crayons.red("pipenv shell"), crayons.red("pipenv run") ) )
[ "Executes", "the", "init", "functionality", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L1152-L1275
[ "def", "do_init", "(", "dev", "=", "False", ",", "requirements", "=", "False", ",", "allow_global", "=", "False", ",", "ignore_pipfile", "=", "False", ",", "skip_lock", "=", "False", ",", "system", "=", "False", ",", "concurrent", "=", "True", ",", "depl...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
fallback_which
A fallback implementation of the `which` utility command that relies exclusively on searching the path for commands. :param str command: The command to search for, optional :param str location: The search location to prioritize (prepend to path), defaults to None :param bool allow_global: Whether to search the global path, defaults to False :param bool system: Whether to use the system python instead of pipenv's python, defaults to False :raises ValueError: Raised if no command is provided :raises TypeError: Raised if the command provided is not a string :return: A path to the discovered command location :rtype: str
pipenv/core.py
def fallback_which(command, location=None, allow_global=False, system=False): """ A fallback implementation of the `which` utility command that relies exclusively on searching the path for commands. :param str command: The command to search for, optional :param str location: The search location to prioritize (prepend to path), defaults to None :param bool allow_global: Whether to search the global path, defaults to False :param bool system: Whether to use the system python instead of pipenv's python, defaults to False :raises ValueError: Raised if no command is provided :raises TypeError: Raised if the command provided is not a string :return: A path to the discovered command location :rtype: str """ from .vendor.pythonfinder import Finder if not command: raise ValueError("fallback_which: Must provide a command to search for...") if not isinstance(command, six.string_types): raise TypeError("Provided command must be a string, received {0!r}".format(command)) global_search = system or allow_global if location is None: global_search = True finder = Finder(system=False, global_search=global_search, path=location) if is_python_command(command): result = find_python(finder, command) if result: return result result = finder.which(command) if result: return result.path.as_posix() return ""
def fallback_which(command, location=None, allow_global=False, system=False): """ A fallback implementation of the `which` utility command that relies exclusively on searching the path for commands. :param str command: The command to search for, optional :param str location: The search location to prioritize (prepend to path), defaults to None :param bool allow_global: Whether to search the global path, defaults to False :param bool system: Whether to use the system python instead of pipenv's python, defaults to False :raises ValueError: Raised if no command is provided :raises TypeError: Raised if the command provided is not a string :return: A path to the discovered command location :rtype: str """ from .vendor.pythonfinder import Finder if not command: raise ValueError("fallback_which: Must provide a command to search for...") if not isinstance(command, six.string_types): raise TypeError("Provided command must be a string, received {0!r}".format(command)) global_search = system or allow_global if location is None: global_search = True finder = Finder(system=False, global_search=global_search, path=location) if is_python_command(command): result = find_python(finder, command) if result: return result result = finder.which(command) if result: return result.path.as_posix() return ""
[ "A", "fallback", "implementation", "of", "the", "which", "utility", "command", "that", "relies", "exclusively", "on", "searching", "the", "path", "for", "commands", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L1544-L1575
[ "def", "fallback_which", "(", "command", ",", "location", "=", "None", ",", "allow_global", "=", "False", ",", "system", "=", "False", ")", ":", "from", ".", "vendor", ".", "pythonfinder", "import", "Finder", "if", "not", "command", ":", "raise", "ValueErr...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
which_pip
Returns the location of virtualenv-installed pip.
pipenv/core.py
def which_pip(allow_global=False): """Returns the location of virtualenv-installed pip.""" location = None if "VIRTUAL_ENV" in os.environ: location = os.environ["VIRTUAL_ENV"] if allow_global: if location: pip = which("pip", location=location) if pip: return pip for p in ("pip", "pip3", "pip2"): where = system_which(p) if where: return where pip = which("pip") if not pip: pip = fallback_which("pip", allow_global=allow_global, location=location) return pip
def which_pip(allow_global=False): """Returns the location of virtualenv-installed pip.""" location = None if "VIRTUAL_ENV" in os.environ: location = os.environ["VIRTUAL_ENV"] if allow_global: if location: pip = which("pip", location=location) if pip: return pip for p in ("pip", "pip3", "pip2"): where = system_which(p) if where: return where pip = which("pip") if not pip: pip = fallback_which("pip", allow_global=allow_global, location=location) return pip
[ "Returns", "the", "location", "of", "virtualenv", "-", "installed", "pip", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L1578-L1598
[ "def", "which_pip", "(", "allow_global", "=", "False", ")", ":", "location", "=", "None", "if", "\"VIRTUAL_ENV\"", "in", "os", ".", "environ", ":", "location", "=", "os", ".", "environ", "[", "\"VIRTUAL_ENV\"", "]", "if", "allow_global", ":", "if", "locati...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
system_which
Emulates the system's which. Returns None if not found.
pipenv/core.py
def system_which(command, mult=False): """Emulates the system's which. Returns None if not found.""" _which = "which -a" if not os.name == "nt" else "where" os.environ = { vistir.compat.fs_str(k): vistir.compat.fs_str(val) for k, val in os.environ.items() } result = None try: c = delegator.run("{0} {1}".format(_which, command)) try: # Which Not found… if c.return_code == 127: click.echo( "{}: the {} system utility is required for Pipenv to find Python installations properly." "\n Please install it.".format( crayons.red("Warning", bold=True), crayons.red(_which) ), err=True, ) assert c.return_code == 0 except AssertionError: result = fallback_which(command, allow_global=True) except TypeError: if not result: result = fallback_which(command, allow_global=True) else: if not result: result = next(iter([c.out, c.err]), "").split("\n") result = next(iter(result)) if not mult else result return result if not result: result = fallback_which(command, allow_global=True) result = [result] if mult else result return result
def system_which(command, mult=False): """Emulates the system's which. Returns None if not found.""" _which = "which -a" if not os.name == "nt" else "where" os.environ = { vistir.compat.fs_str(k): vistir.compat.fs_str(val) for k, val in os.environ.items() } result = None try: c = delegator.run("{0} {1}".format(_which, command)) try: # Which Not found… if c.return_code == 127: click.echo( "{}: the {} system utility is required for Pipenv to find Python installations properly." "\n Please install it.".format( crayons.red("Warning", bold=True), crayons.red(_which) ), err=True, ) assert c.return_code == 0 except AssertionError: result = fallback_which(command, allow_global=True) except TypeError: if not result: result = fallback_which(command, allow_global=True) else: if not result: result = next(iter([c.out, c.err]), "").split("\n") result = next(iter(result)) if not mult else result return result if not result: result = fallback_which(command, allow_global=True) result = [result] if mult else result return result
[ "Emulates", "the", "system", "s", "which", ".", "Returns", "None", "if", "not", "found", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L1601-L1635
[ "def", "system_which", "(", "command", ",", "mult", "=", "False", ")", ":", "_which", "=", "\"which -a\"", "if", "not", "os", ".", "name", "==", "\"nt\"", "else", "\"where\"", "os", ".", "environ", "=", "{", "vistir", ".", "compat", ".", "fs_str", "(",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
format_help
Formats the help string.
pipenv/core.py
def format_help(help): """Formats the help string.""" help = help.replace("Options:", str(crayons.normal("Options:", bold=True))) help = help.replace( "Usage: pipenv", str("Usage: {0}".format(crayons.normal("pipenv", bold=True))) ) help = help.replace(" check", str(crayons.red(" check", bold=True))) help = help.replace(" clean", str(crayons.red(" clean", bold=True))) help = help.replace(" graph", str(crayons.red(" graph", bold=True))) help = help.replace(" install", str(crayons.magenta(" install", bold=True))) help = help.replace(" lock", str(crayons.green(" lock", bold=True))) help = help.replace(" open", str(crayons.red(" open", bold=True))) help = help.replace(" run", str(crayons.yellow(" run", bold=True))) help = help.replace(" shell", str(crayons.yellow(" shell", bold=True))) help = help.replace(" sync", str(crayons.green(" sync", bold=True))) help = help.replace(" uninstall", str(crayons.magenta(" uninstall", bold=True))) help = help.replace(" update", str(crayons.green(" update", bold=True))) additional_help = """ Usage Examples: Create a new project using Python 3.7, specifically: $ {1} Remove project virtualenv (inferred from current directory): $ {9} Install all dependencies for a project (including dev): $ {2} Create a lockfile containing pre-releases: $ {6} Show a graph of your installed dependencies: $ {4} Check your installed dependencies for security vulnerabilities: $ {7} Install a local setup.py into your virtual environment/Pipfile: $ {5} Use a lower-level pip command: $ {8} Commands:""".format( crayons.red("pipenv --three"), crayons.red("pipenv --python 3.7"), crayons.red("pipenv install --dev"), crayons.red("pipenv lock"), crayons.red("pipenv graph"), crayons.red("pipenv install -e ."), crayons.red("pipenv lock --pre"), crayons.red("pipenv check"), crayons.red("pipenv run pip freeze"), crayons.red("pipenv --rm"), ) help = help.replace("Commands:", additional_help) return help
def format_help(help): """Formats the help string.""" help = help.replace("Options:", str(crayons.normal("Options:", bold=True))) help = help.replace( "Usage: pipenv", str("Usage: {0}".format(crayons.normal("pipenv", bold=True))) ) help = help.replace(" check", str(crayons.red(" check", bold=True))) help = help.replace(" clean", str(crayons.red(" clean", bold=True))) help = help.replace(" graph", str(crayons.red(" graph", bold=True))) help = help.replace(" install", str(crayons.magenta(" install", bold=True))) help = help.replace(" lock", str(crayons.green(" lock", bold=True))) help = help.replace(" open", str(crayons.red(" open", bold=True))) help = help.replace(" run", str(crayons.yellow(" run", bold=True))) help = help.replace(" shell", str(crayons.yellow(" shell", bold=True))) help = help.replace(" sync", str(crayons.green(" sync", bold=True))) help = help.replace(" uninstall", str(crayons.magenta(" uninstall", bold=True))) help = help.replace(" update", str(crayons.green(" update", bold=True))) additional_help = """ Usage Examples: Create a new project using Python 3.7, specifically: $ {1} Remove project virtualenv (inferred from current directory): $ {9} Install all dependencies for a project (including dev): $ {2} Create a lockfile containing pre-releases: $ {6} Show a graph of your installed dependencies: $ {4} Check your installed dependencies for security vulnerabilities: $ {7} Install a local setup.py into your virtual environment/Pipfile: $ {5} Use a lower-level pip command: $ {8} Commands:""".format( crayons.red("pipenv --three"), crayons.red("pipenv --python 3.7"), crayons.red("pipenv install --dev"), crayons.red("pipenv lock"), crayons.red("pipenv graph"), crayons.red("pipenv install -e ."), crayons.red("pipenv lock --pre"), crayons.red("pipenv check"), crayons.red("pipenv run pip freeze"), crayons.red("pipenv --rm"), ) help = help.replace("Commands:", additional_help) return help
[ "Formats", "the", "help", "string", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L1639-L1695
[ "def", "format_help", "(", "help", ")", ":", "help", "=", "help", ".", "replace", "(", "\"Options:\"", ",", "str", "(", "crayons", ".", "normal", "(", "\"Options:\"", ",", "bold", "=", "True", ")", ")", ")", "help", "=", "help", ".", "replace", "(", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ensure_lockfile
Ensures that the lockfile is up-to-date.
pipenv/core.py
def ensure_lockfile(keep_outdated=False, pypi_mirror=None): """Ensures that the lockfile is up-to-date.""" if not keep_outdated: keep_outdated = project.settings.get("keep_outdated") # Write out the lockfile if it doesn't exist, but not if the Pipfile is being ignored if project.lockfile_exists: old_hash = project.get_lockfile_hash() new_hash = project.calculate_pipfile_hash() if new_hash != old_hash: click.echo( crayons.red( fix_utf8("Pipfile.lock ({0}) out of date, updating to ({1})…".format( old_hash[-6:], new_hash[-6:] )), bold=True, ), err=True, ) do_lock(keep_outdated=keep_outdated, pypi_mirror=pypi_mirror) else: do_lock(keep_outdated=keep_outdated, pypi_mirror=pypi_mirror)
def ensure_lockfile(keep_outdated=False, pypi_mirror=None): """Ensures that the lockfile is up-to-date.""" if not keep_outdated: keep_outdated = project.settings.get("keep_outdated") # Write out the lockfile if it doesn't exist, but not if the Pipfile is being ignored if project.lockfile_exists: old_hash = project.get_lockfile_hash() new_hash = project.calculate_pipfile_hash() if new_hash != old_hash: click.echo( crayons.red( fix_utf8("Pipfile.lock ({0}) out of date, updating to ({1})…".format( old_hash[-6:], new_hash[-6:] )), bold=True, ), err=True, ) do_lock(keep_outdated=keep_outdated, pypi_mirror=pypi_mirror) else: do_lock(keep_outdated=keep_outdated, pypi_mirror=pypi_mirror)
[ "Ensures", "that", "the", "lockfile", "is", "up", "-", "to", "-", "date", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L1749-L1769
[ "def", "ensure_lockfile", "(", "keep_outdated", "=", "False", ",", "pypi_mirror", "=", "None", ")", ":", "if", "not", "keep_outdated", ":", "keep_outdated", "=", "project", ".", "settings", ".", "get", "(", "\"keep_outdated\"", ")", "# Write out the lockfile if it...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_inline_activate_venv
Built-in venv doesn't have activate_this.py, but doesn't need it anyway. As long as we find the correct executable, built-in venv sets up the environment automatically. See: https://bugs.python.org/issue21496#msg218455
pipenv/core.py
def _inline_activate_venv(): """Built-in venv doesn't have activate_this.py, but doesn't need it anyway. As long as we find the correct executable, built-in venv sets up the environment automatically. See: https://bugs.python.org/issue21496#msg218455 """ components = [] for name in ("bin", "Scripts"): bindir = os.path.join(project.virtualenv_location, name) if os.path.exists(bindir): components.append(bindir) if "PATH" in os.environ: components.append(os.environ["PATH"]) os.environ["PATH"] = os.pathsep.join(components)
def _inline_activate_venv(): """Built-in venv doesn't have activate_this.py, but doesn't need it anyway. As long as we find the correct executable, built-in venv sets up the environment automatically. See: https://bugs.python.org/issue21496#msg218455 """ components = [] for name in ("bin", "Scripts"): bindir = os.path.join(project.virtualenv_location, name) if os.path.exists(bindir): components.append(bindir) if "PATH" in os.environ: components.append(os.environ["PATH"]) os.environ["PATH"] = os.pathsep.join(components)
[ "Built", "-", "in", "venv", "doesn", "t", "have", "activate_this", ".", "py", "but", "doesn", "t", "need", "it", "anyway", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L2376-L2391
[ "def", "_inline_activate_venv", "(", ")", ":", "components", "=", "[", "]", "for", "name", "in", "(", "\"bin\"", ",", "\"Scripts\"", ")", ":", "bindir", "=", "os", ".", "path", ".", "join", "(", "project", ".", "virtualenv_location", ",", "name", ")", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_run
Attempt to run command either pulling from project or interpreting as executable. Args are appended to the command in [scripts] section of project if found.
pipenv/core.py
def do_run(command, args, three=None, python=False, pypi_mirror=None): """Attempt to run command either pulling from project or interpreting as executable. Args are appended to the command in [scripts] section of project if found. """ from .cmdparse import ScriptEmptyError # Ensure that virtualenv is available. ensure_project( three=three, python=python, validate=False, pypi_mirror=pypi_mirror, ) load_dot_env() previous_pip_shims_module = os.environ.pop("PIP_SHIMS_BASE_MODULE", None) # Activate virtualenv under the current interpreter's environment inline_activate_virtual_environment() # Set an environment variable, so we know we're in the environment. # Only set PIPENV_ACTIVE after finishing reading virtualenv_location # such as in inline_activate_virtual_environment # otherwise its value will be changed previous_pipenv_active_value = os.environ.get("PIPENV_ACTIVE") os.environ["PIPENV_ACTIVE"] = vistir.misc.fs_str("1") try: script = project.build_script(command, args) cmd_string = ' '.join([script.command] + script.args) if environments.is_verbose(): click.echo(crayons.normal("$ {0}".format(cmd_string)), err=True) except ScriptEmptyError: click.echo("Can't run script {0!r}-it's empty?", err=True) run_args = [script] run_kwargs = {} if os.name == "nt": run_fn = do_run_nt else: run_fn = do_run_posix run_kwargs = {"command": command} try: run_fn(*run_args, **run_kwargs) finally: os.environ.pop("PIPENV_ACTIVE", None) if previous_pipenv_active_value is not None: os.environ["PIPENV_ACTIVE"] = previous_pipenv_active_value if previous_pip_shims_module is not None: os.environ["PIP_SHIMS_BASE_MODULE"] = previous_pip_shims_module
def do_run(command, args, three=None, python=False, pypi_mirror=None): """Attempt to run command either pulling from project or interpreting as executable. Args are appended to the command in [scripts] section of project if found. """ from .cmdparse import ScriptEmptyError # Ensure that virtualenv is available. ensure_project( three=three, python=python, validate=False, pypi_mirror=pypi_mirror, ) load_dot_env() previous_pip_shims_module = os.environ.pop("PIP_SHIMS_BASE_MODULE", None) # Activate virtualenv under the current interpreter's environment inline_activate_virtual_environment() # Set an environment variable, so we know we're in the environment. # Only set PIPENV_ACTIVE after finishing reading virtualenv_location # such as in inline_activate_virtual_environment # otherwise its value will be changed previous_pipenv_active_value = os.environ.get("PIPENV_ACTIVE") os.environ["PIPENV_ACTIVE"] = vistir.misc.fs_str("1") try: script = project.build_script(command, args) cmd_string = ' '.join([script.command] + script.args) if environments.is_verbose(): click.echo(crayons.normal("$ {0}".format(cmd_string)), err=True) except ScriptEmptyError: click.echo("Can't run script {0!r}-it's empty?", err=True) run_args = [script] run_kwargs = {} if os.name == "nt": run_fn = do_run_nt else: run_fn = do_run_posix run_kwargs = {"command": command} try: run_fn(*run_args, **run_kwargs) finally: os.environ.pop("PIPENV_ACTIVE", None) if previous_pipenv_active_value is not None: os.environ["PIPENV_ACTIVE"] = previous_pipenv_active_value if previous_pip_shims_module is not None: os.environ["PIP_SHIMS_BASE_MODULE"] = previous_pip_shims_module
[ "Attempt", "to", "run", "command", "either", "pulling", "from", "project", "or", "interpreting", "as", "executable", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L2464-L2511
[ "def", "do_run", "(", "command", ",", "args", ",", "three", "=", "None", ",", "python", "=", "False", ",", "pypi_mirror", "=", "None", ")", ":", "from", ".", "cmdparse", "import", "ScriptEmptyError", "# Ensure that virtualenv is available.", "ensure_project", "(...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_iter_process
Iterate through processes, yielding process ID and properties of each. Example usage:: >>> for pid, info in _iter_process(): ... print(pid, '->', info) 1509 -> {'parent_pid': 1201, 'executable': 'python.exe'}
pipenv/vendor/shellingham/nt.py
def _iter_process(): """Iterate through processes, yielding process ID and properties of each. Example usage:: >>> for pid, info in _iter_process(): ... print(pid, '->', info) 1509 -> {'parent_pid': 1201, 'executable': 'python.exe'} """ # TODO: Process32{First,Next} does not return full executable path, only # the name. To get the full path, Module32{First,Next} is needed, but that # does not contain parent process information. We probably need to call # BOTH to build the correct process tree. h_process = windll.kernel32.CreateToolhelp32Snapshot( 2, # dwFlags=TH32CS_SNAPPROCESS (include all processes). 0, # th32ProcessID=0 (the current process). ) if h_process == INVALID_HANDLE_VALUE: raise WinError() pe = PROCESSENTRY32() pe.dwSize = sizeof(PROCESSENTRY32) success = windll.kernel32.Process32First(h_process, byref(pe)) while True: if not success: errcode = windll.kernel32.GetLastError() if errcode == ERROR_NO_MORE_FILES: # No more processes to iterate through, we're done here. return elif errcode == ERROR_INSUFFICIENT_BUFFER: # This is likely because the file path is longer than the # Windows limit. Just ignore it, it's likely not what we're # looking for. We can fix this when it actually matters. (#8) continue raise WinError() # The executable name would be encoded with the current code page if # we're in ANSI mode (usually). Try to decode it into str/unicode, # replacing invalid characters to be safe (not thoeratically necessary, # I think). Note that we need to use 'mbcs' instead of encoding # settings from sys because this is from the Windows API, not Python # internals (which those settings reflect). (pypa/pipenv#3382) executable = pe.szExeFile if isinstance(executable, bytes): executable = executable.decode('mbcs', 'replace') info = {'executable': executable} if pe.th32ParentProcessID: info['parent_pid'] = pe.th32ParentProcessID yield pe.th32ProcessID, info success = windll.kernel32.Process32Next(h_process, byref(pe))
def _iter_process(): """Iterate through processes, yielding process ID and properties of each. Example usage:: >>> for pid, info in _iter_process(): ... print(pid, '->', info) 1509 -> {'parent_pid': 1201, 'executable': 'python.exe'} """ # TODO: Process32{First,Next} does not return full executable path, only # the name. To get the full path, Module32{First,Next} is needed, but that # does not contain parent process information. We probably need to call # BOTH to build the correct process tree. h_process = windll.kernel32.CreateToolhelp32Snapshot( 2, # dwFlags=TH32CS_SNAPPROCESS (include all processes). 0, # th32ProcessID=0 (the current process). ) if h_process == INVALID_HANDLE_VALUE: raise WinError() pe = PROCESSENTRY32() pe.dwSize = sizeof(PROCESSENTRY32) success = windll.kernel32.Process32First(h_process, byref(pe)) while True: if not success: errcode = windll.kernel32.GetLastError() if errcode == ERROR_NO_MORE_FILES: # No more processes to iterate through, we're done here. return elif errcode == ERROR_INSUFFICIENT_BUFFER: # This is likely because the file path is longer than the # Windows limit. Just ignore it, it's likely not what we're # looking for. We can fix this when it actually matters. (#8) continue raise WinError() # The executable name would be encoded with the current code page if # we're in ANSI mode (usually). Try to decode it into str/unicode, # replacing invalid characters to be safe (not thoeratically necessary, # I think). Note that we need to use 'mbcs' instead of encoding # settings from sys because this is from the Windows API, not Python # internals (which those settings reflect). (pypa/pipenv#3382) executable = pe.szExeFile if isinstance(executable, bytes): executable = executable.decode('mbcs', 'replace') info = {'executable': executable} if pe.th32ParentProcessID: info['parent_pid'] = pe.th32ParentProcessID yield pe.th32ProcessID, info success = windll.kernel32.Process32Next(h_process, byref(pe))
[ "Iterate", "through", "processes", "yielding", "process", "ID", "and", "properties", "of", "each", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/shellingham/nt.py#L44-L93
[ "def", "_iter_process", "(", ")", ":", "# TODO: Process32{First,Next} does not return full executable path, only", "# the name. To get the full path, Module32{First,Next} is needed, but that", "# does not contain parent process information. We probably need to call", "# BOTH to build the correct pro...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_shell
Get the shell that the supplied pid or os.getpid() is running in.
pipenv/vendor/shellingham/nt.py
def get_shell(pid=None, max_depth=6): """Get the shell that the supplied pid or os.getpid() is running in. """ if not pid: pid = os.getpid() processes = dict(_iter_process()) def check_parent(pid, lvl=0): ppid = processes[pid].get('parent_pid') shell_name = _get_executable(processes.get(ppid)) if shell_name in SHELL_NAMES: return (shell_name, processes[ppid]['executable']) if lvl >= max_depth: return None return check_parent(ppid, lvl=lvl + 1) shell_name = _get_executable(processes.get(pid)) if shell_name in SHELL_NAMES: return (shell_name, processes[pid]['executable']) try: return check_parent(pid) except KeyError: return None
def get_shell(pid=None, max_depth=6): """Get the shell that the supplied pid or os.getpid() is running in. """ if not pid: pid = os.getpid() processes = dict(_iter_process()) def check_parent(pid, lvl=0): ppid = processes[pid].get('parent_pid') shell_name = _get_executable(processes.get(ppid)) if shell_name in SHELL_NAMES: return (shell_name, processes[ppid]['executable']) if lvl >= max_depth: return None return check_parent(ppid, lvl=lvl + 1) shell_name = _get_executable(processes.get(pid)) if shell_name in SHELL_NAMES: return (shell_name, processes[pid]['executable']) try: return check_parent(pid) except KeyError: return None
[ "Get", "the", "shell", "that", "the", "supplied", "pid", "or", "os", ".", "getpid", "()", "is", "running", "in", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/shellingham/nt.py#L106-L128
[ "def", "get_shell", "(", "pid", "=", "None", ",", "max_depth", "=", "6", ")", ":", "if", "not", "pid", ":", "pid", "=", "os", ".", "getpid", "(", ")", "processes", "=", "dict", "(", "_iter_process", "(", ")", ")", "def", "check_parent", "(", "pid",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ParamType.fail
Helper method to fail with an invalid value message.
pipenv/vendor/click/types.py
def fail(self, message, param=None, ctx=None): """Helper method to fail with an invalid value message.""" raise BadParameter(message, ctx=ctx, param=param)
def fail(self, message, param=None, ctx=None): """Helper method to fail with an invalid value message.""" raise BadParameter(message, ctx=ctx, param=param)
[ "Helper", "method", "to", "fail", "with", "an", "invalid", "value", "message", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/types.py#L67-L69
[ "def", "fail", "(", "self", ",", "message", ",", "param", "=", "None", ",", "ctx", "=", "None", ")", ":", "raise", "BadParameter", "(", "message", ",", "ctx", "=", "ctx", ",", "param", "=", "param", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
user_cache_dir
r""" Return full path to the user-specific cache dir for this application. "appname" is the name of application. Typical user cache directories are: macOS: ~/Library/Caches/<AppName> Unix: ~/.cache/<AppName> (XDG default) Windows: C:\Users\<username>\AppData\Local\<AppName>\Cache On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming app data dir (the default returned by `user_data_dir`). Apps typically put cache data somewhere *under* the given dir here. Some examples: ...\Mozilla\Firefox\Profiles\<ProfileName>\Cache ...\Acme\SuperApp\Cache\1.0 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value.
pipenv/patched/notpip/_internal/utils/appdirs.py
def user_cache_dir(appname): # type: (str) -> str r""" Return full path to the user-specific cache dir for this application. "appname" is the name of application. Typical user cache directories are: macOS: ~/Library/Caches/<AppName> Unix: ~/.cache/<AppName> (XDG default) Windows: C:\Users\<username>\AppData\Local\<AppName>\Cache On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming app data dir (the default returned by `user_data_dir`). Apps typically put cache data somewhere *under* the given dir here. Some examples: ...\Mozilla\Firefox\Profiles\<ProfileName>\Cache ...\Acme\SuperApp\Cache\1.0 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. """ if WINDOWS: # Get the base path path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) # When using Python 2, return paths as bytes on Windows like we do on # other operating systems. See helper function docs for more details. if PY2 and isinstance(path, text_type): path = _win_path_to_bytes(path) # Add our app name and Cache directory to it path = os.path.join(path, appname, "Cache") elif sys.platform == "darwin": # Get the base path path = expanduser("~/Library/Caches") # Add our app name to it path = os.path.join(path, appname) else: # Get the base path path = os.getenv("XDG_CACHE_HOME", expanduser("~/.cache")) # Add our app name to it path = os.path.join(path, appname) return path
def user_cache_dir(appname): # type: (str) -> str r""" Return full path to the user-specific cache dir for this application. "appname" is the name of application. Typical user cache directories are: macOS: ~/Library/Caches/<AppName> Unix: ~/.cache/<AppName> (XDG default) Windows: C:\Users\<username>\AppData\Local\<AppName>\Cache On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming app data dir (the default returned by `user_data_dir`). Apps typically put cache data somewhere *under* the given dir here. Some examples: ...\Mozilla\Firefox\Profiles\<ProfileName>\Cache ...\Acme\SuperApp\Cache\1.0 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. """ if WINDOWS: # Get the base path path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) # When using Python 2, return paths as bytes on Windows like we do on # other operating systems. See helper function docs for more details. if PY2 and isinstance(path, text_type): path = _win_path_to_bytes(path) # Add our app name and Cache directory to it path = os.path.join(path, appname, "Cache") elif sys.platform == "darwin": # Get the base path path = expanduser("~/Library/Caches") # Add our app name to it path = os.path.join(path, appname) else: # Get the base path path = os.getenv("XDG_CACHE_HOME", expanduser("~/.cache")) # Add our app name to it path = os.path.join(path, appname) return path
[ "r", "Return", "full", "path", "to", "the", "user", "-", "specific", "cache", "dir", "for", "this", "application", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/appdirs.py#L21-L67
[ "def", "user_cache_dir", "(", "appname", ")", ":", "# type: (str) -> str", "if", "WINDOWS", ":", "# Get the base path", "path", "=", "os", ".", "path", ".", "normpath", "(", "_get_win_folder", "(", "\"CSIDL_LOCAL_APPDATA\"", ")", ")", "# When using Python 2, return pa...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
auto_decode
Check a bytes string for a BOM to correctly detect the encoding Fallback to locale.getpreferredencoding(False) like open() on Python3
pipenv/patched/notpip/_internal/utils/encoding.py
def auto_decode(data): # type: (bytes) -> Text """Check a bytes string for a BOM to correctly detect the encoding Fallback to locale.getpreferredencoding(False) like open() on Python3""" for bom, encoding in BOMS: if data.startswith(bom): return data[len(bom):].decode(encoding) # Lets check the first two lines as in PEP263 for line in data.split(b'\n')[:2]: if line[0:1] == b'#' and ENCODING_RE.search(line): encoding = ENCODING_RE.search(line).groups()[0].decode('ascii') return data.decode(encoding) return data.decode( locale.getpreferredencoding(False) or sys.getdefaultencoding(), )
def auto_decode(data): # type: (bytes) -> Text """Check a bytes string for a BOM to correctly detect the encoding Fallback to locale.getpreferredencoding(False) like open() on Python3""" for bom, encoding in BOMS: if data.startswith(bom): return data[len(bom):].decode(encoding) # Lets check the first two lines as in PEP263 for line in data.split(b'\n')[:2]: if line[0:1] == b'#' and ENCODING_RE.search(line): encoding = ENCODING_RE.search(line).groups()[0].decode('ascii') return data.decode(encoding) return data.decode( locale.getpreferredencoding(False) or sys.getdefaultencoding(), )
[ "Check", "a", "bytes", "string", "for", "a", "BOM", "to", "correctly", "detect", "the", "encoding" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/encoding.py#L24-L39
[ "def", "auto_decode", "(", "data", ")", ":", "# type: (bytes) -> Text", "for", "bom", ",", "encoding", "in", "BOMS", ":", "if", "data", ".", "startswith", "(", "bom", ")", ":", "return", "data", "[", "len", "(", "bom", ")", ":", "]", ".", "decode", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
resolve_color_default
Internal helper to get the default value of the color flag. If a value is passed it's returned unchanged, otherwise it's looked up from the current context.
pipenv/vendor/click/globals.py
def resolve_color_default(color=None): """"Internal helper to get the default value of the color flag. If a value is passed it's returned unchanged, otherwise it's looked up from the current context. """ if color is not None: return color ctx = get_current_context(silent=True) if ctx is not None: return ctx.color
def resolve_color_default(color=None): """"Internal helper to get the default value of the color flag. If a value is passed it's returned unchanged, otherwise it's looked up from the current context. """ if color is not None: return color ctx = get_current_context(silent=True) if ctx is not None: return ctx.color
[ "Internal", "helper", "to", "get", "the", "default", "value", "of", "the", "color", "flag", ".", "If", "a", "value", "is", "passed", "it", "s", "returned", "unchanged", "otherwise", "it", "s", "looked", "up", "from", "the", "current", "context", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/globals.py#L39-L48
[ "def", "resolve_color_default", "(", "color", "=", "None", ")", ":", "if", "color", "is", "not", "None", ":", "return", "color", "ctx", "=", "get_current_context", "(", "silent", "=", "True", ")", "if", "ctx", "is", "not", "None", ":", "return", "ctx", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
load
Parses named file or files as toml and returns a dictionary Args: f: Path to the file to open, array of files to read into single dict or a file descriptor _dict: (optional) Specifies the class of the returned toml dictionary Returns: Parsed toml file represented as a dictionary Raises: TypeError -- When f is invalid type TomlDecodeError: Error while decoding toml IOError / FileNotFoundError -- When an array with no valid (existing) (Python 2 / Python 3) file paths is passed
pipenv/vendor/toml/decoder.py
def load(f, _dict=dict, decoder=None): """Parses named file or files as toml and returns a dictionary Args: f: Path to the file to open, array of files to read into single dict or a file descriptor _dict: (optional) Specifies the class of the returned toml dictionary Returns: Parsed toml file represented as a dictionary Raises: TypeError -- When f is invalid type TomlDecodeError: Error while decoding toml IOError / FileNotFoundError -- When an array with no valid (existing) (Python 2 / Python 3) file paths is passed """ if _ispath(f): with io.open(_getpath(f), encoding='utf-8') as ffile: return loads(ffile.read(), _dict, decoder) elif isinstance(f, list): from os import path as op from warnings import warn if not [path for path in f if op.exists(path)]: error_msg = "Load expects a list to contain filenames only." error_msg += linesep error_msg += ("The list needs to contain the path of at least one " "existing file.") raise FNFError(error_msg) if decoder is None: decoder = TomlDecoder() d = decoder.get_empty_table() for l in f: if op.exists(l): d.update(load(l, _dict, decoder)) else: warn("Non-existent filename in list with at least one valid " "filename") return d else: try: return loads(f.read(), _dict, decoder) except AttributeError: raise TypeError("You can only load a file descriptor, filename or " "list")
def load(f, _dict=dict, decoder=None): """Parses named file or files as toml and returns a dictionary Args: f: Path to the file to open, array of files to read into single dict or a file descriptor _dict: (optional) Specifies the class of the returned toml dictionary Returns: Parsed toml file represented as a dictionary Raises: TypeError -- When f is invalid type TomlDecodeError: Error while decoding toml IOError / FileNotFoundError -- When an array with no valid (existing) (Python 2 / Python 3) file paths is passed """ if _ispath(f): with io.open(_getpath(f), encoding='utf-8') as ffile: return loads(ffile.read(), _dict, decoder) elif isinstance(f, list): from os import path as op from warnings import warn if not [path for path in f if op.exists(path)]: error_msg = "Load expects a list to contain filenames only." error_msg += linesep error_msg += ("The list needs to contain the path of at least one " "existing file.") raise FNFError(error_msg) if decoder is None: decoder = TomlDecoder() d = decoder.get_empty_table() for l in f: if op.exists(l): d.update(load(l, _dict, decoder)) else: warn("Non-existent filename in list with at least one valid " "filename") return d else: try: return loads(f.read(), _dict, decoder) except AttributeError: raise TypeError("You can only load a file descriptor, filename or " "list")
[ "Parses", "named", "file", "or", "files", "as", "toml", "and", "returns", "a", "dictionary" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/toml/decoder.py#L92-L137
[ "def", "load", "(", "f", ",", "_dict", "=", "dict", ",", "decoder", "=", "None", ")", ":", "if", "_ispath", "(", "f", ")", ":", "with", "io", ".", "open", "(", "_getpath", "(", "f", ")", ",", "encoding", "=", "'utf-8'", ")", "as", "ffile", ":",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
loads
Parses string as toml Args: s: String to be parsed _dict: (optional) Specifies the class of the returned toml dictionary Returns: Parsed toml file represented as a dictionary Raises: TypeError: When a non-string is passed TomlDecodeError: Error while decoding toml
pipenv/vendor/toml/decoder.py
def loads(s, _dict=dict, decoder=None): """Parses string as toml Args: s: String to be parsed _dict: (optional) Specifies the class of the returned toml dictionary Returns: Parsed toml file represented as a dictionary Raises: TypeError: When a non-string is passed TomlDecodeError: Error while decoding toml """ implicitgroups = [] if decoder is None: decoder = TomlDecoder(_dict) retval = decoder.get_empty_table() currentlevel = retval if not isinstance(s, basestring): raise TypeError("Expecting something like a string") if not isinstance(s, unicode): s = s.decode('utf8') original = s sl = list(s) openarr = 0 openstring = False openstrchar = "" multilinestr = False arrayoftables = False beginline = True keygroup = False dottedkey = False keyname = 0 for i, item in enumerate(sl): if item == '\r' and sl[i + 1] == '\n': sl[i] = ' ' continue if keyname: if item == '\n': raise TomlDecodeError("Key name found without value." " Reached end of line.", original, i) if openstring: if item == openstrchar: keyname = 2 openstring = False openstrchar = "" continue elif keyname == 1: if item.isspace(): keyname = 2 continue elif item == '.': dottedkey = True continue elif item.isalnum() or item == '_' or item == '-': continue elif (dottedkey and sl[i - 1] == '.' and (item == '"' or item == "'")): openstring = True openstrchar = item continue elif keyname == 2: if item.isspace(): if dottedkey: nextitem = sl[i + 1] if not nextitem.isspace() and nextitem != '.': keyname = 1 continue if item == '.': dottedkey = True nextitem = sl[i + 1] if not nextitem.isspace() and nextitem != '.': keyname = 1 continue if item == '=': keyname = 0 dottedkey = False else: raise TomlDecodeError("Found invalid character in key name: '" + item + "'. Try quoting the key name.", original, i) if item == "'" and openstrchar != '"': k = 1 try: while sl[i - k] == "'": k += 1 if k == 3: break except IndexError: pass if k == 3: multilinestr = not multilinestr openstring = multilinestr else: openstring = not openstring if openstring: openstrchar = "'" else: openstrchar = "" if item == '"' and openstrchar != "'": oddbackslash = False k = 1 tripquote = False try: while sl[i - k] == '"': k += 1 if k == 3: tripquote = True break if k == 1 or (k == 3 and tripquote): while sl[i - k] == '\\': oddbackslash = not oddbackslash k += 1 except IndexError: pass if not oddbackslash: if tripquote: multilinestr = not multilinestr openstring = multilinestr else: openstring = not openstring if openstring: openstrchar = '"' else: openstrchar = "" if item == '#' and (not openstring and not keygroup and not arrayoftables): j = i try: while sl[j] != '\n': sl[j] = ' ' j += 1 except IndexError: break if item == '[' and (not openstring and not keygroup and not arrayoftables): if beginline: if len(sl) > i + 1 and sl[i + 1] == '[': arrayoftables = True else: keygroup = True else: openarr += 1 if item == ']' and not openstring: if keygroup: keygroup = False elif arrayoftables: if sl[i - 1] == ']': arrayoftables = False else: openarr -= 1 if item == '\n': if openstring or multilinestr: if not multilinestr: raise TomlDecodeError("Unbalanced quotes", original, i) if ((sl[i - 1] == "'" or sl[i - 1] == '"') and ( sl[i - 2] == sl[i - 1])): sl[i] = sl[i - 1] if sl[i - 3] == sl[i - 1]: sl[i - 3] = ' ' elif openarr: sl[i] = ' ' else: beginline = True elif beginline and sl[i] != ' ' and sl[i] != '\t': beginline = False if not keygroup and not arrayoftables: if sl[i] == '=': raise TomlDecodeError("Found empty keyname. ", original, i) keyname = 1 s = ''.join(sl) s = s.split('\n') multikey = None multilinestr = "" multibackslash = False pos = 0 for idx, line in enumerate(s): if idx > 0: pos += len(s[idx - 1]) + 1 if not multilinestr or multibackslash or '\n' not in multilinestr: line = line.strip() if line == "" and (not multikey or multibackslash): continue if multikey: if multibackslash: multilinestr += line else: multilinestr += line multibackslash = False if len(line) > 2 and (line[-1] == multilinestr[0] and line[-2] == multilinestr[0] and line[-3] == multilinestr[0]): try: value, vtype = decoder.load_value(multilinestr) except ValueError as err: raise TomlDecodeError(str(err), original, pos) currentlevel[multikey] = value multikey = None multilinestr = "" else: k = len(multilinestr) - 1 while k > -1 and multilinestr[k] == '\\': multibackslash = not multibackslash k -= 1 if multibackslash: multilinestr = multilinestr[:-1] else: multilinestr += "\n" continue if line[0] == '[': arrayoftables = False if len(line) == 1: raise TomlDecodeError("Opening key group bracket on line by " "itself.", original, pos) if line[1] == '[': arrayoftables = True line = line[2:] splitstr = ']]' else: line = line[1:] splitstr = ']' i = 1 quotesplits = decoder._get_split_on_quotes(line) quoted = False for quotesplit in quotesplits: if not quoted and splitstr in quotesplit: break i += quotesplit.count(splitstr) quoted = not quoted line = line.split(splitstr, i) if len(line) < i + 1 or line[-1].strip() != "": raise TomlDecodeError("Key group not on a line by itself.", original, pos) groups = splitstr.join(line[:-1]).split('.') i = 0 while i < len(groups): groups[i] = groups[i].strip() if len(groups[i]) > 0 and (groups[i][0] == '"' or groups[i][0] == "'"): groupstr = groups[i] j = i + 1 while not groupstr[0] == groupstr[-1]: j += 1 if j > len(groups) + 2: raise TomlDecodeError("Invalid group name '" + groupstr + "' Something " + "went wrong.", original, pos) groupstr = '.'.join(groups[i:j]).strip() groups[i] = groupstr[1:-1] groups[i + 1:j] = [] else: if not _groupname_re.match(groups[i]): raise TomlDecodeError("Invalid group name '" + groups[i] + "'. Try quoting it.", original, pos) i += 1 currentlevel = retval for i in _range(len(groups)): group = groups[i] if group == "": raise TomlDecodeError("Can't have a keygroup with an empty " "name", original, pos) try: currentlevel[group] if i == len(groups) - 1: if group in implicitgroups: implicitgroups.remove(group) if arrayoftables: raise TomlDecodeError("An implicitly defined " "table can't be an array", original, pos) elif arrayoftables: currentlevel[group].append(decoder.get_empty_table() ) else: raise TomlDecodeError("What? " + group + " already exists?" + str(currentlevel), original, pos) except TypeError: currentlevel = currentlevel[-1] if group not in currentlevel: currentlevel[group] = decoder.get_empty_table() if i == len(groups) - 1 and arrayoftables: currentlevel[group] = [decoder.get_empty_table()] except KeyError: if i != len(groups) - 1: implicitgroups.append(group) currentlevel[group] = decoder.get_empty_table() if i == len(groups) - 1 and arrayoftables: currentlevel[group] = [decoder.get_empty_table()] currentlevel = currentlevel[group] if arrayoftables: try: currentlevel = currentlevel[-1] except KeyError: pass elif line[0] == "{": if line[-1] != "}": raise TomlDecodeError("Line breaks are not allowed in inline" "objects", original, pos) try: decoder.load_inline_object(line, currentlevel, multikey, multibackslash) except ValueError as err: raise TomlDecodeError(str(err), original, pos) elif "=" in line: try: ret = decoder.load_line(line, currentlevel, multikey, multibackslash) except ValueError as err: raise TomlDecodeError(str(err), original, pos) if ret is not None: multikey, multilinestr, multibackslash = ret return retval
def loads(s, _dict=dict, decoder=None): """Parses string as toml Args: s: String to be parsed _dict: (optional) Specifies the class of the returned toml dictionary Returns: Parsed toml file represented as a dictionary Raises: TypeError: When a non-string is passed TomlDecodeError: Error while decoding toml """ implicitgroups = [] if decoder is None: decoder = TomlDecoder(_dict) retval = decoder.get_empty_table() currentlevel = retval if not isinstance(s, basestring): raise TypeError("Expecting something like a string") if not isinstance(s, unicode): s = s.decode('utf8') original = s sl = list(s) openarr = 0 openstring = False openstrchar = "" multilinestr = False arrayoftables = False beginline = True keygroup = False dottedkey = False keyname = 0 for i, item in enumerate(sl): if item == '\r' and sl[i + 1] == '\n': sl[i] = ' ' continue if keyname: if item == '\n': raise TomlDecodeError("Key name found without value." " Reached end of line.", original, i) if openstring: if item == openstrchar: keyname = 2 openstring = False openstrchar = "" continue elif keyname == 1: if item.isspace(): keyname = 2 continue elif item == '.': dottedkey = True continue elif item.isalnum() or item == '_' or item == '-': continue elif (dottedkey and sl[i - 1] == '.' and (item == '"' or item == "'")): openstring = True openstrchar = item continue elif keyname == 2: if item.isspace(): if dottedkey: nextitem = sl[i + 1] if not nextitem.isspace() and nextitem != '.': keyname = 1 continue if item == '.': dottedkey = True nextitem = sl[i + 1] if not nextitem.isspace() and nextitem != '.': keyname = 1 continue if item == '=': keyname = 0 dottedkey = False else: raise TomlDecodeError("Found invalid character in key name: '" + item + "'. Try quoting the key name.", original, i) if item == "'" and openstrchar != '"': k = 1 try: while sl[i - k] == "'": k += 1 if k == 3: break except IndexError: pass if k == 3: multilinestr = not multilinestr openstring = multilinestr else: openstring = not openstring if openstring: openstrchar = "'" else: openstrchar = "" if item == '"' and openstrchar != "'": oddbackslash = False k = 1 tripquote = False try: while sl[i - k] == '"': k += 1 if k == 3: tripquote = True break if k == 1 or (k == 3 and tripquote): while sl[i - k] == '\\': oddbackslash = not oddbackslash k += 1 except IndexError: pass if not oddbackslash: if tripquote: multilinestr = not multilinestr openstring = multilinestr else: openstring = not openstring if openstring: openstrchar = '"' else: openstrchar = "" if item == '#' and (not openstring and not keygroup and not arrayoftables): j = i try: while sl[j] != '\n': sl[j] = ' ' j += 1 except IndexError: break if item == '[' and (not openstring and not keygroup and not arrayoftables): if beginline: if len(sl) > i + 1 and sl[i + 1] == '[': arrayoftables = True else: keygroup = True else: openarr += 1 if item == ']' and not openstring: if keygroup: keygroup = False elif arrayoftables: if sl[i - 1] == ']': arrayoftables = False else: openarr -= 1 if item == '\n': if openstring or multilinestr: if not multilinestr: raise TomlDecodeError("Unbalanced quotes", original, i) if ((sl[i - 1] == "'" or sl[i - 1] == '"') and ( sl[i - 2] == sl[i - 1])): sl[i] = sl[i - 1] if sl[i - 3] == sl[i - 1]: sl[i - 3] = ' ' elif openarr: sl[i] = ' ' else: beginline = True elif beginline and sl[i] != ' ' and sl[i] != '\t': beginline = False if not keygroup and not arrayoftables: if sl[i] == '=': raise TomlDecodeError("Found empty keyname. ", original, i) keyname = 1 s = ''.join(sl) s = s.split('\n') multikey = None multilinestr = "" multibackslash = False pos = 0 for idx, line in enumerate(s): if idx > 0: pos += len(s[idx - 1]) + 1 if not multilinestr or multibackslash or '\n' not in multilinestr: line = line.strip() if line == "" and (not multikey or multibackslash): continue if multikey: if multibackslash: multilinestr += line else: multilinestr += line multibackslash = False if len(line) > 2 and (line[-1] == multilinestr[0] and line[-2] == multilinestr[0] and line[-3] == multilinestr[0]): try: value, vtype = decoder.load_value(multilinestr) except ValueError as err: raise TomlDecodeError(str(err), original, pos) currentlevel[multikey] = value multikey = None multilinestr = "" else: k = len(multilinestr) - 1 while k > -1 and multilinestr[k] == '\\': multibackslash = not multibackslash k -= 1 if multibackslash: multilinestr = multilinestr[:-1] else: multilinestr += "\n" continue if line[0] == '[': arrayoftables = False if len(line) == 1: raise TomlDecodeError("Opening key group bracket on line by " "itself.", original, pos) if line[1] == '[': arrayoftables = True line = line[2:] splitstr = ']]' else: line = line[1:] splitstr = ']' i = 1 quotesplits = decoder._get_split_on_quotes(line) quoted = False for quotesplit in quotesplits: if not quoted and splitstr in quotesplit: break i += quotesplit.count(splitstr) quoted = not quoted line = line.split(splitstr, i) if len(line) < i + 1 or line[-1].strip() != "": raise TomlDecodeError("Key group not on a line by itself.", original, pos) groups = splitstr.join(line[:-1]).split('.') i = 0 while i < len(groups): groups[i] = groups[i].strip() if len(groups[i]) > 0 and (groups[i][0] == '"' or groups[i][0] == "'"): groupstr = groups[i] j = i + 1 while not groupstr[0] == groupstr[-1]: j += 1 if j > len(groups) + 2: raise TomlDecodeError("Invalid group name '" + groupstr + "' Something " + "went wrong.", original, pos) groupstr = '.'.join(groups[i:j]).strip() groups[i] = groupstr[1:-1] groups[i + 1:j] = [] else: if not _groupname_re.match(groups[i]): raise TomlDecodeError("Invalid group name '" + groups[i] + "'. Try quoting it.", original, pos) i += 1 currentlevel = retval for i in _range(len(groups)): group = groups[i] if group == "": raise TomlDecodeError("Can't have a keygroup with an empty " "name", original, pos) try: currentlevel[group] if i == len(groups) - 1: if group in implicitgroups: implicitgroups.remove(group) if arrayoftables: raise TomlDecodeError("An implicitly defined " "table can't be an array", original, pos) elif arrayoftables: currentlevel[group].append(decoder.get_empty_table() ) else: raise TomlDecodeError("What? " + group + " already exists?" + str(currentlevel), original, pos) except TypeError: currentlevel = currentlevel[-1] if group not in currentlevel: currentlevel[group] = decoder.get_empty_table() if i == len(groups) - 1 and arrayoftables: currentlevel[group] = [decoder.get_empty_table()] except KeyError: if i != len(groups) - 1: implicitgroups.append(group) currentlevel[group] = decoder.get_empty_table() if i == len(groups) - 1 and arrayoftables: currentlevel[group] = [decoder.get_empty_table()] currentlevel = currentlevel[group] if arrayoftables: try: currentlevel = currentlevel[-1] except KeyError: pass elif line[0] == "{": if line[-1] != "}": raise TomlDecodeError("Line breaks are not allowed in inline" "objects", original, pos) try: decoder.load_inline_object(line, currentlevel, multikey, multibackslash) except ValueError as err: raise TomlDecodeError(str(err), original, pos) elif "=" in line: try: ret = decoder.load_line(line, currentlevel, multikey, multibackslash) except ValueError as err: raise TomlDecodeError(str(err), original, pos) if ret is not None: multikey, multilinestr, multibackslash = ret return retval
[ "Parses", "string", "as", "toml" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/toml/decoder.py#L143-L461
[ "def", "loads", "(", "s", ",", "_dict", "=", "dict", ",", "decoder", "=", "None", ")", ":", "implicitgroups", "=", "[", "]", "if", "decoder", "is", "None", ":", "decoder", "=", "TomlDecoder", "(", "_dict", ")", "retval", "=", "decoder", ".", "get_emp...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
markup_join
Concatenation that escapes if necessary and converts to unicode.
pipenv/vendor/jinja2/runtime.py
def markup_join(seq): """Concatenation that escapes if necessary and converts to unicode.""" buf = [] iterator = imap(soft_unicode, seq) for arg in iterator: buf.append(arg) if hasattr(arg, '__html__'): return Markup(u'').join(chain(buf, iterator)) return concat(buf)
def markup_join(seq): """Concatenation that escapes if necessary and converts to unicode.""" buf = [] iterator = imap(soft_unicode, seq) for arg in iterator: buf.append(arg) if hasattr(arg, '__html__'): return Markup(u'').join(chain(buf, iterator)) return concat(buf)
[ "Concatenation", "that", "escapes", "if", "necessary", "and", "converts", "to", "unicode", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/runtime.py#L43-L51
[ "def", "markup_join", "(", "seq", ")", ":", "buf", "=", "[", "]", "iterator", "=", "imap", "(", "soft_unicode", ",", "seq", ")", "for", "arg", "in", "iterator", ":", "buf", ".", "append", "(", "arg", ")", "if", "hasattr", "(", "arg", ",", "'__html_...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
new_context
Internal helper to for context creation.
pipenv/vendor/jinja2/runtime.py
def new_context(environment, template_name, blocks, vars=None, shared=None, globals=None, locals=None): """Internal helper to for context creation.""" if vars is None: vars = {} if shared: parent = vars else: parent = dict(globals or (), **vars) if locals: # if the parent is shared a copy should be created because # we don't want to modify the dict passed if shared: parent = dict(parent) for key, value in iteritems(locals): if value is not missing: parent[key] = value return environment.context_class(environment, parent, template_name, blocks)
def new_context(environment, template_name, blocks, vars=None, shared=None, globals=None, locals=None): """Internal helper to for context creation.""" if vars is None: vars = {} if shared: parent = vars else: parent = dict(globals or (), **vars) if locals: # if the parent is shared a copy should be created because # we don't want to modify the dict passed if shared: parent = dict(parent) for key, value in iteritems(locals): if value is not missing: parent[key] = value return environment.context_class(environment, parent, template_name, blocks)
[ "Internal", "helper", "to", "for", "context", "creation", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/runtime.py#L59-L77
[ "def", "new_context", "(", "environment", ",", "template_name", ",", "blocks", ",", "vars", "=", "None", ",", "shared", "=", "None", ",", "globals", "=", "None", ",", "locals", "=", "None", ")", ":", "if", "vars", "is", "None", ":", "vars", "=", "{",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
make_logging_undefined
Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined ) .. versionadded:: 2.8 :param logger: the logger to use. If not provided, a default logger is created. :param base: the base class to add logging functionality to. This defaults to :class:`Undefined`.
pipenv/vendor/jinja2/runtime.py
def make_logging_undefined(logger=None, base=None): """Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined ) .. versionadded:: 2.8 :param logger: the logger to use. If not provided, a default logger is created. :param base: the base class to add logging functionality to. This defaults to :class:`Undefined`. """ if logger is None: import logging logger = logging.getLogger(__name__) logger.addHandler(logging.StreamHandler(sys.stderr)) if base is None: base = Undefined def _log_message(undef): if undef._undefined_hint is None: if undef._undefined_obj is missing: hint = '%s is undefined' % undef._undefined_name elif not isinstance(undef._undefined_name, string_types): hint = '%s has no element %s' % ( object_type_repr(undef._undefined_obj), undef._undefined_name) else: hint = '%s has no attribute %s' % ( object_type_repr(undef._undefined_obj), undef._undefined_name) else: hint = undef._undefined_hint logger.warning('Template variable warning: %s', hint) class LoggingUndefined(base): def _fail_with_undefined_error(self, *args, **kwargs): try: return base._fail_with_undefined_error(self, *args, **kwargs) except self._undefined_exception as e: logger.error('Template variable error: %s', str(e)) raise e def __str__(self): rv = base.__str__(self) _log_message(self) return rv def __iter__(self): rv = base.__iter__(self) _log_message(self) return rv if PY2: def __nonzero__(self): rv = base.__nonzero__(self) _log_message(self) return rv def __unicode__(self): rv = base.__unicode__(self) _log_message(self) return rv else: def __bool__(self): rv = base.__bool__(self) _log_message(self) return rv return LoggingUndefined
def make_logging_undefined(logger=None, base=None): """Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined ) .. versionadded:: 2.8 :param logger: the logger to use. If not provided, a default logger is created. :param base: the base class to add logging functionality to. This defaults to :class:`Undefined`. """ if logger is None: import logging logger = logging.getLogger(__name__) logger.addHandler(logging.StreamHandler(sys.stderr)) if base is None: base = Undefined def _log_message(undef): if undef._undefined_hint is None: if undef._undefined_obj is missing: hint = '%s is undefined' % undef._undefined_name elif not isinstance(undef._undefined_name, string_types): hint = '%s has no element %s' % ( object_type_repr(undef._undefined_obj), undef._undefined_name) else: hint = '%s has no attribute %s' % ( object_type_repr(undef._undefined_obj), undef._undefined_name) else: hint = undef._undefined_hint logger.warning('Template variable warning: %s', hint) class LoggingUndefined(base): def _fail_with_undefined_error(self, *args, **kwargs): try: return base._fail_with_undefined_error(self, *args, **kwargs) except self._undefined_exception as e: logger.error('Template variable error: %s', str(e)) raise e def __str__(self): rv = base.__str__(self) _log_message(self) return rv def __iter__(self): rv = base.__iter__(self) _log_message(self) return rv if PY2: def __nonzero__(self): rv = base.__nonzero__(self) _log_message(self) return rv def __unicode__(self): rv = base.__unicode__(self) _log_message(self) return rv else: def __bool__(self): rv = base.__bool__(self) _log_message(self) return rv return LoggingUndefined
[ "Given", "a", "logger", "object", "this", "returns", "a", "new", "undefined", "class", "that", "will", "log", "certain", "failures", ".", "It", "will", "log", "iterations", "and", "printing", ".", "If", "no", "logger", "is", "given", "a", "default", "logge...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/runtime.py#L677-L755
[ "def", "make_logging_undefined", "(", "logger", "=", "None", ",", "base", "=", "None", ")", ":", "if", "logger", "is", "None", ":", "import", "logging", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "addHandler", "(", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Context.super
Render a parent block.
pipenv/vendor/jinja2/runtime.py
def super(self, name, current): """Render a parent block.""" try: blocks = self.blocks[name] index = blocks.index(current) + 1 blocks[index] except LookupError: return self.environment.undefined('there is no parent block ' 'called %r.' % name, name='super') return BlockReference(name, self, blocks, index)
def super(self, name, current): """Render a parent block.""" try: blocks = self.blocks[name] index = blocks.index(current) + 1 blocks[index] except LookupError: return self.environment.undefined('there is no parent block ' 'called %r.' % name, name='super') return BlockReference(name, self, blocks, index)
[ "Render", "a", "parent", "block", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/runtime.py#L175-L185
[ "def", "super", "(", "self", ",", "name", ",", "current", ")", ":", "try", ":", "blocks", "=", "self", ".", "blocks", "[", "name", "]", "index", "=", "blocks", ".", "index", "(", "current", ")", "+", "1", "blocks", "[", "index", "]", "except", "L...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Context.resolve
Looks up a variable like `__getitem__` or `get` but returns an :class:`Undefined` object with the name of the name looked up.
pipenv/vendor/jinja2/runtime.py
def resolve(self, key): """Looks up a variable like `__getitem__` or `get` but returns an :class:`Undefined` object with the name of the name looked up. """ if self._legacy_resolve_mode: rv = resolve_or_missing(self, key) else: rv = self.resolve_or_missing(key) if rv is missing: return self.environment.undefined(name=key) return rv
def resolve(self, key): """Looks up a variable like `__getitem__` or `get` but returns an :class:`Undefined` object with the name of the name looked up. """ if self._legacy_resolve_mode: rv = resolve_or_missing(self, key) else: rv = self.resolve_or_missing(key) if rv is missing: return self.environment.undefined(name=key) return rv
[ "Looks", "up", "a", "variable", "like", "__getitem__", "or", "get", "but", "returns", "an", ":", "class", ":", "Undefined", "object", "with", "the", "name", "of", "the", "name", "looked", "up", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/runtime.py#L196-L206
[ "def", "resolve", "(", "self", ",", "key", ")", ":", "if", "self", ".", "_legacy_resolve_mode", ":", "rv", "=", "resolve_or_missing", "(", "self", ",", "key", ")", "else", ":", "rv", "=", "self", ".", "resolve_or_missing", "(", "key", ")", "if", "rv", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Context.resolve_or_missing
Resolves a variable like :meth:`resolve` but returns the special `missing` value if it cannot be found.
pipenv/vendor/jinja2/runtime.py
def resolve_or_missing(self, key): """Resolves a variable like :meth:`resolve` but returns the special `missing` value if it cannot be found. """ if self._legacy_resolve_mode: rv = self.resolve(key) if isinstance(rv, Undefined): rv = missing return rv return resolve_or_missing(self, key)
def resolve_or_missing(self, key): """Resolves a variable like :meth:`resolve` but returns the special `missing` value if it cannot be found. """ if self._legacy_resolve_mode: rv = self.resolve(key) if isinstance(rv, Undefined): rv = missing return rv return resolve_or_missing(self, key)
[ "Resolves", "a", "variable", "like", ":", "meth", ":", "resolve", "but", "returns", "the", "special", "missing", "value", "if", "it", "cannot", "be", "found", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/runtime.py#L208-L217
[ "def", "resolve_or_missing", "(", "self", ",", "key", ")", ":", "if", "self", ".", "_legacy_resolve_mode", ":", "rv", "=", "self", ".", "resolve", "(", "key", ")", "if", "isinstance", "(", "rv", ",", "Undefined", ")", ":", "rv", "=", "missing", "return...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Context.get_exported
Get a new dict with the exported variables.
pipenv/vendor/jinja2/runtime.py
def get_exported(self): """Get a new dict with the exported variables.""" return dict((k, self.vars[k]) for k in self.exported_vars)
def get_exported(self): """Get a new dict with the exported variables.""" return dict((k, self.vars[k]) for k in self.exported_vars)
[ "Get", "a", "new", "dict", "with", "the", "exported", "variables", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/runtime.py#L219-L221
[ "def", "get_exported", "(", "self", ")", ":", "return", "dict", "(", "(", "k", ",", "self", ".", "vars", "[", "k", "]", ")", "for", "k", "in", "self", ".", "exported_vars", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Context.get_all
Return the complete context as dict including the exported variables. For optimizations reasons this might not return an actual copy so be careful with using it.
pipenv/vendor/jinja2/runtime.py
def get_all(self): """Return the complete context as dict including the exported variables. For optimizations reasons this might not return an actual copy so be careful with using it. """ if not self.vars: return self.parent if not self.parent: return self.vars return dict(self.parent, **self.vars)
def get_all(self): """Return the complete context as dict including the exported variables. For optimizations reasons this might not return an actual copy so be careful with using it. """ if not self.vars: return self.parent if not self.parent: return self.vars return dict(self.parent, **self.vars)
[ "Return", "the", "complete", "context", "as", "dict", "including", "the", "exported", "variables", ".", "For", "optimizations", "reasons", "this", "might", "not", "return", "an", "actual", "copy", "so", "be", "careful", "with", "using", "it", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/runtime.py#L223-L232
[ "def", "get_all", "(", "self", ")", ":", "if", "not", "self", ".", "vars", ":", "return", "self", ".", "parent", "if", "not", "self", ".", "parent", ":", "return", "self", ".", "vars", "return", "dict", "(", "self", ".", "parent", ",", "*", "*", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Context.derived
Internal helper function to create a derived context. This is used in situations where the system needs a new context in the same template that is independent.
pipenv/vendor/jinja2/runtime.py
def derived(self, locals=None): """Internal helper function to create a derived context. This is used in situations where the system needs a new context in the same template that is independent. """ context = new_context(self.environment, self.name, {}, self.get_all(), True, None, locals) context.eval_ctx = self.eval_ctx context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks)) return context
def derived(self, locals=None): """Internal helper function to create a derived context. This is used in situations where the system needs a new context in the same template that is independent. """ context = new_context(self.environment, self.name, {}, self.get_all(), True, None, locals) context.eval_ctx = self.eval_ctx context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks)) return context
[ "Internal", "helper", "function", "to", "create", "a", "derived", "context", ".", "This", "is", "used", "in", "situations", "where", "the", "system", "needs", "a", "new", "context", "in", "the", "same", "template", "that", "is", "independent", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/runtime.py#L268-L277
[ "def", "derived", "(", "self", ",", "locals", "=", "None", ")", ":", "context", "=", "new_context", "(", "self", ".", "environment", ",", "self", ".", "name", ",", "{", "}", ",", "self", ".", "get_all", "(", ")", ",", "True", ",", "None", ",", "l...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BlockReference.super
Super the block.
pipenv/vendor/jinja2/runtime.py
def super(self): """Super the block.""" if self._depth + 1 >= len(self._stack): return self._context.environment. \ undefined('there is no parent block called %r.' % self.name, name='super') return BlockReference(self.name, self._context, self._stack, self._depth + 1)
def super(self): """Super the block.""" if self._depth + 1 >= len(self._stack): return self._context.environment. \ undefined('there is no parent block called %r.' % self.name, name='super') return BlockReference(self.name, self._context, self._stack, self._depth + 1)
[ "Super", "the", "block", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/runtime.py#L334-L341
[ "def", "super", "(", "self", ")", ":", "if", "self", ".", "_depth", "+", "1", ">=", "len", "(", "self", ".", "_stack", ")", ":", "return", "self", ".", "_context", ".", "environment", ".", "undefined", "(", "'there is no parent block called %r.'", "%", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
LoopContextBase.cycle
Cycles among the arguments with the current loop index.
pipenv/vendor/jinja2/runtime.py
def cycle(self, *args): """Cycles among the arguments with the current loop index.""" if not args: raise TypeError('no items for cycling given') return args[self.index0 % len(args)]
def cycle(self, *args): """Cycles among the arguments with the current loop index.""" if not args: raise TypeError('no items for cycling given') return args[self.index0 % len(args)]
[ "Cycles", "among", "the", "arguments", "with", "the", "current", "loop", "index", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/runtime.py#L366-L370
[ "def", "cycle", "(", "self", ",", "*", "args", ")", ":", "if", "not", "args", ":", "raise", "TypeError", "(", "'no items for cycling given'", ")", "return", "args", "[", "self", ".", "index0", "%", "len", "(", "args", ")", "]" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
LoopContextBase.changed
Checks whether the value has changed since the last call.
pipenv/vendor/jinja2/runtime.py
def changed(self, *value): """Checks whether the value has changed since the last call.""" if self._last_checked_value != value: self._last_checked_value = value return True return False
def changed(self, *value): """Checks whether the value has changed since the last call.""" if self._last_checked_value != value: self._last_checked_value = value return True return False
[ "Checks", "whether", "the", "value", "has", "changed", "since", "the", "last", "call", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/runtime.py#L372-L377
[ "def", "changed", "(", "self", ",", "*", "value", ")", ":", "if", "self", ".", "_last_checked_value", "!=", "value", ":", "self", ".", "_last_checked_value", "=", "value", "return", "True", "return", "False" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Macro._invoke
This method is being swapped out by the async implementation.
pipenv/vendor/jinja2/runtime.py
def _invoke(self, arguments, autoescape): """This method is being swapped out by the async implementation.""" rv = self._func(*arguments) if autoescape: rv = Markup(rv) return rv
def _invoke(self, arguments, autoescape): """This method is being swapped out by the async implementation.""" rv = self._func(*arguments) if autoescape: rv = Markup(rv) return rv
[ "This", "method", "is", "being", "swapped", "out", "by", "the", "async", "implementation", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/runtime.py#L577-L582
[ "def", "_invoke", "(", "self", ",", "arguments", ",", "autoescape", ")", ":", "rv", "=", "self", ".", "_func", "(", "*", "arguments", ")", "if", "autoescape", ":", "rv", "=", "Markup", "(", "rv", ")", "return", "rv" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
main
This is where the example starts and the FSM state transitions are defined. Note that states are strings (such as 'INIT'). This is not necessary, but it makes the example easier to read.
pipenv/vendor/pexpect/FSM.py
def main(): '''This is where the example starts and the FSM state transitions are defined. Note that states are strings (such as 'INIT'). This is not necessary, but it makes the example easier to read. ''' f = FSM ('INIT', []) f.set_default_transition (Error, 'INIT') f.add_transition_any ('INIT', None, 'INIT') f.add_transition ('=', 'INIT', DoEqual, 'INIT') f.add_transition_list (string.digits, 'INIT', BeginBuildNumber, 'BUILDING_NUMBER') f.add_transition_list (string.digits, 'BUILDING_NUMBER', BuildNumber, 'BUILDING_NUMBER') f.add_transition_list (string.whitespace, 'BUILDING_NUMBER', EndBuildNumber, 'INIT') f.add_transition_list ('+-*/', 'INIT', DoOperator, 'INIT') print() print('Enter an RPN Expression.') print('Numbers may be integers. Operators are * / + -') print('Use the = sign to evaluate and print the expression.') print('For example: ') print(' 167 3 2 2 * * * 1 - =') inputstr = (input if PY3 else raw_input)('> ') # analysis:ignore f.process_list(inputstr)
def main(): '''This is where the example starts and the FSM state transitions are defined. Note that states are strings (such as 'INIT'). This is not necessary, but it makes the example easier to read. ''' f = FSM ('INIT', []) f.set_default_transition (Error, 'INIT') f.add_transition_any ('INIT', None, 'INIT') f.add_transition ('=', 'INIT', DoEqual, 'INIT') f.add_transition_list (string.digits, 'INIT', BeginBuildNumber, 'BUILDING_NUMBER') f.add_transition_list (string.digits, 'BUILDING_NUMBER', BuildNumber, 'BUILDING_NUMBER') f.add_transition_list (string.whitespace, 'BUILDING_NUMBER', EndBuildNumber, 'INIT') f.add_transition_list ('+-*/', 'INIT', DoOperator, 'INIT') print() print('Enter an RPN Expression.') print('Numbers may be integers. Operators are * / + -') print('Use the = sign to evaluate and print the expression.') print('For example: ') print(' 167 3 2 2 * * * 1 - =') inputstr = (input if PY3 else raw_input)('> ') # analysis:ignore f.process_list(inputstr)
[ "This", "is", "where", "the", "example", "starts", "and", "the", "FSM", "state", "transitions", "are", "defined", ".", "Note", "that", "states", "are", "strings", "(", "such", "as", "INIT", ")", ".", "This", "is", "not", "necessary", "but", "it", "makes"...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/FSM.py#L308-L330
[ "def", "main", "(", ")", ":", "f", "=", "FSM", "(", "'INIT'", ",", "[", "]", ")", "f", ".", "set_default_transition", "(", "Error", ",", "'INIT'", ")", "f", ".", "add_transition_any", "(", "'INIT'", ",", "None", ",", "'INIT'", ")", "f", ".", "add_t...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
FSM.add_transition
This adds a transition that associates: (input_symbol, current_state) --> (action, next_state) The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. You can also set transitions for a list of symbols by using add_transition_list().
pipenv/vendor/pexpect/FSM.py
def add_transition (self, input_symbol, state, action=None, next_state=None): '''This adds a transition that associates: (input_symbol, current_state) --> (action, next_state) The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. You can also set transitions for a list of symbols by using add_transition_list(). ''' if next_state is None: next_state = state self.state_transitions[(input_symbol, state)] = (action, next_state)
def add_transition (self, input_symbol, state, action=None, next_state=None): '''This adds a transition that associates: (input_symbol, current_state) --> (action, next_state) The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. You can also set transitions for a list of symbols by using add_transition_list(). ''' if next_state is None: next_state = state self.state_transitions[(input_symbol, state)] = (action, next_state)
[ "This", "adds", "a", "transition", "that", "associates", ":" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/FSM.py#L131-L146
[ "def", "add_transition", "(", "self", ",", "input_symbol", ",", "state", ",", "action", "=", "None", ",", "next_state", "=", "None", ")", ":", "if", "next_state", "is", "None", ":", "next_state", "=", "state", "self", ".", "state_transitions", "[", "(", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
FSM.add_transition_list
This adds the same transition for a list of input symbols. You can pass a list or a string. Note that it is handy to use string.digits, string.whitespace, string.letters, etc. to add transitions that match character classes. The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged.
pipenv/vendor/pexpect/FSM.py
def add_transition_list (self, list_input_symbols, state, action=None, next_state=None): '''This adds the same transition for a list of input symbols. You can pass a list or a string. Note that it is handy to use string.digits, string.whitespace, string.letters, etc. to add transitions that match character classes. The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. ''' if next_state is None: next_state = state for input_symbol in list_input_symbols: self.add_transition (input_symbol, state, action, next_state)
def add_transition_list (self, list_input_symbols, state, action=None, next_state=None): '''This adds the same transition for a list of input symbols. You can pass a list or a string. Note that it is handy to use string.digits, string.whitespace, string.letters, etc. to add transitions that match character classes. The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. ''' if next_state is None: next_state = state for input_symbol in list_input_symbols: self.add_transition (input_symbol, state, action, next_state)
[ "This", "adds", "the", "same", "transition", "for", "a", "list", "of", "input", "symbols", ".", "You", "can", "pass", "a", "list", "or", "a", "string", ".", "Note", "that", "it", "is", "handy", "to", "use", "string", ".", "digits", "string", ".", "wh...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/FSM.py#L148-L162
[ "def", "add_transition_list", "(", "self", ",", "list_input_symbols", ",", "state", ",", "action", "=", "None", ",", "next_state", "=", "None", ")", ":", "if", "next_state", "is", "None", ":", "next_state", "=", "state", "for", "input_symbol", "in", "list_in...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
FSM.add_transition_any
This adds a transition that associates: (current_state) --> (action, next_state) That is, any input symbol will match the current state. The process() method checks the "any" state associations after it first checks for an exact match of (input_symbol, current_state). The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged.
pipenv/vendor/pexpect/FSM.py
def add_transition_any (self, state, action=None, next_state=None): '''This adds a transition that associates: (current_state) --> (action, next_state) That is, any input symbol will match the current state. The process() method checks the "any" state associations after it first checks for an exact match of (input_symbol, current_state). The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. ''' if next_state is None: next_state = state self.state_transitions_any [state] = (action, next_state)
def add_transition_any (self, state, action=None, next_state=None): '''This adds a transition that associates: (current_state) --> (action, next_state) That is, any input symbol will match the current state. The process() method checks the "any" state associations after it first checks for an exact match of (input_symbol, current_state). The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. ''' if next_state is None: next_state = state self.state_transitions_any [state] = (action, next_state)
[ "This", "adds", "a", "transition", "that", "associates", ":" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/FSM.py#L164-L180
[ "def", "add_transition_any", "(", "self", ",", "state", ",", "action", "=", "None", ",", "next_state", "=", "None", ")", ":", "if", "next_state", "is", "None", ":", "next_state", "=", "state", "self", ".", "state_transitions_any", "[", "state", "]", "=", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
FSM.get_transition
This returns (action, next state) given an input_symbol and state. This does not modify the FSM state, so calling this method has no side effects. Normally you do not call this method directly. It is called by process(). The sequence of steps to check for a defined transition goes from the most specific to the least specific. 1. Check state_transitions[] that match exactly the tuple, (input_symbol, state) 2. Check state_transitions_any[] that match (state) In other words, match a specific state and ANY input_symbol. 3. Check if the default_transition is defined. This catches any input_symbol and any state. This is a handler for errors, undefined states, or defaults. 4. No transition was defined. If we get here then raise an exception.
pipenv/vendor/pexpect/FSM.py
def get_transition (self, input_symbol, state): '''This returns (action, next state) given an input_symbol and state. This does not modify the FSM state, so calling this method has no side effects. Normally you do not call this method directly. It is called by process(). The sequence of steps to check for a defined transition goes from the most specific to the least specific. 1. Check state_transitions[] that match exactly the tuple, (input_symbol, state) 2. Check state_transitions_any[] that match (state) In other words, match a specific state and ANY input_symbol. 3. Check if the default_transition is defined. This catches any input_symbol and any state. This is a handler for errors, undefined states, or defaults. 4. No transition was defined. If we get here then raise an exception. ''' if (input_symbol, state) in self.state_transitions: return self.state_transitions[(input_symbol, state)] elif state in self.state_transitions_any: return self.state_transitions_any[state] elif self.default_transition is not None: return self.default_transition else: raise ExceptionFSM ('Transition is undefined: (%s, %s).' % (str(input_symbol), str(state)) )
def get_transition (self, input_symbol, state): '''This returns (action, next state) given an input_symbol and state. This does not modify the FSM state, so calling this method has no side effects. Normally you do not call this method directly. It is called by process(). The sequence of steps to check for a defined transition goes from the most specific to the least specific. 1. Check state_transitions[] that match exactly the tuple, (input_symbol, state) 2. Check state_transitions_any[] that match (state) In other words, match a specific state and ANY input_symbol. 3. Check if the default_transition is defined. This catches any input_symbol and any state. This is a handler for errors, undefined states, or defaults. 4. No transition was defined. If we get here then raise an exception. ''' if (input_symbol, state) in self.state_transitions: return self.state_transitions[(input_symbol, state)] elif state in self.state_transitions_any: return self.state_transitions_any[state] elif self.default_transition is not None: return self.default_transition else: raise ExceptionFSM ('Transition is undefined: (%s, %s).' % (str(input_symbol), str(state)) )
[ "This", "returns", "(", "action", "next", "state", ")", "given", "an", "input_symbol", "and", "state", ".", "This", "does", "not", "modify", "the", "FSM", "state", "so", "calling", "this", "method", "has", "no", "side", "effects", ".", "Normally", "you", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/FSM.py#L195-L226
[ "def", "get_transition", "(", "self", ",", "input_symbol", ",", "state", ")", ":", "if", "(", "input_symbol", ",", "state", ")", "in", "self", ".", "state_transitions", ":", "return", "self", ".", "state_transitions", "[", "(", "input_symbol", ",", "state", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
FSM.process
This is the main method that you call to process input. This may cause the FSM to change state and call an action. This method calls get_transition() to find the action and next_state associated with the input_symbol and current_state. If the action is None then the action is not called and only the current state is changed. This method processes one complete input symbol. You can process a list of symbols (or a string) by calling process_list().
pipenv/vendor/pexpect/FSM.py
def process (self, input_symbol): '''This is the main method that you call to process input. This may cause the FSM to change state and call an action. This method calls get_transition() to find the action and next_state associated with the input_symbol and current_state. If the action is None then the action is not called and only the current state is changed. This method processes one complete input symbol. You can process a list of symbols (or a string) by calling process_list(). ''' self.input_symbol = input_symbol (self.action, self.next_state) = self.get_transition (self.input_symbol, self.current_state) if self.action is not None: self.action (self) self.current_state = self.next_state self.next_state = None
def process (self, input_symbol): '''This is the main method that you call to process input. This may cause the FSM to change state and call an action. This method calls get_transition() to find the action and next_state associated with the input_symbol and current_state. If the action is None then the action is not called and only the current state is changed. This method processes one complete input symbol. You can process a list of symbols (or a string) by calling process_list(). ''' self.input_symbol = input_symbol (self.action, self.next_state) = self.get_transition (self.input_symbol, self.current_state) if self.action is not None: self.action (self) self.current_state = self.next_state self.next_state = None
[ "This", "is", "the", "main", "method", "that", "you", "call", "to", "process", "input", ".", "This", "may", "cause", "the", "FSM", "to", "change", "state", "and", "call", "an", "action", ".", "This", "method", "calls", "get_transition", "()", "to", "find...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/FSM.py#L228-L243
[ "def", "process", "(", "self", ",", "input_symbol", ")", ":", "self", ".", "input_symbol", "=", "input_symbol", "(", "self", ".", "action", ",", "self", ".", "next_state", ")", "=", "self", ".", "get_transition", "(", "self", ".", "input_symbol", ",", "s...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ip_address
Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the *address* passed isn't either a v4 or a v6 address
pipenv/patched/notpip/_vendor/ipaddress.py
def ip_address(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the *address* passed isn't either a v4 or a v6 address """ try: return IPv4Address(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Address(address) except (AddressValueError, NetmaskValueError): pass if isinstance(address, bytes): raise AddressValueError( '%r does not appear to be an IPv4 or IPv6 address. ' 'Did you pass in a bytes (str in Python 2) instead of' ' a unicode object?' % address) raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % address)
def ip_address(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the *address* passed isn't either a v4 or a v6 address """ try: return IPv4Address(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Address(address) except (AddressValueError, NetmaskValueError): pass if isinstance(address, bytes): raise AddressValueError( '%r does not appear to be an IPv4 or IPv6 address. ' 'Did you pass in a bytes (str in Python 2) instead of' ' a unicode object?' % address) raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % address)
[ "Take", "an", "IP", "string", "/", "int", "and", "return", "an", "object", "of", "the", "correct", "type", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L135-L168
[ "def", "ip_address", "(", "address", ")", ":", "try", ":", "return", "IPv4Address", "(", "address", ")", "except", "(", "AddressValueError", ",", "NetmaskValueError", ")", ":", "pass", "try", ":", "return", "IPv6Address", "(", "address", ")", "except", "(", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ip_interface
Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Notes: The IPv?Interface classes describe an Address on a particular Network, so they're basically a combination of both the Address and Network classes.
pipenv/patched/notpip/_vendor/ipaddress.py
def ip_interface(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Notes: The IPv?Interface classes describe an Address on a particular Network, so they're basically a combination of both the Address and Network classes. """ try: return IPv4Interface(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Interface(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' % address)
def ip_interface(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Notes: The IPv?Interface classes describe an Address on a particular Network, so they're basically a combination of both the Address and Network classes. """ try: return IPv4Interface(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Interface(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' % address)
[ "Take", "an", "IP", "string", "/", "int", "and", "return", "an", "object", "of", "the", "correct", "type", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L207-L239
[ "def", "ip_interface", "(", "address", ")", ":", "try", ":", "return", "IPv4Interface", "(", "address", ")", "except", "(", "AddressValueError", ",", "NetmaskValueError", ")", ":", "pass", "try", ":", "return", "IPv6Interface", "(", "address", ")", "except", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_split_optional_netmask
Helper to split the netmask and raise AddressValueError if needed
pipenv/patched/notpip/_vendor/ipaddress.py
def _split_optional_netmask(address): """Helper to split the netmask and raise AddressValueError if needed""" addr = _compat_str(address).split('/') if len(addr) > 2: raise AddressValueError("Only one '/' permitted in %r" % address) return addr
def _split_optional_netmask(address): """Helper to split the netmask and raise AddressValueError if needed""" addr = _compat_str(address).split('/') if len(addr) > 2: raise AddressValueError("Only one '/' permitted in %r" % address) return addr
[ "Helper", "to", "split", "the", "netmask", "and", "raise", "AddressValueError", "if", "needed" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L278-L283
[ "def", "_split_optional_netmask", "(", "address", ")", ":", "addr", "=", "_compat_str", "(", "address", ")", ".", "split", "(", "'/'", ")", "if", "len", "(", "addr", ")", ">", "2", ":", "raise", "AddressValueError", "(", "\"Only one '/' permitted in %r\"", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_find_address_range
Find a sequence of sorted deduplicated IPv#Address. Args: addresses: a list of IPv#Address objects. Yields: A tuple containing the first and last IP addresses in the sequence.
pipenv/patched/notpip/_vendor/ipaddress.py
def _find_address_range(addresses): """Find a sequence of sorted deduplicated IPv#Address. Args: addresses: a list of IPv#Address objects. Yields: A tuple containing the first and last IP addresses in the sequence. """ it = iter(addresses) first = last = next(it) for ip in it: if ip._ip != last._ip + 1: yield first, last first = ip last = ip yield first, last
def _find_address_range(addresses): """Find a sequence of sorted deduplicated IPv#Address. Args: addresses: a list of IPv#Address objects. Yields: A tuple containing the first and last IP addresses in the sequence. """ it = iter(addresses) first = last = next(it) for ip in it: if ip._ip != last._ip + 1: yield first, last first = ip last = ip yield first, last
[ "Find", "a", "sequence", "of", "sorted", "deduplicated", "IPv#Address", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L286-L303
[ "def", "_find_address_range", "(", "addresses", ")", ":", "it", "=", "iter", "(", "addresses", ")", "first", "=", "last", "=", "next", "(", "it", ")", "for", "ip", "in", "it", ":", "if", "ip", ".", "_ip", "!=", "last", ".", "_ip", "+", "1", ":", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_count_righthand_zero_bits
Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number.
pipenv/patched/notpip/_vendor/ipaddress.py
def _count_righthand_zero_bits(number, bits): """Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number. """ if number == 0: return bits return min(bits, _compat_bit_length(~number & (number - 1)))
def _count_righthand_zero_bits(number, bits): """Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number. """ if number == 0: return bits return min(bits, _compat_bit_length(~number & (number - 1)))
[ "Count", "the", "number", "of", "zero", "bits", "on", "the", "right", "hand", "side", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L306-L319
[ "def", "_count_righthand_zero_bits", "(", "number", ",", "bits", ")", ":", "if", "number", "==", "0", ":", "return", "bits", "return", "min", "(", "bits", ",", "_compat_bit_length", "(", "~", "number", "&", "(", "number", "-", "1", ")", ")", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_collapse_addresses_internal
Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse_addresses_internal([ip1, ip2, ip3, ip4]) -> [IPv4Network('192.0.2.0/24')] This shouldn't be called directly; it is called via collapse_addresses([]). Args: addresses: A list of IPv4Network's or IPv6Network's Returns: A list of IPv4Network's or IPv6Network's depending on what we were passed.
pipenv/patched/notpip/_vendor/ipaddress.py
def _collapse_addresses_internal(addresses): """Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse_addresses_internal([ip1, ip2, ip3, ip4]) -> [IPv4Network('192.0.2.0/24')] This shouldn't be called directly; it is called via collapse_addresses([]). Args: addresses: A list of IPv4Network's or IPv6Network's Returns: A list of IPv4Network's or IPv6Network's depending on what we were passed. """ # First merge to_merge = list(addresses) subnets = {} while to_merge: net = to_merge.pop() supernet = net.supernet() existing = subnets.get(supernet) if existing is None: subnets[supernet] = net elif existing != net: # Merge consecutive subnets del subnets[supernet] to_merge.append(supernet) # Then iterate over resulting networks, skipping subsumed subnets last = None for net in sorted(subnets.values()): if last is not None: # Since they are sorted, # last.network_address <= net.network_address is a given. if last.broadcast_address >= net.broadcast_address: continue yield net last = net
def _collapse_addresses_internal(addresses): """Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse_addresses_internal([ip1, ip2, ip3, ip4]) -> [IPv4Network('192.0.2.0/24')] This shouldn't be called directly; it is called via collapse_addresses([]). Args: addresses: A list of IPv4Network's or IPv6Network's Returns: A list of IPv4Network's or IPv6Network's depending on what we were passed. """ # First merge to_merge = list(addresses) subnets = {} while to_merge: net = to_merge.pop() supernet = net.supernet() existing = subnets.get(supernet) if existing is None: subnets[supernet] = net elif existing != net: # Merge consecutive subnets del subnets[supernet] to_merge.append(supernet) # Then iterate over resulting networks, skipping subsumed subnets last = None for net in sorted(subnets.values()): if last is not None: # Since they are sorted, # last.network_address <= net.network_address is a given. if last.broadcast_address >= net.broadcast_address: continue yield net last = net
[ "Loops", "through", "the", "addresses", "collapsing", "concurrent", "netblocks", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L377-L423
[ "def", "_collapse_addresses_internal", "(", "addresses", ")", ":", "# First merge", "to_merge", "=", "list", "(", "addresses", ")", "subnets", "=", "{", "}", "while", "to_merge", ":", "net", "=", "to_merge", ".", "pop", "(", ")", "supernet", "=", "net", "....
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
collapse_addresses
Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network or IPv6Network objects. Returns: An iterator of the collapsed IPv(4|6)Network objects. Raises: TypeError: If passed a list of mixed version objects.
pipenv/patched/notpip/_vendor/ipaddress.py
def collapse_addresses(addresses): """Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network or IPv6Network objects. Returns: An iterator of the collapsed IPv(4|6)Network objects. Raises: TypeError: If passed a list of mixed version objects. """ addrs = [] ips = [] nets = [] # split IP addresses and networks for ip in addresses: if isinstance(ip, _BaseAddress): if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) ips.append(ip) elif ip._prefixlen == ip._max_prefixlen: if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) try: ips.append(ip.ip) except AttributeError: ips.append(ip.network_address) else: if nets and nets[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, nets[-1])) nets.append(ip) # sort and dedup ips = sorted(set(ips)) # find consecutive address ranges in the sorted sequence and summarize them if ips: for first, last in _find_address_range(ips): addrs.extend(summarize_address_range(first, last)) return _collapse_addresses_internal(addrs + nets)
def collapse_addresses(addresses): """Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network or IPv6Network objects. Returns: An iterator of the collapsed IPv(4|6)Network objects. Raises: TypeError: If passed a list of mixed version objects. """ addrs = [] ips = [] nets = [] # split IP addresses and networks for ip in addresses: if isinstance(ip, _BaseAddress): if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) ips.append(ip) elif ip._prefixlen == ip._max_prefixlen: if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) try: ips.append(ip.ip) except AttributeError: ips.append(ip.network_address) else: if nets and nets[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, nets[-1])) nets.append(ip) # sort and dedup ips = sorted(set(ips)) # find consecutive address ranges in the sorted sequence and summarize them if ips: for first, last in _find_address_range(ips): addrs.extend(summarize_address_range(first, last)) return _collapse_addresses_internal(addrs + nets)
[ "Collapse", "a", "list", "of", "IP", "objects", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L426-L477
[ "def", "collapse_addresses", "(", "addresses", ")", ":", "addrs", "=", "[", "]", "ips", "=", "[", "]", "nets", "=", "[", "]", "# split IP addresses and networks", "for", "ip", "in", "addresses", ":", "if", "isinstance", "(", "ip", ",", "_BaseAddress", ")",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_mixed_type_key
Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may wish to have ipaddress sort these for you anyway. If you need to do this, you can use this function as the key= argument to sorted(). Args: obj: either a Network or Address object. Returns: appropriate key.
pipenv/patched/notpip/_vendor/ipaddress.py
def get_mixed_type_key(obj): """Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may wish to have ipaddress sort these for you anyway. If you need to do this, you can use this function as the key= argument to sorted(). Args: obj: either a Network or Address object. Returns: appropriate key. """ if isinstance(obj, _BaseNetwork): return obj._get_networks_key() elif isinstance(obj, _BaseAddress): return obj._get_address_key() return NotImplemented
def get_mixed_type_key(obj): """Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may wish to have ipaddress sort these for you anyway. If you need to do this, you can use this function as the key= argument to sorted(). Args: obj: either a Network or Address object. Returns: appropriate key. """ if isinstance(obj, _BaseNetwork): return obj._get_networks_key() elif isinstance(obj, _BaseAddress): return obj._get_address_key() return NotImplemented
[ "Return", "a", "key", "suitable", "for", "sorting", "between", "networks", "and", "addresses", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L480-L502
[ "def", "get_mixed_type_key", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "_BaseNetwork", ")", ":", "return", "obj", ".", "_get_networks_key", "(", ")", "elif", "isinstance", "(", "obj", ",", "_BaseAddress", ")", ":", "return", "obj", ".", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_IPAddressBase._prefix_from_ip_int
Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones
pipenv/patched/notpip/_vendor/ipaddress.py
def _prefix_from_ip_int(cls, ip_int): """Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones """ trailing_zeroes = _count_righthand_zero_bits(ip_int, cls._max_prefixlen) prefixlen = cls._max_prefixlen - trailing_zeroes leading_ones = ip_int >> trailing_zeroes all_ones = (1 << prefixlen) - 1 if leading_ones != all_ones: byteslen = cls._max_prefixlen // 8 details = _compat_to_bytes(ip_int, byteslen, 'big') msg = 'Netmask pattern %r mixes zeroes & ones' raise ValueError(msg % details) return prefixlen
def _prefix_from_ip_int(cls, ip_int): """Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones """ trailing_zeroes = _count_righthand_zero_bits(ip_int, cls._max_prefixlen) prefixlen = cls._max_prefixlen - trailing_zeroes leading_ones = ip_int >> trailing_zeroes all_ones = (1 << prefixlen) - 1 if leading_ones != all_ones: byteslen = cls._max_prefixlen // 8 details = _compat_to_bytes(ip_int, byteslen, 'big') msg = 'Netmask pattern %r mixes zeroes & ones' raise ValueError(msg % details) return prefixlen
[ "Return", "prefix", "length", "from", "the", "bitwise", "netmask", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L570-L592
[ "def", "_prefix_from_ip_int", "(", "cls", ",", "ip_int", ")", ":", "trailing_zeroes", "=", "_count_righthand_zero_bits", "(", "ip_int", ",", "cls", ".", "_max_prefixlen", ")", "prefixlen", "=", "cls", ".", "_max_prefixlen", "-", "trailing_zeroes", "leading_ones", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_IPAddressBase._prefix_from_prefix_string
Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask
pipenv/patched/notpip/_vendor/ipaddress.py
def _prefix_from_prefix_string(cls, prefixlen_str): """Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask """ # int allows a leading +/- as well as surrounding whitespace, # so we ensure that isn't the case if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str): cls._report_invalid_netmask(prefixlen_str) try: prefixlen = int(prefixlen_str) except ValueError: cls._report_invalid_netmask(prefixlen_str) if not (0 <= prefixlen <= cls._max_prefixlen): cls._report_invalid_netmask(prefixlen_str) return prefixlen
def _prefix_from_prefix_string(cls, prefixlen_str): """Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask """ # int allows a leading +/- as well as surrounding whitespace, # so we ensure that isn't the case if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str): cls._report_invalid_netmask(prefixlen_str) try: prefixlen = int(prefixlen_str) except ValueError: cls._report_invalid_netmask(prefixlen_str) if not (0 <= prefixlen <= cls._max_prefixlen): cls._report_invalid_netmask(prefixlen_str) return prefixlen
[ "Return", "prefix", "length", "from", "a", "numeric", "string" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L600-L622
[ "def", "_prefix_from_prefix_string", "(", "cls", ",", "prefixlen_str", ")", ":", "# int allows a leading +/- as well as surrounding whitespace,", "# so we ensure that isn't the case", "if", "not", "_BaseV4", ".", "_DECIMAL_DIGITS", ".", "issuperset", "(", "prefixlen_str", ")", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_IPAddressBase._prefix_from_ip_string
Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask
pipenv/patched/notpip/_vendor/ipaddress.py
def _prefix_from_ip_string(cls, ip_str): """Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask """ # Parse the netmask/hostmask like an IP address. try: ip_int = cls._ip_int_from_string(ip_str) except AddressValueError: cls._report_invalid_netmask(ip_str) # Try matching a netmask (this would be /1*0*/ as a bitwise regexp). # Note that the two ambiguous cases (all-ones and all-zeroes) are # treated as netmasks. try: return cls._prefix_from_ip_int(ip_int) except ValueError: pass # Invert the bits, and try matching a /0+1+/ hostmask instead. ip_int ^= cls._ALL_ONES try: return cls._prefix_from_ip_int(ip_int) except ValueError: cls._report_invalid_netmask(ip_str)
def _prefix_from_ip_string(cls, ip_str): """Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask """ # Parse the netmask/hostmask like an IP address. try: ip_int = cls._ip_int_from_string(ip_str) except AddressValueError: cls._report_invalid_netmask(ip_str) # Try matching a netmask (this would be /1*0*/ as a bitwise regexp). # Note that the two ambiguous cases (all-ones and all-zeroes) are # treated as netmasks. try: return cls._prefix_from_ip_int(ip_int) except ValueError: pass # Invert the bits, and try matching a /0+1+/ hostmask instead. ip_int ^= cls._ALL_ONES try: return cls._prefix_from_ip_int(ip_int) except ValueError: cls._report_invalid_netmask(ip_str)
[ "Turn", "a", "netmask", "/", "hostmask", "string", "into", "a", "prefix", "length" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L625-L656
[ "def", "_prefix_from_ip_string", "(", "cls", ",", "ip_str", ")", ":", "# Parse the netmask/hostmask like an IP address.", "try", ":", "ip_int", "=", "cls", ".", "_ip_int_from_string", "(", "ip_str", ")", "except", "AddressValueError", ":", "cls", ".", "_report_invalid...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_BaseNetwork.overlaps
Tell if self is partly contained in other.
pipenv/patched/notpip/_vendor/ipaddress.py
def overlaps(self, other): """Tell if self is partly contained in other.""" return self.network_address in other or ( self.broadcast_address in other or ( other.network_address in self or ( other.broadcast_address in self)))
def overlaps(self, other): """Tell if self is partly contained in other.""" return self.network_address in other or ( self.broadcast_address in other or ( other.network_address in self or ( other.broadcast_address in self)))
[ "Tell", "if", "self", "is", "partly", "contained", "in", "other", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L810-L815
[ "def", "overlaps", "(", "self", ",", "other", ")", ":", "return", "self", ".", "network_address", "in", "other", "or", "(", "self", ".", "broadcast_address", "in", "other", "or", "(", "other", ".", "network_address", "in", "self", "or", "(", "other", "."...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_BaseNetwork.address_exclude
Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') list(addr1.address_exclude(addr2)) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] or IPv6: addr1 = ip_network('2001:db8::1/32') addr2 = ip_network('2001:db8::1/128') list(addr1.address_exclude(addr2)) = [ip_network('2001:db8::1/128'), ip_network('2001:db8::2/127'), ip_network('2001:db8::4/126'), ip_network('2001:db8::8/125'), ... ip_network('2001:db8:8000::/33')] Args: other: An IPv4Network or IPv6Network object of the same type. Returns: An iterator of the IPv(4|6)Network objects which is self minus other. Raises: TypeError: If self and other are of differing address versions, or if other is not a network object. ValueError: If other is not completely contained by self.
pipenv/patched/notpip/_vendor/ipaddress.py
def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') list(addr1.address_exclude(addr2)) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] or IPv6: addr1 = ip_network('2001:db8::1/32') addr2 = ip_network('2001:db8::1/128') list(addr1.address_exclude(addr2)) = [ip_network('2001:db8::1/128'), ip_network('2001:db8::2/127'), ip_network('2001:db8::4/126'), ip_network('2001:db8::8/125'), ... ip_network('2001:db8:8000::/33')] Args: other: An IPv4Network or IPv6Network object of the same type. Returns: An iterator of the IPv(4|6)Network objects which is self minus other. Raises: TypeError: If self and other are of differing address versions, or if other is not a network object. ValueError: If other is not completely contained by self. """ if not self._version == other._version: raise TypeError("%s and %s are not of the same version" % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError("%s is not a network object" % other) if not other.subnet_of(self): raise ValueError('%s not contained in %s' % (other, self)) if other == self: return # Make sure we're comparing the network of other. other = other.__class__('%s/%s' % (other.network_address, other.prefixlen)) s1, s2 = self.subnets() while s1 != other and s2 != other: if other.subnet_of(s1): yield s2 s1, s2 = s1.subnets() elif other.subnet_of(s2): yield s1 s1, s2 = s2.subnets() else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) if s1 == other: yield s2 elif s2 == other: yield s1 else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other))
def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') list(addr1.address_exclude(addr2)) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] or IPv6: addr1 = ip_network('2001:db8::1/32') addr2 = ip_network('2001:db8::1/128') list(addr1.address_exclude(addr2)) = [ip_network('2001:db8::1/128'), ip_network('2001:db8::2/127'), ip_network('2001:db8::4/126'), ip_network('2001:db8::8/125'), ... ip_network('2001:db8:8000::/33')] Args: other: An IPv4Network or IPv6Network object of the same type. Returns: An iterator of the IPv(4|6)Network objects which is self minus other. Raises: TypeError: If self and other are of differing address versions, or if other is not a network object. ValueError: If other is not completely contained by self. """ if not self._version == other._version: raise TypeError("%s and %s are not of the same version" % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError("%s is not a network object" % other) if not other.subnet_of(self): raise ValueError('%s not contained in %s' % (other, self)) if other == self: return # Make sure we're comparing the network of other. other = other.__class__('%s/%s' % (other.network_address, other.prefixlen)) s1, s2 = self.subnets() while s1 != other and s2 != other: if other.subnet_of(s1): yield s2 s1, s2 = s1.subnets() elif other.subnet_of(s2): yield s1 s1, s2 = s2.subnets() else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) if s1 == other: yield s2 elif s2 == other: yield s1 else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other))
[ "Remove", "an", "address", "from", "a", "larger", "block", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L863-L936
[ "def", "address_exclude", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "_version", "==", "other", ".", "_version", ":", "raise", "TypeError", "(", "\"%s and %s are not of the same version\"", "%", "(", "self", ",", "other", ")", ")", "if", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_BaseNetwork.compare_networks
Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._ip' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25') IPv6Network('2001:db8::1000/124') < IPv6Network('2001:db8::2000/124') 0 if self == other eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24') IPv6Network('2001:db8::1000/124') == IPv6Network('2001:db8::1000/124') 1 if self > other eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25') IPv6Network('2001:db8::2000/124') > IPv6Network('2001:db8::1000/124') Raises: TypeError if the IP versions are different.
pipenv/patched/notpip/_vendor/ipaddress.py
def compare_networks(self, other): """Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._ip' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25') IPv6Network('2001:db8::1000/124') < IPv6Network('2001:db8::2000/124') 0 if self == other eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24') IPv6Network('2001:db8::1000/124') == IPv6Network('2001:db8::1000/124') 1 if self > other eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25') IPv6Network('2001:db8::2000/124') > IPv6Network('2001:db8::1000/124') Raises: TypeError if the IP versions are different. """ # does this need to raise a ValueError? if self._version != other._version: raise TypeError('%s and %s are not of the same type' % ( self, other)) # self._version == other._version below here: if self.network_address < other.network_address: return -1 if self.network_address > other.network_address: return 1 # self.network_address == other.network_address below here: if self.netmask < other.netmask: return -1 if self.netmask > other.netmask: return 1 return 0
def compare_networks(self, other): """Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._ip' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25') IPv6Network('2001:db8::1000/124') < IPv6Network('2001:db8::2000/124') 0 if self == other eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24') IPv6Network('2001:db8::1000/124') == IPv6Network('2001:db8::1000/124') 1 if self > other eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25') IPv6Network('2001:db8::2000/124') > IPv6Network('2001:db8::1000/124') Raises: TypeError if the IP versions are different. """ # does this need to raise a ValueError? if self._version != other._version: raise TypeError('%s and %s are not of the same type' % ( self, other)) # self._version == other._version below here: if self.network_address < other.network_address: return -1 if self.network_address > other.network_address: return 1 # self.network_address == other.network_address below here: if self.netmask < other.netmask: return -1 if self.netmask > other.netmask: return 1 return 0
[ "Compare", "two", "IP", "objects", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L938-L984
[ "def", "compare_networks", "(", "self", ",", "other", ")", ":", "# does this need to raise a ValueError?", "if", "self", ".", "_version", "!=", "other", ".", "_version", ":", "raise", "TypeError", "(", "'%s and %s are not of the same type'", "%", "(", "self", ",", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_BaseNetwork.subnets
The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network)
pipenv/patched/notpip/_vendor/ipaddress.py
def subnets(self, prefixlen_diff=1, new_prefix=None): """The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network) """ if self._prefixlen == self._max_prefixlen: yield self return if new_prefix is not None: if new_prefix < self._prefixlen: raise ValueError('new prefix must be longer') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = new_prefix - self._prefixlen if prefixlen_diff < 0: raise ValueError('prefix length diff must be > 0') new_prefixlen = self._prefixlen + prefixlen_diff if new_prefixlen > self._max_prefixlen: raise ValueError( 'prefix length diff %d is invalid for netblock %s' % ( new_prefixlen, self)) start = int(self.network_address) end = int(self.broadcast_address) + 1 step = (int(self.hostmask) + 1) >> prefixlen_diff for new_addr in _compat_range(start, end, step): current = self.__class__((new_addr, new_prefixlen)) yield current
def subnets(self, prefixlen_diff=1, new_prefix=None): """The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network) """ if self._prefixlen == self._max_prefixlen: yield self return if new_prefix is not None: if new_prefix < self._prefixlen: raise ValueError('new prefix must be longer') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = new_prefix - self._prefixlen if prefixlen_diff < 0: raise ValueError('prefix length diff must be > 0') new_prefixlen = self._prefixlen + prefixlen_diff if new_prefixlen > self._max_prefixlen: raise ValueError( 'prefix length diff %d is invalid for netblock %s' % ( new_prefixlen, self)) start = int(self.network_address) end = int(self.broadcast_address) + 1 step = (int(self.hostmask) + 1) >> prefixlen_diff for new_addr in _compat_range(start, end, step): current = self.__class__((new_addr, new_prefixlen)) yield current
[ "The", "subnets", "which", "join", "to", "make", "the", "current", "subnet", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L996-L1047
[ "def", "subnets", "(", "self", ",", "prefixlen_diff", "=", "1", ",", "new_prefix", "=", "None", ")", ":", "if", "self", ".", "_prefixlen", "==", "self", ".", "_max_prefixlen", ":", "yield", "self", "return", "if", "new_prefix", "is", "not", "None", ":", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_BaseNetwork.supernet
The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network)
pipenv/patched/notpip/_vendor/ipaddress.py
def supernet(self, prefixlen_diff=1, new_prefix=None): """The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network) """ if self._prefixlen == 0: return self if new_prefix is not None: if new_prefix > self._prefixlen: raise ValueError('new prefix must be shorter') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = self._prefixlen - new_prefix new_prefixlen = self.prefixlen - prefixlen_diff if new_prefixlen < 0: raise ValueError( 'current prefixlen is %d, cannot have a prefixlen_diff of %d' % (self.prefixlen, prefixlen_diff)) return self.__class__(( int(self.network_address) & (int(self.netmask) << prefixlen_diff), new_prefixlen))
def supernet(self, prefixlen_diff=1, new_prefix=None): """The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network) """ if self._prefixlen == 0: return self if new_prefix is not None: if new_prefix > self._prefixlen: raise ValueError('new prefix must be shorter') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = self._prefixlen - new_prefix new_prefixlen = self.prefixlen - prefixlen_diff if new_prefixlen < 0: raise ValueError( 'current prefixlen is %d, cannot have a prefixlen_diff of %d' % (self.prefixlen, prefixlen_diff)) return self.__class__(( int(self.network_address) & (int(self.netmask) << prefixlen_diff), new_prefixlen))
[ "The", "supernet", "containing", "the", "current", "network", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1049-L1087
[ "def", "supernet", "(", "self", ",", "prefixlen_diff", "=", "1", ",", "new_prefix", "=", "None", ")", ":", "if", "self", ".", "_prefixlen", "==", "0", ":", "return", "self", "if", "new_prefix", "is", "not", "None", ":", "if", "new_prefix", ">", "self",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_BaseV4._make_netmask
Make a (netmask, prefix_len) tuple from the given argument. Argument can be: - an integer (the prefix length) - a string representing the prefix length (e.g. "24") - a string representing the prefix netmask (e.g. "255.255.255.0")
pipenv/patched/notpip/_vendor/ipaddress.py
def _make_netmask(cls, arg): """Make a (netmask, prefix_len) tuple from the given argument. Argument can be: - an integer (the prefix length) - a string representing the prefix length (e.g. "24") - a string representing the prefix netmask (e.g. "255.255.255.0") """ if arg not in cls._netmask_cache: if isinstance(arg, _compat_int_types): prefixlen = arg else: try: # Check for a netmask in prefix length form prefixlen = cls._prefix_from_prefix_string(arg) except NetmaskValueError: # Check for a netmask or hostmask in dotted-quad form. # This may raise NetmaskValueError. prefixlen = cls._prefix_from_ip_string(arg) netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen)) cls._netmask_cache[arg] = netmask, prefixlen return cls._netmask_cache[arg]
def _make_netmask(cls, arg): """Make a (netmask, prefix_len) tuple from the given argument. Argument can be: - an integer (the prefix length) - a string representing the prefix length (e.g. "24") - a string representing the prefix netmask (e.g. "255.255.255.0") """ if arg not in cls._netmask_cache: if isinstance(arg, _compat_int_types): prefixlen = arg else: try: # Check for a netmask in prefix length form prefixlen = cls._prefix_from_prefix_string(arg) except NetmaskValueError: # Check for a netmask or hostmask in dotted-quad form. # This may raise NetmaskValueError. prefixlen = cls._prefix_from_ip_string(arg) netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen)) cls._netmask_cache[arg] = netmask, prefixlen return cls._netmask_cache[arg]
[ "Make", "a", "(", "netmask", "prefix_len", ")", "tuple", "from", "the", "given", "argument", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1219-L1240
[ "def", "_make_netmask", "(", "cls", ",", "arg", ")", ":", "if", "arg", "not", "in", "cls", ".", "_netmask_cache", ":", "if", "isinstance", "(", "arg", ",", "_compat_int_types", ")", ":", "prefixlen", "=", "arg", "else", ":", "try", ":", "# Check for a ne...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_BaseV4._ip_int_from_string
Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address.
pipenv/patched/notpip/_vendor/ipaddress.py
def _ip_int_from_string(cls, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') octets = ip_str.split('.') if len(octets) != 4: raise AddressValueError("Expected 4 octets in %r" % ip_str) try: return _compat_int_from_byte_vals( map(cls._parse_octet, octets), 'big') except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str))
def _ip_int_from_string(cls, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') octets = ip_str.split('.') if len(octets) != 4: raise AddressValueError("Expected 4 octets in %r" % ip_str) try: return _compat_int_from_byte_vals( map(cls._parse_octet, octets), 'big') except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str))
[ "Turn", "the", "given", "IP", "string", "into", "an", "integer", "for", "comparison", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1243-L1267
[ "def", "_ip_int_from_string", "(", "cls", ",", "ip_str", ")", ":", "if", "not", "ip_str", ":", "raise", "AddressValueError", "(", "'Address cannot be empty'", ")", "octets", "=", "ip_str", ".", "split", "(", "'.'", ")", "if", "len", "(", "octets", ")", "!=...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_BaseV4._string_from_ip_int
Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation.
pipenv/patched/notpip/_vendor/ipaddress.py
def _string_from_ip_int(cls, ip_int): """Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation. """ return '.'.join(_compat_str(struct.unpack(b'!B', b)[0] if isinstance(b, bytes) else b) for b in _compat_to_bytes(ip_int, 4, 'big'))
def _string_from_ip_int(cls, ip_int): """Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation. """ return '.'.join(_compat_str(struct.unpack(b'!B', b)[0] if isinstance(b, bytes) else b) for b in _compat_to_bytes(ip_int, 4, 'big'))
[ "Turns", "a", "32", "-", "bit", "integer", "into", "dotted", "decimal", "notation", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1307-L1320
[ "def", "_string_from_ip_int", "(", "cls", ",", "ip_int", ")", ":", "return", "'.'", ".", "join", "(", "_compat_str", "(", "struct", ".", "unpack", "(", "b'!B'", ",", "b", ")", "[", "0", "]", "if", "isinstance", "(", "b", ",", "bytes", ")", "else", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_BaseV4._is_hostmask
Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask.
pipenv/patched/notpip/_vendor/ipaddress.py
def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. """ bits = ip_str.split('.') try: parts = [x for x in map(int, bits) if x in self._valid_mask_octets] except ValueError: return False if len(parts) != len(bits): return False if parts[0] < parts[-1]: return True return False
def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. """ bits = ip_str.split('.') try: parts = [x for x in map(int, bits) if x in self._valid_mask_octets] except ValueError: return False if len(parts) != len(bits): return False if parts[0] < parts[-1]: return True return False
[ "Test", "if", "the", "IP", "string", "is", "a", "hostmask", "(", "rather", "than", "a", "netmask", ")", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1322-L1341
[ "def", "_is_hostmask", "(", "self", ",", "ip_str", ")", ":", "bits", "=", "ip_str", ".", "split", "(", "'.'", ")", "try", ":", "parts", "=", "[", "x", "for", "x", "in", "map", "(", "int", ",", "bits", ")", "if", "x", "in", "self", ".", "_valid_...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
IPv4Network.is_global
Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry.
pipenv/patched/notpip/_vendor/ipaddress.py
def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry. """ return (not (self.network_address in IPv4Network('100.64.0.0/10') and self.broadcast_address in IPv4Network('100.64.0.0/10')) and not self.is_private)
def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry. """ return (not (self.network_address in IPv4Network('100.64.0.0/10') and self.broadcast_address in IPv4Network('100.64.0.0/10')) and not self.is_private)
[ "Test", "if", "this", "address", "is", "allocated", "for", "public", "networks", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1663-L1673
[ "def", "is_global", "(", "self", ")", ":", "return", "(", "not", "(", "self", ".", "network_address", "in", "IPv4Network", "(", "'100.64.0.0/10'", ")", "and", "self", ".", "broadcast_address", "in", "IPv4Network", "(", "'100.64.0.0/10'", ")", ")", "and", "no...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_BaseV6._make_netmask
Make a (netmask, prefix_len) tuple from the given argument. Argument can be: - an integer (the prefix length) - a string representing the prefix length (e.g. "24") - a string representing the prefix netmask (e.g. "255.255.255.0")
pipenv/patched/notpip/_vendor/ipaddress.py
def _make_netmask(cls, arg): """Make a (netmask, prefix_len) tuple from the given argument. Argument can be: - an integer (the prefix length) - a string representing the prefix length (e.g. "24") - a string representing the prefix netmask (e.g. "255.255.255.0") """ if arg not in cls._netmask_cache: if isinstance(arg, _compat_int_types): prefixlen = arg else: prefixlen = cls._prefix_from_prefix_string(arg) netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen)) cls._netmask_cache[arg] = netmask, prefixlen return cls._netmask_cache[arg]
def _make_netmask(cls, arg): """Make a (netmask, prefix_len) tuple from the given argument. Argument can be: - an integer (the prefix length) - a string representing the prefix length (e.g. "24") - a string representing the prefix netmask (e.g. "255.255.255.0") """ if arg not in cls._netmask_cache: if isinstance(arg, _compat_int_types): prefixlen = arg else: prefixlen = cls._prefix_from_prefix_string(arg) netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen)) cls._netmask_cache[arg] = netmask, prefixlen return cls._netmask_cache[arg]
[ "Make", "a", "(", "netmask", "prefix_len", ")", "tuple", "from", "the", "given", "argument", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1732-L1747
[ "def", "_make_netmask", "(", "cls", ",", "arg", ")", ":", "if", "arg", "not", "in", "cls", ".", "_netmask_cache", ":", "if", "isinstance", "(", "arg", ",", "_compat_int_types", ")", ":", "prefixlen", "=", "arg", "else", ":", "prefixlen", "=", "cls", "....
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_BaseV6._ip_int_from_string
Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: An int, the IPv6 address Raises: AddressValueError: if ip_str isn't a valid IPv6 Address.
pipenv/patched/notpip/_vendor/ipaddress.py
def _ip_int_from_string(cls, ip_str): """Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: An int, the IPv6 address Raises: AddressValueError: if ip_str isn't a valid IPv6 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') parts = ip_str.split(':') # An IPv6 address needs at least 2 colons (3 parts). _min_parts = 3 if len(parts) < _min_parts: msg = "At least %d parts expected in %r" % (_min_parts, ip_str) raise AddressValueError(msg) # If the address has an IPv4-style suffix, convert it to hexadecimal. if '.' in parts[-1]: try: ipv4_int = IPv4Address(parts.pop())._ip except AddressValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF)) parts.append('%x' % (ipv4_int & 0xFFFF)) # An IPv6 address can't have more than 8 colons (9 parts). # The extra colon comes from using the "::" notation for a single # leading or trailing zero part. _max_parts = cls._HEXTET_COUNT + 1 if len(parts) > _max_parts: msg = "At most %d colons permitted in %r" % ( _max_parts - 1, ip_str) raise AddressValueError(msg) # Disregarding the endpoints, find '::' with nothing in between. # This indicates that a run of zeroes has been skipped. skip_index = None for i in _compat_range(1, len(parts) - 1): if not parts[i]: if skip_index is not None: # Can't have more than one '::' msg = "At most one '::' permitted in %r" % ip_str raise AddressValueError(msg) skip_index = i # parts_hi is the number of parts to copy from above/before the '::' # parts_lo is the number of parts to copy from below/after the '::' if skip_index is not None: # If we found a '::', then check if it also covers the endpoints. parts_hi = skip_index parts_lo = len(parts) - skip_index - 1 if not parts[0]: parts_hi -= 1 if parts_hi: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: parts_lo -= 1 if parts_lo: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo) if parts_skipped < 1: msg = "Expected at most %d other parts with '::' in %r" raise AddressValueError(msg % (cls._HEXTET_COUNT - 1, ip_str)) else: # Otherwise, allocate the entire address to parts_hi. The # endpoints could still be empty, but _parse_hextet() will check # for that. if len(parts) != cls._HEXTET_COUNT: msg = "Exactly %d parts expected without '::' in %r" raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str)) if not parts[0]: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_hi = len(parts) parts_lo = 0 parts_skipped = 0 try: # Now, parse the hextets into a 128-bit integer. ip_int = 0 for i in range(parts_hi): ip_int <<= 16 ip_int |= cls._parse_hextet(parts[i]) ip_int <<= 16 * parts_skipped for i in range(-parts_lo, 0): ip_int <<= 16 ip_int |= cls._parse_hextet(parts[i]) return ip_int except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str))
def _ip_int_from_string(cls, ip_str): """Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: An int, the IPv6 address Raises: AddressValueError: if ip_str isn't a valid IPv6 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') parts = ip_str.split(':') # An IPv6 address needs at least 2 colons (3 parts). _min_parts = 3 if len(parts) < _min_parts: msg = "At least %d parts expected in %r" % (_min_parts, ip_str) raise AddressValueError(msg) # If the address has an IPv4-style suffix, convert it to hexadecimal. if '.' in parts[-1]: try: ipv4_int = IPv4Address(parts.pop())._ip except AddressValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF)) parts.append('%x' % (ipv4_int & 0xFFFF)) # An IPv6 address can't have more than 8 colons (9 parts). # The extra colon comes from using the "::" notation for a single # leading or trailing zero part. _max_parts = cls._HEXTET_COUNT + 1 if len(parts) > _max_parts: msg = "At most %d colons permitted in %r" % ( _max_parts - 1, ip_str) raise AddressValueError(msg) # Disregarding the endpoints, find '::' with nothing in between. # This indicates that a run of zeroes has been skipped. skip_index = None for i in _compat_range(1, len(parts) - 1): if not parts[i]: if skip_index is not None: # Can't have more than one '::' msg = "At most one '::' permitted in %r" % ip_str raise AddressValueError(msg) skip_index = i # parts_hi is the number of parts to copy from above/before the '::' # parts_lo is the number of parts to copy from below/after the '::' if skip_index is not None: # If we found a '::', then check if it also covers the endpoints. parts_hi = skip_index parts_lo = len(parts) - skip_index - 1 if not parts[0]: parts_hi -= 1 if parts_hi: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: parts_lo -= 1 if parts_lo: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo) if parts_skipped < 1: msg = "Expected at most %d other parts with '::' in %r" raise AddressValueError(msg % (cls._HEXTET_COUNT - 1, ip_str)) else: # Otherwise, allocate the entire address to parts_hi. The # endpoints could still be empty, but _parse_hextet() will check # for that. if len(parts) != cls._HEXTET_COUNT: msg = "Exactly %d parts expected without '::' in %r" raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str)) if not parts[0]: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_hi = len(parts) parts_lo = 0 parts_skipped = 0 try: # Now, parse the hextets into a 128-bit integer. ip_int = 0 for i in range(parts_hi): ip_int <<= 16 ip_int |= cls._parse_hextet(parts[i]) ip_int <<= 16 * parts_skipped for i in range(-parts_lo, 0): ip_int <<= 16 ip_int |= cls._parse_hextet(parts[i]) return ip_int except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str))
[ "Turn", "an", "IPv6", "ip_str", "into", "an", "integer", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1750-L1852
[ "def", "_ip_int_from_string", "(", "cls", ",", "ip_str", ")", ":", "if", "not", "ip_str", ":", "raise", "AddressValueError", "(", "'Address cannot be empty'", ")", "parts", "=", "ip_str", ".", "split", "(", "':'", ")", "# An IPv6 address needs at least 2 colons (3 p...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_BaseV6._parse_hextet
Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF].
pipenv/patched/notpip/_vendor/ipaddress.py
def _parse_hextet(cls, hextet_str): """Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF]. """ # Whitelist the characters, since int() allows a lot of bizarre stuff. if not cls._HEX_DIGITS.issuperset(hextet_str): raise ValueError("Only hex digits permitted in %r" % hextet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(hextet_str) > 4: msg = "At most 4 characters permitted in %r" raise ValueError(msg % hextet_str) # Length check means we can skip checking the integer value return int(hextet_str, 16)
def _parse_hextet(cls, hextet_str): """Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF]. """ # Whitelist the characters, since int() allows a lot of bizarre stuff. if not cls._HEX_DIGITS.issuperset(hextet_str): raise ValueError("Only hex digits permitted in %r" % hextet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(hextet_str) > 4: msg = "At most 4 characters permitted in %r" raise ValueError(msg % hextet_str) # Length check means we can skip checking the integer value return int(hextet_str, 16)
[ "Convert", "an", "IPv6", "hextet", "string", "into", "an", "integer", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1855-L1878
[ "def", "_parse_hextet", "(", "cls", ",", "hextet_str", ")", ":", "# Whitelist the characters, since int() allows a lot of bizarre stuff.", "if", "not", "cls", ".", "_HEX_DIGITS", ".", "issuperset", "(", "hextet_str", ")", ":", "raise", "ValueError", "(", "\"Only hex dig...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_BaseV6._compress_hextets
Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets: A list of strings, the hextets to compress. Returns: A list of strings.
pipenv/patched/notpip/_vendor/ipaddress.py
def _compress_hextets(cls, hextets): """Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets: A list of strings, the hextets to compress. Returns: A list of strings. """ best_doublecolon_start = -1 best_doublecolon_len = 0 doublecolon_start = -1 doublecolon_len = 0 for index, hextet in enumerate(hextets): if hextet == '0': doublecolon_len += 1 if doublecolon_start == -1: # Start of a sequence of zeros. doublecolon_start = index if doublecolon_len > best_doublecolon_len: # This is the longest sequence of zeros so far. best_doublecolon_len = doublecolon_len best_doublecolon_start = doublecolon_start else: doublecolon_len = 0 doublecolon_start = -1 if best_doublecolon_len > 1: best_doublecolon_end = (best_doublecolon_start + best_doublecolon_len) # For zeros at the end of the address. if best_doublecolon_end == len(hextets): hextets += [''] hextets[best_doublecolon_start:best_doublecolon_end] = [''] # For zeros at the beginning of the address. if best_doublecolon_start == 0: hextets = [''] + hextets return hextets
def _compress_hextets(cls, hextets): """Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets: A list of strings, the hextets to compress. Returns: A list of strings. """ best_doublecolon_start = -1 best_doublecolon_len = 0 doublecolon_start = -1 doublecolon_len = 0 for index, hextet in enumerate(hextets): if hextet == '0': doublecolon_len += 1 if doublecolon_start == -1: # Start of a sequence of zeros. doublecolon_start = index if doublecolon_len > best_doublecolon_len: # This is the longest sequence of zeros so far. best_doublecolon_len = doublecolon_len best_doublecolon_start = doublecolon_start else: doublecolon_len = 0 doublecolon_start = -1 if best_doublecolon_len > 1: best_doublecolon_end = (best_doublecolon_start + best_doublecolon_len) # For zeros at the end of the address. if best_doublecolon_end == len(hextets): hextets += [''] hextets[best_doublecolon_start:best_doublecolon_end] = [''] # For zeros at the beginning of the address. if best_doublecolon_start == 0: hextets = [''] + hextets return hextets
[ "Compresses", "a", "list", "of", "hextets", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1881-L1926
[ "def", "_compress_hextets", "(", "cls", ",", "hextets", ")", ":", "best_doublecolon_start", "=", "-", "1", "best_doublecolon_len", "=", "0", "doublecolon_start", "=", "-", "1", "doublecolon_len", "=", "0", "for", "index", ",", "hextet", "in", "enumerate", "(",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
IPv6Address.teredo
Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32)
pipenv/patched/notpip/_vendor/ipaddress.py
def teredo(self): """Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32) """ if (self._ip >> 96) != 0x20010000: return None return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), IPv4Address(~self._ip & 0xFFFFFFFF))
def teredo(self): """Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32) """ if (self._ip >> 96) != 0x20010000: return None return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), IPv4Address(~self._ip & 0xFFFFFFFF))
[ "Tuple", "of", "embedded", "teredo", "IPs", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L2148-L2160
[ "def", "teredo", "(", "self", ")", ":", "if", "(", "self", ".", "_ip", ">>", "96", ")", "!=", "0x20010000", ":", "return", "None", "return", "(", "IPv4Address", "(", "(", "self", ".", "_ip", ">>", "64", ")", "&", "0xFFFFFFFF", ")", ",", "IPv4Addres...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde