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 | Parameter.get_error_hint | Get a stringified version of the param for use in error messages to
indicate which param caused the error. | pipenv/vendor/click/core.py | def get_error_hint(self, ctx):
"""Get a stringified version of the param for use in error messages to
indicate which param caused the error.
"""
hint_list = self.opts or [self.human_readable_name]
return ' / '.join('"%s"' % x for x in hint_list) | def get_error_hint(self, ctx):
"""Get a stringified version of the param for use in error messages to
indicate which param caused the error.
"""
hint_list = self.opts or [self.human_readable_name]
return ' / '.join('"%s"' % x for x in hint_list) | [
"Get",
"a",
"stringified",
"version",
"of",
"the",
"param",
"for",
"use",
"in",
"error",
"messages",
"to",
"indicate",
"which",
"param",
"caused",
"the",
"error",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L1492-L1497 | [
"def",
"get_error_hint",
"(",
"self",
",",
"ctx",
")",
":",
"hint_list",
"=",
"self",
".",
"opts",
"or",
"[",
"self",
".",
"human_readable_name",
"]",
"return",
"' / '",
".",
"join",
"(",
"'\"%s\"'",
"%",
"x",
"for",
"x",
"in",
"hint_list",
")"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | Option.prompt_for_value | This is an alternative flow that can be activated in the full
value processing if a value does not exist. It will prompt the
user until a valid value exists and then returns the processed
value as result. | pipenv/vendor/click/core.py | def prompt_for_value(self, ctx):
"""This is an alternative flow that can be activated in the full
value processing if a value does not exist. It will prompt the
user until a valid value exists and then returns the processed
value as result.
"""
# Calculate the default before prompting anything to be stable.
default = self.get_default(ctx)
# If this is a prompt for a flag we need to handle this
# differently.
if self.is_bool_flag:
return confirm(self.prompt, default)
return prompt(self.prompt, default=default, type=self.type,
hide_input=self.hide_input, show_choices=self.show_choices,
confirmation_prompt=self.confirmation_prompt,
value_proc=lambda x: self.process_value(ctx, x)) | def prompt_for_value(self, ctx):
"""This is an alternative flow that can be activated in the full
value processing if a value does not exist. It will prompt the
user until a valid value exists and then returns the processed
value as result.
"""
# Calculate the default before prompting anything to be stable.
default = self.get_default(ctx)
# If this is a prompt for a flag we need to handle this
# differently.
if self.is_bool_flag:
return confirm(self.prompt, default)
return prompt(self.prompt, default=default, type=self.type,
hide_input=self.hide_input, show_choices=self.show_choices,
confirmation_prompt=self.confirmation_prompt,
value_proc=lambda x: self.process_value(ctx, x)) | [
"This",
"is",
"an",
"alternative",
"flow",
"that",
"can",
"be",
"activated",
"in",
"the",
"full",
"value",
"processing",
"if",
"a",
"value",
"does",
"not",
"exist",
".",
"It",
"will",
"prompt",
"the",
"user",
"until",
"a",
"valid",
"value",
"exists",
"an... | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L1747-L1764 | [
"def",
"prompt_for_value",
"(",
"self",
",",
"ctx",
")",
":",
"# Calculate the default before prompting anything to be stable.",
"default",
"=",
"self",
".",
"get_default",
"(",
"ctx",
")",
"# If this is a prompt for a flag we need to handle this",
"# differently.",
"if",
"se... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | find_all_matches | Find all matching dependencies using the supplied finder and the
given ireq.
:param finder: A package finder for discovering matching candidates.
:type finder: :class:`~pip._internal.index.PackageFinder`
:param ireq: An install requirement.
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A list of matching candidates.
:rtype: list[:class:`~pip._internal.index.InstallationCandidate`] | pipenv/vendor/requirementslib/models/dependencies.py | def find_all_matches(finder, ireq, pre=False):
# type: (PackageFinder, InstallRequirement, bool) -> List[InstallationCandidate]
"""Find all matching dependencies using the supplied finder and the
given ireq.
:param finder: A package finder for discovering matching candidates.
:type finder: :class:`~pip._internal.index.PackageFinder`
:param ireq: An install requirement.
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A list of matching candidates.
:rtype: list[:class:`~pip._internal.index.InstallationCandidate`]
"""
candidates = clean_requires_python(finder.find_all_candidates(ireq.name))
versions = {candidate.version for candidate in candidates}
allowed_versions = _get_filtered_versions(ireq, versions, pre)
if not pre and not allowed_versions:
allowed_versions = _get_filtered_versions(ireq, versions, True)
candidates = {c for c in candidates if c.version in allowed_versions}
return candidates | def find_all_matches(finder, ireq, pre=False):
# type: (PackageFinder, InstallRequirement, bool) -> List[InstallationCandidate]
"""Find all matching dependencies using the supplied finder and the
given ireq.
:param finder: A package finder for discovering matching candidates.
:type finder: :class:`~pip._internal.index.PackageFinder`
:param ireq: An install requirement.
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A list of matching candidates.
:rtype: list[:class:`~pip._internal.index.InstallationCandidate`]
"""
candidates = clean_requires_python(finder.find_all_candidates(ireq.name))
versions = {candidate.version for candidate in candidates}
allowed_versions = _get_filtered_versions(ireq, versions, pre)
if not pre and not allowed_versions:
allowed_versions = _get_filtered_versions(ireq, versions, True)
candidates = {c for c in candidates if c.version in allowed_versions}
return candidates | [
"Find",
"all",
"matching",
"dependencies",
"using",
"the",
"supplied",
"finder",
"and",
"the",
"given",
"ireq",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L57-L77 | [
"def",
"find_all_matches",
"(",
"finder",
",",
"ireq",
",",
"pre",
"=",
"False",
")",
":",
"# type: (PackageFinder, InstallRequirement, bool) -> List[InstallationCandidate]",
"candidates",
"=",
"clean_requires_python",
"(",
"finder",
".",
"find_all_candidates",
"(",
"ireq",... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | get_abstract_dependencies | Get all abstract dependencies for a given list of requirements.
Given a set of requirements, convert each requirement to an Abstract Dependency.
:param reqs: A list of Requirements
:type reqs: list[:class:`~requirementslib.models.requirements.Requirement`]
:param sources: Pipfile-formatted sources, defaults to None
:param sources: list[dict], optional
:param parent: The parent of this list of dependencies, defaults to None
:param parent: :class:`~requirementslib.models.requirements.Requirement`, optional
:return: A list of Abstract Dependencies
:rtype: list[:class:`~requirementslib.models.dependency.AbstractDependency`] | pipenv/vendor/requirementslib/models/dependencies.py | def get_abstract_dependencies(reqs, sources=None, parent=None):
"""Get all abstract dependencies for a given list of requirements.
Given a set of requirements, convert each requirement to an Abstract Dependency.
:param reqs: A list of Requirements
:type reqs: list[:class:`~requirementslib.models.requirements.Requirement`]
:param sources: Pipfile-formatted sources, defaults to None
:param sources: list[dict], optional
:param parent: The parent of this list of dependencies, defaults to None
:param parent: :class:`~requirementslib.models.requirements.Requirement`, optional
:return: A list of Abstract Dependencies
:rtype: list[:class:`~requirementslib.models.dependency.AbstractDependency`]
"""
deps = []
from .requirements import Requirement
for req in reqs:
if isinstance(req, pip_shims.shims.InstallRequirement):
requirement = Requirement.from_line(
"{0}{1}".format(req.name, req.specifier)
)
if req.link:
requirement.req.link = req.link
requirement.markers = req.markers
requirement.req.markers = req.markers
requirement.extras = req.extras
requirement.req.extras = req.extras
elif isinstance(req, Requirement):
requirement = copy.deepcopy(req)
else:
requirement = Requirement.from_line(req)
dep = AbstractDependency.from_requirement(requirement, parent=parent)
deps.append(dep)
return deps | def get_abstract_dependencies(reqs, sources=None, parent=None):
"""Get all abstract dependencies for a given list of requirements.
Given a set of requirements, convert each requirement to an Abstract Dependency.
:param reqs: A list of Requirements
:type reqs: list[:class:`~requirementslib.models.requirements.Requirement`]
:param sources: Pipfile-formatted sources, defaults to None
:param sources: list[dict], optional
:param parent: The parent of this list of dependencies, defaults to None
:param parent: :class:`~requirementslib.models.requirements.Requirement`, optional
:return: A list of Abstract Dependencies
:rtype: list[:class:`~requirementslib.models.dependency.AbstractDependency`]
"""
deps = []
from .requirements import Requirement
for req in reqs:
if isinstance(req, pip_shims.shims.InstallRequirement):
requirement = Requirement.from_line(
"{0}{1}".format(req.name, req.specifier)
)
if req.link:
requirement.req.link = req.link
requirement.markers = req.markers
requirement.req.markers = req.markers
requirement.extras = req.extras
requirement.req.extras = req.extras
elif isinstance(req, Requirement):
requirement = copy.deepcopy(req)
else:
requirement = Requirement.from_line(req)
dep = AbstractDependency.from_requirement(requirement, parent=parent)
deps.append(dep)
return deps | [
"Get",
"all",
"abstract",
"dependencies",
"for",
"a",
"given",
"list",
"of",
"requirements",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L262-L297 | [
"def",
"get_abstract_dependencies",
"(",
"reqs",
",",
"sources",
"=",
"None",
",",
"parent",
"=",
"None",
")",
":",
"deps",
"=",
"[",
"]",
"from",
".",
"requirements",
"import",
"Requirement",
"for",
"req",
"in",
"reqs",
":",
"if",
"isinstance",
"(",
"re... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | get_dependencies | Get all dependencies for a given install requirement.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:param sources: Pipfile-formatted sources, defaults to None
:type sources: list[dict], optional
:param parent: The parent of this list of dependencies, defaults to None
:type parent: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallRequirements.
:rtype: set(str) | pipenv/vendor/requirementslib/models/dependencies.py | def get_dependencies(ireq, sources=None, parent=None):
# type: (Union[InstallRequirement, InstallationCandidate], Optional[List[Dict[S, Union[S, bool]]]], Optional[AbstractDependency]) -> Set[S, ...]
"""Get all dependencies for a given install requirement.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:param sources: Pipfile-formatted sources, defaults to None
:type sources: list[dict], optional
:param parent: The parent of this list of dependencies, defaults to None
:type parent: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallRequirements.
:rtype: set(str)
"""
if not isinstance(ireq, pip_shims.shims.InstallRequirement):
name = getattr(
ireq, "project_name",
getattr(ireq, "project", ireq.name),
)
version = getattr(ireq, "version", None)
if not version:
ireq = pip_shims.shims.InstallRequirement.from_line("{0}".format(name))
else:
ireq = pip_shims.shims.InstallRequirement.from_line("{0}=={1}".format(name, version))
pip_options = get_pip_options(sources=sources)
getters = [
get_dependencies_from_cache,
get_dependencies_from_wheel_cache,
get_dependencies_from_json,
functools.partial(get_dependencies_from_index, pip_options=pip_options)
]
for getter in getters:
deps = getter(ireq)
if deps is not None:
return deps
raise RuntimeError('failed to get dependencies for {}'.format(ireq)) | def get_dependencies(ireq, sources=None, parent=None):
# type: (Union[InstallRequirement, InstallationCandidate], Optional[List[Dict[S, Union[S, bool]]]], Optional[AbstractDependency]) -> Set[S, ...]
"""Get all dependencies for a given install requirement.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:param sources: Pipfile-formatted sources, defaults to None
:type sources: list[dict], optional
:param parent: The parent of this list of dependencies, defaults to None
:type parent: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallRequirements.
:rtype: set(str)
"""
if not isinstance(ireq, pip_shims.shims.InstallRequirement):
name = getattr(
ireq, "project_name",
getattr(ireq, "project", ireq.name),
)
version = getattr(ireq, "version", None)
if not version:
ireq = pip_shims.shims.InstallRequirement.from_line("{0}".format(name))
else:
ireq = pip_shims.shims.InstallRequirement.from_line("{0}=={1}".format(name, version))
pip_options = get_pip_options(sources=sources)
getters = [
get_dependencies_from_cache,
get_dependencies_from_wheel_cache,
get_dependencies_from_json,
functools.partial(get_dependencies_from_index, pip_options=pip_options)
]
for getter in getters:
deps = getter(ireq)
if deps is not None:
return deps
raise RuntimeError('failed to get dependencies for {}'.format(ireq)) | [
"Get",
"all",
"dependencies",
"for",
"a",
"given",
"install",
"requirement",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L300-L334 | [
"def",
"get_dependencies",
"(",
"ireq",
",",
"sources",
"=",
"None",
",",
"parent",
"=",
"None",
")",
":",
"# type: (Union[InstallRequirement, InstallationCandidate], Optional[List[Dict[S, Union[S, bool]]]], Optional[AbstractDependency]) -> Set[S, ...]",
"if",
"not",
"isinstance",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | get_dependencies_from_wheel_cache | Retrieves dependencies for the given install requirement from the wheel cache.
: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/requirementslib/models/dependencies.py | def get_dependencies_from_wheel_cache(ireq):
"""Retrieves dependencies for the given install requirement from the wheel cache.
: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 ireq.editable or not is_pinned_requirement(ireq):
return
matches = WHEEL_CACHE.get(ireq.link, name_from_req(ireq.req))
if matches:
matches = set(matches)
if not DEPENDENCY_CACHE.get(ireq):
DEPENDENCY_CACHE[ireq] = [format_requirement(m) for m in matches]
return matches
return | def get_dependencies_from_wheel_cache(ireq):
"""Retrieves dependencies for the given install requirement from the wheel cache.
: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 ireq.editable or not is_pinned_requirement(ireq):
return
matches = WHEEL_CACHE.get(ireq.link, name_from_req(ireq.req))
if matches:
matches = set(matches)
if not DEPENDENCY_CACHE.get(ireq):
DEPENDENCY_CACHE[ireq] = [format_requirement(m) for m in matches]
return matches
return | [
"Retrieves",
"dependencies",
"for",
"the",
"given",
"install",
"requirement",
"from",
"the",
"wheel",
"cache",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L337-L354 | [
"def",
"get_dependencies_from_wheel_cache",
"(",
"ireq",
")",
":",
"if",
"ireq",
".",
"editable",
"or",
"not",
"is_pinned_requirement",
"(",
"ireq",
")",
":",
"return",
"matches",
"=",
"WHEEL_CACHE",
".",
"get",
"(",
"ireq",
".",
"link",
",",
"name_from_req",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | get_dependencies_from_json | Retrieves dependencies for the given 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/requirementslib/models/dependencies.py | def get_dependencies_from_json(ireq):
"""Retrieves dependencies for the given 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 ireq.editable or not is_pinned_requirement(ireq):
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
session = requests.session()
atexit.register(session.close)
version = str(ireq.req.specifier).lstrip("=")
def gen(ireq):
info = None
try:
info = session.get(
"https://pypi.org/pypi/{0}/{1}/json".format(ireq.req.name, version)
).json()["info"]
finally:
session.close()
requires_dist = info.get("requires_dist", info.get("requires"))
if not requires_dist: # The API can return None for this.
return
for requires in requires_dist:
i = pip_shims.shims.InstallRequirement.from_line(requires)
# See above, we don't handle requirements with extras.
if not _marker_contains_extra(i):
yield format_requirement(i)
if ireq not in DEPENDENCY_CACHE:
try:
reqs = DEPENDENCY_CACHE[ireq] = list(gen(ireq))
except JSONDecodeError:
return
req_iter = iter(reqs)
else:
req_iter = gen(ireq)
return set(req_iter) | def get_dependencies_from_json(ireq):
"""Retrieves dependencies for the given 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 ireq.editable or not is_pinned_requirement(ireq):
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
session = requests.session()
atexit.register(session.close)
version = str(ireq.req.specifier).lstrip("=")
def gen(ireq):
info = None
try:
info = session.get(
"https://pypi.org/pypi/{0}/{1}/json".format(ireq.req.name, version)
).json()["info"]
finally:
session.close()
requires_dist = info.get("requires_dist", info.get("requires"))
if not requires_dist: # The API can return None for this.
return
for requires in requires_dist:
i = pip_shims.shims.InstallRequirement.from_line(requires)
# See above, we don't handle requirements with extras.
if not _marker_contains_extra(i):
yield format_requirement(i)
if ireq not in DEPENDENCY_CACHE:
try:
reqs = DEPENDENCY_CACHE[ireq] = list(gen(ireq))
except JSONDecodeError:
return
req_iter = iter(reqs)
else:
req_iter = gen(ireq)
return set(req_iter) | [
"Retrieves",
"dependencies",
"for",
"the",
"given",
"install",
"requirement",
"from",
"the",
"json",
"api",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L362-L408 | [
"def",
"get_dependencies_from_json",
"(",
"ireq",
")",
":",
"if",
"ireq",
".",
"editable",
"or",
"not",
"is_pinned_requirement",
"(",
"ireq",
")",
":",
"return",
"# It is technically possible to parse extras out of the JSON API's",
"# requirement format, but it is such a chore ... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | get_dependencies_from_cache | Retrieves dependencies for the given install requirement from the dependency cache.
: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/requirementslib/models/dependencies.py | def get_dependencies_from_cache(ireq):
"""Retrieves dependencies for the given install requirement from the dependency cache.
: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 ireq.editable or not is_pinned_requirement(ireq):
return
if ireq not in DEPENDENCY_CACHE:
return
cached = set(DEPENDENCY_CACHE[ireq])
# 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:
broken = False
for line in cached:
dep_ireq = pip_shims.shims.InstallRequirement.from_line(line)
name = canonicalize_name(dep_ireq.name)
if _marker_contains_extra(dep_ireq):
broken = True # The "extra =" marker breaks everything.
elif name == canonicalize_name(ireq.name):
broken = True # A package cannot depend on itself.
if broken:
break
except Exception:
broken = True
if broken:
del DEPENDENCY_CACHE[ireq]
return
return cached | def get_dependencies_from_cache(ireq):
"""Retrieves dependencies for the given install requirement from the dependency cache.
: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 ireq.editable or not is_pinned_requirement(ireq):
return
if ireq not in DEPENDENCY_CACHE:
return
cached = set(DEPENDENCY_CACHE[ireq])
# 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:
broken = False
for line in cached:
dep_ireq = pip_shims.shims.InstallRequirement.from_line(line)
name = canonicalize_name(dep_ireq.name)
if _marker_contains_extra(dep_ireq):
broken = True # The "extra =" marker breaks everything.
elif name == canonicalize_name(ireq.name):
broken = True # A package cannot depend on itself.
if broken:
break
except Exception:
broken = True
if broken:
del DEPENDENCY_CACHE[ireq]
return
return cached | [
"Retrieves",
"dependencies",
"for",
"the",
"given",
"install",
"requirement",
"from",
"the",
"dependency",
"cache",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L411-L445 | [
"def",
"get_dependencies_from_cache",
"(",
"ireq",
")",
":",
"if",
"ireq",
".",
"editable",
"or",
"not",
"is_pinned_requirement",
"(",
"ireq",
")",
":",
"return",
"if",
"ireq",
"not",
"in",
"DEPENDENCY_CACHE",
":",
"return",
"cached",
"=",
"set",
"(",
"DEPEN... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | get_dependencies_from_index | Retrieves dependencies for the given install requirement from the pip resolver.
:param dep: A single InstallRequirement
:type dep: :class:`~pip._internal.req.req_install.InstallRequirement`
:param sources: Pipfile-formatted sources, defaults to None
:type sources: list[dict], optional
:return: A set of dependency lines for generating new InstallRequirements.
:rtype: set(str) or None | pipenv/vendor/requirementslib/models/dependencies.py | def get_dependencies_from_index(dep, sources=None, pip_options=None, wheel_cache=None):
"""Retrieves dependencies for the given install requirement from the pip resolver.
:param dep: A single InstallRequirement
:type dep: :class:`~pip._internal.req.req_install.InstallRequirement`
:param sources: Pipfile-formatted sources, defaults to None
:type sources: list[dict], optional
:return: A set of dependency lines for generating new InstallRequirements.
:rtype: set(str) or None
"""
finder = get_finder(sources=sources, pip_options=pip_options)
if not wheel_cache:
wheel_cache = WHEEL_CACHE
dep.is_direct = True
reqset = pip_shims.shims.RequirementSet()
reqset.add_requirement(dep)
requirements = None
setup_requires = {}
with temp_environ(), start_resolver(finder=finder, wheel_cache=wheel_cache) as resolver:
os.environ['PIP_EXISTS_ACTION'] = 'i'
dist = None
if dep.editable and not dep.prepared and not dep.req:
with cd(dep.setup_py_dir):
from setuptools.dist import distutils
try:
dist = distutils.core.run_setup(dep.setup_py)
except (ImportError, TypeError, AttributeError):
dist = None
else:
setup_requires[dist.get_name()] = dist.setup_requires
if not dist:
try:
dist = dep.get_dist()
except (TypeError, ValueError, AttributeError):
pass
else:
setup_requires[dist.get_name()] = dist.setup_requires
resolver.require_hashes = False
try:
results = resolver._resolve_one(reqset, dep)
except Exception:
# FIXME: Needs to bubble the exception somehow to the user.
results = []
finally:
try:
wheel_cache.cleanup()
except AttributeError:
pass
resolver_requires_python = getattr(resolver, "requires_python", None)
requires_python = getattr(reqset, "requires_python", resolver_requires_python)
if requires_python:
add_marker = fix_requires_python_marker(requires_python)
reqset.remove(dep)
if dep.req.marker:
dep.req.marker._markers.extend(['and',].extend(add_marker._markers))
else:
dep.req.marker = add_marker
reqset.add(dep)
requirements = set()
for r in results:
if requires_python:
if r.req.marker:
r.req.marker._markers.extend(['and',].extend(add_marker._markers))
else:
r.req.marker = add_marker
requirements.add(format_requirement(r))
for section in setup_requires:
python_version = section
not_python = not is_python(section)
# This is for cleaning up :extras: formatted markers
# by adding them to the results of the resolver
# since any such extra would have been returned as a result anyway
for value in setup_requires[section]:
# This is a marker.
if is_python(section):
python_version = value[1:-1]
else:
not_python = True
if ':' not in value and not_python:
try:
requirement_str = "{0}{1}".format(value, python_version).replace(":", ";")
requirements.add(format_requirement(make_install_requirement(requirement_str).ireq))
# Anything could go wrong here -- can't be too careful.
except Exception:
pass
if not dep.editable and is_pinned_requirement(dep) and requirements is not None:
DEPENDENCY_CACHE[dep] = list(requirements)
return requirements | def get_dependencies_from_index(dep, sources=None, pip_options=None, wheel_cache=None):
"""Retrieves dependencies for the given install requirement from the pip resolver.
:param dep: A single InstallRequirement
:type dep: :class:`~pip._internal.req.req_install.InstallRequirement`
:param sources: Pipfile-formatted sources, defaults to None
:type sources: list[dict], optional
:return: A set of dependency lines for generating new InstallRequirements.
:rtype: set(str) or None
"""
finder = get_finder(sources=sources, pip_options=pip_options)
if not wheel_cache:
wheel_cache = WHEEL_CACHE
dep.is_direct = True
reqset = pip_shims.shims.RequirementSet()
reqset.add_requirement(dep)
requirements = None
setup_requires = {}
with temp_environ(), start_resolver(finder=finder, wheel_cache=wheel_cache) as resolver:
os.environ['PIP_EXISTS_ACTION'] = 'i'
dist = None
if dep.editable and not dep.prepared and not dep.req:
with cd(dep.setup_py_dir):
from setuptools.dist import distutils
try:
dist = distutils.core.run_setup(dep.setup_py)
except (ImportError, TypeError, AttributeError):
dist = None
else:
setup_requires[dist.get_name()] = dist.setup_requires
if not dist:
try:
dist = dep.get_dist()
except (TypeError, ValueError, AttributeError):
pass
else:
setup_requires[dist.get_name()] = dist.setup_requires
resolver.require_hashes = False
try:
results = resolver._resolve_one(reqset, dep)
except Exception:
# FIXME: Needs to bubble the exception somehow to the user.
results = []
finally:
try:
wheel_cache.cleanup()
except AttributeError:
pass
resolver_requires_python = getattr(resolver, "requires_python", None)
requires_python = getattr(reqset, "requires_python", resolver_requires_python)
if requires_python:
add_marker = fix_requires_python_marker(requires_python)
reqset.remove(dep)
if dep.req.marker:
dep.req.marker._markers.extend(['and',].extend(add_marker._markers))
else:
dep.req.marker = add_marker
reqset.add(dep)
requirements = set()
for r in results:
if requires_python:
if r.req.marker:
r.req.marker._markers.extend(['and',].extend(add_marker._markers))
else:
r.req.marker = add_marker
requirements.add(format_requirement(r))
for section in setup_requires:
python_version = section
not_python = not is_python(section)
# This is for cleaning up :extras: formatted markers
# by adding them to the results of the resolver
# since any such extra would have been returned as a result anyway
for value in setup_requires[section]:
# This is a marker.
if is_python(section):
python_version = value[1:-1]
else:
not_python = True
if ':' not in value and not_python:
try:
requirement_str = "{0}{1}".format(value, python_version).replace(":", ";")
requirements.add(format_requirement(make_install_requirement(requirement_str).ireq))
# Anything could go wrong here -- can't be too careful.
except Exception:
pass
if not dep.editable and is_pinned_requirement(dep) and requirements is not None:
DEPENDENCY_CACHE[dep] = list(requirements)
return requirements | [
"Retrieves",
"dependencies",
"for",
"the",
"given",
"install",
"requirement",
"from",
"the",
"pip",
"resolver",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L452-L544 | [
"def",
"get_dependencies_from_index",
"(",
"dep",
",",
"sources",
"=",
"None",
",",
"pip_options",
"=",
"None",
",",
"wheel_cache",
"=",
"None",
")",
":",
"finder",
"=",
"get_finder",
"(",
"sources",
"=",
"sources",
",",
"pip_options",
"=",
"pip_options",
")... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | get_pip_options | Build a pip command from a list of sources
:param args: positional arguments passed through to the pip parser
:param sources: A list of pipfile-formatted sources, defaults to None
:param sources: list[dict], optional
:param pip_command: A pre-built pip command instance
:type pip_command: :class:`~pip._internal.cli.base_command.Command`
:return: An instance of pip_options using the supplied arguments plus sane defaults
:rtype: :class:`~pip._internal.cli.cmdoptions` | pipenv/vendor/requirementslib/models/dependencies.py | def get_pip_options(args=[], sources=None, pip_command=None):
"""Build a pip command from a list of sources
:param args: positional arguments passed through to the pip parser
:param sources: A list of pipfile-formatted sources, defaults to None
:param sources: list[dict], optional
:param pip_command: A pre-built pip command instance
:type pip_command: :class:`~pip._internal.cli.base_command.Command`
:return: An instance of pip_options using the supplied arguments plus sane defaults
:rtype: :class:`~pip._internal.cli.cmdoptions`
"""
if not pip_command:
pip_command = get_pip_command()
if not sources:
sources = [
{"url": "https://pypi.org/simple", "name": "pypi", "verify_ssl": True}
]
_ensure_dir(CACHE_DIR)
pip_args = args
pip_args = prepare_pip_source_args(sources, pip_args)
pip_options, _ = pip_command.parser.parse_args(pip_args)
pip_options.cache_dir = CACHE_DIR
return pip_options | def get_pip_options(args=[], sources=None, pip_command=None):
"""Build a pip command from a list of sources
:param args: positional arguments passed through to the pip parser
:param sources: A list of pipfile-formatted sources, defaults to None
:param sources: list[dict], optional
:param pip_command: A pre-built pip command instance
:type pip_command: :class:`~pip._internal.cli.base_command.Command`
:return: An instance of pip_options using the supplied arguments plus sane defaults
:rtype: :class:`~pip._internal.cli.cmdoptions`
"""
if not pip_command:
pip_command = get_pip_command()
if not sources:
sources = [
{"url": "https://pypi.org/simple", "name": "pypi", "verify_ssl": True}
]
_ensure_dir(CACHE_DIR)
pip_args = args
pip_args = prepare_pip_source_args(sources, pip_args)
pip_options, _ = pip_command.parser.parse_args(pip_args)
pip_options.cache_dir = CACHE_DIR
return pip_options | [
"Build",
"a",
"pip",
"command",
"from",
"a",
"list",
"of",
"sources"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L547-L570 | [
"def",
"get_pip_options",
"(",
"args",
"=",
"[",
"]",
",",
"sources",
"=",
"None",
",",
"pip_command",
"=",
"None",
")",
":",
"if",
"not",
"pip_command",
":",
"pip_command",
"=",
"get_pip_command",
"(",
")",
"if",
"not",
"sources",
":",
"sources",
"=",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | get_finder | Get a package finder for looking up candidates to install
:param sources: A list of pipfile-formatted sources, defaults to None
:param sources: list[dict], optional
:param pip_command: A pip command instance, defaults to None
:type pip_command: :class:`~pip._internal.cli.base_command.Command`
:param pip_options: A pip options, defaults to None
:type pip_options: :class:`~pip._internal.cli.cmdoptions`
:return: A package finder
:rtype: :class:`~pip._internal.index.PackageFinder` | pipenv/vendor/requirementslib/models/dependencies.py | def get_finder(sources=None, pip_command=None, pip_options=None):
# type: (List[Dict[S, Union[S, bool]]], Optional[Command], Any) -> PackageFinder
"""Get a package finder for looking up candidates to install
:param sources: A list of pipfile-formatted sources, defaults to None
:param sources: list[dict], optional
:param pip_command: A pip command instance, defaults to None
:type pip_command: :class:`~pip._internal.cli.base_command.Command`
:param pip_options: A pip options, defaults to None
:type pip_options: :class:`~pip._internal.cli.cmdoptions`
:return: A package finder
:rtype: :class:`~pip._internal.index.PackageFinder`
"""
if not pip_command:
pip_command = get_pip_command()
if not sources:
sources = [
{"url": "https://pypi.org/simple", "name": "pypi", "verify_ssl": True}
]
if not pip_options:
pip_options = get_pip_options(sources=sources, pip_command=pip_command)
session = pip_command._build_session(pip_options)
atexit.register(session.close)
finder = pip_shims.shims.PackageFinder(
find_links=[],
index_urls=[s.get("url") for s in sources],
trusted_hosts=[],
allow_all_prereleases=pip_options.pre,
session=session,
)
return finder | def get_finder(sources=None, pip_command=None, pip_options=None):
# type: (List[Dict[S, Union[S, bool]]], Optional[Command], Any) -> PackageFinder
"""Get a package finder for looking up candidates to install
:param sources: A list of pipfile-formatted sources, defaults to None
:param sources: list[dict], optional
:param pip_command: A pip command instance, defaults to None
:type pip_command: :class:`~pip._internal.cli.base_command.Command`
:param pip_options: A pip options, defaults to None
:type pip_options: :class:`~pip._internal.cli.cmdoptions`
:return: A package finder
:rtype: :class:`~pip._internal.index.PackageFinder`
"""
if not pip_command:
pip_command = get_pip_command()
if not sources:
sources = [
{"url": "https://pypi.org/simple", "name": "pypi", "verify_ssl": True}
]
if not pip_options:
pip_options = get_pip_options(sources=sources, pip_command=pip_command)
session = pip_command._build_session(pip_options)
atexit.register(session.close)
finder = pip_shims.shims.PackageFinder(
find_links=[],
index_urls=[s.get("url") for s in sources],
trusted_hosts=[],
allow_all_prereleases=pip_options.pre,
session=session,
)
return finder | [
"Get",
"a",
"package",
"finder",
"for",
"looking",
"up",
"candidates",
"to",
"install"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L573-L604 | [
"def",
"get_finder",
"(",
"sources",
"=",
"None",
",",
"pip_command",
"=",
"None",
",",
"pip_options",
"=",
"None",
")",
":",
"# type: (List[Dict[S, Union[S, bool]]], Optional[Command], Any) -> PackageFinder",
"if",
"not",
"pip_command",
":",
"pip_command",
"=",
"get_pi... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | start_resolver | Context manager to produce a resolver.
:param finder: A package finder to use for searching the index
:type finder: :class:`~pip._internal.index.PackageFinder`
:return: A 3-tuple of finder, preparer, resolver
:rtype: (:class:`~pip._internal.operations.prepare.RequirementPreparer`, :class:`~pip._internal.resolve.Resolver`) | pipenv/vendor/requirementslib/models/dependencies.py | def start_resolver(finder=None, wheel_cache=None):
"""Context manager to produce a resolver.
:param finder: A package finder to use for searching the index
:type finder: :class:`~pip._internal.index.PackageFinder`
:return: A 3-tuple of finder, preparer, resolver
:rtype: (:class:`~pip._internal.operations.prepare.RequirementPreparer`, :class:`~pip._internal.resolve.Resolver`)
"""
pip_command = get_pip_command()
pip_options = get_pip_options(pip_command=pip_command)
if not finder:
finder = get_finder(pip_command=pip_command, pip_options=pip_options)
if not wheel_cache:
wheel_cache = WHEEL_CACHE
_ensure_dir(fs_str(os.path.join(wheel_cache.cache_dir, "wheels")))
download_dir = PKGS_DOWNLOAD_DIR
_ensure_dir(download_dir)
_build_dir = create_tracked_tempdir(fs_str("build"))
_source_dir = create_tracked_tempdir(fs_str("source"))
preparer = partialclass(
pip_shims.shims.RequirementPreparer,
build_dir=_build_dir,
src_dir=_source_dir,
download_dir=download_dir,
wheel_download_dir=WHEEL_DOWNLOAD_DIR,
progress_bar="off",
build_isolation=False,
)
resolver = partialclass(
pip_shims.shims.Resolver,
finder=finder,
session=finder.session,
upgrade_strategy="to-satisfy-only",
force_reinstall=True,
ignore_dependencies=False,
ignore_requires_python=True,
ignore_installed=True,
isolated=False,
wheel_cache=wheel_cache,
use_user_site=False,
)
try:
if packaging.version.parse(pip_shims.shims.pip_version) >= packaging.version.parse('18'):
with pip_shims.shims.RequirementTracker() as req_tracker:
preparer = preparer(req_tracker=req_tracker)
yield resolver(preparer=preparer)
else:
preparer = preparer()
yield resolver(preparer=preparer)
finally:
finder.session.close() | def start_resolver(finder=None, wheel_cache=None):
"""Context manager to produce a resolver.
:param finder: A package finder to use for searching the index
:type finder: :class:`~pip._internal.index.PackageFinder`
:return: A 3-tuple of finder, preparer, resolver
:rtype: (:class:`~pip._internal.operations.prepare.RequirementPreparer`, :class:`~pip._internal.resolve.Resolver`)
"""
pip_command = get_pip_command()
pip_options = get_pip_options(pip_command=pip_command)
if not finder:
finder = get_finder(pip_command=pip_command, pip_options=pip_options)
if not wheel_cache:
wheel_cache = WHEEL_CACHE
_ensure_dir(fs_str(os.path.join(wheel_cache.cache_dir, "wheels")))
download_dir = PKGS_DOWNLOAD_DIR
_ensure_dir(download_dir)
_build_dir = create_tracked_tempdir(fs_str("build"))
_source_dir = create_tracked_tempdir(fs_str("source"))
preparer = partialclass(
pip_shims.shims.RequirementPreparer,
build_dir=_build_dir,
src_dir=_source_dir,
download_dir=download_dir,
wheel_download_dir=WHEEL_DOWNLOAD_DIR,
progress_bar="off",
build_isolation=False,
)
resolver = partialclass(
pip_shims.shims.Resolver,
finder=finder,
session=finder.session,
upgrade_strategy="to-satisfy-only",
force_reinstall=True,
ignore_dependencies=False,
ignore_requires_python=True,
ignore_installed=True,
isolated=False,
wheel_cache=wheel_cache,
use_user_site=False,
)
try:
if packaging.version.parse(pip_shims.shims.pip_version) >= packaging.version.parse('18'):
with pip_shims.shims.RequirementTracker() as req_tracker:
preparer = preparer(req_tracker=req_tracker)
yield resolver(preparer=preparer)
else:
preparer = preparer()
yield resolver(preparer=preparer)
finally:
finder.session.close() | [
"Context",
"manager",
"to",
"produce",
"a",
"resolver",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L608-L663 | [
"def",
"start_resolver",
"(",
"finder",
"=",
"None",
",",
"wheel_cache",
"=",
"None",
")",
":",
"pip_command",
"=",
"get_pip_command",
"(",
")",
"pip_options",
"=",
"get_pip_options",
"(",
"pip_command",
"=",
"pip_command",
")",
"if",
"not",
"finder",
":",
"... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | DependencyCache.as_cache_key | Given a requirement, return its cache key. This behavior is a little weird in order to allow backwards
compatibility with cache files. For a requirement without extras, this will return, for example:
("ipython", "2.1.0")
For a requirement with extras, the extras will be comma-separated and appended to the version, inside brackets,
like so:
("ipython", "2.1.0[nbconvert,notebook]") | pipenv/vendor/requirementslib/models/cache.py | def as_cache_key(self, ireq):
"""
Given a requirement, return its cache key. This behavior is a little weird in order to allow backwards
compatibility with cache files. For a requirement without extras, this will return, for example:
("ipython", "2.1.0")
For a requirement with extras, the extras will be comma-separated and appended to the version, inside brackets,
like so:
("ipython", "2.1.0[nbconvert,notebook]")
"""
name, version, extras = as_tuple(ireq)
if not extras:
extras_string = ""
else:
extras_string = "[{}]".format(",".join(extras))
return name, "{}{}".format(version, extras_string) | def as_cache_key(self, ireq):
"""
Given a requirement, return its cache key. This behavior is a little weird in order to allow backwards
compatibility with cache files. For a requirement without extras, this will return, for example:
("ipython", "2.1.0")
For a requirement with extras, the extras will be comma-separated and appended to the version, inside brackets,
like so:
("ipython", "2.1.0[nbconvert,notebook]")
"""
name, version, extras = as_tuple(ireq)
if not extras:
extras_string = ""
else:
extras_string = "[{}]".format(",".join(extras))
return name, "{}{}".format(version, extras_string) | [
"Given",
"a",
"requirement",
"return",
"its",
"cache",
"key",
".",
"This",
"behavior",
"is",
"a",
"little",
"weird",
"in",
"order",
"to",
"allow",
"backwards",
"compatibility",
"with",
"cache",
"files",
".",
"For",
"a",
"requirement",
"without",
"extras",
"t... | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/cache.py#L86-L103 | [
"def",
"as_cache_key",
"(",
"self",
",",
"ireq",
")",
":",
"name",
",",
"version",
",",
"extras",
"=",
"as_tuple",
"(",
"ireq",
")",
"if",
"not",
"extras",
":",
"extras_string",
"=",
"\"\"",
"else",
":",
"extras_string",
"=",
"\"[{}]\"",
".",
"format",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | DependencyCache.read_cache | Reads the cached contents into memory. | pipenv/vendor/requirementslib/models/cache.py | def read_cache(self):
"""Reads the cached contents into memory."""
if os.path.exists(self._cache_file):
self._cache = read_cache_file(self._cache_file)
else:
self._cache = {} | def read_cache(self):
"""Reads the cached contents into memory."""
if os.path.exists(self._cache_file):
self._cache = read_cache_file(self._cache_file)
else:
self._cache = {} | [
"Reads",
"the",
"cached",
"contents",
"into",
"memory",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/cache.py#L105-L110 | [
"def",
"read_cache",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_cache_file",
")",
":",
"self",
".",
"_cache",
"=",
"read_cache_file",
"(",
"self",
".",
"_cache_file",
")",
"else",
":",
"self",
".",
"_cache",
"=... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | DependencyCache.write_cache | Writes the cache to disk as JSON. | pipenv/vendor/requirementslib/models/cache.py | def write_cache(self):
"""Writes the cache to disk as JSON."""
doc = {
'__format__': 1,
'dependencies': self._cache,
}
with open(self._cache_file, 'w') as f:
json.dump(doc, f, sort_keys=True) | def write_cache(self):
"""Writes the cache to disk as JSON."""
doc = {
'__format__': 1,
'dependencies': self._cache,
}
with open(self._cache_file, 'w') as f:
json.dump(doc, f, sort_keys=True) | [
"Writes",
"the",
"cache",
"to",
"disk",
"as",
"JSON",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/cache.py#L112-L119 | [
"def",
"write_cache",
"(",
"self",
")",
":",
"doc",
"=",
"{",
"'__format__'",
":",
"1",
",",
"'dependencies'",
":",
"self",
".",
"_cache",
",",
"}",
"with",
"open",
"(",
"self",
".",
"_cache_file",
",",
"'w'",
")",
"as",
"f",
":",
"json",
".",
"dum... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | DependencyCache.reverse_dependencies | Returns a lookup table of reverse dependencies for all the given ireqs.
Since this is all static, it only works if the dependency cache
contains the complete data, otherwise you end up with a partial view.
This is typically no problem if you use this function after the entire
dependency tree is resolved. | pipenv/vendor/requirementslib/models/cache.py | def reverse_dependencies(self, ireqs):
"""
Returns a lookup table of reverse dependencies for all the given ireqs.
Since this is all static, it only works if the dependency cache
contains the complete data, otherwise you end up with a partial view.
This is typically no problem if you use this function after the entire
dependency tree is resolved.
"""
ireqs_as_cache_values = [self.as_cache_key(ireq) for ireq in ireqs]
return self._reverse_dependencies(ireqs_as_cache_values) | def reverse_dependencies(self, ireqs):
"""
Returns a lookup table of reverse dependencies for all the given ireqs.
Since this is all static, it only works if the dependency cache
contains the complete data, otherwise you end up with a partial view.
This is typically no problem if you use this function after the entire
dependency tree is resolved.
"""
ireqs_as_cache_values = [self.as_cache_key(ireq) for ireq in ireqs]
return self._reverse_dependencies(ireqs_as_cache_values) | [
"Returns",
"a",
"lookup",
"table",
"of",
"reverse",
"dependencies",
"for",
"all",
"the",
"given",
"ireqs",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/cache.py#L151-L161 | [
"def",
"reverse_dependencies",
"(",
"self",
",",
"ireqs",
")",
":",
"ireqs_as_cache_values",
"=",
"[",
"self",
".",
"as_cache_key",
"(",
"ireq",
")",
"for",
"ireq",
"in",
"ireqs",
"]",
"return",
"self",
".",
"_reverse_dependencies",
"(",
"ireqs_as_cache_values",... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | DependencyCache._reverse_dependencies | Returns a lookup table of reverse dependencies for all the given cache keys.
Example input:
[('pep8', '1.5.7'),
('flake8', '2.4.0'),
('mccabe', '0.3'),
('pyflakes', '0.8.1')]
Example output:
{'pep8': ['flake8'],
'flake8': [],
'mccabe': ['flake8'],
'pyflakes': ['flake8']} | pipenv/vendor/requirementslib/models/cache.py | def _reverse_dependencies(self, cache_keys):
"""
Returns a lookup table of reverse dependencies for all the given cache keys.
Example input:
[('pep8', '1.5.7'),
('flake8', '2.4.0'),
('mccabe', '0.3'),
('pyflakes', '0.8.1')]
Example output:
{'pep8': ['flake8'],
'flake8': [],
'mccabe': ['flake8'],
'pyflakes': ['flake8']}
"""
# First, collect all the dependencies into a sequence of (parent, child) tuples, like [('flake8', 'pep8'),
# ('flake8', 'mccabe'), ...]
return lookup_table((key_from_req(Requirement(dep_name)), name)
for name, version_and_extras in cache_keys
for dep_name in self.cache[name][version_and_extras]) | def _reverse_dependencies(self, cache_keys):
"""
Returns a lookup table of reverse dependencies for all the given cache keys.
Example input:
[('pep8', '1.5.7'),
('flake8', '2.4.0'),
('mccabe', '0.3'),
('pyflakes', '0.8.1')]
Example output:
{'pep8': ['flake8'],
'flake8': [],
'mccabe': ['flake8'],
'pyflakes': ['flake8']}
"""
# First, collect all the dependencies into a sequence of (parent, child) tuples, like [('flake8', 'pep8'),
# ('flake8', 'mccabe'), ...]
return lookup_table((key_from_req(Requirement(dep_name)), name)
for name, version_and_extras in cache_keys
for dep_name in self.cache[name][version_and_extras]) | [
"Returns",
"a",
"lookup",
"table",
"of",
"reverse",
"dependencies",
"for",
"all",
"the",
"given",
"cache",
"keys",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/cache.py#L163-L186 | [
"def",
"_reverse_dependencies",
"(",
"self",
",",
"cache_keys",
")",
":",
"# First, collect all the dependencies into a sequence of (parent, child) tuples, like [('flake8', 'pep8'),",
"# ('flake8', 'mccabe'), ...]",
"return",
"lookup_table",
"(",
"(",
"key_from_req",
"(",
"Requiremen... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | _JSONCache.as_cache_key | Given a requirement, return its cache key.
This behavior is a little weird in order to allow backwards
compatibility with cache files. For a requirement without extras, this
will return, for example::
("ipython", "2.1.0")
For a requirement with extras, the extras will be comma-separated and
appended to the version, inside brackets, like so::
("ipython", "2.1.0[nbconvert,notebook]") | pipenv/vendor/requirementslib/models/cache.py | def as_cache_key(self, ireq):
"""Given a requirement, return its cache key.
This behavior is a little weird in order to allow backwards
compatibility with cache files. For a requirement without extras, this
will return, for example::
("ipython", "2.1.0")
For a requirement with extras, the extras will be comma-separated and
appended to the version, inside brackets, like so::
("ipython", "2.1.0[nbconvert,notebook]")
"""
extras = tuple(sorted(ireq.extras))
if not extras:
extras_string = ""
else:
extras_string = "[{}]".format(",".join(extras))
name = key_from_req(ireq.req)
version = get_pinned_version(ireq)
return name, "{}{}".format(version, extras_string) | def as_cache_key(self, ireq):
"""Given a requirement, return its cache key.
This behavior is a little weird in order to allow backwards
compatibility with cache files. For a requirement without extras, this
will return, for example::
("ipython", "2.1.0")
For a requirement with extras, the extras will be comma-separated and
appended to the version, inside brackets, like so::
("ipython", "2.1.0[nbconvert,notebook]")
"""
extras = tuple(sorted(ireq.extras))
if not extras:
extras_string = ""
else:
extras_string = "[{}]".format(",".join(extras))
name = key_from_req(ireq.req)
version = get_pinned_version(ireq)
return name, "{}{}".format(version, extras_string) | [
"Given",
"a",
"requirement",
"return",
"its",
"cache",
"key",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/cache.py#L266-L287 | [
"def",
"as_cache_key",
"(",
"self",
",",
"ireq",
")",
":",
"extras",
"=",
"tuple",
"(",
"sorted",
"(",
"ireq",
".",
"extras",
")",
")",
"if",
"not",
"extras",
":",
"extras_string",
"=",
"\"\"",
"else",
":",
"extras_string",
"=",
"\"[{}]\"",
".",
"forma... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | locked | Decorator which enables locks for decorated function.
Arguments:
- path: path for lockfile.
- timeout (optional): Timeout for acquiring lock.
Usage:
@locked('/var/run/myname', timeout=0)
def myname(...):
... | pipenv/patched/notpip/_vendor/lockfile/__init__.py | def locked(path, timeout=None):
"""Decorator which enables locks for decorated function.
Arguments:
- path: path for lockfile.
- timeout (optional): Timeout for acquiring lock.
Usage:
@locked('/var/run/myname', timeout=0)
def myname(...):
...
"""
def decor(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
lock = FileLock(path, timeout=timeout)
lock.acquire()
try:
return func(*args, **kwargs)
finally:
lock.release()
return wrapper
return decor | def locked(path, timeout=None):
"""Decorator which enables locks for decorated function.
Arguments:
- path: path for lockfile.
- timeout (optional): Timeout for acquiring lock.
Usage:
@locked('/var/run/myname', timeout=0)
def myname(...):
...
"""
def decor(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
lock = FileLock(path, timeout=timeout)
lock.acquire()
try:
return func(*args, **kwargs)
finally:
lock.release()
return wrapper
return decor | [
"Decorator",
"which",
"enables",
"locks",
"for",
"decorated",
"function",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/lockfile/__init__.py#L315-L337 | [
"def",
"locked",
"(",
"path",
",",
"timeout",
"=",
"None",
")",
":",
"def",
"decor",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lock",
"=",
"F... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | getTreeWalker | Get a TreeWalker class for various types of tree with built-in support
:arg str treeType: the name of the tree type required (case-insensitive).
Supported values are:
* "dom": The xml.dom.minidom DOM implementation
* "etree": A generic walker for tree implementations exposing an
elementtree-like interface (known to work with ElementTree,
cElementTree and lxml.etree).
* "lxml": Optimized walker for lxml.etree
* "genshi": a Genshi stream
:arg implementation: A module implementing the tree type e.g.
xml.etree.ElementTree or cElementTree (Currently applies to the "etree"
tree type only).
:arg kwargs: keyword arguments passed to the etree walker--for other
walkers, this has no effect
:returns: a TreeWalker class | pipenv/patched/notpip/_vendor/html5lib/treewalkers/__init__.py | def getTreeWalker(treeType, implementation=None, **kwargs):
"""Get a TreeWalker class for various types of tree with built-in support
:arg str treeType: the name of the tree type required (case-insensitive).
Supported values are:
* "dom": The xml.dom.minidom DOM implementation
* "etree": A generic walker for tree implementations exposing an
elementtree-like interface (known to work with ElementTree,
cElementTree and lxml.etree).
* "lxml": Optimized walker for lxml.etree
* "genshi": a Genshi stream
:arg implementation: A module implementing the tree type e.g.
xml.etree.ElementTree or cElementTree (Currently applies to the "etree"
tree type only).
:arg kwargs: keyword arguments passed to the etree walker--for other
walkers, this has no effect
:returns: a TreeWalker class
"""
treeType = treeType.lower()
if treeType not in treeWalkerCache:
if treeType == "dom":
from . import dom
treeWalkerCache[treeType] = dom.TreeWalker
elif treeType == "genshi":
from . import genshi
treeWalkerCache[treeType] = genshi.TreeWalker
elif treeType == "lxml":
from . import etree_lxml
treeWalkerCache[treeType] = etree_lxml.TreeWalker
elif treeType == "etree":
from . import etree
if implementation is None:
implementation = default_etree
# XXX: NEVER cache here, caching is done in the etree submodule
return etree.getETreeModule(implementation, **kwargs).TreeWalker
return treeWalkerCache.get(treeType) | def getTreeWalker(treeType, implementation=None, **kwargs):
"""Get a TreeWalker class for various types of tree with built-in support
:arg str treeType: the name of the tree type required (case-insensitive).
Supported values are:
* "dom": The xml.dom.minidom DOM implementation
* "etree": A generic walker for tree implementations exposing an
elementtree-like interface (known to work with ElementTree,
cElementTree and lxml.etree).
* "lxml": Optimized walker for lxml.etree
* "genshi": a Genshi stream
:arg implementation: A module implementing the tree type e.g.
xml.etree.ElementTree or cElementTree (Currently applies to the "etree"
tree type only).
:arg kwargs: keyword arguments passed to the etree walker--for other
walkers, this has no effect
:returns: a TreeWalker class
"""
treeType = treeType.lower()
if treeType not in treeWalkerCache:
if treeType == "dom":
from . import dom
treeWalkerCache[treeType] = dom.TreeWalker
elif treeType == "genshi":
from . import genshi
treeWalkerCache[treeType] = genshi.TreeWalker
elif treeType == "lxml":
from . import etree_lxml
treeWalkerCache[treeType] = etree_lxml.TreeWalker
elif treeType == "etree":
from . import etree
if implementation is None:
implementation = default_etree
# XXX: NEVER cache here, caching is done in the etree submodule
return etree.getETreeModule(implementation, **kwargs).TreeWalker
return treeWalkerCache.get(treeType) | [
"Get",
"a",
"TreeWalker",
"class",
"for",
"various",
"types",
"of",
"tree",
"with",
"built",
"-",
"in",
"support"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treewalkers/__init__.py#L21-L62 | [
"def",
"getTreeWalker",
"(",
"treeType",
",",
"implementation",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"treeType",
"=",
"treeType",
".",
"lower",
"(",
")",
"if",
"treeType",
"not",
"in",
"treeWalkerCache",
":",
"if",
"treeType",
"==",
"\"dom\"",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | pprint | Pretty printer for tree walkers
Takes a TreeWalker instance and pretty prints the output of walking the tree.
:arg walker: a TreeWalker instance | pipenv/patched/notpip/_vendor/html5lib/treewalkers/__init__.py | def pprint(walker):
"""Pretty printer for tree walkers
Takes a TreeWalker instance and pretty prints the output of walking the tree.
:arg walker: a TreeWalker instance
"""
output = []
indent = 0
for token in concatenateCharacterTokens(walker):
type = token["type"]
if type in ("StartTag", "EmptyTag"):
# tag name
if token["namespace"] and token["namespace"] != constants.namespaces["html"]:
if token["namespace"] in constants.prefixes:
ns = constants.prefixes[token["namespace"]]
else:
ns = token["namespace"]
name = "%s %s" % (ns, token["name"])
else:
name = token["name"]
output.append("%s<%s>" % (" " * indent, name))
indent += 2
# attributes (sorted for consistent ordering)
attrs = token["data"]
for (namespace, localname), value in sorted(attrs.items()):
if namespace:
if namespace in constants.prefixes:
ns = constants.prefixes[namespace]
else:
ns = namespace
name = "%s %s" % (ns, localname)
else:
name = localname
output.append("%s%s=\"%s\"" % (" " * indent, name, value))
# self-closing
if type == "EmptyTag":
indent -= 2
elif type == "EndTag":
indent -= 2
elif type == "Comment":
output.append("%s<!-- %s -->" % (" " * indent, token["data"]))
elif type == "Doctype":
if token["name"]:
if token["publicId"]:
output.append("""%s<!DOCTYPE %s "%s" "%s">""" %
(" " * indent,
token["name"],
token["publicId"],
token["systemId"] if token["systemId"] else ""))
elif token["systemId"]:
output.append("""%s<!DOCTYPE %s "" "%s">""" %
(" " * indent,
token["name"],
token["systemId"]))
else:
output.append("%s<!DOCTYPE %s>" % (" " * indent,
token["name"]))
else:
output.append("%s<!DOCTYPE >" % (" " * indent,))
elif type == "Characters":
output.append("%s\"%s\"" % (" " * indent, token["data"]))
elif type == "SpaceCharacters":
assert False, "concatenateCharacterTokens should have got rid of all Space tokens"
else:
raise ValueError("Unknown token type, %s" % type)
return "\n".join(output) | def pprint(walker):
"""Pretty printer for tree walkers
Takes a TreeWalker instance and pretty prints the output of walking the tree.
:arg walker: a TreeWalker instance
"""
output = []
indent = 0
for token in concatenateCharacterTokens(walker):
type = token["type"]
if type in ("StartTag", "EmptyTag"):
# tag name
if token["namespace"] and token["namespace"] != constants.namespaces["html"]:
if token["namespace"] in constants.prefixes:
ns = constants.prefixes[token["namespace"]]
else:
ns = token["namespace"]
name = "%s %s" % (ns, token["name"])
else:
name = token["name"]
output.append("%s<%s>" % (" " * indent, name))
indent += 2
# attributes (sorted for consistent ordering)
attrs = token["data"]
for (namespace, localname), value in sorted(attrs.items()):
if namespace:
if namespace in constants.prefixes:
ns = constants.prefixes[namespace]
else:
ns = namespace
name = "%s %s" % (ns, localname)
else:
name = localname
output.append("%s%s=\"%s\"" % (" " * indent, name, value))
# self-closing
if type == "EmptyTag":
indent -= 2
elif type == "EndTag":
indent -= 2
elif type == "Comment":
output.append("%s<!-- %s -->" % (" " * indent, token["data"]))
elif type == "Doctype":
if token["name"]:
if token["publicId"]:
output.append("""%s<!DOCTYPE %s "%s" "%s">""" %
(" " * indent,
token["name"],
token["publicId"],
token["systemId"] if token["systemId"] else ""))
elif token["systemId"]:
output.append("""%s<!DOCTYPE %s "" "%s">""" %
(" " * indent,
token["name"],
token["systemId"]))
else:
output.append("%s<!DOCTYPE %s>" % (" " * indent,
token["name"]))
else:
output.append("%s<!DOCTYPE >" % (" " * indent,))
elif type == "Characters":
output.append("%s\"%s\"" % (" " * indent, token["data"]))
elif type == "SpaceCharacters":
assert False, "concatenateCharacterTokens should have got rid of all Space tokens"
else:
raise ValueError("Unknown token type, %s" % type)
return "\n".join(output) | [
"Pretty",
"printer",
"for",
"tree",
"walkers"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treewalkers/__init__.py#L80-L154 | [
"def",
"pprint",
"(",
"walker",
")",
":",
"output",
"=",
"[",
"]",
"indent",
"=",
"0",
"for",
"token",
"in",
"concatenateCharacterTokens",
"(",
"walker",
")",
":",
"type",
"=",
"token",
"[",
"\"type\"",
"]",
"if",
"type",
"in",
"(",
"\"StartTag\"",
","... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | Yaspin.hide | Hide the spinner to allow for custom writing to the terminal. | pipenv/vendor/yaspin/core.py | def hide(self):
"""Hide the spinner to allow for custom writing to the terminal."""
thr_is_alive = self._spin_thread and self._spin_thread.is_alive()
if thr_is_alive and not self._hide_spin.is_set():
# set the hidden spinner flag
self._hide_spin.set()
# clear the current line
sys.stdout.write("\r")
self._clear_line()
# flush the stdout buffer so the current line can be rewritten to
sys.stdout.flush() | def hide(self):
"""Hide the spinner to allow for custom writing to the terminal."""
thr_is_alive = self._spin_thread and self._spin_thread.is_alive()
if thr_is_alive and not self._hide_spin.is_set():
# set the hidden spinner flag
self._hide_spin.set()
# clear the current line
sys.stdout.write("\r")
self._clear_line()
# flush the stdout buffer so the current line can be rewritten to
sys.stdout.flush() | [
"Hide",
"the",
"spinner",
"to",
"allow",
"for",
"custom",
"writing",
"to",
"the",
"terminal",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yaspin/core.py#L251-L264 | [
"def",
"hide",
"(",
"self",
")",
":",
"thr_is_alive",
"=",
"self",
".",
"_spin_thread",
"and",
"self",
".",
"_spin_thread",
".",
"is_alive",
"(",
")",
"if",
"thr_is_alive",
"and",
"not",
"self",
".",
"_hide_spin",
".",
"is_set",
"(",
")",
":",
"# set the... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | Yaspin.show | Show the hidden spinner. | pipenv/vendor/yaspin/core.py | def show(self):
"""Show the hidden spinner."""
thr_is_alive = self._spin_thread and self._spin_thread.is_alive()
if thr_is_alive and self._hide_spin.is_set():
# clear the hidden spinner flag
self._hide_spin.clear()
# clear the current line so the spinner is not appended to it
sys.stdout.write("\r")
self._clear_line() | def show(self):
"""Show the hidden spinner."""
thr_is_alive = self._spin_thread and self._spin_thread.is_alive()
if thr_is_alive and self._hide_spin.is_set():
# clear the hidden spinner flag
self._hide_spin.clear()
# clear the current line so the spinner is not appended to it
sys.stdout.write("\r")
self._clear_line() | [
"Show",
"the",
"hidden",
"spinner",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yaspin/core.py#L266-L276 | [
"def",
"show",
"(",
"self",
")",
":",
"thr_is_alive",
"=",
"self",
".",
"_spin_thread",
"and",
"self",
".",
"_spin_thread",
".",
"is_alive",
"(",
")",
"if",
"thr_is_alive",
"and",
"self",
".",
"_hide_spin",
".",
"is_set",
"(",
")",
":",
"# clear the hidden... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | Yaspin.write | Write text in the terminal without breaking the spinner. | pipenv/vendor/yaspin/core.py | def write(self, text):
"""Write text in the terminal without breaking the spinner."""
# similar to tqdm.write()
# https://pypi.python.org/pypi/tqdm#writing-messages
sys.stdout.write("\r")
self._clear_line()
_text = to_unicode(text)
if PY2:
_text = _text.encode(ENCODING)
# Ensure output is bytes for Py2 and Unicode for Py3
assert isinstance(_text, builtin_str)
sys.stdout.write("{0}\n".format(_text)) | def write(self, text):
"""Write text in the terminal without breaking the spinner."""
# similar to tqdm.write()
# https://pypi.python.org/pypi/tqdm#writing-messages
sys.stdout.write("\r")
self._clear_line()
_text = to_unicode(text)
if PY2:
_text = _text.encode(ENCODING)
# Ensure output is bytes for Py2 and Unicode for Py3
assert isinstance(_text, builtin_str)
sys.stdout.write("{0}\n".format(_text)) | [
"Write",
"text",
"in",
"the",
"terminal",
"without",
"breaking",
"the",
"spinner",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yaspin/core.py#L278-L292 | [
"def",
"write",
"(",
"self",
",",
"text",
")",
":",
"# similar to tqdm.write()",
"# https://pypi.python.org/pypi/tqdm#writing-messages",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"\\r\"",
")",
"self",
".",
"_clear_line",
"(",
")",
"_text",
"=",
"to_unicode",
"(",... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | Yaspin._freeze | Stop spinner, compose last frame and 'freeze' it. | pipenv/vendor/yaspin/core.py | def _freeze(self, final_text):
"""Stop spinner, compose last frame and 'freeze' it."""
text = to_unicode(final_text)
self._last_frame = self._compose_out(text, mode="last")
# Should be stopped here, otherwise prints after
# self._freeze call will mess up the spinner
self.stop()
sys.stdout.write(self._last_frame) | def _freeze(self, final_text):
"""Stop spinner, compose last frame and 'freeze' it."""
text = to_unicode(final_text)
self._last_frame = self._compose_out(text, mode="last")
# Should be stopped here, otherwise prints after
# self._freeze call will mess up the spinner
self.stop()
sys.stdout.write(self._last_frame) | [
"Stop",
"spinner",
"compose",
"last",
"frame",
"and",
"freeze",
"it",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yaspin/core.py#L307-L315 | [
"def",
"_freeze",
"(",
"self",
",",
"final_text",
")",
":",
"text",
"=",
"to_unicode",
"(",
"final_text",
")",
"self",
".",
"_last_frame",
"=",
"self",
".",
"_compose_out",
"(",
"text",
",",
"mode",
"=",
"\"last\"",
")",
"# Should be stopped here, otherwise pr... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | RevOptions.to_args | Return the VCS-specific command arguments. | pipenv/patched/notpip/_internal/vcs/__init__.py | def to_args(self):
# type: () -> List[str]
"""
Return the VCS-specific command arguments.
"""
args = [] # type: List[str]
rev = self.arg_rev
if rev is not None:
args += self.vcs.get_base_rev_args(rev)
args += self.extra_args
return args | def to_args(self):
# type: () -> List[str]
"""
Return the VCS-specific command arguments.
"""
args = [] # type: List[str]
rev = self.arg_rev
if rev is not None:
args += self.vcs.get_base_rev_args(rev)
args += self.extra_args
return args | [
"Return",
"the",
"VCS",
"-",
"specific",
"command",
"arguments",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L71-L82 | [
"def",
"to_args",
"(",
"self",
")",
":",
"# type: () -> List[str]",
"args",
"=",
"[",
"]",
"# type: List[str]",
"rev",
"=",
"self",
".",
"arg_rev",
"if",
"rev",
"is",
"not",
"None",
":",
"args",
"+=",
"self",
".",
"vcs",
".",
"get_base_rev_args",
"(",
"r... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | RevOptions.make_new | Make a copy of the current instance, but with a new rev.
Args:
rev: the name of the revision for the new object. | pipenv/patched/notpip/_internal/vcs/__init__.py | def make_new(self, rev):
# type: (str) -> RevOptions
"""
Make a copy of the current instance, but with a new rev.
Args:
rev: the name of the revision for the new object.
"""
return self.vcs.make_rev_options(rev, extra_args=self.extra_args) | def make_new(self, rev):
# type: (str) -> RevOptions
"""
Make a copy of the current instance, but with a new rev.
Args:
rev: the name of the revision for the new object.
"""
return self.vcs.make_rev_options(rev, extra_args=self.extra_args) | [
"Make",
"a",
"copy",
"of",
"the",
"current",
"instance",
"but",
"with",
"a",
"new",
"rev",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L91-L99 | [
"def",
"make_new",
"(",
"self",
",",
"rev",
")",
":",
"# type: (str) -> RevOptions",
"return",
"self",
".",
"vcs",
".",
"make_rev_options",
"(",
"rev",
",",
"extra_args",
"=",
"self",
".",
"extra_args",
")"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | VcsSupport.get_backend_type | Return the type of the version control backend if found at given
location, e.g. vcs.get_backend_type('/path/to/vcs/checkout') | pipenv/patched/notpip/_internal/vcs/__init__.py | def get_backend_type(self, location):
# type: (str) -> Optional[Type[VersionControl]]
"""
Return the type of the version control backend if found at given
location, e.g. vcs.get_backend_type('/path/to/vcs/checkout')
"""
for vc_type in self._registry.values():
if vc_type.controls_location(location):
logger.debug('Determine that %s uses VCS: %s',
location, vc_type.name)
return vc_type
return None | def get_backend_type(self, location):
# type: (str) -> Optional[Type[VersionControl]]
"""
Return the type of the version control backend if found at given
location, e.g. vcs.get_backend_type('/path/to/vcs/checkout')
"""
for vc_type in self._registry.values():
if vc_type.controls_location(location):
logger.debug('Determine that %s uses VCS: %s',
location, vc_type.name)
return vc_type
return None | [
"Return",
"the",
"type",
"of",
"the",
"version",
"control",
"backend",
"if",
"found",
"at",
"given",
"location",
"e",
".",
"g",
".",
"vcs",
".",
"get_backend_type",
"(",
"/",
"path",
"/",
"to",
"/",
"vcs",
"/",
"checkout",
")"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L155-L166 | [
"def",
"get_backend_type",
"(",
"self",
",",
"location",
")",
":",
"# type: (str) -> Optional[Type[VersionControl]]",
"for",
"vc_type",
"in",
"self",
".",
"_registry",
".",
"values",
"(",
")",
":",
"if",
"vc_type",
".",
"controls_location",
"(",
"location",
")",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | VersionControl._is_local_repository | posix absolute paths start with os.path.sep,
win32 ones start with drive (like c:\\folder) | pipenv/patched/notpip/_internal/vcs/__init__.py | def _is_local_repository(cls, repo):
# type: (str) -> bool
"""
posix absolute paths start with os.path.sep,
win32 ones start with drive (like c:\\folder)
"""
drive, tail = os.path.splitdrive(repo)
return repo.startswith(os.path.sep) or bool(drive) | def _is_local_repository(cls, repo):
# type: (str) -> bool
"""
posix absolute paths start with os.path.sep,
win32 ones start with drive (like c:\\folder)
"""
drive, tail = os.path.splitdrive(repo)
return repo.startswith(os.path.sep) or bool(drive) | [
"posix",
"absolute",
"paths",
"start",
"with",
"os",
".",
"path",
".",
"sep",
"win32",
"ones",
"start",
"with",
"drive",
"(",
"like",
"c",
":",
"\\\\",
"folder",
")"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L214-L221 | [
"def",
"_is_local_repository",
"(",
"cls",
",",
"repo",
")",
":",
"# type: (str) -> bool",
"drive",
",",
"tail",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"repo",
")",
"return",
"repo",
".",
"startswith",
"(",
"os",
".",
"path",
".",
"sep",
")",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | VersionControl.get_url_rev_and_auth | Parse the repository URL to use, and return the URL, revision,
and auth info to use.
Returns: (url, rev, (username, password)). | pipenv/patched/notpip/_internal/vcs/__init__.py | def get_url_rev_and_auth(self, url):
# type: (str) -> Tuple[str, Optional[str], AuthInfo]
"""
Parse the repository URL to use, and return the URL, revision,
and auth info to use.
Returns: (url, rev, (username, password)).
"""
scheme, netloc, path, query, frag = urllib_parse.urlsplit(url)
if '+' not in scheme:
raise ValueError(
"Sorry, {!r} is a malformed VCS url. "
"The format is <vcs>+<protocol>://<url>, "
"e.g. svn+http://myrepo/svn/MyApp#egg=MyApp".format(url)
)
# Remove the vcs prefix.
scheme = scheme.split('+', 1)[1]
netloc, user_pass = self.get_netloc_and_auth(netloc, scheme)
rev = None
if '@' in path:
path, rev = path.rsplit('@', 1)
url = urllib_parse.urlunsplit((scheme, netloc, path, query, ''))
return url, rev, user_pass | def get_url_rev_and_auth(self, url):
# type: (str) -> Tuple[str, Optional[str], AuthInfo]
"""
Parse the repository URL to use, and return the URL, revision,
and auth info to use.
Returns: (url, rev, (username, password)).
"""
scheme, netloc, path, query, frag = urllib_parse.urlsplit(url)
if '+' not in scheme:
raise ValueError(
"Sorry, {!r} is a malformed VCS url. "
"The format is <vcs>+<protocol>://<url>, "
"e.g. svn+http://myrepo/svn/MyApp#egg=MyApp".format(url)
)
# Remove the vcs prefix.
scheme = scheme.split('+', 1)[1]
netloc, user_pass = self.get_netloc_and_auth(netloc, scheme)
rev = None
if '@' in path:
path, rev = path.rsplit('@', 1)
url = urllib_parse.urlunsplit((scheme, netloc, path, query, ''))
return url, rev, user_pass | [
"Parse",
"the",
"repository",
"URL",
"to",
"use",
"and",
"return",
"the",
"URL",
"revision",
"and",
"auth",
"info",
"to",
"use",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L248-L270 | [
"def",
"get_url_rev_and_auth",
"(",
"self",
",",
"url",
")",
":",
"# type: (str) -> Tuple[str, Optional[str], AuthInfo]",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"frag",
"=",
"urllib_parse",
".",
"urlsplit",
"(",
"url",
")",
"if",
"'+'",
"not",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | VersionControl.get_url_rev_options | Return the URL and RevOptions object to use in obtain() and in
some cases export(), as a tuple (url, rev_options). | pipenv/patched/notpip/_internal/vcs/__init__.py | def get_url_rev_options(self, url):
# type: (str) -> Tuple[str, RevOptions]
"""
Return the URL and RevOptions object to use in obtain() and in
some cases export(), as a tuple (url, rev_options).
"""
url, rev, user_pass = self.get_url_rev_and_auth(url)
username, password = user_pass
extra_args = self.make_rev_args(username, password)
rev_options = self.make_rev_options(rev, extra_args=extra_args)
return url, rev_options | def get_url_rev_options(self, url):
# type: (str) -> Tuple[str, RevOptions]
"""
Return the URL and RevOptions object to use in obtain() and in
some cases export(), as a tuple (url, rev_options).
"""
url, rev, user_pass = self.get_url_rev_and_auth(url)
username, password = user_pass
extra_args = self.make_rev_args(username, password)
rev_options = self.make_rev_options(rev, extra_args=extra_args)
return url, rev_options | [
"Return",
"the",
"URL",
"and",
"RevOptions",
"object",
"to",
"use",
"in",
"obtain",
"()",
"and",
"in",
"some",
"cases",
"export",
"()",
"as",
"a",
"tuple",
"(",
"url",
"rev_options",
")",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L278-L289 | [
"def",
"get_url_rev_options",
"(",
"self",
",",
"url",
")",
":",
"# type: (str) -> Tuple[str, RevOptions]",
"url",
",",
"rev",
",",
"user_pass",
"=",
"self",
".",
"get_url_rev_and_auth",
"(",
"url",
")",
"username",
",",
"password",
"=",
"user_pass",
"extra_args",... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | VersionControl.compare_urls | Compare two repo URLs for identity, ignoring incidental differences. | pipenv/patched/notpip/_internal/vcs/__init__.py | def compare_urls(self, url1, url2):
# type: (str, str) -> bool
"""
Compare two repo URLs for identity, ignoring incidental differences.
"""
return (self.normalize_url(url1) == self.normalize_url(url2)) | def compare_urls(self, url1, url2):
# type: (str, str) -> bool
"""
Compare two repo URLs for identity, ignoring incidental differences.
"""
return (self.normalize_url(url1) == self.normalize_url(url2)) | [
"Compare",
"two",
"repo",
"URLs",
"for",
"identity",
"ignoring",
"incidental",
"differences",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L299-L304 | [
"def",
"compare_urls",
"(",
"self",
",",
"url1",
",",
"url2",
")",
":",
"# type: (str, str) -> bool",
"return",
"(",
"self",
".",
"normalize_url",
"(",
"url1",
")",
"==",
"self",
".",
"normalize_url",
"(",
"url2",
")",
")"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | VersionControl.obtain | Install or update in editable mode the package represented by this
VersionControl object.
Args:
dest: the repository directory in which to install or update. | pipenv/patched/notpip/_internal/vcs/__init__.py | def obtain(self, dest):
# type: (str) -> None
"""
Install or update in editable mode the package represented by this
VersionControl object.
Args:
dest: the repository directory in which to install or update.
"""
url, rev_options = self.get_url_rev_options(self.url)
if not os.path.exists(dest):
self.fetch_new(dest, url, rev_options)
return
rev_display = rev_options.to_display()
if self.is_repository_directory(dest):
existing_url = self.get_remote_url(dest)
if self.compare_urls(existing_url, url):
logger.debug(
'%s in %s exists, and has correct URL (%s)',
self.repo_name.title(),
display_path(dest),
url,
)
if not self.is_commit_id_equal(dest, rev_options.rev):
logger.info(
'Updating %s %s%s',
display_path(dest),
self.repo_name,
rev_display,
)
self.update(dest, url, rev_options)
else:
logger.info('Skipping because already up-to-date.')
return
logger.warning(
'%s %s in %s exists with URL %s',
self.name,
self.repo_name,
display_path(dest),
existing_url,
)
prompt = ('(s)witch, (i)gnore, (w)ipe, (b)ackup ',
('s', 'i', 'w', 'b'))
else:
logger.warning(
'Directory %s already exists, and is not a %s %s.',
dest,
self.name,
self.repo_name,
)
# https://github.com/python/mypy/issues/1174
prompt = ('(i)gnore, (w)ipe, (b)ackup ', # type: ignore
('i', 'w', 'b'))
logger.warning(
'The plan is to install the %s repository %s',
self.name,
url,
)
response = ask_path_exists('What to do? %s' % prompt[0], prompt[1])
if response == 'a':
sys.exit(-1)
if response == 'w':
logger.warning('Deleting %s', display_path(dest))
rmtree(dest)
self.fetch_new(dest, url, rev_options)
return
if response == 'b':
dest_dir = backup_dir(dest)
logger.warning(
'Backing up %s to %s', display_path(dest), dest_dir,
)
shutil.move(dest, dest_dir)
self.fetch_new(dest, url, rev_options)
return
# Do nothing if the response is "i".
if response == 's':
logger.info(
'Switching %s %s to %s%s',
self.repo_name,
display_path(dest),
url,
rev_display,
)
self.switch(dest, url, rev_options) | def obtain(self, dest):
# type: (str) -> None
"""
Install or update in editable mode the package represented by this
VersionControl object.
Args:
dest: the repository directory in which to install or update.
"""
url, rev_options = self.get_url_rev_options(self.url)
if not os.path.exists(dest):
self.fetch_new(dest, url, rev_options)
return
rev_display = rev_options.to_display()
if self.is_repository_directory(dest):
existing_url = self.get_remote_url(dest)
if self.compare_urls(existing_url, url):
logger.debug(
'%s in %s exists, and has correct URL (%s)',
self.repo_name.title(),
display_path(dest),
url,
)
if not self.is_commit_id_equal(dest, rev_options.rev):
logger.info(
'Updating %s %s%s',
display_path(dest),
self.repo_name,
rev_display,
)
self.update(dest, url, rev_options)
else:
logger.info('Skipping because already up-to-date.')
return
logger.warning(
'%s %s in %s exists with URL %s',
self.name,
self.repo_name,
display_path(dest),
existing_url,
)
prompt = ('(s)witch, (i)gnore, (w)ipe, (b)ackup ',
('s', 'i', 'w', 'b'))
else:
logger.warning(
'Directory %s already exists, and is not a %s %s.',
dest,
self.name,
self.repo_name,
)
# https://github.com/python/mypy/issues/1174
prompt = ('(i)gnore, (w)ipe, (b)ackup ', # type: ignore
('i', 'w', 'b'))
logger.warning(
'The plan is to install the %s repository %s',
self.name,
url,
)
response = ask_path_exists('What to do? %s' % prompt[0], prompt[1])
if response == 'a':
sys.exit(-1)
if response == 'w':
logger.warning('Deleting %s', display_path(dest))
rmtree(dest)
self.fetch_new(dest, url, rev_options)
return
if response == 'b':
dest_dir = backup_dir(dest)
logger.warning(
'Backing up %s to %s', display_path(dest), dest_dir,
)
shutil.move(dest, dest_dir)
self.fetch_new(dest, url, rev_options)
return
# Do nothing if the response is "i".
if response == 's':
logger.info(
'Switching %s %s to %s%s',
self.repo_name,
display_path(dest),
url,
rev_display,
)
self.switch(dest, url, rev_options) | [
"Install",
"or",
"update",
"in",
"editable",
"mode",
"the",
"package",
"represented",
"by",
"this",
"VersionControl",
"object",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L345-L436 | [
"def",
"obtain",
"(",
"self",
",",
"dest",
")",
":",
"# type: (str) -> None",
"url",
",",
"rev_options",
"=",
"self",
".",
"get_url_rev_options",
"(",
"self",
".",
"url",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dest",
")",
":",
"self"... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | VersionControl.run_command | Run a VCS subcommand
This is simply a wrapper around call_subprocess that adds the VCS
command name, and checks that the VCS is available | pipenv/patched/notpip/_internal/vcs/__init__.py | def run_command(
cls,
cmd, # type: List[str]
show_stdout=True, # type: bool
cwd=None, # type: Optional[str]
on_returncode='raise', # type: str
extra_ok_returncodes=None, # type: Optional[Iterable[int]]
command_desc=None, # type: Optional[str]
extra_environ=None, # type: Optional[Mapping[str, Any]]
spinner=None # type: Optional[SpinnerInterface]
):
# type: (...) -> Optional[Text]
"""
Run a VCS subcommand
This is simply a wrapper around call_subprocess that adds the VCS
command name, and checks that the VCS is available
"""
cmd = [cls.name] + cmd
try:
return call_subprocess(cmd, show_stdout, cwd,
on_returncode=on_returncode,
extra_ok_returncodes=extra_ok_returncodes,
command_desc=command_desc,
extra_environ=extra_environ,
unset_environ=cls.unset_environ,
spinner=spinner)
except OSError as e:
# errno.ENOENT = no such file or directory
# In other words, the VCS executable isn't available
if e.errno == errno.ENOENT:
raise BadCommand(
'Cannot find command %r - do you have '
'%r installed and in your '
'PATH?' % (cls.name, cls.name))
else:
raise | def run_command(
cls,
cmd, # type: List[str]
show_stdout=True, # type: bool
cwd=None, # type: Optional[str]
on_returncode='raise', # type: str
extra_ok_returncodes=None, # type: Optional[Iterable[int]]
command_desc=None, # type: Optional[str]
extra_environ=None, # type: Optional[Mapping[str, Any]]
spinner=None # type: Optional[SpinnerInterface]
):
# type: (...) -> Optional[Text]
"""
Run a VCS subcommand
This is simply a wrapper around call_subprocess that adds the VCS
command name, and checks that the VCS is available
"""
cmd = [cls.name] + cmd
try:
return call_subprocess(cmd, show_stdout, cwd,
on_returncode=on_returncode,
extra_ok_returncodes=extra_ok_returncodes,
command_desc=command_desc,
extra_environ=extra_environ,
unset_environ=cls.unset_environ,
spinner=spinner)
except OSError as e:
# errno.ENOENT = no such file or directory
# In other words, the VCS executable isn't available
if e.errno == errno.ENOENT:
raise BadCommand(
'Cannot find command %r - do you have '
'%r installed and in your '
'PATH?' % (cls.name, cls.name))
else:
raise | [
"Run",
"a",
"VCS",
"subcommand",
"This",
"is",
"simply",
"a",
"wrapper",
"around",
"call_subprocess",
"that",
"adds",
"the",
"VCS",
"command",
"name",
"and",
"checks",
"that",
"the",
"VCS",
"is",
"available"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L476-L511 | [
"def",
"run_command",
"(",
"cls",
",",
"cmd",
",",
"# type: List[str]",
"show_stdout",
"=",
"True",
",",
"# type: bool",
"cwd",
"=",
"None",
",",
"# type: Optional[str]",
"on_returncode",
"=",
"'raise'",
",",
"# type: str",
"extra_ok_returncodes",
"=",
"None",
","... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | VersionControl.is_repository_directory | Return whether a directory path is a repository directory. | pipenv/patched/notpip/_internal/vcs/__init__.py | def is_repository_directory(cls, path):
# type: (str) -> bool
"""
Return whether a directory path is a repository directory.
"""
logger.debug('Checking in %s for %s (%s)...',
path, cls.dirname, cls.name)
return os.path.exists(os.path.join(path, cls.dirname)) | def is_repository_directory(cls, path):
# type: (str) -> bool
"""
Return whether a directory path is a repository directory.
"""
logger.debug('Checking in %s for %s (%s)...',
path, cls.dirname, cls.name)
return os.path.exists(os.path.join(path, cls.dirname)) | [
"Return",
"whether",
"a",
"directory",
"path",
"is",
"a",
"repository",
"directory",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L514-L521 | [
"def",
"is_repository_directory",
"(",
"cls",
",",
"path",
")",
":",
"# type: (str) -> bool",
"logger",
".",
"debug",
"(",
"'Checking in %s for %s (%s)...'",
",",
"path",
",",
"cls",
".",
"dirname",
",",
"cls",
".",
"name",
")",
"return",
"os",
".",
"path",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | _script_names | Create the fully qualified name of the files created by
{console,gui}_scripts for the given ``dist``.
Returns the list of file names | pipenv/patched/notpip/_internal/req/req_uninstall.py | def _script_names(dist, script_name, is_gui):
"""Create the fully qualified name of the files created by
{console,gui}_scripts for the given ``dist``.
Returns the list of file names
"""
if dist_in_usersite(dist):
bin_dir = bin_user
else:
bin_dir = bin_py
exe_name = os.path.join(bin_dir, script_name)
paths_to_remove = [exe_name]
if WINDOWS:
paths_to_remove.append(exe_name + '.exe')
paths_to_remove.append(exe_name + '.exe.manifest')
if is_gui:
paths_to_remove.append(exe_name + '-script.pyw')
else:
paths_to_remove.append(exe_name + '-script.py')
return paths_to_remove | def _script_names(dist, script_name, is_gui):
"""Create the fully qualified name of the files created by
{console,gui}_scripts for the given ``dist``.
Returns the list of file names
"""
if dist_in_usersite(dist):
bin_dir = bin_user
else:
bin_dir = bin_py
exe_name = os.path.join(bin_dir, script_name)
paths_to_remove = [exe_name]
if WINDOWS:
paths_to_remove.append(exe_name + '.exe')
paths_to_remove.append(exe_name + '.exe.manifest')
if is_gui:
paths_to_remove.append(exe_name + '-script.pyw')
else:
paths_to_remove.append(exe_name + '-script.py')
return paths_to_remove | [
"Create",
"the",
"fully",
"qualified",
"name",
"of",
"the",
"files",
"created",
"by",
"{",
"console",
"gui",
"}",
"_scripts",
"for",
"the",
"given",
"dist",
".",
"Returns",
"the",
"list",
"of",
"file",
"names"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L25-L43 | [
"def",
"_script_names",
"(",
"dist",
",",
"script_name",
",",
"is_gui",
")",
":",
"if",
"dist_in_usersite",
"(",
"dist",
")",
":",
"bin_dir",
"=",
"bin_user",
"else",
":",
"bin_dir",
"=",
"bin_py",
"exe_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | compact | Compact a path set to contain the minimal number of paths
necessary to contain all paths in the set. If /a/path/ and
/a/path/to/a/file.txt are both in the set, leave only the
shorter path. | pipenv/patched/notpip/_internal/req/req_uninstall.py | def compact(paths):
"""Compact a path set to contain the minimal number of paths
necessary to contain all paths in the set. If /a/path/ and
/a/path/to/a/file.txt are both in the set, leave only the
shorter path."""
sep = os.path.sep
short_paths = set()
for path in sorted(paths, key=len):
should_skip = any(
path.startswith(shortpath.rstrip("*")) and
path[len(shortpath.rstrip("*").rstrip(sep))] == sep
for shortpath in short_paths
)
if not should_skip:
short_paths.add(path)
return short_paths | def compact(paths):
"""Compact a path set to contain the minimal number of paths
necessary to contain all paths in the set. If /a/path/ and
/a/path/to/a/file.txt are both in the set, leave only the
shorter path."""
sep = os.path.sep
short_paths = set()
for path in sorted(paths, key=len):
should_skip = any(
path.startswith(shortpath.rstrip("*")) and
path[len(shortpath.rstrip("*").rstrip(sep))] == sep
for shortpath in short_paths
)
if not should_skip:
short_paths.add(path)
return short_paths | [
"Compact",
"a",
"path",
"set",
"to",
"contain",
"the",
"minimal",
"number",
"of",
"paths",
"necessary",
"to",
"contain",
"all",
"paths",
"in",
"the",
"set",
".",
"If",
"/",
"a",
"/",
"path",
"/",
"and",
"/",
"a",
"/",
"path",
"/",
"to",
"/",
"a",
... | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L80-L96 | [
"def",
"compact",
"(",
"paths",
")",
":",
"sep",
"=",
"os",
".",
"path",
".",
"sep",
"short_paths",
"=",
"set",
"(",
")",
"for",
"path",
"in",
"sorted",
"(",
"paths",
",",
"key",
"=",
"len",
")",
":",
"should_skip",
"=",
"any",
"(",
"path",
".",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | compress_for_rename | Returns a set containing the paths that need to be renamed.
This set may include directories when the original sequence of paths
included every file on disk. | pipenv/patched/notpip/_internal/req/req_uninstall.py | def compress_for_rename(paths):
"""Returns a set containing the paths that need to be renamed.
This set may include directories when the original sequence of paths
included every file on disk.
"""
case_map = dict((os.path.normcase(p), p) for p in paths)
remaining = set(case_map)
unchecked = sorted(set(os.path.split(p)[0]
for p in case_map.values()), key=len)
wildcards = set()
def norm_join(*a):
return os.path.normcase(os.path.join(*a))
for root in unchecked:
if any(os.path.normcase(root).startswith(w)
for w in wildcards):
# This directory has already been handled.
continue
all_files = set()
all_subdirs = set()
for dirname, subdirs, files in os.walk(root):
all_subdirs.update(norm_join(root, dirname, d)
for d in subdirs)
all_files.update(norm_join(root, dirname, f)
for f in files)
# If all the files we found are in our remaining set of files to
# remove, then remove them from the latter set and add a wildcard
# for the directory.
if not (all_files - remaining):
remaining.difference_update(all_files)
wildcards.add(root + os.sep)
return set(map(case_map.__getitem__, remaining)) | wildcards | def compress_for_rename(paths):
"""Returns a set containing the paths that need to be renamed.
This set may include directories when the original sequence of paths
included every file on disk.
"""
case_map = dict((os.path.normcase(p), p) for p in paths)
remaining = set(case_map)
unchecked = sorted(set(os.path.split(p)[0]
for p in case_map.values()), key=len)
wildcards = set()
def norm_join(*a):
return os.path.normcase(os.path.join(*a))
for root in unchecked:
if any(os.path.normcase(root).startswith(w)
for w in wildcards):
# This directory has already been handled.
continue
all_files = set()
all_subdirs = set()
for dirname, subdirs, files in os.walk(root):
all_subdirs.update(norm_join(root, dirname, d)
for d in subdirs)
all_files.update(norm_join(root, dirname, f)
for f in files)
# If all the files we found are in our remaining set of files to
# remove, then remove them from the latter set and add a wildcard
# for the directory.
if not (all_files - remaining):
remaining.difference_update(all_files)
wildcards.add(root + os.sep)
return set(map(case_map.__getitem__, remaining)) | wildcards | [
"Returns",
"a",
"set",
"containing",
"the",
"paths",
"that",
"need",
"to",
"be",
"renamed",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L99-L134 | [
"def",
"compress_for_rename",
"(",
"paths",
")",
":",
"case_map",
"=",
"dict",
"(",
"(",
"os",
".",
"path",
".",
"normcase",
"(",
"p",
")",
",",
"p",
")",
"for",
"p",
"in",
"paths",
")",
"remaining",
"=",
"set",
"(",
"case_map",
")",
"unchecked",
"... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | compress_for_output_listing | Returns a tuple of 2 sets of which paths to display to user
The first set contains paths that would be deleted. Files of a package
are not added and the top-level directory of the package has a '*' added
at the end - to signify that all it's contents are removed.
The second set contains files that would have been skipped in the above
folders. | pipenv/patched/notpip/_internal/req/req_uninstall.py | def compress_for_output_listing(paths):
"""Returns a tuple of 2 sets of which paths to display to user
The first set contains paths that would be deleted. Files of a package
are not added and the top-level directory of the package has a '*' added
at the end - to signify that all it's contents are removed.
The second set contains files that would have been skipped in the above
folders.
"""
will_remove = list(paths)
will_skip = set()
# Determine folders and files
folders = set()
files = set()
for path in will_remove:
if path.endswith(".pyc"):
continue
if path.endswith("__init__.py") or ".dist-info" in path:
folders.add(os.path.dirname(path))
files.add(path)
_normcased_files = set(map(os.path.normcase, files))
folders = compact(folders)
# This walks the tree using os.walk to not miss extra folders
# that might get added.
for folder in folders:
for dirpath, _, dirfiles in os.walk(folder):
for fname in dirfiles:
if fname.endswith(".pyc"):
continue
file_ = os.path.join(dirpath, fname)
if (os.path.isfile(file_) and
os.path.normcase(file_) not in _normcased_files):
# We are skipping this file. Add it to the set.
will_skip.add(file_)
will_remove = files | {
os.path.join(folder, "*") for folder in folders
}
return will_remove, will_skip | def compress_for_output_listing(paths):
"""Returns a tuple of 2 sets of which paths to display to user
The first set contains paths that would be deleted. Files of a package
are not added and the top-level directory of the package has a '*' added
at the end - to signify that all it's contents are removed.
The second set contains files that would have been skipped in the above
folders.
"""
will_remove = list(paths)
will_skip = set()
# Determine folders and files
folders = set()
files = set()
for path in will_remove:
if path.endswith(".pyc"):
continue
if path.endswith("__init__.py") or ".dist-info" in path:
folders.add(os.path.dirname(path))
files.add(path)
_normcased_files = set(map(os.path.normcase, files))
folders = compact(folders)
# This walks the tree using os.walk to not miss extra folders
# that might get added.
for folder in folders:
for dirpath, _, dirfiles in os.walk(folder):
for fname in dirfiles:
if fname.endswith(".pyc"):
continue
file_ = os.path.join(dirpath, fname)
if (os.path.isfile(file_) and
os.path.normcase(file_) not in _normcased_files):
# We are skipping this file. Add it to the set.
will_skip.add(file_)
will_remove = files | {
os.path.join(folder, "*") for folder in folders
}
return will_remove, will_skip | [
"Returns",
"a",
"tuple",
"of",
"2",
"sets",
"of",
"which",
"paths",
"to",
"display",
"to",
"user"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L137-L183 | [
"def",
"compress_for_output_listing",
"(",
"paths",
")",
":",
"will_remove",
"=",
"list",
"(",
"paths",
")",
"will_skip",
"=",
"set",
"(",
")",
"# Determine folders and files",
"folders",
"=",
"set",
"(",
")",
"files",
"=",
"set",
"(",
")",
"for",
"path",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | StashedUninstallPathSet._get_directory_stash | Stashes a directory.
Directories are stashed adjacent to their original location if
possible, or else moved/copied into the user's temp dir. | pipenv/patched/notpip/_internal/req/req_uninstall.py | def _get_directory_stash(self, path):
"""Stashes a directory.
Directories are stashed adjacent to their original location if
possible, or else moved/copied into the user's temp dir."""
try:
save_dir = AdjacentTempDirectory(path)
save_dir.create()
except OSError:
save_dir = TempDirectory(kind="uninstall")
save_dir.create()
self._save_dirs[os.path.normcase(path)] = save_dir
return save_dir.path | def _get_directory_stash(self, path):
"""Stashes a directory.
Directories are stashed adjacent to their original location if
possible, or else moved/copied into the user's temp dir."""
try:
save_dir = AdjacentTempDirectory(path)
save_dir.create()
except OSError:
save_dir = TempDirectory(kind="uninstall")
save_dir.create()
self._save_dirs[os.path.normcase(path)] = save_dir
return save_dir.path | [
"Stashes",
"a",
"directory",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L197-L211 | [
"def",
"_get_directory_stash",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"save_dir",
"=",
"AdjacentTempDirectory",
"(",
"path",
")",
"save_dir",
".",
"create",
"(",
")",
"except",
"OSError",
":",
"save_dir",
"=",
"TempDirectory",
"(",
"kind",
"=",
"\... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | StashedUninstallPathSet._get_file_stash | Stashes a file.
If no root has been provided, one will be created for the directory
in the user's temp directory. | pipenv/patched/notpip/_internal/req/req_uninstall.py | def _get_file_stash(self, path):
"""Stashes a file.
If no root has been provided, one will be created for the directory
in the user's temp directory."""
path = os.path.normcase(path)
head, old_head = os.path.dirname(path), None
save_dir = None
while head != old_head:
try:
save_dir = self._save_dirs[head]
break
except KeyError:
pass
head, old_head = os.path.dirname(head), head
else:
# Did not find any suitable root
head = os.path.dirname(path)
save_dir = TempDirectory(kind='uninstall')
save_dir.create()
self._save_dirs[head] = save_dir
relpath = os.path.relpath(path, head)
if relpath and relpath != os.path.curdir:
return os.path.join(save_dir.path, relpath)
return save_dir.path | def _get_file_stash(self, path):
"""Stashes a file.
If no root has been provided, one will be created for the directory
in the user's temp directory."""
path = os.path.normcase(path)
head, old_head = os.path.dirname(path), None
save_dir = None
while head != old_head:
try:
save_dir = self._save_dirs[head]
break
except KeyError:
pass
head, old_head = os.path.dirname(head), head
else:
# Did not find any suitable root
head = os.path.dirname(path)
save_dir = TempDirectory(kind='uninstall')
save_dir.create()
self._save_dirs[head] = save_dir
relpath = os.path.relpath(path, head)
if relpath and relpath != os.path.curdir:
return os.path.join(save_dir.path, relpath)
return save_dir.path | [
"Stashes",
"a",
"file",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L213-L239 | [
"def",
"_get_file_stash",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"path",
")",
"head",
",",
"old_head",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
",",
"None",
"save_dir",
"=",
"None"... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | StashedUninstallPathSet.stash | Stashes the directory or file and returns its new location. | pipenv/patched/notpip/_internal/req/req_uninstall.py | def stash(self, path):
"""Stashes the directory or file and returns its new location.
"""
if os.path.isdir(path):
new_path = self._get_directory_stash(path)
else:
new_path = self._get_file_stash(path)
self._moves.append((path, new_path))
if os.path.isdir(path) and os.path.isdir(new_path):
# If we're moving a directory, we need to
# remove the destination first or else it will be
# moved to inside the existing directory.
# We just created new_path ourselves, so it will
# be removable.
os.rmdir(new_path)
renames(path, new_path)
return new_path | def stash(self, path):
"""Stashes the directory or file and returns its new location.
"""
if os.path.isdir(path):
new_path = self._get_directory_stash(path)
else:
new_path = self._get_file_stash(path)
self._moves.append((path, new_path))
if os.path.isdir(path) and os.path.isdir(new_path):
# If we're moving a directory, we need to
# remove the destination first or else it will be
# moved to inside the existing directory.
# We just created new_path ourselves, so it will
# be removable.
os.rmdir(new_path)
renames(path, new_path)
return new_path | [
"Stashes",
"the",
"directory",
"or",
"file",
"and",
"returns",
"its",
"new",
"location",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L241-L258 | [
"def",
"stash",
"(",
"self",
",",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"new_path",
"=",
"self",
".",
"_get_directory_stash",
"(",
"path",
")",
"else",
":",
"new_path",
"=",
"self",
".",
"_get_file_stash",
"(... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | StashedUninstallPathSet.commit | Commits the uninstall by removing stashed files. | pipenv/patched/notpip/_internal/req/req_uninstall.py | def commit(self):
"""Commits the uninstall by removing stashed files."""
for _, save_dir in self._save_dirs.items():
save_dir.cleanup()
self._moves = []
self._save_dirs = {} | def commit(self):
"""Commits the uninstall by removing stashed files."""
for _, save_dir in self._save_dirs.items():
save_dir.cleanup()
self._moves = []
self._save_dirs = {} | [
"Commits",
"the",
"uninstall",
"by",
"removing",
"stashed",
"files",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L260-L265 | [
"def",
"commit",
"(",
"self",
")",
":",
"for",
"_",
",",
"save_dir",
"in",
"self",
".",
"_save_dirs",
".",
"items",
"(",
")",
":",
"save_dir",
".",
"cleanup",
"(",
")",
"self",
".",
"_moves",
"=",
"[",
"]",
"self",
".",
"_save_dirs",
"=",
"{",
"}... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | StashedUninstallPathSet.rollback | Undoes the uninstall by moving stashed files back. | pipenv/patched/notpip/_internal/req/req_uninstall.py | def rollback(self):
"""Undoes the uninstall by moving stashed files back."""
for p in self._moves:
logging.info("Moving to %s\n from %s", *p)
for new_path, path in self._moves:
try:
logger.debug('Replacing %s from %s', new_path, path)
if os.path.isfile(new_path):
os.unlink(new_path)
elif os.path.isdir(new_path):
rmtree(new_path)
renames(path, new_path)
except OSError as ex:
logger.error("Failed to restore %s", new_path)
logger.debug("Exception: %s", ex)
self.commit() | def rollback(self):
"""Undoes the uninstall by moving stashed files back."""
for p in self._moves:
logging.info("Moving to %s\n from %s", *p)
for new_path, path in self._moves:
try:
logger.debug('Replacing %s from %s', new_path, path)
if os.path.isfile(new_path):
os.unlink(new_path)
elif os.path.isdir(new_path):
rmtree(new_path)
renames(path, new_path)
except OSError as ex:
logger.error("Failed to restore %s", new_path)
logger.debug("Exception: %s", ex)
self.commit() | [
"Undoes",
"the",
"uninstall",
"by",
"moving",
"stashed",
"files",
"back",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L267-L284 | [
"def",
"rollback",
"(",
"self",
")",
":",
"for",
"p",
"in",
"self",
".",
"_moves",
":",
"logging",
".",
"info",
"(",
"\"Moving to %s\\n from %s\"",
",",
"*",
"p",
")",
"for",
"new_path",
",",
"path",
"in",
"self",
".",
"_moves",
":",
"try",
":",
"log... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | UninstallPathSet.remove | Remove paths in ``self.paths`` with confirmation (unless
``auto_confirm`` is True). | pipenv/patched/notpip/_internal/req/req_uninstall.py | def remove(self, auto_confirm=False, verbose=False):
"""Remove paths in ``self.paths`` with confirmation (unless
``auto_confirm`` is True)."""
if not self.paths:
logger.info(
"Can't uninstall '%s'. No files were found to uninstall.",
self.dist.project_name,
)
return
dist_name_version = (
self.dist.project_name + "-" + self.dist.version
)
logger.info('Uninstalling %s:', dist_name_version)
with indent_log():
if auto_confirm or self._allowed_to_proceed(verbose):
moved = self._moved_paths
for_rename = compress_for_rename(self.paths)
for path in sorted(compact(for_rename)):
moved.stash(path)
logger.debug('Removing file or directory %s', path)
for pth in self.pth.values():
pth.remove()
logger.info('Successfully uninstalled %s', dist_name_version) | def remove(self, auto_confirm=False, verbose=False):
"""Remove paths in ``self.paths`` with confirmation (unless
``auto_confirm`` is True)."""
if not self.paths:
logger.info(
"Can't uninstall '%s'. No files were found to uninstall.",
self.dist.project_name,
)
return
dist_name_version = (
self.dist.project_name + "-" + self.dist.version
)
logger.info('Uninstalling %s:', dist_name_version)
with indent_log():
if auto_confirm or self._allowed_to_proceed(verbose):
moved = self._moved_paths
for_rename = compress_for_rename(self.paths)
for path in sorted(compact(for_rename)):
moved.stash(path)
logger.debug('Removing file or directory %s', path)
for pth in self.pth.values():
pth.remove()
logger.info('Successfully uninstalled %s', dist_name_version) | [
"Remove",
"paths",
"in",
"self",
".",
"paths",
"with",
"confirmation",
"(",
"unless",
"auto_confirm",
"is",
"True",
")",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L337-L366 | [
"def",
"remove",
"(",
"self",
",",
"auto_confirm",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"paths",
":",
"logger",
".",
"info",
"(",
"\"Can't uninstall '%s'. No files were found to uninstall.\"",
",",
"self",
".",
"dist"... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | UninstallPathSet._allowed_to_proceed | Display which files would be deleted and prompt for confirmation | pipenv/patched/notpip/_internal/req/req_uninstall.py | def _allowed_to_proceed(self, verbose):
"""Display which files would be deleted and prompt for confirmation
"""
def _display(msg, paths):
if not paths:
return
logger.info(msg)
with indent_log():
for path in sorted(compact(paths)):
logger.info(path)
if not verbose:
will_remove, will_skip = compress_for_output_listing(self.paths)
else:
# In verbose mode, display all the files that are going to be
# deleted.
will_remove = list(self.paths)
will_skip = set()
_display('Would remove:', will_remove)
_display('Would not remove (might be manually added):', will_skip)
_display('Would not remove (outside of prefix):', self._refuse)
if verbose:
_display('Will actually move:', compress_for_rename(self.paths))
return ask('Proceed (y/n)? ', ('y', 'n')) == 'y' | def _allowed_to_proceed(self, verbose):
"""Display which files would be deleted and prompt for confirmation
"""
def _display(msg, paths):
if not paths:
return
logger.info(msg)
with indent_log():
for path in sorted(compact(paths)):
logger.info(path)
if not verbose:
will_remove, will_skip = compress_for_output_listing(self.paths)
else:
# In verbose mode, display all the files that are going to be
# deleted.
will_remove = list(self.paths)
will_skip = set()
_display('Would remove:', will_remove)
_display('Would not remove (might be manually added):', will_skip)
_display('Would not remove (outside of prefix):', self._refuse)
if verbose:
_display('Will actually move:', compress_for_rename(self.paths))
return ask('Proceed (y/n)? ', ('y', 'n')) == 'y' | [
"Display",
"which",
"files",
"would",
"be",
"deleted",
"and",
"prompt",
"for",
"confirmation"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L368-L395 | [
"def",
"_allowed_to_proceed",
"(",
"self",
",",
"verbose",
")",
":",
"def",
"_display",
"(",
"msg",
",",
"paths",
")",
":",
"if",
"not",
"paths",
":",
"return",
"logger",
".",
"info",
"(",
"msg",
")",
"with",
"indent_log",
"(",
")",
":",
"for",
"path... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | UninstallPathSet.rollback | Rollback the changes previously made by remove(). | pipenv/patched/notpip/_internal/req/req_uninstall.py | def rollback(self):
"""Rollback the changes previously made by remove()."""
if not self._moved_paths.can_rollback:
logger.error(
"Can't roll back %s; was not uninstalled",
self.dist.project_name,
)
return False
logger.info('Rolling back uninstall of %s', self.dist.project_name)
self._moved_paths.rollback()
for pth in self.pth.values():
pth.rollback() | def rollback(self):
"""Rollback the changes previously made by remove()."""
if not self._moved_paths.can_rollback:
logger.error(
"Can't roll back %s; was not uninstalled",
self.dist.project_name,
)
return False
logger.info('Rolling back uninstall of %s', self.dist.project_name)
self._moved_paths.rollback()
for pth in self.pth.values():
pth.rollback() | [
"Rollback",
"the",
"changes",
"previously",
"made",
"by",
"remove",
"()",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L397-L408 | [
"def",
"rollback",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_moved_paths",
".",
"can_rollback",
":",
"logger",
".",
"error",
"(",
"\"Can't roll back %s; was not uninstalled\"",
",",
"self",
".",
"dist",
".",
"project_name",
",",
")",
"return",
"False"... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | Package.author | >>> package = yarg.get('yarg')
>>> package.author
Author(name=u'Kura', email=u'kura@kura.io') | pipenv/vendor/yarg/package.py | def author(self):
"""
>>> package = yarg.get('yarg')
>>> package.author
Author(name=u'Kura', email=u'kura@kura.io')
"""
author = namedtuple('Author', 'name email')
return author(name=self._package['author'],
email=self._package['author_email']) | def author(self):
"""
>>> package = yarg.get('yarg')
>>> package.author
Author(name=u'Kura', email=u'kura@kura.io')
"""
author = namedtuple('Author', 'name email')
return author(name=self._package['author'],
email=self._package['author_email']) | [
">>>",
"package",
"=",
"yarg",
".",
"get",
"(",
"yarg",
")",
">>>",
"package",
".",
"author",
"Author",
"(",
"name",
"=",
"u",
"Kura",
"email",
"=",
"u",
"kura"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yarg/package.py#L123-L131 | [
"def",
"author",
"(",
"self",
")",
":",
"author",
"=",
"namedtuple",
"(",
"'Author'",
",",
"'name email'",
")",
"return",
"author",
"(",
"name",
"=",
"self",
".",
"_package",
"[",
"'author'",
"]",
",",
"email",
"=",
"self",
".",
"_package",
"[",
"'auth... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | Package.maintainer | >>> package = yarg.get('yarg')
>>> package.maintainer
Maintainer(name=u'Kura', email=u'kura@kura.io') | pipenv/vendor/yarg/package.py | def maintainer(self):
"""
>>> package = yarg.get('yarg')
>>> package.maintainer
Maintainer(name=u'Kura', email=u'kura@kura.io')
"""
maintainer = namedtuple('Maintainer', 'name email')
return maintainer(name=self._package['maintainer'],
email=self._package['maintainer_email']) | def maintainer(self):
"""
>>> package = yarg.get('yarg')
>>> package.maintainer
Maintainer(name=u'Kura', email=u'kura@kura.io')
"""
maintainer = namedtuple('Maintainer', 'name email')
return maintainer(name=self._package['maintainer'],
email=self._package['maintainer_email']) | [
">>>",
"package",
"=",
"yarg",
".",
"get",
"(",
"yarg",
")",
">>>",
"package",
".",
"maintainer",
"Maintainer",
"(",
"name",
"=",
"u",
"Kura",
"email",
"=",
"u",
"kura"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yarg/package.py#L134-L142 | [
"def",
"maintainer",
"(",
"self",
")",
":",
"maintainer",
"=",
"namedtuple",
"(",
"'Maintainer'",
",",
"'name email'",
")",
"return",
"maintainer",
"(",
"name",
"=",
"self",
".",
"_package",
"[",
"'maintainer'",
"]",
",",
"email",
"=",
"self",
".",
"_packa... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | Package.license_from_classifiers | >>> package = yarg.get('yarg')
>>> package.license_from_classifiers
u'MIT License' | pipenv/vendor/yarg/package.py | def license_from_classifiers(self):
"""
>>> package = yarg.get('yarg')
>>> package.license_from_classifiers
u'MIT License'
"""
if len(self.classifiers) > 0:
for c in self.classifiers:
if c.startswith("License"):
return c.split(" :: ")[-1] | def license_from_classifiers(self):
"""
>>> package = yarg.get('yarg')
>>> package.license_from_classifiers
u'MIT License'
"""
if len(self.classifiers) > 0:
for c in self.classifiers:
if c.startswith("License"):
return c.split(" :: ")[-1] | [
">>>",
"package",
"=",
"yarg",
".",
"get",
"(",
"yarg",
")",
">>>",
"package",
".",
"license_from_classifiers",
"u",
"MIT",
"License"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yarg/package.py#L154-L163 | [
"def",
"license_from_classifiers",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"classifiers",
")",
">",
"0",
":",
"for",
"c",
"in",
"self",
".",
"classifiers",
":",
"if",
"c",
".",
"startswith",
"(",
"\"License\"",
")",
":",
"return",
"c",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | Package.downloads | >>> package = yarg.get('yarg')
>>> package.downloads
Downloads(day=50100, week=367941, month=1601938) # I wish | pipenv/vendor/yarg/package.py | def downloads(self):
"""
>>> package = yarg.get('yarg')
>>> package.downloads
Downloads(day=50100, week=367941, month=1601938) # I wish
"""
_downloads = self._package['downloads']
downloads = namedtuple('Downloads', 'day week month')
return downloads(day=_downloads['last_day'],
week=_downloads['last_week'],
month=_downloads['last_month']) | def downloads(self):
"""
>>> package = yarg.get('yarg')
>>> package.downloads
Downloads(day=50100, week=367941, month=1601938) # I wish
"""
_downloads = self._package['downloads']
downloads = namedtuple('Downloads', 'day week month')
return downloads(day=_downloads['last_day'],
week=_downloads['last_week'],
month=_downloads['last_month']) | [
">>>",
"package",
"=",
"yarg",
".",
"get",
"(",
"yarg",
")",
">>>",
"package",
".",
"downloads",
"Downloads",
"(",
"day",
"=",
"50100",
"week",
"=",
"367941",
"month",
"=",
"1601938",
")",
"#",
"I",
"wish"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yarg/package.py#L166-L176 | [
"def",
"downloads",
"(",
"self",
")",
":",
"_downloads",
"=",
"self",
".",
"_package",
"[",
"'downloads'",
"]",
"downloads",
"=",
"namedtuple",
"(",
"'Downloads'",
",",
"'day week month'",
")",
"return",
"downloads",
"(",
"day",
"=",
"_downloads",
"[",
"'las... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | Package.python_versions | Returns a list of Python version strings that
the package has listed in :attr:`yarg.Release.classifiers`.
>>> package = yarg.get('yarg')
>>> package.python_versions
[u'2.6', u'2.7', u'3.3', u'3.4'] | pipenv/vendor/yarg/package.py | def python_versions(self):
"""
Returns a list of Python version strings that
the package has listed in :attr:`yarg.Release.classifiers`.
>>> package = yarg.get('yarg')
>>> package.python_versions
[u'2.6', u'2.7', u'3.3', u'3.4']
"""
version_re = re.compile(r"""Programming Language \:\: """
"""Python \:\: \d\.\d""")
return [c.split(' :: ')[-1] for c in self.classifiers
if version_re.match(c)] | def python_versions(self):
"""
Returns a list of Python version strings that
the package has listed in :attr:`yarg.Release.classifiers`.
>>> package = yarg.get('yarg')
>>> package.python_versions
[u'2.6', u'2.7', u'3.3', u'3.4']
"""
version_re = re.compile(r"""Programming Language \:\: """
"""Python \:\: \d\.\d""")
return [c.split(' :: ')[-1] for c in self.classifiers
if version_re.match(c)] | [
"Returns",
"a",
"list",
"of",
"Python",
"version",
"strings",
"that",
"the",
"package",
"has",
"listed",
"in",
":",
"attr",
":",
"yarg",
".",
"Release",
".",
"classifiers",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yarg/package.py#L190-L202 | [
"def",
"python_versions",
"(",
"self",
")",
":",
"version_re",
"=",
"re",
".",
"compile",
"(",
"r\"\"\"Programming Language \\:\\: \"\"\"",
"\"\"\"Python \\:\\: \\d\\.\\d\"\"\"",
")",
"return",
"[",
"c",
".",
"split",
"(",
"' :: '",
")",
"[",
"-",
"1",
"]",
"for... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | Package.release_ids | >>> package = yarg.get('yarg')
>>> package.release_ids
[u'0.0.1', u'0.0.5', u'0.1.0'] | pipenv/vendor/yarg/package.py | def release_ids(self):
"""
>>> package = yarg.get('yarg')
>>> package.release_ids
[u'0.0.1', u'0.0.5', u'0.1.0']
"""
r = [(k, self._releases[k][0]['upload_time'])
for k in self._releases.keys()
if len(self._releases[k]) > 0]
return [k[0] for k in sorted(r, key=lambda k: k[1])] | def release_ids(self):
"""
>>> package = yarg.get('yarg')
>>> package.release_ids
[u'0.0.1', u'0.0.5', u'0.1.0']
"""
r = [(k, self._releases[k][0]['upload_time'])
for k in self._releases.keys()
if len(self._releases[k]) > 0]
return [k[0] for k in sorted(r, key=lambda k: k[1])] | [
">>>",
"package",
"=",
"yarg",
".",
"get",
"(",
"yarg",
")",
">>>",
"package",
".",
"release_ids",
"[",
"u",
"0",
".",
"0",
".",
"1",
"u",
"0",
".",
"0",
".",
"5",
"u",
"0",
".",
"1",
".",
"0",
"]"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yarg/package.py#L289-L298 | [
"def",
"release_ids",
"(",
"self",
")",
":",
"r",
"=",
"[",
"(",
"k",
",",
"self",
".",
"_releases",
"[",
"k",
"]",
"[",
"0",
"]",
"[",
"'upload_time'",
"]",
")",
"for",
"k",
"in",
"self",
".",
"_releases",
".",
"keys",
"(",
")",
"if",
"len",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | Package.release | A list of :class:`yarg.release.Release` objects for each file in a
release.
:param release_id: A pypi release id.
>>> package = yarg.get('yarg')
>>> last_release = yarg.releases[-1]
>>> package.release(last_release)
[<Release 0.1.0>, <Release 0.1.0>] | pipenv/vendor/yarg/package.py | def release(self, release_id):
"""
A list of :class:`yarg.release.Release` objects for each file in a
release.
:param release_id: A pypi release id.
>>> package = yarg.get('yarg')
>>> last_release = yarg.releases[-1]
>>> package.release(last_release)
[<Release 0.1.0>, <Release 0.1.0>]
"""
if release_id not in self.release_ids:
return None
return [Release(release_id, r) for r in self._releases[release_id]] | def release(self, release_id):
"""
A list of :class:`yarg.release.Release` objects for each file in a
release.
:param release_id: A pypi release id.
>>> package = yarg.get('yarg')
>>> last_release = yarg.releases[-1]
>>> package.release(last_release)
[<Release 0.1.0>, <Release 0.1.0>]
"""
if release_id not in self.release_ids:
return None
return [Release(release_id, r) for r in self._releases[release_id]] | [
"A",
"list",
"of",
":",
"class",
":",
"yarg",
".",
"release",
".",
"Release",
"objects",
"for",
"each",
"file",
"in",
"a",
"release",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yarg/package.py#L300-L314 | [
"def",
"release",
"(",
"self",
",",
"release_id",
")",
":",
"if",
"release_id",
"not",
"in",
"self",
".",
"release_ids",
":",
"return",
"None",
"return",
"[",
"Release",
"(",
"release_id",
",",
"r",
")",
"for",
"r",
"in",
"self",
".",
"_releases",
"[",... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | is_executable_file | Checks that path is an executable regular file, or a symlink towards one.
This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``. | pipenv/vendor/pexpect/utils.py | def is_executable_file(path):
"""Checks that path is an executable regular file, or a symlink towards one.
This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``.
"""
# follow symlinks,
fpath = os.path.realpath(path)
if not os.path.isfile(fpath):
# non-files (directories, fifo, etc.)
return False
mode = os.stat(fpath).st_mode
if (sys.platform.startswith('sunos')
and os.getuid() == 0):
# When root on Solaris, os.X_OK is True for *all* files, irregardless
# of their executability -- instead, any permission bit of any user,
# group, or other is fine enough.
#
# (This may be true for other "Unix98" OS's such as HP-UX and AIX)
return bool(mode & (stat.S_IXUSR |
stat.S_IXGRP |
stat.S_IXOTH))
return os.access(fpath, os.X_OK) | def is_executable_file(path):
"""Checks that path is an executable regular file, or a symlink towards one.
This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``.
"""
# follow symlinks,
fpath = os.path.realpath(path)
if not os.path.isfile(fpath):
# non-files (directories, fifo, etc.)
return False
mode = os.stat(fpath).st_mode
if (sys.platform.startswith('sunos')
and os.getuid() == 0):
# When root on Solaris, os.X_OK is True for *all* files, irregardless
# of their executability -- instead, any permission bit of any user,
# group, or other is fine enough.
#
# (This may be true for other "Unix98" OS's such as HP-UX and AIX)
return bool(mode & (stat.S_IXUSR |
stat.S_IXGRP |
stat.S_IXOTH))
return os.access(fpath, os.X_OK) | [
"Checks",
"that",
"path",
"is",
"an",
"executable",
"regular",
"file",
"or",
"a",
"symlink",
"towards",
"one",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/utils.py#L20-L45 | [
"def",
"is_executable_file",
"(",
"path",
")",
":",
"# follow symlinks,",
"fpath",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"fpath",
")",
":",
"# non-files (directories, fifo, etc.)",
"ret... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | which | This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None. | pipenv/vendor/pexpect/utils.py | def which(filename, env=None):
'''This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None.'''
# Special case where filename contains an explicit path.
if os.path.dirname(filename) != '' and is_executable_file(filename):
return filename
if env is None:
env = os.environ
p = env.get('PATH')
if not p:
p = os.defpath
pathlist = p.split(os.pathsep)
for path in pathlist:
ff = os.path.join(path, filename)
if is_executable_file(ff):
return ff
return None | def which(filename, env=None):
'''This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None.'''
# Special case where filename contains an explicit path.
if os.path.dirname(filename) != '' and is_executable_file(filename):
return filename
if env is None:
env = os.environ
p = env.get('PATH')
if not p:
p = os.defpath
pathlist = p.split(os.pathsep)
for path in pathlist:
ff = os.path.join(path, filename)
if is_executable_file(ff):
return ff
return None | [
"This",
"takes",
"a",
"given",
"filename",
";",
"tries",
"to",
"find",
"it",
"in",
"the",
"environment",
"path",
";",
"then",
"checks",
"if",
"it",
"is",
"executable",
".",
"This",
"returns",
"the",
"full",
"path",
"to",
"the",
"filename",
"if",
"found",... | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/utils.py#L48-L66 | [
"def",
"which",
"(",
"filename",
",",
"env",
"=",
"None",
")",
":",
"# Special case where filename contains an explicit path.",
"if",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"!=",
"''",
"and",
"is_executable_file",
"(",
"filename",
")",
":",
"... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | split_command_line | This splits a command line into a list of arguments. It splits arguments
on spaces, but handles embedded quotes, doublequotes, and escaped
characters. It's impossible to do this with a regular expression, so I
wrote a little state machine to parse the command line. | pipenv/vendor/pexpect/utils.py | def split_command_line(command_line):
'''This splits a command line into a list of arguments. It splits arguments
on spaces, but handles embedded quotes, doublequotes, and escaped
characters. It's impossible to do this with a regular expression, so I
wrote a little state machine to parse the command line. '''
arg_list = []
arg = ''
# Constants to name the states we can be in.
state_basic = 0
state_esc = 1
state_singlequote = 2
state_doublequote = 3
# The state when consuming whitespace between commands.
state_whitespace = 4
state = state_basic
for c in command_line:
if state == state_basic or state == state_whitespace:
if c == '\\':
# Escape the next character
state = state_esc
elif c == r"'":
# Handle single quote
state = state_singlequote
elif c == r'"':
# Handle double quote
state = state_doublequote
elif c.isspace():
# Add arg to arg_list if we aren't in the middle of whitespace.
if state == state_whitespace:
# Do nothing.
None
else:
arg_list.append(arg)
arg = ''
state = state_whitespace
else:
arg = arg + c
state = state_basic
elif state == state_esc:
arg = arg + c
state = state_basic
elif state == state_singlequote:
if c == r"'":
state = state_basic
else:
arg = arg + c
elif state == state_doublequote:
if c == r'"':
state = state_basic
else:
arg = arg + c
if arg != '':
arg_list.append(arg)
return arg_list | def split_command_line(command_line):
'''This splits a command line into a list of arguments. It splits arguments
on spaces, but handles embedded quotes, doublequotes, and escaped
characters. It's impossible to do this with a regular expression, so I
wrote a little state machine to parse the command line. '''
arg_list = []
arg = ''
# Constants to name the states we can be in.
state_basic = 0
state_esc = 1
state_singlequote = 2
state_doublequote = 3
# The state when consuming whitespace between commands.
state_whitespace = 4
state = state_basic
for c in command_line:
if state == state_basic or state == state_whitespace:
if c == '\\':
# Escape the next character
state = state_esc
elif c == r"'":
# Handle single quote
state = state_singlequote
elif c == r'"':
# Handle double quote
state = state_doublequote
elif c.isspace():
# Add arg to arg_list if we aren't in the middle of whitespace.
if state == state_whitespace:
# Do nothing.
None
else:
arg_list.append(arg)
arg = ''
state = state_whitespace
else:
arg = arg + c
state = state_basic
elif state == state_esc:
arg = arg + c
state = state_basic
elif state == state_singlequote:
if c == r"'":
state = state_basic
else:
arg = arg + c
elif state == state_doublequote:
if c == r'"':
state = state_basic
else:
arg = arg + c
if arg != '':
arg_list.append(arg)
return arg_list | [
"This",
"splits",
"a",
"command",
"line",
"into",
"a",
"list",
"of",
"arguments",
".",
"It",
"splits",
"arguments",
"on",
"spaces",
"but",
"handles",
"embedded",
"quotes",
"doublequotes",
"and",
"escaped",
"characters",
".",
"It",
"s",
"impossible",
"to",
"d... | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/utils.py#L69-L127 | [
"def",
"split_command_line",
"(",
"command_line",
")",
":",
"arg_list",
"=",
"[",
"]",
"arg",
"=",
"''",
"# Constants to name the states we can be in.",
"state_basic",
"=",
"0",
"state_esc",
"=",
"1",
"state_singlequote",
"=",
"2",
"state_doublequote",
"=",
"3",
"... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | select_ignore_interrupts | This is a wrapper around select.select() that ignores signals. If
select.select raises a select.error exception and errno is an EINTR
error then it is ignored. Mainly this is used to ignore sigwinch
(terminal resize). | pipenv/vendor/pexpect/utils.py | def select_ignore_interrupts(iwtd, owtd, ewtd, timeout=None):
'''This is a wrapper around select.select() that ignores signals. If
select.select raises a select.error exception and errno is an EINTR
error then it is ignored. Mainly this is used to ignore sigwinch
(terminal resize). '''
# if select() is interrupted by a signal (errno==EINTR) then
# we loop back and enter the select() again.
if timeout is not None:
end_time = time.time() + timeout
while True:
try:
return select.select(iwtd, owtd, ewtd, timeout)
except InterruptedError:
err = sys.exc_info()[1]
if err.args[0] == errno.EINTR:
# if we loop back we have to subtract the
# amount of time we already waited.
if timeout is not None:
timeout = end_time - time.time()
if timeout < 0:
return([], [], [])
else:
# something else caused the select.error, so
# this actually is an exception.
raise | def select_ignore_interrupts(iwtd, owtd, ewtd, timeout=None):
'''This is a wrapper around select.select() that ignores signals. If
select.select raises a select.error exception and errno is an EINTR
error then it is ignored. Mainly this is used to ignore sigwinch
(terminal resize). '''
# if select() is interrupted by a signal (errno==EINTR) then
# we loop back and enter the select() again.
if timeout is not None:
end_time = time.time() + timeout
while True:
try:
return select.select(iwtd, owtd, ewtd, timeout)
except InterruptedError:
err = sys.exc_info()[1]
if err.args[0] == errno.EINTR:
# if we loop back we have to subtract the
# amount of time we already waited.
if timeout is not None:
timeout = end_time - time.time()
if timeout < 0:
return([], [], [])
else:
# something else caused the select.error, so
# this actually is an exception.
raise | [
"This",
"is",
"a",
"wrapper",
"around",
"select",
".",
"select",
"()",
"that",
"ignores",
"signals",
".",
"If",
"select",
".",
"select",
"raises",
"a",
"select",
".",
"error",
"exception",
"and",
"errno",
"is",
"an",
"EINTR",
"error",
"then",
"it",
"is",... | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/utils.py#L130-L156 | [
"def",
"select_ignore_interrupts",
"(",
"iwtd",
",",
"owtd",
",",
"ewtd",
",",
"timeout",
"=",
"None",
")",
":",
"# if select() is interrupted by a signal (errno==EINTR) then",
"# we loop back and enter the select() again.",
"if",
"timeout",
"is",
"not",
"None",
":",
"end... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | poll_ignore_interrupts | Simple wrapper around poll to register file descriptors and
ignore signals. | pipenv/vendor/pexpect/utils.py | def poll_ignore_interrupts(fds, timeout=None):
'''Simple wrapper around poll to register file descriptors and
ignore signals.'''
if timeout is not None:
end_time = time.time() + timeout
poller = select.poll()
for fd in fds:
poller.register(fd, select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR)
while True:
try:
timeout_ms = None if timeout is None else timeout * 1000
results = poller.poll(timeout_ms)
return [afd for afd, _ in results]
except InterruptedError:
err = sys.exc_info()[1]
if err.args[0] == errno.EINTR:
# if we loop back we have to subtract the
# amount of time we already waited.
if timeout is not None:
timeout = end_time - time.time()
if timeout < 0:
return []
else:
# something else caused the select.error, so
# this actually is an exception.
raise | def poll_ignore_interrupts(fds, timeout=None):
'''Simple wrapper around poll to register file descriptors and
ignore signals.'''
if timeout is not None:
end_time = time.time() + timeout
poller = select.poll()
for fd in fds:
poller.register(fd, select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR)
while True:
try:
timeout_ms = None if timeout is None else timeout * 1000
results = poller.poll(timeout_ms)
return [afd for afd, _ in results]
except InterruptedError:
err = sys.exc_info()[1]
if err.args[0] == errno.EINTR:
# if we loop back we have to subtract the
# amount of time we already waited.
if timeout is not None:
timeout = end_time - time.time()
if timeout < 0:
return []
else:
# something else caused the select.error, so
# this actually is an exception.
raise | [
"Simple",
"wrapper",
"around",
"poll",
"to",
"register",
"file",
"descriptors",
"and",
"ignore",
"signals",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/utils.py#L159-L187 | [
"def",
"poll_ignore_interrupts",
"(",
"fds",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"poller",
"=",
"select",
".",
"poll",
"(",
")",
"for",
"fd"... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | _suggest_semantic_version | Try to suggest a semantic form for a version for which
_suggest_normalized_version couldn't come up with anything. | pipenv/vendor/distlib/version.py | def _suggest_semantic_version(s):
"""
Try to suggest a semantic form for a version for which
_suggest_normalized_version couldn't come up with anything.
"""
result = s.strip().lower()
for pat, repl in _REPLACEMENTS:
result = pat.sub(repl, result)
if not result:
result = '0.0.0'
# Now look for numeric prefix, and separate it out from
# the rest.
#import pdb; pdb.set_trace()
m = _NUMERIC_PREFIX.match(result)
if not m:
prefix = '0.0.0'
suffix = result
else:
prefix = m.groups()[0].split('.')
prefix = [int(i) for i in prefix]
while len(prefix) < 3:
prefix.append(0)
if len(prefix) == 3:
suffix = result[m.end():]
else:
suffix = '.'.join([str(i) for i in prefix[3:]]) + result[m.end():]
prefix = prefix[:3]
prefix = '.'.join([str(i) for i in prefix])
suffix = suffix.strip()
if suffix:
#import pdb; pdb.set_trace()
# massage the suffix.
for pat, repl in _SUFFIX_REPLACEMENTS:
suffix = pat.sub(repl, suffix)
if not suffix:
result = prefix
else:
sep = '-' if 'dev' in suffix else '+'
result = prefix + sep + suffix
if not is_semver(result):
result = None
return result | def _suggest_semantic_version(s):
"""
Try to suggest a semantic form for a version for which
_suggest_normalized_version couldn't come up with anything.
"""
result = s.strip().lower()
for pat, repl in _REPLACEMENTS:
result = pat.sub(repl, result)
if not result:
result = '0.0.0'
# Now look for numeric prefix, and separate it out from
# the rest.
#import pdb; pdb.set_trace()
m = _NUMERIC_PREFIX.match(result)
if not m:
prefix = '0.0.0'
suffix = result
else:
prefix = m.groups()[0].split('.')
prefix = [int(i) for i in prefix]
while len(prefix) < 3:
prefix.append(0)
if len(prefix) == 3:
suffix = result[m.end():]
else:
suffix = '.'.join([str(i) for i in prefix[3:]]) + result[m.end():]
prefix = prefix[:3]
prefix = '.'.join([str(i) for i in prefix])
suffix = suffix.strip()
if suffix:
#import pdb; pdb.set_trace()
# massage the suffix.
for pat, repl in _SUFFIX_REPLACEMENTS:
suffix = pat.sub(repl, suffix)
if not suffix:
result = prefix
else:
sep = '-' if 'dev' in suffix else '+'
result = prefix + sep + suffix
if not is_semver(result):
result = None
return result | [
"Try",
"to",
"suggest",
"a",
"semantic",
"form",
"for",
"a",
"version",
"for",
"which",
"_suggest_normalized_version",
"couldn",
"t",
"come",
"up",
"with",
"anything",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/version.py#L406-L449 | [
"def",
"_suggest_semantic_version",
"(",
"s",
")",
":",
"result",
"=",
"s",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"for",
"pat",
",",
"repl",
"in",
"_REPLACEMENTS",
":",
"result",
"=",
"pat",
".",
"sub",
"(",
"repl",
",",
"result",
")",
"i... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | _suggest_normalized_version | Suggest a normalized version close to the given version string.
If you have a version string that isn't rational (i.e. NormalizedVersion
doesn't like it) then you might be able to get an equivalent (or close)
rational version from this function.
This does a number of simple normalizations to the given string, based
on observation of versions currently in use on PyPI. Given a dump of
those version during PyCon 2009, 4287 of them:
- 2312 (53.93%) match NormalizedVersion without change
with the automatic suggestion
- 3474 (81.04%) match when using this suggestion method
@param s {str} An irrational version string.
@returns A rational version string, or None, if couldn't determine one. | pipenv/vendor/distlib/version.py | def _suggest_normalized_version(s):
"""Suggest a normalized version close to the given version string.
If you have a version string that isn't rational (i.e. NormalizedVersion
doesn't like it) then you might be able to get an equivalent (or close)
rational version from this function.
This does a number of simple normalizations to the given string, based
on observation of versions currently in use on PyPI. Given a dump of
those version during PyCon 2009, 4287 of them:
- 2312 (53.93%) match NormalizedVersion without change
with the automatic suggestion
- 3474 (81.04%) match when using this suggestion method
@param s {str} An irrational version string.
@returns A rational version string, or None, if couldn't determine one.
"""
try:
_normalized_key(s)
return s # already rational
except UnsupportedVersionError:
pass
rs = s.lower()
# part of this could use maketrans
for orig, repl in (('-alpha', 'a'), ('-beta', 'b'), ('alpha', 'a'),
('beta', 'b'), ('rc', 'c'), ('-final', ''),
('-pre', 'c'),
('-release', ''), ('.release', ''), ('-stable', ''),
('+', '.'), ('_', '.'), (' ', ''), ('.final', ''),
('final', '')):
rs = rs.replace(orig, repl)
# if something ends with dev or pre, we add a 0
rs = re.sub(r"pre$", r"pre0", rs)
rs = re.sub(r"dev$", r"dev0", rs)
# if we have something like "b-2" or "a.2" at the end of the
# version, that is probably beta, alpha, etc
# let's remove the dash or dot
rs = re.sub(r"([abc]|rc)[\-\.](\d+)$", r"\1\2", rs)
# 1.0-dev-r371 -> 1.0.dev371
# 0.1-dev-r79 -> 0.1.dev79
rs = re.sub(r"[\-\.](dev)[\-\.]?r?(\d+)$", r".\1\2", rs)
# Clean: 2.0.a.3, 2.0.b1, 0.9.0~c1
rs = re.sub(r"[.~]?([abc])\.?", r"\1", rs)
# Clean: v0.3, v1.0
if rs.startswith('v'):
rs = rs[1:]
# Clean leading '0's on numbers.
#TODO: unintended side-effect on, e.g., "2003.05.09"
# PyPI stats: 77 (~2%) better
rs = re.sub(r"\b0+(\d+)(?!\d)", r"\1", rs)
# Clean a/b/c with no version. E.g. "1.0a" -> "1.0a0". Setuptools infers
# zero.
# PyPI stats: 245 (7.56%) better
rs = re.sub(r"(\d+[abc])$", r"\g<1>0", rs)
# the 'dev-rNNN' tag is a dev tag
rs = re.sub(r"\.?(dev-r|dev\.r)\.?(\d+)$", r".dev\2", rs)
# clean the - when used as a pre delimiter
rs = re.sub(r"-(a|b|c)(\d+)$", r"\1\2", rs)
# a terminal "dev" or "devel" can be changed into ".dev0"
rs = re.sub(r"[\.\-](dev|devel)$", r".dev0", rs)
# a terminal "dev" can be changed into ".dev0"
rs = re.sub(r"(?![\.\-])dev$", r".dev0", rs)
# a terminal "final" or "stable" can be removed
rs = re.sub(r"(final|stable)$", "", rs)
# The 'r' and the '-' tags are post release tags
# 0.4a1.r10 -> 0.4a1.post10
# 0.9.33-17222 -> 0.9.33.post17222
# 0.9.33-r17222 -> 0.9.33.post17222
rs = re.sub(r"\.?(r|-|-r)\.?(\d+)$", r".post\2", rs)
# Clean 'r' instead of 'dev' usage:
# 0.9.33+r17222 -> 0.9.33.dev17222
# 1.0dev123 -> 1.0.dev123
# 1.0.git123 -> 1.0.dev123
# 1.0.bzr123 -> 1.0.dev123
# 0.1a0dev.123 -> 0.1a0.dev123
# PyPI stats: ~150 (~4%) better
rs = re.sub(r"\.?(dev|git|bzr)\.?(\d+)$", r".dev\2", rs)
# Clean '.pre' (normalized from '-pre' above) instead of 'c' usage:
# 0.2.pre1 -> 0.2c1
# 0.2-c1 -> 0.2c1
# 1.0preview123 -> 1.0c123
# PyPI stats: ~21 (0.62%) better
rs = re.sub(r"\.?(pre|preview|-c)(\d+)$", r"c\g<2>", rs)
# Tcl/Tk uses "px" for their post release markers
rs = re.sub(r"p(\d+)$", r".post\1", rs)
try:
_normalized_key(rs)
except UnsupportedVersionError:
rs = None
return rs | def _suggest_normalized_version(s):
"""Suggest a normalized version close to the given version string.
If you have a version string that isn't rational (i.e. NormalizedVersion
doesn't like it) then you might be able to get an equivalent (or close)
rational version from this function.
This does a number of simple normalizations to the given string, based
on observation of versions currently in use on PyPI. Given a dump of
those version during PyCon 2009, 4287 of them:
- 2312 (53.93%) match NormalizedVersion without change
with the automatic suggestion
- 3474 (81.04%) match when using this suggestion method
@param s {str} An irrational version string.
@returns A rational version string, or None, if couldn't determine one.
"""
try:
_normalized_key(s)
return s # already rational
except UnsupportedVersionError:
pass
rs = s.lower()
# part of this could use maketrans
for orig, repl in (('-alpha', 'a'), ('-beta', 'b'), ('alpha', 'a'),
('beta', 'b'), ('rc', 'c'), ('-final', ''),
('-pre', 'c'),
('-release', ''), ('.release', ''), ('-stable', ''),
('+', '.'), ('_', '.'), (' ', ''), ('.final', ''),
('final', '')):
rs = rs.replace(orig, repl)
# if something ends with dev or pre, we add a 0
rs = re.sub(r"pre$", r"pre0", rs)
rs = re.sub(r"dev$", r"dev0", rs)
# if we have something like "b-2" or "a.2" at the end of the
# version, that is probably beta, alpha, etc
# let's remove the dash or dot
rs = re.sub(r"([abc]|rc)[\-\.](\d+)$", r"\1\2", rs)
# 1.0-dev-r371 -> 1.0.dev371
# 0.1-dev-r79 -> 0.1.dev79
rs = re.sub(r"[\-\.](dev)[\-\.]?r?(\d+)$", r".\1\2", rs)
# Clean: 2.0.a.3, 2.0.b1, 0.9.0~c1
rs = re.sub(r"[.~]?([abc])\.?", r"\1", rs)
# Clean: v0.3, v1.0
if rs.startswith('v'):
rs = rs[1:]
# Clean leading '0's on numbers.
#TODO: unintended side-effect on, e.g., "2003.05.09"
# PyPI stats: 77 (~2%) better
rs = re.sub(r"\b0+(\d+)(?!\d)", r"\1", rs)
# Clean a/b/c with no version. E.g. "1.0a" -> "1.0a0". Setuptools infers
# zero.
# PyPI stats: 245 (7.56%) better
rs = re.sub(r"(\d+[abc])$", r"\g<1>0", rs)
# the 'dev-rNNN' tag is a dev tag
rs = re.sub(r"\.?(dev-r|dev\.r)\.?(\d+)$", r".dev\2", rs)
# clean the - when used as a pre delimiter
rs = re.sub(r"-(a|b|c)(\d+)$", r"\1\2", rs)
# a terminal "dev" or "devel" can be changed into ".dev0"
rs = re.sub(r"[\.\-](dev|devel)$", r".dev0", rs)
# a terminal "dev" can be changed into ".dev0"
rs = re.sub(r"(?![\.\-])dev$", r".dev0", rs)
# a terminal "final" or "stable" can be removed
rs = re.sub(r"(final|stable)$", "", rs)
# The 'r' and the '-' tags are post release tags
# 0.4a1.r10 -> 0.4a1.post10
# 0.9.33-17222 -> 0.9.33.post17222
# 0.9.33-r17222 -> 0.9.33.post17222
rs = re.sub(r"\.?(r|-|-r)\.?(\d+)$", r".post\2", rs)
# Clean 'r' instead of 'dev' usage:
# 0.9.33+r17222 -> 0.9.33.dev17222
# 1.0dev123 -> 1.0.dev123
# 1.0.git123 -> 1.0.dev123
# 1.0.bzr123 -> 1.0.dev123
# 0.1a0dev.123 -> 0.1a0.dev123
# PyPI stats: ~150 (~4%) better
rs = re.sub(r"\.?(dev|git|bzr)\.?(\d+)$", r".dev\2", rs)
# Clean '.pre' (normalized from '-pre' above) instead of 'c' usage:
# 0.2.pre1 -> 0.2c1
# 0.2-c1 -> 0.2c1
# 1.0preview123 -> 1.0c123
# PyPI stats: ~21 (0.62%) better
rs = re.sub(r"\.?(pre|preview|-c)(\d+)$", r"c\g<2>", rs)
# Tcl/Tk uses "px" for their post release markers
rs = re.sub(r"p(\d+)$", r".post\1", rs)
try:
_normalized_key(rs)
except UnsupportedVersionError:
rs = None
return rs | [
"Suggest",
"a",
"normalized",
"version",
"close",
"to",
"the",
"given",
"version",
"string",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/version.py#L452-L560 | [
"def",
"_suggest_normalized_version",
"(",
"s",
")",
":",
"try",
":",
"_normalized_key",
"(",
"s",
")",
"return",
"s",
"# already rational",
"except",
"UnsupportedVersionError",
":",
"pass",
"rs",
"=",
"s",
".",
"lower",
"(",
")",
"# part of this could use maketra... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | Matcher.match | Check if the provided version matches the constraints.
:param version: The version to match against this instance.
:type version: String or :class:`Version` instance. | pipenv/vendor/distlib/version.py | def match(self, version):
"""
Check if the provided version matches the constraints.
:param version: The version to match against this instance.
:type version: String or :class:`Version` instance.
"""
if isinstance(version, string_types):
version = self.version_class(version)
for operator, constraint, prefix in self._parts:
f = self._operators.get(operator)
if isinstance(f, string_types):
f = getattr(self, f)
if not f:
msg = ('%r not implemented '
'for %s' % (operator, self.__class__.__name__))
raise NotImplementedError(msg)
if not f(version, constraint, prefix):
return False
return True | def match(self, version):
"""
Check if the provided version matches the constraints.
:param version: The version to match against this instance.
:type version: String or :class:`Version` instance.
"""
if isinstance(version, string_types):
version = self.version_class(version)
for operator, constraint, prefix in self._parts:
f = self._operators.get(operator)
if isinstance(f, string_types):
f = getattr(self, f)
if not f:
msg = ('%r not implemented '
'for %s' % (operator, self.__class__.__name__))
raise NotImplementedError(msg)
if not f(version, constraint, prefix):
return False
return True | [
"Check",
"if",
"the",
"provided",
"version",
"matches",
"the",
"constraints",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/version.py#L129-L148 | [
"def",
"match",
"(",
"self",
",",
"version",
")",
":",
"if",
"isinstance",
"(",
"version",
",",
"string_types",
")",
":",
"version",
"=",
"self",
".",
"version_class",
"(",
"version",
")",
"for",
"operator",
",",
"constraint",
",",
"prefix",
"in",
"self"... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | set_key | Adds or Updates a key/value to the given .env
If the .env path given doesn't exist, fails instead of risking creating
an orphan .env somewhere in the filesystem | pipenv/vendor/dotenv/main.py | def set_key(dotenv_path, key_to_set, value_to_set, quote_mode="always"):
"""
Adds or Updates a key/value to the given .env
If the .env path given doesn't exist, fails instead of risking creating
an orphan .env somewhere in the filesystem
"""
value_to_set = value_to_set.strip("'").strip('"')
if not os.path.exists(dotenv_path):
warnings.warn("can't write to %s - it doesn't exist." % dotenv_path)
return None, key_to_set, value_to_set
if " " in value_to_set:
quote_mode = "always"
line_template = '{}="{}"\n' if quote_mode == "always" else '{}={}\n'
line_out = line_template.format(key_to_set, value_to_set)
with rewrite(dotenv_path) as (source, dest):
replaced = False
for mapping in parse_stream(source):
if mapping.key == key_to_set:
dest.write(line_out)
replaced = True
else:
dest.write(mapping.original)
if not replaced:
dest.write(line_out)
return True, key_to_set, value_to_set | def set_key(dotenv_path, key_to_set, value_to_set, quote_mode="always"):
"""
Adds or Updates a key/value to the given .env
If the .env path given doesn't exist, fails instead of risking creating
an orphan .env somewhere in the filesystem
"""
value_to_set = value_to_set.strip("'").strip('"')
if not os.path.exists(dotenv_path):
warnings.warn("can't write to %s - it doesn't exist." % dotenv_path)
return None, key_to_set, value_to_set
if " " in value_to_set:
quote_mode = "always"
line_template = '{}="{}"\n' if quote_mode == "always" else '{}={}\n'
line_out = line_template.format(key_to_set, value_to_set)
with rewrite(dotenv_path) as (source, dest):
replaced = False
for mapping in parse_stream(source):
if mapping.key == key_to_set:
dest.write(line_out)
replaced = True
else:
dest.write(mapping.original)
if not replaced:
dest.write(line_out)
return True, key_to_set, value_to_set | [
"Adds",
"or",
"Updates",
"a",
"key",
"/",
"value",
"to",
"the",
"given",
".",
"env"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/main.py#L177-L206 | [
"def",
"set_key",
"(",
"dotenv_path",
",",
"key_to_set",
",",
"value_to_set",
",",
"quote_mode",
"=",
"\"always\"",
")",
":",
"value_to_set",
"=",
"value_to_set",
".",
"strip",
"(",
"\"'\"",
")",
".",
"strip",
"(",
"'\"'",
")",
"if",
"not",
"os",
".",
"p... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | unset_key | Removes a given key from the given .env
If the .env path given doesn't exist, fails
If the given key doesn't exist in the .env, fails | pipenv/vendor/dotenv/main.py | def unset_key(dotenv_path, key_to_unset, quote_mode="always"):
"""
Removes a given key from the given .env
If the .env path given doesn't exist, fails
If the given key doesn't exist in the .env, fails
"""
if not os.path.exists(dotenv_path):
warnings.warn("can't delete from %s - it doesn't exist." % dotenv_path)
return None, key_to_unset
removed = False
with rewrite(dotenv_path) as (source, dest):
for mapping in parse_stream(source):
if mapping.key == key_to_unset:
removed = True
else:
dest.write(mapping.original)
if not removed:
warnings.warn("key %s not removed from %s - key doesn't exist." % (key_to_unset, dotenv_path))
return None, key_to_unset
return removed, key_to_unset | def unset_key(dotenv_path, key_to_unset, quote_mode="always"):
"""
Removes a given key from the given .env
If the .env path given doesn't exist, fails
If the given key doesn't exist in the .env, fails
"""
if not os.path.exists(dotenv_path):
warnings.warn("can't delete from %s - it doesn't exist." % dotenv_path)
return None, key_to_unset
removed = False
with rewrite(dotenv_path) as (source, dest):
for mapping in parse_stream(source):
if mapping.key == key_to_unset:
removed = True
else:
dest.write(mapping.original)
if not removed:
warnings.warn("key %s not removed from %s - key doesn't exist." % (key_to_unset, dotenv_path))
return None, key_to_unset
return removed, key_to_unset | [
"Removes",
"a",
"given",
"key",
"from",
"the",
"given",
".",
"env"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/main.py#L209-L232 | [
"def",
"unset_key",
"(",
"dotenv_path",
",",
"key_to_unset",
",",
"quote_mode",
"=",
"\"always\"",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dotenv_path",
")",
":",
"warnings",
".",
"warn",
"(",
"\"can't delete from %s - it doesn't exist.\""... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | _walk_to_root | Yield directories starting from the given directory up to the root | pipenv/vendor/dotenv/main.py | def _walk_to_root(path):
"""
Yield directories starting from the given directory up to the root
"""
if not os.path.exists(path):
raise IOError('Starting path not found')
if os.path.isfile(path):
path = os.path.dirname(path)
last_dir = None
current_dir = os.path.abspath(path)
while last_dir != current_dir:
yield current_dir
parent_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir))
last_dir, current_dir = current_dir, parent_dir | def _walk_to_root(path):
"""
Yield directories starting from the given directory up to the root
"""
if not os.path.exists(path):
raise IOError('Starting path not found')
if os.path.isfile(path):
path = os.path.dirname(path)
last_dir = None
current_dir = os.path.abspath(path)
while last_dir != current_dir:
yield current_dir
parent_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir))
last_dir, current_dir = current_dir, parent_dir | [
"Yield",
"directories",
"starting",
"from",
"the",
"given",
"directory",
"up",
"to",
"the",
"root"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/main.py#L260-L275 | [
"def",
"_walk_to_root",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"IOError",
"(",
"'Starting path not found'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"path",
"="... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | run_command | Run command in sub process.
Runs the command in a sub process with the variables from `env`
added in the current environment variables.
Parameters
----------
command: List[str]
The command and it's parameters
env: Dict
The additional environment variables
Returns
-------
int
The return code of the command | pipenv/vendor/dotenv/main.py | def run_command(command, env):
"""Run command in sub process.
Runs the command in a sub process with the variables from `env`
added in the current environment variables.
Parameters
----------
command: List[str]
The command and it's parameters
env: Dict
The additional environment variables
Returns
-------
int
The return code of the command
"""
# copy the current environment variables and add the vales from
# `env`
cmd_env = os.environ.copy()
cmd_env.update(env)
p = Popen(command,
universal_newlines=True,
bufsize=0,
shell=False,
env=cmd_env)
_, _ = p.communicate()
return p.returncode | def run_command(command, env):
"""Run command in sub process.
Runs the command in a sub process with the variables from `env`
added in the current environment variables.
Parameters
----------
command: List[str]
The command and it's parameters
env: Dict
The additional environment variables
Returns
-------
int
The return code of the command
"""
# copy the current environment variables and add the vales from
# `env`
cmd_env = os.environ.copy()
cmd_env.update(env)
p = Popen(command,
universal_newlines=True,
bufsize=0,
shell=False,
env=cmd_env)
_, _ = p.communicate()
return p.returncode | [
"Run",
"command",
"in",
"sub",
"process",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/main.py#L317-L348 | [
"def",
"run_command",
"(",
"command",
",",
"env",
")",
":",
"# copy the current environment variables and add the vales from",
"# `env`",
"cmd_env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"cmd_env",
".",
"update",
"(",
"env",
")",
"p",
"=",
"Popen",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | DotEnv.dict | Return dotenv as dict | pipenv/vendor/dotenv/main.py | def dict(self):
"""Return dotenv as dict"""
if self._dict:
return self._dict
values = OrderedDict(self.parse())
self._dict = resolve_nested_variables(values)
return self._dict | def dict(self):
"""Return dotenv as dict"""
if self._dict:
return self._dict
values = OrderedDict(self.parse())
self._dict = resolve_nested_variables(values)
return self._dict | [
"Return",
"dotenv",
"as",
"dict"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/main.py#L110-L117 | [
"def",
"dict",
"(",
"self",
")",
":",
"if",
"self",
".",
"_dict",
":",
"return",
"self",
".",
"_dict",
"values",
"=",
"OrderedDict",
"(",
"self",
".",
"parse",
"(",
")",
")",
"self",
".",
"_dict",
"=",
"resolve_nested_variables",
"(",
"values",
")",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | DotEnv.set_as_environment_variables | Load the current dotenv as system environemt variable. | pipenv/vendor/dotenv/main.py | def set_as_environment_variables(self, override=False):
"""
Load the current dotenv as system environemt variable.
"""
for k, v in self.dict().items():
if k in os.environ and not override:
continue
# With Python2 on Windows, force environment variables to str to avoid
# "TypeError: environment can only contain strings" in Python's subprocess.py.
if PY2 and WIN:
if isinstance(k, text_type) or isinstance(v, text_type):
k = k.encode('ascii')
v = v.encode('ascii')
os.environ[k] = v
return True | def set_as_environment_variables(self, override=False):
"""
Load the current dotenv as system environemt variable.
"""
for k, v in self.dict().items():
if k in os.environ and not override:
continue
# With Python2 on Windows, force environment variables to str to avoid
# "TypeError: environment can only contain strings" in Python's subprocess.py.
if PY2 and WIN:
if isinstance(k, text_type) or isinstance(v, text_type):
k = k.encode('ascii')
v = v.encode('ascii')
os.environ[k] = v
return True | [
"Load",
"the",
"current",
"dotenv",
"as",
"system",
"environemt",
"variable",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/main.py#L125-L140 | [
"def",
"set_as_environment_variables",
"(",
"self",
",",
"override",
"=",
"False",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"dict",
"(",
")",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"os",
".",
"environ",
"and",
"not",
"override",
":... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | _key_from_req | Get an all-lowercase version of the requirement's name. | pipenv/vendor/passa/models/caches.py | def _key_from_req(req):
"""Get an all-lowercase version of the requirement's name."""
if hasattr(req, 'key'):
# from pkg_resources, such as installed dists for pip-sync
key = req.key
else:
# from packaging, such as install requirements from requirements.txt
key = req.name
key = key.replace('_', '-').lower()
return key | def _key_from_req(req):
"""Get an all-lowercase version of the requirement's name."""
if hasattr(req, 'key'):
# from pkg_resources, such as installed dists for pip-sync
key = req.key
else:
# from packaging, such as install requirements from requirements.txt
key = req.name
key = key.replace('_', '-').lower()
return key | [
"Get",
"an",
"all",
"-",
"lowercase",
"version",
"of",
"the",
"requirement",
"s",
"name",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/models/caches.py#L77-L87 | [
"def",
"_key_from_req",
"(",
"req",
")",
":",
"if",
"hasattr",
"(",
"req",
",",
"'key'",
")",
":",
"# from pkg_resources, such as installed dists for pip-sync",
"key",
"=",
"req",
".",
"key",
"else",
":",
"# from packaging, such as install requirements from requirements.t... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | _JSONCache.read_cache | Reads the cached contents into memory. | pipenv/vendor/passa/models/caches.py | def read_cache(self):
"""Reads the cached contents into memory.
"""
if os.path.exists(self._cache_file):
self._cache = _read_cache_file(self._cache_file)
else:
self._cache = {} | def read_cache(self):
"""Reads the cached contents into memory.
"""
if os.path.exists(self._cache_file):
self._cache = _read_cache_file(self._cache_file)
else:
self._cache = {} | [
"Reads",
"the",
"cached",
"contents",
"into",
"memory",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/models/caches.py#L156-L162 | [
"def",
"read_cache",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_cache_file",
")",
":",
"self",
".",
"_cache",
"=",
"_read_cache_file",
"(",
"self",
".",
"_cache_file",
")",
"else",
":",
"self",
".",
"_cache",
"... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | inject_into_urllib3 | Monkey-patch urllib3 with PyOpenSSL-backed SSL-support. | pipenv/patched/notpip/_vendor/urllib3/contrib/pyopenssl.py | def inject_into_urllib3():
'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'
_validate_dependencies_met()
util.ssl_.SSLContext = PyOpenSSLContext
util.HAS_SNI = HAS_SNI
util.ssl_.HAS_SNI = HAS_SNI
util.IS_PYOPENSSL = True
util.ssl_.IS_PYOPENSSL = True | def inject_into_urllib3():
'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'
_validate_dependencies_met()
util.ssl_.SSLContext = PyOpenSSLContext
util.HAS_SNI = HAS_SNI
util.ssl_.HAS_SNI = HAS_SNI
util.IS_PYOPENSSL = True
util.ssl_.IS_PYOPENSSL = True | [
"Monkey",
"-",
"patch",
"urllib3",
"with",
"PyOpenSSL",
"-",
"backed",
"SSL",
"-",
"support",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/urllib3/contrib/pyopenssl.py#L115-L124 | [
"def",
"inject_into_urllib3",
"(",
")",
":",
"_validate_dependencies_met",
"(",
")",
"util",
".",
"ssl_",
".",
"SSLContext",
"=",
"PyOpenSSLContext",
"util",
".",
"HAS_SNI",
"=",
"HAS_SNI",
"util",
".",
"ssl_",
".",
"HAS_SNI",
"=",
"HAS_SNI",
"util",
".",
"I... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | _validate_dependencies_met | Verifies that PyOpenSSL's package-level dependencies have been met.
Throws `ImportError` if they are not met. | pipenv/patched/notpip/_vendor/urllib3/contrib/pyopenssl.py | def _validate_dependencies_met():
"""
Verifies that PyOpenSSL's package-level dependencies have been met.
Throws `ImportError` if they are not met.
"""
# Method added in `cryptography==1.1`; not available in older versions
from cryptography.x509.extensions import Extensions
if getattr(Extensions, "get_extension_for_class", None) is None:
raise ImportError("'cryptography' module missing required functionality. "
"Try upgrading to v1.3.4 or newer.")
# pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509
# attribute is only present on those versions.
from OpenSSL.crypto import X509
x509 = X509()
if getattr(x509, "_x509", None) is None:
raise ImportError("'pyOpenSSL' module missing required functionality. "
"Try upgrading to v0.14 or newer.") | def _validate_dependencies_met():
"""
Verifies that PyOpenSSL's package-level dependencies have been met.
Throws `ImportError` if they are not met.
"""
# Method added in `cryptography==1.1`; not available in older versions
from cryptography.x509.extensions import Extensions
if getattr(Extensions, "get_extension_for_class", None) is None:
raise ImportError("'cryptography' module missing required functionality. "
"Try upgrading to v1.3.4 or newer.")
# pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509
# attribute is only present on those versions.
from OpenSSL.crypto import X509
x509 = X509()
if getattr(x509, "_x509", None) is None:
raise ImportError("'pyOpenSSL' module missing required functionality. "
"Try upgrading to v0.14 or newer.") | [
"Verifies",
"that",
"PyOpenSSL",
"s",
"package",
"-",
"level",
"dependencies",
"have",
"been",
"met",
".",
"Throws",
"ImportError",
"if",
"they",
"are",
"not",
"met",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/urllib3/contrib/pyopenssl.py#L137-L154 | [
"def",
"_validate_dependencies_met",
"(",
")",
":",
"# Method added in `cryptography==1.1`; not available in older versions",
"from",
"cryptography",
".",
"x509",
".",
"extensions",
"import",
"Extensions",
"if",
"getattr",
"(",
"Extensions",
",",
"\"get_extension_for_class\"",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | _dnsname_to_stdlib | Converts a dNSName SubjectAlternativeName field to the form used by the
standard library on the given Python version.
Cryptography produces a dNSName as a unicode string that was idna-decoded
from ASCII bytes. We need to idna-encode that string to get it back, and
then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib
uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).
If the name cannot be idna-encoded then we return None signalling that
the name given should be skipped. | pipenv/patched/notpip/_vendor/urllib3/contrib/pyopenssl.py | def _dnsname_to_stdlib(name):
"""
Converts a dNSName SubjectAlternativeName field to the form used by the
standard library on the given Python version.
Cryptography produces a dNSName as a unicode string that was idna-decoded
from ASCII bytes. We need to idna-encode that string to get it back, and
then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib
uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).
If the name cannot be idna-encoded then we return None signalling that
the name given should be skipped.
"""
def idna_encode(name):
"""
Borrowed wholesale from the Python Cryptography Project. It turns out
that we can't just safely call `idna.encode`: it can explode for
wildcard names. This avoids that problem.
"""
from pipenv.patched.notpip._vendor import idna
try:
for prefix in [u'*.', u'.']:
if name.startswith(prefix):
name = name[len(prefix):]
return prefix.encode('ascii') + idna.encode(name)
return idna.encode(name)
except idna.core.IDNAError:
return None
name = idna_encode(name)
if name is None:
return None
elif sys.version_info >= (3, 0):
name = name.decode('utf-8')
return name | def _dnsname_to_stdlib(name):
"""
Converts a dNSName SubjectAlternativeName field to the form used by the
standard library on the given Python version.
Cryptography produces a dNSName as a unicode string that was idna-decoded
from ASCII bytes. We need to idna-encode that string to get it back, and
then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib
uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).
If the name cannot be idna-encoded then we return None signalling that
the name given should be skipped.
"""
def idna_encode(name):
"""
Borrowed wholesale from the Python Cryptography Project. It turns out
that we can't just safely call `idna.encode`: it can explode for
wildcard names. This avoids that problem.
"""
from pipenv.patched.notpip._vendor import idna
try:
for prefix in [u'*.', u'.']:
if name.startswith(prefix):
name = name[len(prefix):]
return prefix.encode('ascii') + idna.encode(name)
return idna.encode(name)
except idna.core.IDNAError:
return None
name = idna_encode(name)
if name is None:
return None
elif sys.version_info >= (3, 0):
name = name.decode('utf-8')
return name | [
"Converts",
"a",
"dNSName",
"SubjectAlternativeName",
"field",
"to",
"the",
"form",
"used",
"by",
"the",
"standard",
"library",
"on",
"the",
"given",
"Python",
"version",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/urllib3/contrib/pyopenssl.py#L157-L192 | [
"def",
"_dnsname_to_stdlib",
"(",
"name",
")",
":",
"def",
"idna_encode",
"(",
"name",
")",
":",
"\"\"\"\n Borrowed wholesale from the Python Cryptography Project. It turns out\n that we can't just safely call `idna.encode`: it can explode for\n wildcard names. This avoi... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | get_subj_alt_name | Given an PyOpenSSL certificate, provides all the subject alternative names. | pipenv/patched/notpip/_vendor/urllib3/contrib/pyopenssl.py | def get_subj_alt_name(peer_cert):
"""
Given an PyOpenSSL certificate, provides all the subject alternative names.
"""
# Pass the cert to cryptography, which has much better APIs for this.
if hasattr(peer_cert, "to_cryptography"):
cert = peer_cert.to_cryptography()
else:
# This is technically using private APIs, but should work across all
# relevant versions before PyOpenSSL got a proper API for this.
cert = _Certificate(openssl_backend, peer_cert._x509)
# We want to find the SAN extension. Ask Cryptography to locate it (it's
# faster than looping in Python)
try:
ext = cert.extensions.get_extension_for_class(
x509.SubjectAlternativeName
).value
except x509.ExtensionNotFound:
# No such extension, return the empty list.
return []
except (x509.DuplicateExtension, UnsupportedExtension,
x509.UnsupportedGeneralNameType, UnicodeError) as e:
# A problem has been found with the quality of the certificate. Assume
# no SAN field is present.
log.warning(
"A problem was encountered with the certificate that prevented "
"urllib3 from finding the SubjectAlternativeName field. This can "
"affect certificate validation. The error was %s",
e,
)
return []
# We want to return dNSName and iPAddress fields. We need to cast the IPs
# back to strings because the match_hostname function wants them as
# strings.
# Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8
# decoded. This is pretty frustrating, but that's what the standard library
# does with certificates, and so we need to attempt to do the same.
# We also want to skip over names which cannot be idna encoded.
names = [
('DNS', name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName))
if name is not None
]
names.extend(
('IP Address', str(name))
for name in ext.get_values_for_type(x509.IPAddress)
)
return names | def get_subj_alt_name(peer_cert):
"""
Given an PyOpenSSL certificate, provides all the subject alternative names.
"""
# Pass the cert to cryptography, which has much better APIs for this.
if hasattr(peer_cert, "to_cryptography"):
cert = peer_cert.to_cryptography()
else:
# This is technically using private APIs, but should work across all
# relevant versions before PyOpenSSL got a proper API for this.
cert = _Certificate(openssl_backend, peer_cert._x509)
# We want to find the SAN extension. Ask Cryptography to locate it (it's
# faster than looping in Python)
try:
ext = cert.extensions.get_extension_for_class(
x509.SubjectAlternativeName
).value
except x509.ExtensionNotFound:
# No such extension, return the empty list.
return []
except (x509.DuplicateExtension, UnsupportedExtension,
x509.UnsupportedGeneralNameType, UnicodeError) as e:
# A problem has been found with the quality of the certificate. Assume
# no SAN field is present.
log.warning(
"A problem was encountered with the certificate that prevented "
"urllib3 from finding the SubjectAlternativeName field. This can "
"affect certificate validation. The error was %s",
e,
)
return []
# We want to return dNSName and iPAddress fields. We need to cast the IPs
# back to strings because the match_hostname function wants them as
# strings.
# Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8
# decoded. This is pretty frustrating, but that's what the standard library
# does with certificates, and so we need to attempt to do the same.
# We also want to skip over names which cannot be idna encoded.
names = [
('DNS', name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName))
if name is not None
]
names.extend(
('IP Address', str(name))
for name in ext.get_values_for_type(x509.IPAddress)
)
return names | [
"Given",
"an",
"PyOpenSSL",
"certificate",
"provides",
"all",
"the",
"subject",
"alternative",
"names",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/urllib3/contrib/pyopenssl.py#L195-L244 | [
"def",
"get_subj_alt_name",
"(",
"peer_cert",
")",
":",
"# Pass the cert to cryptography, which has much better APIs for this.",
"if",
"hasattr",
"(",
"peer_cert",
",",
"\"to_cryptography\"",
")",
":",
"cert",
"=",
"peer_cert",
".",
"to_cryptography",
"(",
")",
"else",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | CharDistributionAnalysis.feed | feed a character with known length | pipenv/vendor/chardet/chardistribution.py | def feed(self, char, char_len):
"""feed a character with known length"""
if char_len == 2:
# we only care about 2-bytes character in our distribution analysis
order = self.get_order(char)
else:
order = -1
if order >= 0:
self._total_chars += 1
# order is valid
if order < self._table_size:
if 512 > self._char_to_freq_order[order]:
self._freq_chars += 1 | def feed(self, char, char_len):
"""feed a character with known length"""
if char_len == 2:
# we only care about 2-bytes character in our distribution analysis
order = self.get_order(char)
else:
order = -1
if order >= 0:
self._total_chars += 1
# order is valid
if order < self._table_size:
if 512 > self._char_to_freq_order[order]:
self._freq_chars += 1 | [
"feed",
"a",
"character",
"with",
"known",
"length"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/chardet/chardistribution.py#L70-L82 | [
"def",
"feed",
"(",
"self",
",",
"char",
",",
"char_len",
")",
":",
"if",
"char_len",
"==",
"2",
":",
"# we only care about 2-bytes character in our distribution analysis",
"order",
"=",
"self",
".",
"get_order",
"(",
"char",
")",
"else",
":",
"order",
"=",
"-... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | CharDistributionAnalysis.get_confidence | return confidence based on existing data | pipenv/vendor/chardet/chardistribution.py | def get_confidence(self):
"""return confidence based on existing data"""
# if we didn't receive any character in our consideration range,
# return negative answer
if self._total_chars <= 0 or self._freq_chars <= self.MINIMUM_DATA_THRESHOLD:
return self.SURE_NO
if self._total_chars != self._freq_chars:
r = (self._freq_chars / ((self._total_chars - self._freq_chars)
* self.typical_distribution_ratio))
if r < self.SURE_YES:
return r
# normalize confidence (we don't want to be 100% sure)
return self.SURE_YES | def get_confidence(self):
"""return confidence based on existing data"""
# if we didn't receive any character in our consideration range,
# return negative answer
if self._total_chars <= 0 or self._freq_chars <= self.MINIMUM_DATA_THRESHOLD:
return self.SURE_NO
if self._total_chars != self._freq_chars:
r = (self._freq_chars / ((self._total_chars - self._freq_chars)
* self.typical_distribution_ratio))
if r < self.SURE_YES:
return r
# normalize confidence (we don't want to be 100% sure)
return self.SURE_YES | [
"return",
"confidence",
"based",
"on",
"existing",
"data"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/chardet/chardistribution.py#L84-L98 | [
"def",
"get_confidence",
"(",
"self",
")",
":",
"# if we didn't receive any character in our consideration range,",
"# return negative answer",
"if",
"self",
".",
"_total_chars",
"<=",
"0",
"or",
"self",
".",
"_freq_chars",
"<=",
"self",
".",
"MINIMUM_DATA_THRESHOLD",
":"... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | _get_requests_session | Load requests lazily. | pipenv/utils.py | def _get_requests_session():
"""Load requests lazily."""
global requests_session
if requests_session is not None:
return requests_session
import requests
requests_session = requests.Session()
adapter = requests.adapters.HTTPAdapter(
max_retries=environments.PIPENV_MAX_RETRIES
)
requests_session.mount("https://pypi.org/pypi", adapter)
return requests_session | def _get_requests_session():
"""Load requests lazily."""
global requests_session
if requests_session is not None:
return requests_session
import requests
requests_session = requests.Session()
adapter = requests.adapters.HTTPAdapter(
max_retries=environments.PIPENV_MAX_RETRIES
)
requests_session.mount("https://pypi.org/pypi", adapter)
return requests_session | [
"Load",
"requests",
"lazily",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L53-L65 | [
"def",
"_get_requests_session",
"(",
")",
":",
"global",
"requests_session",
"if",
"requests_session",
"is",
"not",
"None",
":",
"return",
"requests_session",
"import",
"requests",
"requests_session",
"=",
"requests",
".",
"Session",
"(",
")",
"adapter",
"=",
"req... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | convert_toml_outline_tables | Converts all outline tables to inline tables. | pipenv/utils.py | def convert_toml_outline_tables(parsed):
"""Converts all outline tables to inline tables."""
def convert_tomlkit_table(section):
for key, value in section._body:
if not key:
continue
if hasattr(value, "keys") and not isinstance(value, tomlkit.items.InlineTable):
table = tomlkit.inline_table()
table.update(value.value)
section[key.key] = table
def convert_toml_table(section):
for package, value in section.items():
if hasattr(value, "keys") and not isinstance(value, toml.decoder.InlineTableDict):
table = toml.TomlDecoder().get_empty_inline_table()
table.update(value)
section[package] = table
is_tomlkit_parsed = isinstance(parsed, tomlkit.container.Container)
for section in ("packages", "dev-packages"):
table_data = parsed.get(section, {})
if not table_data:
continue
if is_tomlkit_parsed:
convert_tomlkit_table(table_data)
else:
convert_toml_table(table_data)
return parsed | def convert_toml_outline_tables(parsed):
"""Converts all outline tables to inline tables."""
def convert_tomlkit_table(section):
for key, value in section._body:
if not key:
continue
if hasattr(value, "keys") and not isinstance(value, tomlkit.items.InlineTable):
table = tomlkit.inline_table()
table.update(value.value)
section[key.key] = table
def convert_toml_table(section):
for package, value in section.items():
if hasattr(value, "keys") and not isinstance(value, toml.decoder.InlineTableDict):
table = toml.TomlDecoder().get_empty_inline_table()
table.update(value)
section[package] = table
is_tomlkit_parsed = isinstance(parsed, tomlkit.container.Container)
for section in ("packages", "dev-packages"):
table_data = parsed.get(section, {})
if not table_data:
continue
if is_tomlkit_parsed:
convert_tomlkit_table(table_data)
else:
convert_toml_table(table_data)
return parsed | [
"Converts",
"all",
"outline",
"tables",
"to",
"inline",
"tables",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L91-L119 | [
"def",
"convert_toml_outline_tables",
"(",
"parsed",
")",
":",
"def",
"convert_tomlkit_table",
"(",
"section",
")",
":",
"for",
"key",
",",
"value",
"in",
"section",
".",
"_body",
":",
"if",
"not",
"key",
":",
"continue",
"if",
"hasattr",
"(",
"value",
","... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | run_command | Take an input command and run it, handling exceptions and error codes and returning
its stdout and stderr.
:param cmd: The list of command and arguments.
:type cmd: list
:returns: A 2-tuple of the output and error from the command
:rtype: Tuple[str, str]
:raises: exceptions.PipenvCmdError | pipenv/utils.py | def run_command(cmd, *args, **kwargs):
"""
Take an input command and run it, handling exceptions and error codes and returning
its stdout and stderr.
:param cmd: The list of command and arguments.
:type cmd: list
:returns: A 2-tuple of the output and error from the command
:rtype: Tuple[str, str]
:raises: exceptions.PipenvCmdError
"""
from pipenv.vendor import delegator
from ._compat import decode_for_output
from .cmdparse import Script
catch_exceptions = kwargs.pop("catch_exceptions", True)
if isinstance(cmd, (six.string_types, list, tuple)):
cmd = Script.parse(cmd)
if not isinstance(cmd, Script):
raise TypeError("Command input must be a string, list or tuple")
if "env" not in kwargs:
kwargs["env"] = os.environ.copy()
kwargs["env"]["PYTHONIOENCODING"] = "UTF-8"
try:
cmd_string = cmd.cmdify()
except TypeError:
click_echo("Error turning command into string: {0}".format(cmd), err=True)
sys.exit(1)
if environments.is_verbose():
click_echo("Running command: $ {0}".format(cmd_string, err=True))
c = delegator.run(cmd_string, *args, **kwargs)
return_code = c.return_code
if environments.is_verbose():
click_echo("Command output: {0}".format(
crayons.blue(decode_for_output(c.out))
), err=True)
if not c.ok and catch_exceptions:
raise PipenvCmdError(cmd_string, c.out, c.err, return_code)
return c | def run_command(cmd, *args, **kwargs):
"""
Take an input command and run it, handling exceptions and error codes and returning
its stdout and stderr.
:param cmd: The list of command and arguments.
:type cmd: list
:returns: A 2-tuple of the output and error from the command
:rtype: Tuple[str, str]
:raises: exceptions.PipenvCmdError
"""
from pipenv.vendor import delegator
from ._compat import decode_for_output
from .cmdparse import Script
catch_exceptions = kwargs.pop("catch_exceptions", True)
if isinstance(cmd, (six.string_types, list, tuple)):
cmd = Script.parse(cmd)
if not isinstance(cmd, Script):
raise TypeError("Command input must be a string, list or tuple")
if "env" not in kwargs:
kwargs["env"] = os.environ.copy()
kwargs["env"]["PYTHONIOENCODING"] = "UTF-8"
try:
cmd_string = cmd.cmdify()
except TypeError:
click_echo("Error turning command into string: {0}".format(cmd), err=True)
sys.exit(1)
if environments.is_verbose():
click_echo("Running command: $ {0}".format(cmd_string, err=True))
c = delegator.run(cmd_string, *args, **kwargs)
return_code = c.return_code
if environments.is_verbose():
click_echo("Command output: {0}".format(
crayons.blue(decode_for_output(c.out))
), err=True)
if not c.ok and catch_exceptions:
raise PipenvCmdError(cmd_string, c.out, c.err, return_code)
return c | [
"Take",
"an",
"input",
"command",
"and",
"run",
"it",
"handling",
"exceptions",
"and",
"error",
"codes",
"and",
"returning",
"its",
"stdout",
"and",
"stderr",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L122-L160 | [
"def",
"run_command",
"(",
"cmd",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"pipenv",
".",
"vendor",
"import",
"delegator",
"from",
".",
"_compat",
"import",
"decode_for_output",
"from",
".",
"cmdparse",
"import",
"Script",
"catch_exceptio... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | parse_python_version | Parse a Python version output returned by `python --version`.
Return a dict with three keys: major, minor, and micro. Each value is a
string containing a version part.
Note: The micro part would be `'0'` if it's missing from the input string. | pipenv/utils.py | def parse_python_version(output):
"""Parse a Python version output returned by `python --version`.
Return a dict with three keys: major, minor, and micro. Each value is a
string containing a version part.
Note: The micro part would be `'0'` if it's missing from the input string.
"""
version_line = output.split("\n", 1)[0]
version_pattern = re.compile(
r"""
^ # Beginning of line.
Python # Literally "Python".
\s # Space.
(?P<major>\d+) # Major = one or more digits.
\. # Dot.
(?P<minor>\d+) # Minor = one or more digits.
(?: # Unnamed group for dot-micro.
\. # Dot.
(?P<micro>\d+) # Micro = one or more digit.
)? # Micro is optional because pypa/pipenv#1893.
.* # Trailing garbage.
$ # End of line.
""",
re.VERBOSE,
)
match = version_pattern.match(version_line)
if not match:
return None
return match.groupdict(default="0") | def parse_python_version(output):
"""Parse a Python version output returned by `python --version`.
Return a dict with three keys: major, minor, and micro. Each value is a
string containing a version part.
Note: The micro part would be `'0'` if it's missing from the input string.
"""
version_line = output.split("\n", 1)[0]
version_pattern = re.compile(
r"""
^ # Beginning of line.
Python # Literally "Python".
\s # Space.
(?P<major>\d+) # Major = one or more digits.
\. # Dot.
(?P<minor>\d+) # Minor = one or more digits.
(?: # Unnamed group for dot-micro.
\. # Dot.
(?P<micro>\d+) # Micro = one or more digit.
)? # Micro is optional because pypa/pipenv#1893.
.* # Trailing garbage.
$ # End of line.
""",
re.VERBOSE,
)
match = version_pattern.match(version_line)
if not match:
return None
return match.groupdict(default="0") | [
"Parse",
"a",
"Python",
"version",
"output",
"returned",
"by",
"python",
"--",
"version",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L163-L193 | [
"def",
"parse_python_version",
"(",
"output",
")",
":",
"version_line",
"=",
"output",
".",
"split",
"(",
"\"\\n\"",
",",
"1",
")",
"[",
"0",
"]",
"version_pattern",
"=",
"re",
".",
"compile",
"(",
"r\"\"\"\n ^ # Beginning of line.\n ... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | escape_grouped_arguments | Prepares a string for the shell (on Windows too!)
Only for use on grouped arguments (passed as a string to Popen) | pipenv/utils.py | def escape_grouped_arguments(s):
"""Prepares a string for the shell (on Windows too!)
Only for use on grouped arguments (passed as a string to Popen)
"""
if s is None:
return None
# Additional escaping for windows paths
if os.name == "nt":
s = "{}".format(s.replace("\\", "\\\\"))
return '"' + s.replace("'", "'\\''") + '"' | def escape_grouped_arguments(s):
"""Prepares a string for the shell (on Windows too!)
Only for use on grouped arguments (passed as a string to Popen)
"""
if s is None:
return None
# Additional escaping for windows paths
if os.name == "nt":
s = "{}".format(s.replace("\\", "\\\\"))
return '"' + s.replace("'", "'\\''") + '"' | [
"Prepares",
"a",
"string",
"for",
"the",
"shell",
"(",
"on",
"Windows",
"too!",
")"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L208-L219 | [
"def",
"escape_grouped_arguments",
"(",
"s",
")",
":",
"if",
"s",
"is",
"None",
":",
"return",
"None",
"# Additional escaping for windows paths",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
":",
"s",
"=",
"\"{}\"",
".",
"format",
"(",
"s",
".",
"replace",
"("... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | venv_resolve_deps | Resolve dependencies for a pipenv project, acts as a portal to the target environment.
Regardless of whether a virtual environment is present or not, this will spawn
a subproces which is isolated to the target environment and which will perform
dependency resolution. This function reads the output of that call and mutates
the provided lockfile accordingly, returning nothing.
:param List[:class:`~requirementslib.Requirement`] deps: A list of dependencies to resolve.
:param Callable which: [description]
:param project: The pipenv Project instance to use during resolution
:param Optional[bool] pre: Whether to resolve pre-release candidates, defaults to False
:param Optional[bool] clear: Whether to clear the cache during resolution, defaults to False
:param Optional[bool] allow_global: Whether to use *sys.executable* as the python binary, defaults to False
:param Optional[str] pypi_mirror: A URL to substitute any time *pypi.org* is encountered, defaults to None
:param Optional[bool] dev: Whether to target *dev-packages* or not, defaults to False
:param pipfile: A Pipfile section to operate on, defaults to None
:type pipfile: Optional[Dict[str, Union[str, Dict[str, bool, List[str]]]]]
:param Dict[str, Any] lockfile: A project lockfile to mutate, defaults to None
:param bool keep_outdated: Whether to retain outdated dependencies and resolve with them in mind, defaults to False
:raises RuntimeError: Raised on resolution failure
:return: Nothing
:rtype: None | pipenv/utils.py | def venv_resolve_deps(
deps,
which,
project,
pre=False,
clear=False,
allow_global=False,
pypi_mirror=None,
dev=False,
pipfile=None,
lockfile=None,
keep_outdated=False
):
"""
Resolve dependencies for a pipenv project, acts as a portal to the target environment.
Regardless of whether a virtual environment is present or not, this will spawn
a subproces which is isolated to the target environment and which will perform
dependency resolution. This function reads the output of that call and mutates
the provided lockfile accordingly, returning nothing.
:param List[:class:`~requirementslib.Requirement`] deps: A list of dependencies to resolve.
:param Callable which: [description]
:param project: The pipenv Project instance to use during resolution
:param Optional[bool] pre: Whether to resolve pre-release candidates, defaults to False
:param Optional[bool] clear: Whether to clear the cache during resolution, defaults to False
:param Optional[bool] allow_global: Whether to use *sys.executable* as the python binary, defaults to False
:param Optional[str] pypi_mirror: A URL to substitute any time *pypi.org* is encountered, defaults to None
:param Optional[bool] dev: Whether to target *dev-packages* or not, defaults to False
:param pipfile: A Pipfile section to operate on, defaults to None
:type pipfile: Optional[Dict[str, Union[str, Dict[str, bool, List[str]]]]]
:param Dict[str, Any] lockfile: A project lockfile to mutate, defaults to None
:param bool keep_outdated: Whether to retain outdated dependencies and resolve with them in mind, defaults to False
:raises RuntimeError: Raised on resolution failure
:return: Nothing
:rtype: None
"""
from .vendor.vistir.misc import fs_str
from .vendor.vistir.compat import Path, JSONDecodeError, NamedTemporaryFile
from .vendor.vistir.path import create_tracked_tempdir
from . import resolver
from ._compat import decode_for_output
import json
results = []
pipfile_section = "dev-packages" if dev else "packages"
lockfile_section = "develop" if dev else "default"
if not deps:
if not project.pipfile_exists:
return None
deps = project.parsed_pipfile.get(pipfile_section, {})
if not deps:
return None
if not pipfile:
pipfile = getattr(project, pipfile_section, {})
if not lockfile:
lockfile = project._lockfile
req_dir = create_tracked_tempdir(prefix="pipenv", suffix="requirements")
cmd = [
which("python", allow_global=allow_global),
Path(resolver.__file__.rstrip("co")).as_posix()
]
if pre:
cmd.append("--pre")
if clear:
cmd.append("--clear")
if allow_global:
cmd.append("--system")
if dev:
cmd.append("--dev")
target_file = NamedTemporaryFile(prefix="resolver", suffix=".json", delete=False)
target_file.close()
cmd.extend(["--write", make_posix(target_file.name)])
with temp_environ():
os.environ.update({fs_str(k): fs_str(val) for k, val in os.environ.items()})
if pypi_mirror:
os.environ["PIPENV_PYPI_MIRROR"] = str(pypi_mirror)
os.environ["PIPENV_VERBOSITY"] = str(environments.PIPENV_VERBOSITY)
os.environ["PIPENV_REQ_DIR"] = fs_str(req_dir)
os.environ["PIP_NO_INPUT"] = fs_str("1")
os.environ["PIPENV_SITE_DIR"] = get_pipenv_sitedir()
if keep_outdated:
os.environ["PIPENV_KEEP_OUTDATED"] = fs_str("1")
with create_spinner(text=decode_for_output("Locking...")) as sp:
# This conversion is somewhat slow on local and file-type requirements since
# we now download those requirements / make temporary folders to perform
# dependency resolution on them, so we are including this step inside the
# spinner context manager for the UX improvement
sp.write(decode_for_output("Building requirements..."))
deps = convert_deps_to_pip(
deps, project, r=False, include_index=True
)
constraints = set(deps)
os.environ["PIPENV_PACKAGES"] = str("\n".join(constraints))
sp.write(decode_for_output("Resolving dependencies..."))
c = resolve(cmd, sp)
results = c.out.strip()
sp.green.ok(environments.PIPENV_SPINNER_OK_TEXT.format("Success!"))
try:
with open(target_file.name, "r") as fh:
results = json.load(fh)
except (IndexError, JSONDecodeError):
click_echo(c.out.strip(), err=True)
click_echo(c.err.strip(), err=True)
if os.path.exists(target_file.name):
os.unlink(target_file.name)
raise RuntimeError("There was a problem with locking.")
if os.path.exists(target_file.name):
os.unlink(target_file.name)
if environments.is_verbose():
click_echo(results, err=True)
if lockfile_section not in lockfile:
lockfile[lockfile_section] = {}
prepare_lockfile(results, pipfile, lockfile[lockfile_section]) | def venv_resolve_deps(
deps,
which,
project,
pre=False,
clear=False,
allow_global=False,
pypi_mirror=None,
dev=False,
pipfile=None,
lockfile=None,
keep_outdated=False
):
"""
Resolve dependencies for a pipenv project, acts as a portal to the target environment.
Regardless of whether a virtual environment is present or not, this will spawn
a subproces which is isolated to the target environment and which will perform
dependency resolution. This function reads the output of that call and mutates
the provided lockfile accordingly, returning nothing.
:param List[:class:`~requirementslib.Requirement`] deps: A list of dependencies to resolve.
:param Callable which: [description]
:param project: The pipenv Project instance to use during resolution
:param Optional[bool] pre: Whether to resolve pre-release candidates, defaults to False
:param Optional[bool] clear: Whether to clear the cache during resolution, defaults to False
:param Optional[bool] allow_global: Whether to use *sys.executable* as the python binary, defaults to False
:param Optional[str] pypi_mirror: A URL to substitute any time *pypi.org* is encountered, defaults to None
:param Optional[bool] dev: Whether to target *dev-packages* or not, defaults to False
:param pipfile: A Pipfile section to operate on, defaults to None
:type pipfile: Optional[Dict[str, Union[str, Dict[str, bool, List[str]]]]]
:param Dict[str, Any] lockfile: A project lockfile to mutate, defaults to None
:param bool keep_outdated: Whether to retain outdated dependencies and resolve with them in mind, defaults to False
:raises RuntimeError: Raised on resolution failure
:return: Nothing
:rtype: None
"""
from .vendor.vistir.misc import fs_str
from .vendor.vistir.compat import Path, JSONDecodeError, NamedTemporaryFile
from .vendor.vistir.path import create_tracked_tempdir
from . import resolver
from ._compat import decode_for_output
import json
results = []
pipfile_section = "dev-packages" if dev else "packages"
lockfile_section = "develop" if dev else "default"
if not deps:
if not project.pipfile_exists:
return None
deps = project.parsed_pipfile.get(pipfile_section, {})
if not deps:
return None
if not pipfile:
pipfile = getattr(project, pipfile_section, {})
if not lockfile:
lockfile = project._lockfile
req_dir = create_tracked_tempdir(prefix="pipenv", suffix="requirements")
cmd = [
which("python", allow_global=allow_global),
Path(resolver.__file__.rstrip("co")).as_posix()
]
if pre:
cmd.append("--pre")
if clear:
cmd.append("--clear")
if allow_global:
cmd.append("--system")
if dev:
cmd.append("--dev")
target_file = NamedTemporaryFile(prefix="resolver", suffix=".json", delete=False)
target_file.close()
cmd.extend(["--write", make_posix(target_file.name)])
with temp_environ():
os.environ.update({fs_str(k): fs_str(val) for k, val in os.environ.items()})
if pypi_mirror:
os.environ["PIPENV_PYPI_MIRROR"] = str(pypi_mirror)
os.environ["PIPENV_VERBOSITY"] = str(environments.PIPENV_VERBOSITY)
os.environ["PIPENV_REQ_DIR"] = fs_str(req_dir)
os.environ["PIP_NO_INPUT"] = fs_str("1")
os.environ["PIPENV_SITE_DIR"] = get_pipenv_sitedir()
if keep_outdated:
os.environ["PIPENV_KEEP_OUTDATED"] = fs_str("1")
with create_spinner(text=decode_for_output("Locking...")) as sp:
# This conversion is somewhat slow on local and file-type requirements since
# we now download those requirements / make temporary folders to perform
# dependency resolution on them, so we are including this step inside the
# spinner context manager for the UX improvement
sp.write(decode_for_output("Building requirements..."))
deps = convert_deps_to_pip(
deps, project, r=False, include_index=True
)
constraints = set(deps)
os.environ["PIPENV_PACKAGES"] = str("\n".join(constraints))
sp.write(decode_for_output("Resolving dependencies..."))
c = resolve(cmd, sp)
results = c.out.strip()
sp.green.ok(environments.PIPENV_SPINNER_OK_TEXT.format("Success!"))
try:
with open(target_file.name, "r") as fh:
results = json.load(fh)
except (IndexError, JSONDecodeError):
click_echo(c.out.strip(), err=True)
click_echo(c.err.strip(), err=True)
if os.path.exists(target_file.name):
os.unlink(target_file.name)
raise RuntimeError("There was a problem with locking.")
if os.path.exists(target_file.name):
os.unlink(target_file.name)
if environments.is_verbose():
click_echo(results, err=True)
if lockfile_section not in lockfile:
lockfile[lockfile_section] = {}
prepare_lockfile(results, pipfile, lockfile[lockfile_section]) | [
"Resolve",
"dependencies",
"for",
"a",
"pipenv",
"project",
"acts",
"as",
"a",
"portal",
"to",
"the",
"target",
"environment",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L930-L1046 | [
"def",
"venv_resolve_deps",
"(",
"deps",
",",
"which",
",",
"project",
",",
"pre",
"=",
"False",
",",
"clear",
"=",
"False",
",",
"allow_global",
"=",
"False",
",",
"pypi_mirror",
"=",
"None",
",",
"dev",
"=",
"False",
",",
"pipfile",
"=",
"None",
",",... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | resolve_deps | Given a list of dependencies, return a resolved list of dependencies,
using pip-tools -- and their hashes, using the warehouse API / pip. | pipenv/utils.py | def resolve_deps(
deps,
which,
project,
sources=None,
python=False,
clear=False,
pre=False,
allow_global=False,
req_dir=None
):
"""Given a list of dependencies, return a resolved list of dependencies,
using pip-tools -- and their hashes, using the warehouse API / pip.
"""
index_lookup = {}
markers_lookup = {}
python_path = which("python", allow_global=allow_global)
if not os.environ.get("PIP_SRC"):
os.environ["PIP_SRC"] = project.virtualenv_src_location
backup_python_path = sys.executable
results = []
resolver = None
if not deps:
return results, resolver
# First (proper) attempt:
req_dir = req_dir if req_dir else os.environ.get("req_dir", None)
if not req_dir:
from .vendor.vistir.path import create_tracked_tempdir
req_dir = create_tracked_tempdir(prefix="pipenv-", suffix="-requirements")
with HackedPythonVersion(python_version=python, python_path=python_path):
try:
results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps(
deps,
index_lookup,
markers_lookup,
project,
sources,
clear,
pre,
req_dir=req_dir,
)
except RuntimeError:
# Don't exit here, like usual.
results = None
# Second (last-resort) attempt:
if results is None:
with HackedPythonVersion(
python_version=".".join([str(s) for s in sys.version_info[:3]]),
python_path=backup_python_path,
):
try:
# Attempt to resolve again, with different Python version information,
# particularly for particularly particular packages.
results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps(
deps,
index_lookup,
markers_lookup,
project,
sources,
clear,
pre,
req_dir=req_dir,
)
except RuntimeError:
sys.exit(1)
return results, resolver | def resolve_deps(
deps,
which,
project,
sources=None,
python=False,
clear=False,
pre=False,
allow_global=False,
req_dir=None
):
"""Given a list of dependencies, return a resolved list of dependencies,
using pip-tools -- and their hashes, using the warehouse API / pip.
"""
index_lookup = {}
markers_lookup = {}
python_path = which("python", allow_global=allow_global)
if not os.environ.get("PIP_SRC"):
os.environ["PIP_SRC"] = project.virtualenv_src_location
backup_python_path = sys.executable
results = []
resolver = None
if not deps:
return results, resolver
# First (proper) attempt:
req_dir = req_dir if req_dir else os.environ.get("req_dir", None)
if not req_dir:
from .vendor.vistir.path import create_tracked_tempdir
req_dir = create_tracked_tempdir(prefix="pipenv-", suffix="-requirements")
with HackedPythonVersion(python_version=python, python_path=python_path):
try:
results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps(
deps,
index_lookup,
markers_lookup,
project,
sources,
clear,
pre,
req_dir=req_dir,
)
except RuntimeError:
# Don't exit here, like usual.
results = None
# Second (last-resort) attempt:
if results is None:
with HackedPythonVersion(
python_version=".".join([str(s) for s in sys.version_info[:3]]),
python_path=backup_python_path,
):
try:
# Attempt to resolve again, with different Python version information,
# particularly for particularly particular packages.
results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps(
deps,
index_lookup,
markers_lookup,
project,
sources,
clear,
pre,
req_dir=req_dir,
)
except RuntimeError:
sys.exit(1)
return results, resolver | [
"Given",
"a",
"list",
"of",
"dependencies",
"return",
"a",
"resolved",
"list",
"of",
"dependencies",
"using",
"pip",
"-",
"tools",
"--",
"and",
"their",
"hashes",
"using",
"the",
"warehouse",
"API",
"/",
"pip",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1049-L1114 | [
"def",
"resolve_deps",
"(",
"deps",
",",
"which",
",",
"project",
",",
"sources",
"=",
"None",
",",
"python",
"=",
"False",
",",
"clear",
"=",
"False",
",",
"pre",
"=",
"False",
",",
"allow_global",
"=",
"False",
",",
"req_dir",
"=",
"None",
")",
":"... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | convert_deps_to_pip | Converts a Pipfile-formatted dependency to a pip-formatted one. | pipenv/utils.py | def convert_deps_to_pip(deps, project=None, r=True, include_index=True):
""""Converts a Pipfile-formatted dependency to a pip-formatted one."""
from .vendor.requirementslib.models.requirements import Requirement
dependencies = []
for dep_name, dep in deps.items():
if project:
project.clear_pipfile_cache()
indexes = getattr(project, "pipfile_sources", []) if project is not None else []
new_dep = Requirement.from_pipfile(dep_name, dep)
if new_dep.index:
include_index = True
req = new_dep.as_line(sources=indexes if include_index else None).strip()
dependencies.append(req)
if not r:
return dependencies
# Write requirements.txt to tmp directory.
from .vendor.vistir.path import create_tracked_tempfile
f = create_tracked_tempfile(suffix="-requirements.txt", delete=False)
f.write("\n".join(dependencies).encode("utf-8"))
f.close()
return f.name | def convert_deps_to_pip(deps, project=None, r=True, include_index=True):
""""Converts a Pipfile-formatted dependency to a pip-formatted one."""
from .vendor.requirementslib.models.requirements import Requirement
dependencies = []
for dep_name, dep in deps.items():
if project:
project.clear_pipfile_cache()
indexes = getattr(project, "pipfile_sources", []) if project is not None else []
new_dep = Requirement.from_pipfile(dep_name, dep)
if new_dep.index:
include_index = True
req = new_dep.as_line(sources=indexes if include_index else None).strip()
dependencies.append(req)
if not r:
return dependencies
# Write requirements.txt to tmp directory.
from .vendor.vistir.path import create_tracked_tempfile
f = create_tracked_tempfile(suffix="-requirements.txt", delete=False)
f.write("\n".join(dependencies).encode("utf-8"))
f.close()
return f.name | [
"Converts",
"a",
"Pipfile",
"-",
"formatted",
"dependency",
"to",
"a",
"pip",
"-",
"formatted",
"one",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1127-L1149 | [
"def",
"convert_deps_to_pip",
"(",
"deps",
",",
"project",
"=",
"None",
",",
"r",
"=",
"True",
",",
"include_index",
"=",
"True",
")",
":",
"from",
".",
"vendor",
".",
"requirementslib",
".",
"models",
".",
"requirements",
"import",
"Requirement",
"dependenc... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | is_required_version | Check to see if there's a hard requirement for version
number provided in the Pipfile. | pipenv/utils.py | def is_required_version(version, specified_version):
"""Check to see if there's a hard requirement for version
number provided in the Pipfile.
"""
# Certain packages may be defined with multiple values.
if isinstance(specified_version, dict):
specified_version = specified_version.get("version", "")
if specified_version.startswith("=="):
return version.strip() == specified_version.split("==")[1].strip()
return True | def is_required_version(version, specified_version):
"""Check to see if there's a hard requirement for version
number provided in the Pipfile.
"""
# Certain packages may be defined with multiple values.
if isinstance(specified_version, dict):
specified_version = specified_version.get("version", "")
if specified_version.startswith("=="):
return version.strip() == specified_version.split("==")[1].strip()
return True | [
"Check",
"to",
"see",
"if",
"there",
"s",
"a",
"hard",
"requirement",
"for",
"version",
"number",
"provided",
"in",
"the",
"Pipfile",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1185-L1195 | [
"def",
"is_required_version",
"(",
"version",
",",
"specified_version",
")",
":",
"# Certain packages may be defined with multiple values.",
"if",
"isinstance",
"(",
"specified_version",
",",
"dict",
")",
":",
"specified_version",
"=",
"specified_version",
".",
"get",
"("... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | is_installable_file | Determine if a path can potentially be installed | pipenv/utils.py | def is_installable_file(path):
"""Determine if a path can potentially be installed"""
from .vendor.pip_shims.shims import is_installable_dir, is_archive_file
from .patched.notpip._internal.utils.packaging import specifiers
from ._compat import Path
if hasattr(path, "keys") and any(
key for key in path.keys() if key in ["file", "path"]
):
path = urlparse(path["file"]).path if "file" in path else path["path"]
if not isinstance(path, six.string_types) or path == "*":
return False
# If the string starts with a valid specifier operator, test if it is a valid
# specifier set before making a path object (to avoid breaking windows)
if any(path.startswith(spec) for spec in "!=<>~"):
try:
specifiers.SpecifierSet(path)
# If this is not a valid specifier, just move on and try it as a path
except specifiers.InvalidSpecifier:
pass
else:
return False
if not os.path.exists(os.path.abspath(path)):
return False
lookup_path = Path(path)
absolute_path = "{0}".format(lookup_path.absolute())
if lookup_path.is_dir() and is_installable_dir(absolute_path):
return True
elif lookup_path.is_file() and is_archive_file(absolute_path):
return True
return False | def is_installable_file(path):
"""Determine if a path can potentially be installed"""
from .vendor.pip_shims.shims import is_installable_dir, is_archive_file
from .patched.notpip._internal.utils.packaging import specifiers
from ._compat import Path
if hasattr(path, "keys") and any(
key for key in path.keys() if key in ["file", "path"]
):
path = urlparse(path["file"]).path if "file" in path else path["path"]
if not isinstance(path, six.string_types) or path == "*":
return False
# If the string starts with a valid specifier operator, test if it is a valid
# specifier set before making a path object (to avoid breaking windows)
if any(path.startswith(spec) for spec in "!=<>~"):
try:
specifiers.SpecifierSet(path)
# If this is not a valid specifier, just move on and try it as a path
except specifiers.InvalidSpecifier:
pass
else:
return False
if not os.path.exists(os.path.abspath(path)):
return False
lookup_path = Path(path)
absolute_path = "{0}".format(lookup_path.absolute())
if lookup_path.is_dir() and is_installable_dir(absolute_path):
return True
elif lookup_path.is_file() and is_archive_file(absolute_path):
return True
return False | [
"Determine",
"if",
"a",
"path",
"can",
"potentially",
"be",
"installed"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1206-L1241 | [
"def",
"is_installable_file",
"(",
"path",
")",
":",
"from",
".",
"vendor",
".",
"pip_shims",
".",
"shims",
"import",
"is_installable_dir",
",",
"is_archive_file",
"from",
".",
"patched",
".",
"notpip",
".",
"_internal",
".",
"utils",
".",
"packaging",
"import... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | is_file | Determine if a package name is for a File dependency. | pipenv/utils.py | def is_file(package):
"""Determine if a package name is for a File dependency."""
if hasattr(package, "keys"):
return any(key for key in package.keys() if key in ["file", "path"])
if os.path.exists(str(package)):
return True
for start in SCHEME_LIST:
if str(package).startswith(start):
return True
return False | def is_file(package):
"""Determine if a package name is for a File dependency."""
if hasattr(package, "keys"):
return any(key for key in package.keys() if key in ["file", "path"])
if os.path.exists(str(package)):
return True
for start in SCHEME_LIST:
if str(package).startswith(start):
return True
return False | [
"Determine",
"if",
"a",
"package",
"name",
"is",
"for",
"a",
"File",
"dependency",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1244-L1256 | [
"def",
"is_file",
"(",
"package",
")",
":",
"if",
"hasattr",
"(",
"package",
",",
"\"keys\"",
")",
":",
"return",
"any",
"(",
"key",
"for",
"key",
"in",
"package",
".",
"keys",
"(",
")",
"if",
"key",
"in",
"[",
"\"file\"",
",",
"\"path\"",
"]",
")"... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | pep423_name | Normalize package name to PEP 423 style standard. | pipenv/utils.py | def pep423_name(name):
"""Normalize package name to PEP 423 style standard."""
name = name.lower()
if any(i not in name for i in (VCS_LIST + SCHEME_LIST)):
return name.replace("_", "-")
else:
return name | def pep423_name(name):
"""Normalize package name to PEP 423 style standard."""
name = name.lower()
if any(i not in name for i in (VCS_LIST + SCHEME_LIST)):
return name.replace("_", "-")
else:
return name | [
"Normalize",
"package",
"name",
"to",
"PEP",
"423",
"style",
"standard",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1267-L1274 | [
"def",
"pep423_name",
"(",
"name",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"any",
"(",
"i",
"not",
"in",
"name",
"for",
"i",
"in",
"(",
"VCS_LIST",
"+",
"SCHEME_LIST",
")",
")",
":",
"return",
"name",
".",
"replace",
"(",
"\"... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | proper_case | Properly case project name from pypi.org. | pipenv/utils.py | def proper_case(package_name):
"""Properly case project name from pypi.org."""
# Hit the simple API.
r = _get_requests_session().get(
"https://pypi.org/pypi/{0}/json".format(package_name), timeout=0.3, stream=True
)
if not r.ok:
raise IOError(
"Unable to find package {0} in PyPI repository.".format(package_name)
)
r = parse.parse("https://pypi.org/pypi/{name}/json", r.url)
good_name = r["name"]
return good_name | def proper_case(package_name):
"""Properly case project name from pypi.org."""
# Hit the simple API.
r = _get_requests_session().get(
"https://pypi.org/pypi/{0}/json".format(package_name), timeout=0.3, stream=True
)
if not r.ok:
raise IOError(
"Unable to find package {0} in PyPI repository.".format(package_name)
)
r = parse.parse("https://pypi.org/pypi/{name}/json", r.url)
good_name = r["name"]
return good_name | [
"Properly",
"case",
"project",
"name",
"from",
"pypi",
".",
"org",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1277-L1290 | [
"def",
"proper_case",
"(",
"package_name",
")",
":",
"# Hit the simple API.",
"r",
"=",
"_get_requests_session",
"(",
")",
".",
"get",
"(",
"\"https://pypi.org/pypi/{0}/json\"",
".",
"format",
"(",
"package_name",
")",
",",
"timeout",
"=",
"0.3",
",",
"stream",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | find_windows_executable | Given an executable name, search the given location for an executable | pipenv/utils.py | def find_windows_executable(bin_path, exe_name):
"""Given an executable name, search the given location for an executable"""
requested_path = get_windows_path(bin_path, exe_name)
if os.path.isfile(requested_path):
return requested_path
try:
pathext = os.environ["PATHEXT"]
except KeyError:
pass
else:
for ext in pathext.split(os.pathsep):
path = get_windows_path(bin_path, exe_name + ext.strip().lower())
if os.path.isfile(path):
return path
return find_executable(exe_name) | def find_windows_executable(bin_path, exe_name):
"""Given an executable name, search the given location for an executable"""
requested_path = get_windows_path(bin_path, exe_name)
if os.path.isfile(requested_path):
return requested_path
try:
pathext = os.environ["PATHEXT"]
except KeyError:
pass
else:
for ext in pathext.split(os.pathsep):
path = get_windows_path(bin_path, exe_name + ext.strip().lower())
if os.path.isfile(path):
return path
return find_executable(exe_name) | [
"Given",
"an",
"executable",
"name",
"search",
"the",
"given",
"location",
"for",
"an",
"executable"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1300-L1316 | [
"def",
"find_windows_executable",
"(",
"bin_path",
",",
"exe_name",
")",
":",
"requested_path",
"=",
"get_windows_path",
"(",
"bin_path",
",",
"exe_name",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"requested_path",
")",
":",
"return",
"requested_path",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | get_canonical_names | Canonicalize a list of packages and return a set of canonical names | pipenv/utils.py | def get_canonical_names(packages):
"""Canonicalize a list of packages and return a set of canonical names"""
from .vendor.packaging.utils import canonicalize_name
if not isinstance(packages, Sequence):
if not isinstance(packages, six.string_types):
return packages
packages = [packages]
return set([canonicalize_name(pkg) for pkg in packages if pkg]) | def get_canonical_names(packages):
"""Canonicalize a list of packages and return a set of canonical names"""
from .vendor.packaging.utils import canonicalize_name
if not isinstance(packages, Sequence):
if not isinstance(packages, six.string_types):
return packages
packages = [packages]
return set([canonicalize_name(pkg) for pkg in packages if pkg]) | [
"Canonicalize",
"a",
"list",
"of",
"packages",
"and",
"return",
"a",
"set",
"of",
"canonical",
"names"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1337-L1345 | [
"def",
"get_canonical_names",
"(",
"packages",
")",
":",
"from",
".",
"vendor",
".",
"packaging",
".",
"utils",
"import",
"canonicalize_name",
"if",
"not",
"isinstance",
"(",
"packages",
",",
"Sequence",
")",
":",
"if",
"not",
"isinstance",
"(",
"packages",
... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | find_requirements | Returns the path of a Pipfile in parent directories. | pipenv/utils.py | def find_requirements(max_depth=3):
"""Returns the path of a Pipfile in parent directories."""
i = 0
for c, d, f in walk_up(os.getcwd()):
i += 1
if i < max_depth:
if "requirements.txt":
r = os.path.join(c, "requirements.txt")
if os.path.isfile(r):
return r
raise RuntimeError("No requirements.txt found!") | def find_requirements(max_depth=3):
"""Returns the path of a Pipfile in parent directories."""
i = 0
for c, d, f in walk_up(os.getcwd()):
i += 1
if i < max_depth:
if "requirements.txt":
r = os.path.join(c, "requirements.txt")
if os.path.isfile(r):
return r
raise RuntimeError("No requirements.txt found!") | [
"Returns",
"the",
"path",
"of",
"a",
"Pipfile",
"in",
"parent",
"directories",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1376-L1387 | [
"def",
"find_requirements",
"(",
"max_depth",
"=",
"3",
")",
":",
"i",
"=",
"0",
"for",
"c",
",",
"d",
",",
"f",
"in",
"walk_up",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
":",
"i",
"+=",
"1",
"if",
"i",
"<",
"max_depth",
":",
"if",
"\"requireme... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | temp_environ | Allow the ability to set os.environ temporarily | pipenv/utils.py | def temp_environ():
"""Allow the ability to set os.environ temporarily"""
environ = dict(os.environ)
try:
yield
finally:
os.environ.clear()
os.environ.update(environ) | def temp_environ():
"""Allow the ability to set os.environ temporarily"""
environ = dict(os.environ)
try:
yield
finally:
os.environ.clear()
os.environ.update(environ) | [
"Allow",
"the",
"ability",
"to",
"set",
"os",
".",
"environ",
"temporarily"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1393-L1401 | [
"def",
"temp_environ",
"(",
")",
":",
"environ",
"=",
"dict",
"(",
"os",
".",
"environ",
")",
"try",
":",
"yield",
"finally",
":",
"os",
".",
"environ",
".",
"clear",
"(",
")",
"os",
".",
"environ",
".",
"update",
"(",
"environ",
")"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | temp_path | Allow the ability to set os.environ temporarily | pipenv/utils.py | def temp_path():
"""Allow the ability to set os.environ temporarily"""
path = [p for p in sys.path]
try:
yield
finally:
sys.path = [p for p in path] | def temp_path():
"""Allow the ability to set os.environ temporarily"""
path = [p for p in sys.path]
try:
yield
finally:
sys.path = [p for p in path] | [
"Allow",
"the",
"ability",
"to",
"set",
"os",
".",
"environ",
"temporarily"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1405-L1411 | [
"def",
"temp_path",
"(",
")",
":",
"path",
"=",
"[",
"p",
"for",
"p",
"in",
"sys",
".",
"path",
"]",
"try",
":",
"yield",
"finally",
":",
"sys",
".",
"path",
"=",
"[",
"p",
"for",
"p",
"in",
"path",
"]"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | is_valid_url | Checks if a given string is an url | pipenv/utils.py | def is_valid_url(url):
"""Checks if a given string is an url"""
pieces = urlparse(url)
return all([pieces.scheme, pieces.netloc]) | def is_valid_url(url):
"""Checks if a given string is an url"""
pieces = urlparse(url)
return all([pieces.scheme, pieces.netloc]) | [
"Checks",
"if",
"a",
"given",
"string",
"is",
"an",
"url"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1427-L1430 | [
"def",
"is_valid_url",
"(",
"url",
")",
":",
"pieces",
"=",
"urlparse",
"(",
"url",
")",
"return",
"all",
"(",
"[",
"pieces",
".",
"scheme",
",",
"pieces",
".",
"netloc",
"]",
")"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | download_file | Downloads file from url to a path with filename | pipenv/utils.py | def download_file(url, filename):
"""Downloads file from url to a path with filename"""
r = _get_requests_session().get(url, stream=True)
if not r.ok:
raise IOError("Unable to download file")
with open(filename, "wb") as f:
f.write(r.content) | def download_file(url, filename):
"""Downloads file from url to a path with filename"""
r = _get_requests_session().get(url, stream=True)
if not r.ok:
raise IOError("Unable to download file")
with open(filename, "wb") as f:
f.write(r.content) | [
"Downloads",
"file",
"from",
"url",
"to",
"a",
"path",
"with",
"filename"
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1451-L1458 | [
"def",
"download_file",
"(",
"url",
",",
"filename",
")",
":",
"r",
"=",
"_get_requests_session",
"(",
")",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"if",
"not",
"r",
".",
"ok",
":",
"raise",
"IOError",
"(",
"\"Unable to download file\"",... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | normalize_drive | Normalize drive in path so they stay consistent.
This currently only affects local drives on Windows, which can be
identified with either upper or lower cased drive names. The case is
always converted to uppercase because it seems to be preferred.
See: <https://github.com/pypa/pipenv/issues/1218> | pipenv/utils.py | def normalize_drive(path):
"""Normalize drive in path so they stay consistent.
This currently only affects local drives on Windows, which can be
identified with either upper or lower cased drive names. The case is
always converted to uppercase because it seems to be preferred.
See: <https://github.com/pypa/pipenv/issues/1218>
"""
if os.name != "nt" or not isinstance(path, six.string_types):
return path
drive, tail = os.path.splitdrive(path)
# Only match (lower cased) local drives (e.g. 'c:'), not UNC mounts.
if drive.islower() and len(drive) == 2 and drive[1] == ":":
return "{}{}".format(drive.upper(), tail)
return path | def normalize_drive(path):
"""Normalize drive in path so they stay consistent.
This currently only affects local drives on Windows, which can be
identified with either upper or lower cased drive names. The case is
always converted to uppercase because it seems to be preferred.
See: <https://github.com/pypa/pipenv/issues/1218>
"""
if os.name != "nt" or not isinstance(path, six.string_types):
return path
drive, tail = os.path.splitdrive(path)
# Only match (lower cased) local drives (e.g. 'c:'), not UNC mounts.
if drive.islower() and len(drive) == 2 and drive[1] == ":":
return "{}{}".format(drive.upper(), tail)
return path | [
"Normalize",
"drive",
"in",
"path",
"so",
"they",
"stay",
"consistent",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1461-L1478 | [
"def",
"normalize_drive",
"(",
"path",
")",
":",
"if",
"os",
".",
"name",
"!=",
"\"nt\"",
"or",
"not",
"isinstance",
"(",
"path",
",",
"six",
".",
"string_types",
")",
":",
"return",
"path",
"drive",
",",
"tail",
"=",
"os",
".",
"path",
".",
"splitdr... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | is_readonly_path | Check if a provided path exists and is readonly.
Permissions check is `bool(path.stat & stat.S_IREAD)` or `not os.access(path, os.W_OK)` | pipenv/utils.py | def is_readonly_path(fn):
"""Check if a provided path exists and is readonly.
Permissions check is `bool(path.stat & stat.S_IREAD)` or `not os.access(path, os.W_OK)`
"""
if os.path.exists(fn):
return (os.stat(fn).st_mode & stat.S_IREAD) or not os.access(fn, os.W_OK)
return False | def is_readonly_path(fn):
"""Check if a provided path exists and is readonly.
Permissions check is `bool(path.stat & stat.S_IREAD)` or `not os.access(path, os.W_OK)`
"""
if os.path.exists(fn):
return (os.stat(fn).st_mode & stat.S_IREAD) or not os.access(fn, os.W_OK)
return False | [
"Check",
"if",
"a",
"provided",
"path",
"exists",
"and",
"is",
"readonly",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1481-L1489 | [
"def",
"is_readonly_path",
"(",
"fn",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
":",
"return",
"(",
"os",
".",
"stat",
"(",
"fn",
")",
".",
"st_mode",
"&",
"stat",
".",
"S_IREAD",
")",
"or",
"not",
"os",
".",
"access",
"... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | handle_remove_readonly | Error handler for shutil.rmtree.
Windows source repo folders are read-only by default, so this error handler
attempts to set them as writeable and then proceed with deletion. | pipenv/utils.py | def handle_remove_readonly(func, path, exc):
"""Error handler for shutil.rmtree.
Windows source repo folders are read-only by default, so this error handler
attempts to set them as writeable and then proceed with deletion."""
# Check for read-only attribute
default_warning_message = (
"Unable to remove file due to permissions restriction: {!r}"
)
# split the initial exception out into its type, exception, and traceback
exc_type, exc_exception, exc_tb = exc
if is_readonly_path(path):
# Apply write permission and call original function
set_write_bit(path)
try:
func(path)
except (OSError, IOError) as e:
if e.errno in [errno.EACCES, errno.EPERM]:
warnings.warn(default_warning_message.format(path), ResourceWarning)
return
if exc_exception.errno in [errno.EACCES, errno.EPERM]:
warnings.warn(default_warning_message.format(path), ResourceWarning)
return
raise exc | def handle_remove_readonly(func, path, exc):
"""Error handler for shutil.rmtree.
Windows source repo folders are read-only by default, so this error handler
attempts to set them as writeable and then proceed with deletion."""
# Check for read-only attribute
default_warning_message = (
"Unable to remove file due to permissions restriction: {!r}"
)
# split the initial exception out into its type, exception, and traceback
exc_type, exc_exception, exc_tb = exc
if is_readonly_path(path):
# Apply write permission and call original function
set_write_bit(path)
try:
func(path)
except (OSError, IOError) as e:
if e.errno in [errno.EACCES, errno.EPERM]:
warnings.warn(default_warning_message.format(path), ResourceWarning)
return
if exc_exception.errno in [errno.EACCES, errno.EPERM]:
warnings.warn(default_warning_message.format(path), ResourceWarning)
return
raise exc | [
"Error",
"handler",
"for",
"shutil",
".",
"rmtree",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1505-L1530 | [
"def",
"handle_remove_readonly",
"(",
"func",
",",
"path",
",",
"exc",
")",
":",
"# Check for read-only attribute",
"default_warning_message",
"=",
"(",
"\"Unable to remove file due to permissions restriction: {!r}\"",
")",
"# split the initial exception out into its type, exception,... | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
train | safe_expandvars | Call os.path.expandvars if value is a string, otherwise do nothing. | pipenv/utils.py | def safe_expandvars(value):
"""Call os.path.expandvars if value is a string, otherwise do nothing.
"""
if isinstance(value, six.string_types):
return os.path.expandvars(value)
return value | def safe_expandvars(value):
"""Call os.path.expandvars if value is a string, otherwise do nothing.
"""
if isinstance(value, six.string_types):
return os.path.expandvars(value)
return value | [
"Call",
"os",
".",
"path",
".",
"expandvars",
"if",
"value",
"is",
"a",
"string",
"otherwise",
"do",
"nothing",
"."
] | pypa/pipenv | python | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1539-L1544 | [
"def",
"safe_expandvars",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"return",
"os",
".",
"path",
".",
"expandvars",
"(",
"value",
")",
"return",
"value"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.