id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
25,300 | pypa/pipenv | pipenv/patched/notpip/_internal/index.py | PackageFinder._get_index_urls_locations | def _get_index_urls_locations(self, project_name):
# type: (str) -> List[str]
"""Returns the locations found via self.index_urls
Checks the url_name on the main (first in the list) index and
use this url_name to produce all locations
"""
def mkurl_pypi_url(url):
loc = posixpath.join(
url,
urllib_parse.quote(canonicalize_name(project_name)))
# For maximum compatibility with easy_install, ensure the path
# ends in a trailing slash. Although this isn't in the spec
# (and PyPI can handle it without the slash) some other index
# implementations might break if they relied on easy_install's
# behavior.
if not loc.endswith('/'):
loc = loc + '/'
return loc
return [mkurl_pypi_url(url) for url in self.index_urls] | python | def _get_index_urls_locations(self, project_name):
# type: (str) -> List[str]
"""Returns the locations found via self.index_urls
Checks the url_name on the main (first in the list) index and
use this url_name to produce all locations
"""
def mkurl_pypi_url(url):
loc = posixpath.join(
url,
urllib_parse.quote(canonicalize_name(project_name)))
# For maximum compatibility with easy_install, ensure the path
# ends in a trailing slash. Although this isn't in the spec
# (and PyPI can handle it without the slash) some other index
# implementations might break if they relied on easy_install's
# behavior.
if not loc.endswith('/'):
loc = loc + '/'
return loc
return [mkurl_pypi_url(url) for url in self.index_urls] | [
"def",
"_get_index_urls_locations",
"(",
"self",
",",
"project_name",
")",
":",
"# type: (str) -> List[str]",
"def",
"mkurl_pypi_url",
"(",
"url",
")",
":",
"loc",
"=",
"posixpath",
".",
"join",
"(",
"url",
",",
"urllib_parse",
".",
"quote",
"(",
"canonicalize_name",
"(",
"project_name",
")",
")",
")",
"# For maximum compatibility with easy_install, ensure the path",
"# ends in a trailing slash. Although this isn't in the spec",
"# (and PyPI can handle it without the slash) some other index",
"# implementations might break if they relied on easy_install's",
"# behavior.",
"if",
"not",
"loc",
".",
"endswith",
"(",
"'/'",
")",
":",
"loc",
"=",
"loc",
"+",
"'/'",
"return",
"loc",
"return",
"[",
"mkurl_pypi_url",
"(",
"url",
")",
"for",
"url",
"in",
"self",
".",
"index_urls",
"]"
] | Returns the locations found via self.index_urls
Checks the url_name on the main (first in the list) index and
use this url_name to produce all locations | [
"Returns",
"the",
"locations",
"found",
"via",
"self",
".",
"index_urls"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/index.py#L565-L586 |
25,301 | pypa/pipenv | pipenv/patched/notpip/_internal/index.py | PackageFinder.find_all_candidates | def find_all_candidates(self, project_name):
# type: (str) -> List[Optional[InstallationCandidate]]
"""Find all available InstallationCandidate for project_name
This checks index_urls and find_links.
All versions found are returned as an InstallationCandidate list.
See _link_package_versions for details on which files are accepted
"""
index_locations = self._get_index_urls_locations(project_name)
index_file_loc, index_url_loc = self._sort_locations(index_locations)
fl_file_loc, fl_url_loc = self._sort_locations(
self.find_links, expand_dir=True,
)
file_locations = (Link(url) for url in itertools.chain(
index_file_loc, fl_file_loc,
))
# We trust every url that the user has given us whether it was given
# via --index-url or --find-links.
# We want to filter out any thing which does not have a secure origin.
url_locations = [
link for link in itertools.chain(
(Link(url) for url in index_url_loc),
(Link(url) for url in fl_url_loc),
)
if self._validate_secure_origin(logger, link)
]
logger.debug('%d location(s) to search for versions of %s:',
len(url_locations), project_name)
for location in url_locations:
logger.debug('* %s', location)
canonical_name = canonicalize_name(project_name)
formats = self.format_control.get_allowed_formats(canonical_name)
search = Search(project_name, canonical_name, formats)
find_links_versions = self._package_versions(
# We trust every directly linked archive in find_links
(Link(url, '-f') for url in self.find_links),
search
)
page_versions = []
for page in self._get_pages(url_locations, project_name):
try:
logger.debug('Analyzing links from page %s', page.url)
except AttributeError:
continue
with indent_log():
page_versions.extend(
self._package_versions(page.iter_links(), search)
)
file_versions = self._package_versions(file_locations, search)
if file_versions:
file_versions.sort(reverse=True)
logger.debug(
'Local files found: %s',
', '.join([
url_to_path(candidate.location.url)
for candidate in file_versions
])
)
# This is an intentional priority ordering
return file_versions + find_links_versions + page_versions | python | def find_all_candidates(self, project_name):
# type: (str) -> List[Optional[InstallationCandidate]]
"""Find all available InstallationCandidate for project_name
This checks index_urls and find_links.
All versions found are returned as an InstallationCandidate list.
See _link_package_versions for details on which files are accepted
"""
index_locations = self._get_index_urls_locations(project_name)
index_file_loc, index_url_loc = self._sort_locations(index_locations)
fl_file_loc, fl_url_loc = self._sort_locations(
self.find_links, expand_dir=True,
)
file_locations = (Link(url) for url in itertools.chain(
index_file_loc, fl_file_loc,
))
# We trust every url that the user has given us whether it was given
# via --index-url or --find-links.
# We want to filter out any thing which does not have a secure origin.
url_locations = [
link for link in itertools.chain(
(Link(url) for url in index_url_loc),
(Link(url) for url in fl_url_loc),
)
if self._validate_secure_origin(logger, link)
]
logger.debug('%d location(s) to search for versions of %s:',
len(url_locations), project_name)
for location in url_locations:
logger.debug('* %s', location)
canonical_name = canonicalize_name(project_name)
formats = self.format_control.get_allowed_formats(canonical_name)
search = Search(project_name, canonical_name, formats)
find_links_versions = self._package_versions(
# We trust every directly linked archive in find_links
(Link(url, '-f') for url in self.find_links),
search
)
page_versions = []
for page in self._get_pages(url_locations, project_name):
try:
logger.debug('Analyzing links from page %s', page.url)
except AttributeError:
continue
with indent_log():
page_versions.extend(
self._package_versions(page.iter_links(), search)
)
file_versions = self._package_versions(file_locations, search)
if file_versions:
file_versions.sort(reverse=True)
logger.debug(
'Local files found: %s',
', '.join([
url_to_path(candidate.location.url)
for candidate in file_versions
])
)
# This is an intentional priority ordering
return file_versions + find_links_versions + page_versions | [
"def",
"find_all_candidates",
"(",
"self",
",",
"project_name",
")",
":",
"# type: (str) -> List[Optional[InstallationCandidate]]",
"index_locations",
"=",
"self",
".",
"_get_index_urls_locations",
"(",
"project_name",
")",
"index_file_loc",
",",
"index_url_loc",
"=",
"self",
".",
"_sort_locations",
"(",
"index_locations",
")",
"fl_file_loc",
",",
"fl_url_loc",
"=",
"self",
".",
"_sort_locations",
"(",
"self",
".",
"find_links",
",",
"expand_dir",
"=",
"True",
",",
")",
"file_locations",
"=",
"(",
"Link",
"(",
"url",
")",
"for",
"url",
"in",
"itertools",
".",
"chain",
"(",
"index_file_loc",
",",
"fl_file_loc",
",",
")",
")",
"# We trust every url that the user has given us whether it was given",
"# via --index-url or --find-links.",
"# We want to filter out any thing which does not have a secure origin.",
"url_locations",
"=",
"[",
"link",
"for",
"link",
"in",
"itertools",
".",
"chain",
"(",
"(",
"Link",
"(",
"url",
")",
"for",
"url",
"in",
"index_url_loc",
")",
",",
"(",
"Link",
"(",
"url",
")",
"for",
"url",
"in",
"fl_url_loc",
")",
",",
")",
"if",
"self",
".",
"_validate_secure_origin",
"(",
"logger",
",",
"link",
")",
"]",
"logger",
".",
"debug",
"(",
"'%d location(s) to search for versions of %s:'",
",",
"len",
"(",
"url_locations",
")",
",",
"project_name",
")",
"for",
"location",
"in",
"url_locations",
":",
"logger",
".",
"debug",
"(",
"'* %s'",
",",
"location",
")",
"canonical_name",
"=",
"canonicalize_name",
"(",
"project_name",
")",
"formats",
"=",
"self",
".",
"format_control",
".",
"get_allowed_formats",
"(",
"canonical_name",
")",
"search",
"=",
"Search",
"(",
"project_name",
",",
"canonical_name",
",",
"formats",
")",
"find_links_versions",
"=",
"self",
".",
"_package_versions",
"(",
"# We trust every directly linked archive in find_links",
"(",
"Link",
"(",
"url",
",",
"'-f'",
")",
"for",
"url",
"in",
"self",
".",
"find_links",
")",
",",
"search",
")",
"page_versions",
"=",
"[",
"]",
"for",
"page",
"in",
"self",
".",
"_get_pages",
"(",
"url_locations",
",",
"project_name",
")",
":",
"try",
":",
"logger",
".",
"debug",
"(",
"'Analyzing links from page %s'",
",",
"page",
".",
"url",
")",
"except",
"AttributeError",
":",
"continue",
"with",
"indent_log",
"(",
")",
":",
"page_versions",
".",
"extend",
"(",
"self",
".",
"_package_versions",
"(",
"page",
".",
"iter_links",
"(",
")",
",",
"search",
")",
")",
"file_versions",
"=",
"self",
".",
"_package_versions",
"(",
"file_locations",
",",
"search",
")",
"if",
"file_versions",
":",
"file_versions",
".",
"sort",
"(",
"reverse",
"=",
"True",
")",
"logger",
".",
"debug",
"(",
"'Local files found: %s'",
",",
"', '",
".",
"join",
"(",
"[",
"url_to_path",
"(",
"candidate",
".",
"location",
".",
"url",
")",
"for",
"candidate",
"in",
"file_versions",
"]",
")",
")",
"# This is an intentional priority ordering",
"return",
"file_versions",
"+",
"find_links_versions",
"+",
"page_versions"
] | Find all available InstallationCandidate for project_name
This checks index_urls and find_links.
All versions found are returned as an InstallationCandidate list.
See _link_package_versions for details on which files are accepted | [
"Find",
"all",
"available",
"InstallationCandidate",
"for",
"project_name"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/index.py#L588-L656 |
25,302 | pypa/pipenv | pipenv/patched/notpip/_internal/index.py | PackageFinder.find_requirement | def find_requirement(self, req, upgrade, ignore_compatibility=False):
# type: (InstallRequirement, bool, bool) -> Optional[Link]
"""Try to find a Link matching req
Expects req, an InstallRequirement and upgrade, a boolean
Returns a Link if found,
Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise
"""
all_candidates = self.find_all_candidates(req.name)
# Filter out anything which doesn't match our specifier
compatible_versions = set(
req.specifier.filter(
# We turn the version object into a str here because otherwise
# when we're debundled but setuptools isn't, Python will see
# packaging.version.Version and
# pkg_resources._vendor.packaging.version.Version as different
# types. This way we'll use a str as a common data interchange
# format. If we stop using the pkg_resources provided specifier
# and start using our own, we can drop the cast to str().
[str(c.version) for c in all_candidates],
prereleases=(
self.allow_all_prereleases
if self.allow_all_prereleases else None
),
)
)
applicable_candidates = [
# Again, converting to str to deal with debundling.
c for c in all_candidates if str(c.version) in compatible_versions
]
if applicable_candidates:
best_candidate = max(applicable_candidates,
key=self._candidate_sort_key)
else:
best_candidate = None
if req.satisfied_by is not None:
installed_version = parse_version(req.satisfied_by.version)
else:
installed_version = None
if installed_version is None and best_candidate is None:
logger.critical(
'Could not find a version that satisfies the requirement %s '
'(from versions: %s)',
req,
', '.join(
sorted(
{str(c.version) for c in all_candidates},
key=parse_version,
)
)
)
raise DistributionNotFound(
'No matching distribution found for %s' % req
)
best_installed = False
if installed_version and (
best_candidate is None or
best_candidate.version <= installed_version):
best_installed = True
if not upgrade and installed_version is not None:
if best_installed:
logger.debug(
'Existing installed version (%s) is most up-to-date and '
'satisfies requirement',
installed_version,
)
else:
logger.debug(
'Existing installed version (%s) satisfies requirement '
'(most up-to-date version is %s)',
installed_version,
best_candidate.version,
)
return None
if best_installed:
# We have an existing version, and its the best version
logger.debug(
'Installed version (%s) is most up-to-date (past versions: '
'%s)',
installed_version,
', '.join(sorted(compatible_versions, key=parse_version)) or
"none",
)
raise BestVersionAlreadyInstalled
logger.debug(
'Using version %s (newest of versions: %s)',
best_candidate.version,
', '.join(sorted(compatible_versions, key=parse_version))
)
return best_candidate.location | python | def find_requirement(self, req, upgrade, ignore_compatibility=False):
# type: (InstallRequirement, bool, bool) -> Optional[Link]
"""Try to find a Link matching req
Expects req, an InstallRequirement and upgrade, a boolean
Returns a Link if found,
Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise
"""
all_candidates = self.find_all_candidates(req.name)
# Filter out anything which doesn't match our specifier
compatible_versions = set(
req.specifier.filter(
# We turn the version object into a str here because otherwise
# when we're debundled but setuptools isn't, Python will see
# packaging.version.Version and
# pkg_resources._vendor.packaging.version.Version as different
# types. This way we'll use a str as a common data interchange
# format. If we stop using the pkg_resources provided specifier
# and start using our own, we can drop the cast to str().
[str(c.version) for c in all_candidates],
prereleases=(
self.allow_all_prereleases
if self.allow_all_prereleases else None
),
)
)
applicable_candidates = [
# Again, converting to str to deal with debundling.
c for c in all_candidates if str(c.version) in compatible_versions
]
if applicable_candidates:
best_candidate = max(applicable_candidates,
key=self._candidate_sort_key)
else:
best_candidate = None
if req.satisfied_by is not None:
installed_version = parse_version(req.satisfied_by.version)
else:
installed_version = None
if installed_version is None and best_candidate is None:
logger.critical(
'Could not find a version that satisfies the requirement %s '
'(from versions: %s)',
req,
', '.join(
sorted(
{str(c.version) for c in all_candidates},
key=parse_version,
)
)
)
raise DistributionNotFound(
'No matching distribution found for %s' % req
)
best_installed = False
if installed_version and (
best_candidate is None or
best_candidate.version <= installed_version):
best_installed = True
if not upgrade and installed_version is not None:
if best_installed:
logger.debug(
'Existing installed version (%s) is most up-to-date and '
'satisfies requirement',
installed_version,
)
else:
logger.debug(
'Existing installed version (%s) satisfies requirement '
'(most up-to-date version is %s)',
installed_version,
best_candidate.version,
)
return None
if best_installed:
# We have an existing version, and its the best version
logger.debug(
'Installed version (%s) is most up-to-date (past versions: '
'%s)',
installed_version,
', '.join(sorted(compatible_versions, key=parse_version)) or
"none",
)
raise BestVersionAlreadyInstalled
logger.debug(
'Using version %s (newest of versions: %s)',
best_candidate.version,
', '.join(sorted(compatible_versions, key=parse_version))
)
return best_candidate.location | [
"def",
"find_requirement",
"(",
"self",
",",
"req",
",",
"upgrade",
",",
"ignore_compatibility",
"=",
"False",
")",
":",
"# type: (InstallRequirement, bool, bool) -> Optional[Link]",
"all_candidates",
"=",
"self",
".",
"find_all_candidates",
"(",
"req",
".",
"name",
")",
"# Filter out anything which doesn't match our specifier",
"compatible_versions",
"=",
"set",
"(",
"req",
".",
"specifier",
".",
"filter",
"(",
"# We turn the version object into a str here because otherwise",
"# when we're debundled but setuptools isn't, Python will see",
"# packaging.version.Version and",
"# pkg_resources._vendor.packaging.version.Version as different",
"# types. This way we'll use a str as a common data interchange",
"# format. If we stop using the pkg_resources provided specifier",
"# and start using our own, we can drop the cast to str().",
"[",
"str",
"(",
"c",
".",
"version",
")",
"for",
"c",
"in",
"all_candidates",
"]",
",",
"prereleases",
"=",
"(",
"self",
".",
"allow_all_prereleases",
"if",
"self",
".",
"allow_all_prereleases",
"else",
"None",
")",
",",
")",
")",
"applicable_candidates",
"=",
"[",
"# Again, converting to str to deal with debundling.",
"c",
"for",
"c",
"in",
"all_candidates",
"if",
"str",
"(",
"c",
".",
"version",
")",
"in",
"compatible_versions",
"]",
"if",
"applicable_candidates",
":",
"best_candidate",
"=",
"max",
"(",
"applicable_candidates",
",",
"key",
"=",
"self",
".",
"_candidate_sort_key",
")",
"else",
":",
"best_candidate",
"=",
"None",
"if",
"req",
".",
"satisfied_by",
"is",
"not",
"None",
":",
"installed_version",
"=",
"parse_version",
"(",
"req",
".",
"satisfied_by",
".",
"version",
")",
"else",
":",
"installed_version",
"=",
"None",
"if",
"installed_version",
"is",
"None",
"and",
"best_candidate",
"is",
"None",
":",
"logger",
".",
"critical",
"(",
"'Could not find a version that satisfies the requirement %s '",
"'(from versions: %s)'",
",",
"req",
",",
"', '",
".",
"join",
"(",
"sorted",
"(",
"{",
"str",
"(",
"c",
".",
"version",
")",
"for",
"c",
"in",
"all_candidates",
"}",
",",
"key",
"=",
"parse_version",
",",
")",
")",
")",
"raise",
"DistributionNotFound",
"(",
"'No matching distribution found for %s'",
"%",
"req",
")",
"best_installed",
"=",
"False",
"if",
"installed_version",
"and",
"(",
"best_candidate",
"is",
"None",
"or",
"best_candidate",
".",
"version",
"<=",
"installed_version",
")",
":",
"best_installed",
"=",
"True",
"if",
"not",
"upgrade",
"and",
"installed_version",
"is",
"not",
"None",
":",
"if",
"best_installed",
":",
"logger",
".",
"debug",
"(",
"'Existing installed version (%s) is most up-to-date and '",
"'satisfies requirement'",
",",
"installed_version",
",",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'Existing installed version (%s) satisfies requirement '",
"'(most up-to-date version is %s)'",
",",
"installed_version",
",",
"best_candidate",
".",
"version",
",",
")",
"return",
"None",
"if",
"best_installed",
":",
"# We have an existing version, and its the best version",
"logger",
".",
"debug",
"(",
"'Installed version (%s) is most up-to-date (past versions: '",
"'%s)'",
",",
"installed_version",
",",
"', '",
".",
"join",
"(",
"sorted",
"(",
"compatible_versions",
",",
"key",
"=",
"parse_version",
")",
")",
"or",
"\"none\"",
",",
")",
"raise",
"BestVersionAlreadyInstalled",
"logger",
".",
"debug",
"(",
"'Using version %s (newest of versions: %s)'",
",",
"best_candidate",
".",
"version",
",",
"', '",
".",
"join",
"(",
"sorted",
"(",
"compatible_versions",
",",
"key",
"=",
"parse_version",
")",
")",
")",
"return",
"best_candidate",
".",
"location"
] | Try to find a Link matching req
Expects req, an InstallRequirement and upgrade, a boolean
Returns a Link if found,
Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise | [
"Try",
"to",
"find",
"a",
"Link",
"matching",
"req"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/index.py#L658-L756 |
25,303 | pypa/pipenv | pipenv/patched/notpip/_internal/index.py | PackageFinder._link_package_versions | def _link_package_versions(self, link, search, ignore_compatibility=True):
# type: (Link, Search, bool) -> Optional[InstallationCandidate]
"""Return an InstallationCandidate or None"""
version = None
if link.egg_fragment:
egg_info = link.egg_fragment
ext = link.ext
else:
egg_info, ext = link.splitext()
if not ext:
self._log_skipped_link(link, 'not a file')
return None
if ext not in SUPPORTED_EXTENSIONS:
self._log_skipped_link(
link, 'unsupported archive format: %s' % ext,
)
return None
if "binary" not in search.formats and ext == WHEEL_EXTENSION and not ignore_compatibility:
self._log_skipped_link(
link, 'No binaries permitted for %s' % search.supplied,
)
return None
if "macosx10" in link.path and ext == '.zip' and not ignore_compatibility:
self._log_skipped_link(link, 'macosx10 one')
return None
if ext == WHEEL_EXTENSION:
try:
wheel = Wheel(link.filename)
except InvalidWheelFilename:
self._log_skipped_link(link, 'invalid wheel filename')
return None
if canonicalize_name(wheel.name) != search.canonical:
self._log_skipped_link(
link, 'wrong project name (not %s)' % search.supplied)
return None
if not wheel.supported(self.valid_tags) and not ignore_compatibility:
self._log_skipped_link(
link, 'it is not compatible with this Python')
return None
version = wheel.version
# This should be up by the search.ok_binary check, but see issue 2700.
if "source" not in search.formats and ext != WHEEL_EXTENSION:
self._log_skipped_link(
link, 'No sources permitted for %s' % search.supplied,
)
return None
if not version:
version = _egg_info_matches(egg_info, search.canonical)
if not version:
self._log_skipped_link(
link, 'Missing project version for %s' % search.supplied)
return None
match = self._py_version_re.search(version)
if match:
version = version[:match.start()]
py_version = match.group(1)
if py_version != sys.version[:3]:
self._log_skipped_link(
link, 'Python version is incorrect')
return None
try:
support_this_python = check_requires_python(link.requires_python)
except specifiers.InvalidSpecifier:
logger.debug("Package %s has an invalid Requires-Python entry: %s",
link.filename, link.requires_python)
support_this_python = True
if not support_this_python and not ignore_compatibility:
logger.debug("The package %s is incompatible with the python "
"version in use. Acceptable python versions are: %s",
link, link.requires_python)
return None
logger.debug('Found link %s, version: %s', link, version)
return InstallationCandidate(search.supplied, version, link, link.requires_python) | python | def _link_package_versions(self, link, search, ignore_compatibility=True):
# type: (Link, Search, bool) -> Optional[InstallationCandidate]
"""Return an InstallationCandidate or None"""
version = None
if link.egg_fragment:
egg_info = link.egg_fragment
ext = link.ext
else:
egg_info, ext = link.splitext()
if not ext:
self._log_skipped_link(link, 'not a file')
return None
if ext not in SUPPORTED_EXTENSIONS:
self._log_skipped_link(
link, 'unsupported archive format: %s' % ext,
)
return None
if "binary" not in search.formats and ext == WHEEL_EXTENSION and not ignore_compatibility:
self._log_skipped_link(
link, 'No binaries permitted for %s' % search.supplied,
)
return None
if "macosx10" in link.path and ext == '.zip' and not ignore_compatibility:
self._log_skipped_link(link, 'macosx10 one')
return None
if ext == WHEEL_EXTENSION:
try:
wheel = Wheel(link.filename)
except InvalidWheelFilename:
self._log_skipped_link(link, 'invalid wheel filename')
return None
if canonicalize_name(wheel.name) != search.canonical:
self._log_skipped_link(
link, 'wrong project name (not %s)' % search.supplied)
return None
if not wheel.supported(self.valid_tags) and not ignore_compatibility:
self._log_skipped_link(
link, 'it is not compatible with this Python')
return None
version = wheel.version
# This should be up by the search.ok_binary check, but see issue 2700.
if "source" not in search.formats and ext != WHEEL_EXTENSION:
self._log_skipped_link(
link, 'No sources permitted for %s' % search.supplied,
)
return None
if not version:
version = _egg_info_matches(egg_info, search.canonical)
if not version:
self._log_skipped_link(
link, 'Missing project version for %s' % search.supplied)
return None
match = self._py_version_re.search(version)
if match:
version = version[:match.start()]
py_version = match.group(1)
if py_version != sys.version[:3]:
self._log_skipped_link(
link, 'Python version is incorrect')
return None
try:
support_this_python = check_requires_python(link.requires_python)
except specifiers.InvalidSpecifier:
logger.debug("Package %s has an invalid Requires-Python entry: %s",
link.filename, link.requires_python)
support_this_python = True
if not support_this_python and not ignore_compatibility:
logger.debug("The package %s is incompatible with the python "
"version in use. Acceptable python versions are: %s",
link, link.requires_python)
return None
logger.debug('Found link %s, version: %s', link, version)
return InstallationCandidate(search.supplied, version, link, link.requires_python) | [
"def",
"_link_package_versions",
"(",
"self",
",",
"link",
",",
"search",
",",
"ignore_compatibility",
"=",
"True",
")",
":",
"# type: (Link, Search, bool) -> Optional[InstallationCandidate]",
"version",
"=",
"None",
"if",
"link",
".",
"egg_fragment",
":",
"egg_info",
"=",
"link",
".",
"egg_fragment",
"ext",
"=",
"link",
".",
"ext",
"else",
":",
"egg_info",
",",
"ext",
"=",
"link",
".",
"splitext",
"(",
")",
"if",
"not",
"ext",
":",
"self",
".",
"_log_skipped_link",
"(",
"link",
",",
"'not a file'",
")",
"return",
"None",
"if",
"ext",
"not",
"in",
"SUPPORTED_EXTENSIONS",
":",
"self",
".",
"_log_skipped_link",
"(",
"link",
",",
"'unsupported archive format: %s'",
"%",
"ext",
",",
")",
"return",
"None",
"if",
"\"binary\"",
"not",
"in",
"search",
".",
"formats",
"and",
"ext",
"==",
"WHEEL_EXTENSION",
"and",
"not",
"ignore_compatibility",
":",
"self",
".",
"_log_skipped_link",
"(",
"link",
",",
"'No binaries permitted for %s'",
"%",
"search",
".",
"supplied",
",",
")",
"return",
"None",
"if",
"\"macosx10\"",
"in",
"link",
".",
"path",
"and",
"ext",
"==",
"'.zip'",
"and",
"not",
"ignore_compatibility",
":",
"self",
".",
"_log_skipped_link",
"(",
"link",
",",
"'macosx10 one'",
")",
"return",
"None",
"if",
"ext",
"==",
"WHEEL_EXTENSION",
":",
"try",
":",
"wheel",
"=",
"Wheel",
"(",
"link",
".",
"filename",
")",
"except",
"InvalidWheelFilename",
":",
"self",
".",
"_log_skipped_link",
"(",
"link",
",",
"'invalid wheel filename'",
")",
"return",
"None",
"if",
"canonicalize_name",
"(",
"wheel",
".",
"name",
")",
"!=",
"search",
".",
"canonical",
":",
"self",
".",
"_log_skipped_link",
"(",
"link",
",",
"'wrong project name (not %s)'",
"%",
"search",
".",
"supplied",
")",
"return",
"None",
"if",
"not",
"wheel",
".",
"supported",
"(",
"self",
".",
"valid_tags",
")",
"and",
"not",
"ignore_compatibility",
":",
"self",
".",
"_log_skipped_link",
"(",
"link",
",",
"'it is not compatible with this Python'",
")",
"return",
"None",
"version",
"=",
"wheel",
".",
"version",
"# This should be up by the search.ok_binary check, but see issue 2700.",
"if",
"\"source\"",
"not",
"in",
"search",
".",
"formats",
"and",
"ext",
"!=",
"WHEEL_EXTENSION",
":",
"self",
".",
"_log_skipped_link",
"(",
"link",
",",
"'No sources permitted for %s'",
"%",
"search",
".",
"supplied",
",",
")",
"return",
"None",
"if",
"not",
"version",
":",
"version",
"=",
"_egg_info_matches",
"(",
"egg_info",
",",
"search",
".",
"canonical",
")",
"if",
"not",
"version",
":",
"self",
".",
"_log_skipped_link",
"(",
"link",
",",
"'Missing project version for %s'",
"%",
"search",
".",
"supplied",
")",
"return",
"None",
"match",
"=",
"self",
".",
"_py_version_re",
".",
"search",
"(",
"version",
")",
"if",
"match",
":",
"version",
"=",
"version",
"[",
":",
"match",
".",
"start",
"(",
")",
"]",
"py_version",
"=",
"match",
".",
"group",
"(",
"1",
")",
"if",
"py_version",
"!=",
"sys",
".",
"version",
"[",
":",
"3",
"]",
":",
"self",
".",
"_log_skipped_link",
"(",
"link",
",",
"'Python version is incorrect'",
")",
"return",
"None",
"try",
":",
"support_this_python",
"=",
"check_requires_python",
"(",
"link",
".",
"requires_python",
")",
"except",
"specifiers",
".",
"InvalidSpecifier",
":",
"logger",
".",
"debug",
"(",
"\"Package %s has an invalid Requires-Python entry: %s\"",
",",
"link",
".",
"filename",
",",
"link",
".",
"requires_python",
")",
"support_this_python",
"=",
"True",
"if",
"not",
"support_this_python",
"and",
"not",
"ignore_compatibility",
":",
"logger",
".",
"debug",
"(",
"\"The package %s is incompatible with the python \"",
"\"version in use. Acceptable python versions are: %s\"",
",",
"link",
",",
"link",
".",
"requires_python",
")",
"return",
"None",
"logger",
".",
"debug",
"(",
"'Found link %s, version: %s'",
",",
"link",
",",
"version",
")",
"return",
"InstallationCandidate",
"(",
"search",
".",
"supplied",
",",
"version",
",",
"link",
",",
"link",
".",
"requires_python",
")"
] | Return an InstallationCandidate or None | [
"Return",
"an",
"InstallationCandidate",
"or",
"None"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/index.py#L814-L893 |
25,304 | pypa/pipenv | pipenv/vendor/pexpect/run.py | run | def run(command, timeout=30, withexitstatus=False, events=None,
extra_args=None, logfile=None, cwd=None, env=None, **kwargs):
'''
This function runs the given command; waits for it to finish; then
returns all output as a string. STDERR is included in output. If the full
path to the command is not given then the path is searched.
Note that lines are terminated by CR/LF (\\r\\n) combination even on
UNIX-like systems because this is the standard for pseudottys. If you set
'withexitstatus' to true, then run will return a tuple of (command_output,
exitstatus). If 'withexitstatus' is false then this returns just
command_output.
The run() function can often be used instead of creating a spawn instance.
For example, the following code uses spawn::
from pexpect import *
child = spawn('scp foo user@example.com:.')
child.expect('(?i)password')
child.sendline(mypassword)
The previous code can be replace with the following::
from pexpect import *
run('scp foo user@example.com:.', events={'(?i)password': mypassword})
**Examples**
Start the apache daemon on the local machine::
from pexpect import *
run("/usr/local/apache/bin/apachectl start")
Check in a file using SVN::
from pexpect import *
run("svn ci -m 'automatic commit' my_file.py")
Run a command and capture exit status::
from pexpect import *
(command_output, exitstatus) = run('ls -l /bin', withexitstatus=1)
The following will run SSH and execute 'ls -l' on the remote machine. The
password 'secret' will be sent if the '(?i)password' pattern is ever seen::
run("ssh username@machine.example.com 'ls -l'",
events={'(?i)password':'secret\\n'})
This will start mencoder to rip a video from DVD. This will also display
progress ticks every 5 seconds as it runs. For example::
from pexpect import *
def print_ticks(d):
print d['event_count'],
run("mencoder dvd://1 -o video.avi -oac copy -ovc copy",
events={TIMEOUT:print_ticks}, timeout=5)
The 'events' argument should be either a dictionary or a tuple list that
contains patterns and responses. Whenever one of the patterns is seen
in the command output, run() will send the associated response string.
So, run() in the above example can be also written as:
run("mencoder dvd://1 -o video.avi -oac copy -ovc copy",
events=[(TIMEOUT,print_ticks)], timeout=5)
Use a tuple list for events if the command output requires a delicate
control over what pattern should be matched, since the tuple list is passed
to pexpect() as its pattern list, with the order of patterns preserved.
Note that you should put newlines in your string if Enter is necessary.
Like the example above, the responses may also contain a callback, either
a function or method. It should accept a dictionary value as an argument.
The dictionary contains all the locals from the run() function, so you can
access the child spawn object or any other variable defined in run()
(event_count, child, and extra_args are the most useful). A callback may
return True to stop the current run process. Otherwise run() continues
until the next event. A callback may also return a string which will be
sent to the child. 'extra_args' is not used by directly run(). It provides
a way to pass data to a callback function through run() through the locals
dictionary passed to a callback.
Like :class:`spawn`, passing *encoding* will make it work with unicode
instead of bytes. You can pass *codec_errors* to control how errors in
encoding and decoding are handled.
'''
if timeout == -1:
child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env,
**kwargs)
else:
child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile,
cwd=cwd, env=env, **kwargs)
if isinstance(events, list):
patterns= [x for x,y in events]
responses = [y for x,y in events]
elif isinstance(events, dict):
patterns = list(events.keys())
responses = list(events.values())
else:
# This assumes EOF or TIMEOUT will eventually cause run to terminate.
patterns = None
responses = None
child_result_list = []
event_count = 0
while True:
try:
index = child.expect(patterns)
if isinstance(child.after, child.allowed_string_types):
child_result_list.append(child.before + child.after)
else:
# child.after may have been a TIMEOUT or EOF,
# which we don't want appended to the list.
child_result_list.append(child.before)
if isinstance(responses[index], child.allowed_string_types):
child.send(responses[index])
elif (isinstance(responses[index], types.FunctionType) or
isinstance(responses[index], types.MethodType)):
callback_result = responses[index](locals())
sys.stdout.flush()
if isinstance(callback_result, child.allowed_string_types):
child.send(callback_result)
elif callback_result:
break
else:
raise TypeError("parameter `event' at index {index} must be "
"a string, method, or function: {value!r}"
.format(index=index, value=responses[index]))
event_count = event_count + 1
except TIMEOUT:
child_result_list.append(child.before)
break
except EOF:
child_result_list.append(child.before)
break
child_result = child.string_type().join(child_result_list)
if withexitstatus:
child.close()
return (child_result, child.exitstatus)
else:
return child_result | python | def run(command, timeout=30, withexitstatus=False, events=None,
extra_args=None, logfile=None, cwd=None, env=None, **kwargs):
'''
This function runs the given command; waits for it to finish; then
returns all output as a string. STDERR is included in output. If the full
path to the command is not given then the path is searched.
Note that lines are terminated by CR/LF (\\r\\n) combination even on
UNIX-like systems because this is the standard for pseudottys. If you set
'withexitstatus' to true, then run will return a tuple of (command_output,
exitstatus). If 'withexitstatus' is false then this returns just
command_output.
The run() function can often be used instead of creating a spawn instance.
For example, the following code uses spawn::
from pexpect import *
child = spawn('scp foo user@example.com:.')
child.expect('(?i)password')
child.sendline(mypassword)
The previous code can be replace with the following::
from pexpect import *
run('scp foo user@example.com:.', events={'(?i)password': mypassword})
**Examples**
Start the apache daemon on the local machine::
from pexpect import *
run("/usr/local/apache/bin/apachectl start")
Check in a file using SVN::
from pexpect import *
run("svn ci -m 'automatic commit' my_file.py")
Run a command and capture exit status::
from pexpect import *
(command_output, exitstatus) = run('ls -l /bin', withexitstatus=1)
The following will run SSH and execute 'ls -l' on the remote machine. The
password 'secret' will be sent if the '(?i)password' pattern is ever seen::
run("ssh username@machine.example.com 'ls -l'",
events={'(?i)password':'secret\\n'})
This will start mencoder to rip a video from DVD. This will also display
progress ticks every 5 seconds as it runs. For example::
from pexpect import *
def print_ticks(d):
print d['event_count'],
run("mencoder dvd://1 -o video.avi -oac copy -ovc copy",
events={TIMEOUT:print_ticks}, timeout=5)
The 'events' argument should be either a dictionary or a tuple list that
contains patterns and responses. Whenever one of the patterns is seen
in the command output, run() will send the associated response string.
So, run() in the above example can be also written as:
run("mencoder dvd://1 -o video.avi -oac copy -ovc copy",
events=[(TIMEOUT,print_ticks)], timeout=5)
Use a tuple list for events if the command output requires a delicate
control over what pattern should be matched, since the tuple list is passed
to pexpect() as its pattern list, with the order of patterns preserved.
Note that you should put newlines in your string if Enter is necessary.
Like the example above, the responses may also contain a callback, either
a function or method. It should accept a dictionary value as an argument.
The dictionary contains all the locals from the run() function, so you can
access the child spawn object or any other variable defined in run()
(event_count, child, and extra_args are the most useful). A callback may
return True to stop the current run process. Otherwise run() continues
until the next event. A callback may also return a string which will be
sent to the child. 'extra_args' is not used by directly run(). It provides
a way to pass data to a callback function through run() through the locals
dictionary passed to a callback.
Like :class:`spawn`, passing *encoding* will make it work with unicode
instead of bytes. You can pass *codec_errors* to control how errors in
encoding and decoding are handled.
'''
if timeout == -1:
child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env,
**kwargs)
else:
child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile,
cwd=cwd, env=env, **kwargs)
if isinstance(events, list):
patterns= [x for x,y in events]
responses = [y for x,y in events]
elif isinstance(events, dict):
patterns = list(events.keys())
responses = list(events.values())
else:
# This assumes EOF or TIMEOUT will eventually cause run to terminate.
patterns = None
responses = None
child_result_list = []
event_count = 0
while True:
try:
index = child.expect(patterns)
if isinstance(child.after, child.allowed_string_types):
child_result_list.append(child.before + child.after)
else:
# child.after may have been a TIMEOUT or EOF,
# which we don't want appended to the list.
child_result_list.append(child.before)
if isinstance(responses[index], child.allowed_string_types):
child.send(responses[index])
elif (isinstance(responses[index], types.FunctionType) or
isinstance(responses[index], types.MethodType)):
callback_result = responses[index](locals())
sys.stdout.flush()
if isinstance(callback_result, child.allowed_string_types):
child.send(callback_result)
elif callback_result:
break
else:
raise TypeError("parameter `event' at index {index} must be "
"a string, method, or function: {value!r}"
.format(index=index, value=responses[index]))
event_count = event_count + 1
except TIMEOUT:
child_result_list.append(child.before)
break
except EOF:
child_result_list.append(child.before)
break
child_result = child.string_type().join(child_result_list)
if withexitstatus:
child.close()
return (child_result, child.exitstatus)
else:
return child_result | [
"def",
"run",
"(",
"command",
",",
"timeout",
"=",
"30",
",",
"withexitstatus",
"=",
"False",
",",
"events",
"=",
"None",
",",
"extra_args",
"=",
"None",
",",
"logfile",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"env",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"timeout",
"==",
"-",
"1",
":",
"child",
"=",
"spawn",
"(",
"command",
",",
"maxread",
"=",
"2000",
",",
"logfile",
"=",
"logfile",
",",
"cwd",
"=",
"cwd",
",",
"env",
"=",
"env",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"child",
"=",
"spawn",
"(",
"command",
",",
"timeout",
"=",
"timeout",
",",
"maxread",
"=",
"2000",
",",
"logfile",
"=",
"logfile",
",",
"cwd",
"=",
"cwd",
",",
"env",
"=",
"env",
",",
"*",
"*",
"kwargs",
")",
"if",
"isinstance",
"(",
"events",
",",
"list",
")",
":",
"patterns",
"=",
"[",
"x",
"for",
"x",
",",
"y",
"in",
"events",
"]",
"responses",
"=",
"[",
"y",
"for",
"x",
",",
"y",
"in",
"events",
"]",
"elif",
"isinstance",
"(",
"events",
",",
"dict",
")",
":",
"patterns",
"=",
"list",
"(",
"events",
".",
"keys",
"(",
")",
")",
"responses",
"=",
"list",
"(",
"events",
".",
"values",
"(",
")",
")",
"else",
":",
"# This assumes EOF or TIMEOUT will eventually cause run to terminate.",
"patterns",
"=",
"None",
"responses",
"=",
"None",
"child_result_list",
"=",
"[",
"]",
"event_count",
"=",
"0",
"while",
"True",
":",
"try",
":",
"index",
"=",
"child",
".",
"expect",
"(",
"patterns",
")",
"if",
"isinstance",
"(",
"child",
".",
"after",
",",
"child",
".",
"allowed_string_types",
")",
":",
"child_result_list",
".",
"append",
"(",
"child",
".",
"before",
"+",
"child",
".",
"after",
")",
"else",
":",
"# child.after may have been a TIMEOUT or EOF,",
"# which we don't want appended to the list.",
"child_result_list",
".",
"append",
"(",
"child",
".",
"before",
")",
"if",
"isinstance",
"(",
"responses",
"[",
"index",
"]",
",",
"child",
".",
"allowed_string_types",
")",
":",
"child",
".",
"send",
"(",
"responses",
"[",
"index",
"]",
")",
"elif",
"(",
"isinstance",
"(",
"responses",
"[",
"index",
"]",
",",
"types",
".",
"FunctionType",
")",
"or",
"isinstance",
"(",
"responses",
"[",
"index",
"]",
",",
"types",
".",
"MethodType",
")",
")",
":",
"callback_result",
"=",
"responses",
"[",
"index",
"]",
"(",
"locals",
"(",
")",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"if",
"isinstance",
"(",
"callback_result",
",",
"child",
".",
"allowed_string_types",
")",
":",
"child",
".",
"send",
"(",
"callback_result",
")",
"elif",
"callback_result",
":",
"break",
"else",
":",
"raise",
"TypeError",
"(",
"\"parameter `event' at index {index} must be \"",
"\"a string, method, or function: {value!r}\"",
".",
"format",
"(",
"index",
"=",
"index",
",",
"value",
"=",
"responses",
"[",
"index",
"]",
")",
")",
"event_count",
"=",
"event_count",
"+",
"1",
"except",
"TIMEOUT",
":",
"child_result_list",
".",
"append",
"(",
"child",
".",
"before",
")",
"break",
"except",
"EOF",
":",
"child_result_list",
".",
"append",
"(",
"child",
".",
"before",
")",
"break",
"child_result",
"=",
"child",
".",
"string_type",
"(",
")",
".",
"join",
"(",
"child_result_list",
")",
"if",
"withexitstatus",
":",
"child",
".",
"close",
"(",
")",
"return",
"(",
"child_result",
",",
"child",
".",
"exitstatus",
")",
"else",
":",
"return",
"child_result"
] | This function runs the given command; waits for it to finish; then
returns all output as a string. STDERR is included in output. If the full
path to the command is not given then the path is searched.
Note that lines are terminated by CR/LF (\\r\\n) combination even on
UNIX-like systems because this is the standard for pseudottys. If you set
'withexitstatus' to true, then run will return a tuple of (command_output,
exitstatus). If 'withexitstatus' is false then this returns just
command_output.
The run() function can often be used instead of creating a spawn instance.
For example, the following code uses spawn::
from pexpect import *
child = spawn('scp foo user@example.com:.')
child.expect('(?i)password')
child.sendline(mypassword)
The previous code can be replace with the following::
from pexpect import *
run('scp foo user@example.com:.', events={'(?i)password': mypassword})
**Examples**
Start the apache daemon on the local machine::
from pexpect import *
run("/usr/local/apache/bin/apachectl start")
Check in a file using SVN::
from pexpect import *
run("svn ci -m 'automatic commit' my_file.py")
Run a command and capture exit status::
from pexpect import *
(command_output, exitstatus) = run('ls -l /bin', withexitstatus=1)
The following will run SSH and execute 'ls -l' on the remote machine. The
password 'secret' will be sent if the '(?i)password' pattern is ever seen::
run("ssh username@machine.example.com 'ls -l'",
events={'(?i)password':'secret\\n'})
This will start mencoder to rip a video from DVD. This will also display
progress ticks every 5 seconds as it runs. For example::
from pexpect import *
def print_ticks(d):
print d['event_count'],
run("mencoder dvd://1 -o video.avi -oac copy -ovc copy",
events={TIMEOUT:print_ticks}, timeout=5)
The 'events' argument should be either a dictionary or a tuple list that
contains patterns and responses. Whenever one of the patterns is seen
in the command output, run() will send the associated response string.
So, run() in the above example can be also written as:
run("mencoder dvd://1 -o video.avi -oac copy -ovc copy",
events=[(TIMEOUT,print_ticks)], timeout=5)
Use a tuple list for events if the command output requires a delicate
control over what pattern should be matched, since the tuple list is passed
to pexpect() as its pattern list, with the order of patterns preserved.
Note that you should put newlines in your string if Enter is necessary.
Like the example above, the responses may also contain a callback, either
a function or method. It should accept a dictionary value as an argument.
The dictionary contains all the locals from the run() function, so you can
access the child spawn object or any other variable defined in run()
(event_count, child, and extra_args are the most useful). A callback may
return True to stop the current run process. Otherwise run() continues
until the next event. A callback may also return a string which will be
sent to the child. 'extra_args' is not used by directly run(). It provides
a way to pass data to a callback function through run() through the locals
dictionary passed to a callback.
Like :class:`spawn`, passing *encoding* will make it work with unicode
instead of bytes. You can pass *codec_errors* to control how errors in
encoding and decoding are handled. | [
"This",
"function",
"runs",
"the",
"given",
"command",
";",
"waits",
"for",
"it",
"to",
"finish",
";",
"then",
"returns",
"all",
"output",
"as",
"a",
"string",
".",
"STDERR",
"is",
"included",
"in",
"output",
".",
"If",
"the",
"full",
"path",
"to",
"the",
"command",
"is",
"not",
"given",
"then",
"the",
"path",
"is",
"searched",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/run.py#L7-L148 |
25,305 | pypa/pipenv | pipenv/vendor/requests/models.py | RequestHooksMixin.register_hook | def register_hook(self, event, hook):
"""Properly register a hook."""
if event not in self.hooks:
raise ValueError('Unsupported event specified, with event name "%s"' % (event))
if isinstance(hook, Callable):
self.hooks[event].append(hook)
elif hasattr(hook, '__iter__'):
self.hooks[event].extend(h for h in hook if isinstance(h, Callable)) | python | def register_hook(self, event, hook):
"""Properly register a hook."""
if event not in self.hooks:
raise ValueError('Unsupported event specified, with event name "%s"' % (event))
if isinstance(hook, Callable):
self.hooks[event].append(hook)
elif hasattr(hook, '__iter__'):
self.hooks[event].extend(h for h in hook if isinstance(h, Callable)) | [
"def",
"register_hook",
"(",
"self",
",",
"event",
",",
"hook",
")",
":",
"if",
"event",
"not",
"in",
"self",
".",
"hooks",
":",
"raise",
"ValueError",
"(",
"'Unsupported event specified, with event name \"%s\"'",
"%",
"(",
"event",
")",
")",
"if",
"isinstance",
"(",
"hook",
",",
"Callable",
")",
":",
"self",
".",
"hooks",
"[",
"event",
"]",
".",
"append",
"(",
"hook",
")",
"elif",
"hasattr",
"(",
"hook",
",",
"'__iter__'",
")",
":",
"self",
".",
"hooks",
"[",
"event",
"]",
".",
"extend",
"(",
"h",
"for",
"h",
"in",
"hook",
"if",
"isinstance",
"(",
"h",
",",
"Callable",
")",
")"
] | Properly register a hook. | [
"Properly",
"register",
"a",
"hook",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/models.py#L175-L184 |
25,306 | pypa/pipenv | pipenv/vendor/requests/models.py | RequestHooksMixin.deregister_hook | def deregister_hook(self, event, hook):
"""Deregister a previously registered hook.
Returns True if the hook existed, False if not.
"""
try:
self.hooks[event].remove(hook)
return True
except ValueError:
return False | python | def deregister_hook(self, event, hook):
"""Deregister a previously registered hook.
Returns True if the hook existed, False if not.
"""
try:
self.hooks[event].remove(hook)
return True
except ValueError:
return False | [
"def",
"deregister_hook",
"(",
"self",
",",
"event",
",",
"hook",
")",
":",
"try",
":",
"self",
".",
"hooks",
"[",
"event",
"]",
".",
"remove",
"(",
"hook",
")",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False"
] | Deregister a previously registered hook.
Returns True if the hook existed, False if not. | [
"Deregister",
"a",
"previously",
"registered",
"hook",
".",
"Returns",
"True",
"if",
"the",
"hook",
"existed",
"False",
"if",
"not",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/models.py#L186-L195 |
25,307 | pypa/pipenv | pipenv/vendor/requests/models.py | PreparedRequest.prepare | def prepare(self,
method=None, url=None, headers=None, files=None, data=None,
params=None, auth=None, cookies=None, hooks=None, json=None):
"""Prepares the entire request with the given parameters."""
self.prepare_method(method)
self.prepare_url(url, params)
self.prepare_headers(headers)
self.prepare_cookies(cookies)
self.prepare_body(data, files, json)
self.prepare_auth(auth, url)
# Note that prepare_auth must be last to enable authentication schemes
# such as OAuth to work on a fully prepared request.
# This MUST go after prepare_auth. Authenticators could add a hook
self.prepare_hooks(hooks) | python | def prepare(self,
method=None, url=None, headers=None, files=None, data=None,
params=None, auth=None, cookies=None, hooks=None, json=None):
"""Prepares the entire request with the given parameters."""
self.prepare_method(method)
self.prepare_url(url, params)
self.prepare_headers(headers)
self.prepare_cookies(cookies)
self.prepare_body(data, files, json)
self.prepare_auth(auth, url)
# Note that prepare_auth must be last to enable authentication schemes
# such as OAuth to work on a fully prepared request.
# This MUST go after prepare_auth. Authenticators could add a hook
self.prepare_hooks(hooks) | [
"def",
"prepare",
"(",
"self",
",",
"method",
"=",
"None",
",",
"url",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"files",
"=",
"None",
",",
"data",
"=",
"None",
",",
"params",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"cookies",
"=",
"None",
",",
"hooks",
"=",
"None",
",",
"json",
"=",
"None",
")",
":",
"self",
".",
"prepare_method",
"(",
"method",
")",
"self",
".",
"prepare_url",
"(",
"url",
",",
"params",
")",
"self",
".",
"prepare_headers",
"(",
"headers",
")",
"self",
".",
"prepare_cookies",
"(",
"cookies",
")",
"self",
".",
"prepare_body",
"(",
"data",
",",
"files",
",",
"json",
")",
"self",
".",
"prepare_auth",
"(",
"auth",
",",
"url",
")",
"# Note that prepare_auth must be last to enable authentication schemes",
"# such as OAuth to work on a fully prepared request.",
"# This MUST go after prepare_auth. Authenticators could add a hook",
"self",
".",
"prepare_hooks",
"(",
"hooks",
")"
] | Prepares the entire request with the given parameters. | [
"Prepares",
"the",
"entire",
"request",
"with",
"the",
"given",
"parameters",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/models.py#L307-L323 |
25,308 | pypa/pipenv | pipenv/vendor/requests/models.py | PreparedRequest.prepare_content_length | def prepare_content_length(self, body):
"""Prepare Content-Length header based on request method and body"""
if body is not None:
length = super_len(body)
if length:
# If length exists, set it. Otherwise, we fallback
# to Transfer-Encoding: chunked.
self.headers['Content-Length'] = builtin_str(length)
elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None:
# Set Content-Length to 0 for methods that can have a body
# but don't provide one. (i.e. not GET or HEAD)
self.headers['Content-Length'] = '0' | python | def prepare_content_length(self, body):
"""Prepare Content-Length header based on request method and body"""
if body is not None:
length = super_len(body)
if length:
# If length exists, set it. Otherwise, we fallback
# to Transfer-Encoding: chunked.
self.headers['Content-Length'] = builtin_str(length)
elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None:
# Set Content-Length to 0 for methods that can have a body
# but don't provide one. (i.e. not GET or HEAD)
self.headers['Content-Length'] = '0' | [
"def",
"prepare_content_length",
"(",
"self",
",",
"body",
")",
":",
"if",
"body",
"is",
"not",
"None",
":",
"length",
"=",
"super_len",
"(",
"body",
")",
"if",
"length",
":",
"# If length exists, set it. Otherwise, we fallback",
"# to Transfer-Encoding: chunked.",
"self",
".",
"headers",
"[",
"'Content-Length'",
"]",
"=",
"builtin_str",
"(",
"length",
")",
"elif",
"self",
".",
"method",
"not",
"in",
"(",
"'GET'",
",",
"'HEAD'",
")",
"and",
"self",
".",
"headers",
".",
"get",
"(",
"'Content-Length'",
")",
"is",
"None",
":",
"# Set Content-Length to 0 for methods that can have a body",
"# but don't provide one. (i.e. not GET or HEAD)",
"self",
".",
"headers",
"[",
"'Content-Length'",
"]",
"=",
"'0'"
] | Prepare Content-Length header based on request method and body | [
"Prepare",
"Content",
"-",
"Length",
"header",
"based",
"on",
"request",
"method",
"and",
"body"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/models.py#L521-L532 |
25,309 | pypa/pipenv | pipenv/vendor/requests/models.py | PreparedRequest.prepare_auth | def prepare_auth(self, auth, url=''):
"""Prepares the given HTTP auth data."""
# If no Auth is explicitly provided, extract it from the URL first.
if auth is None:
url_auth = get_auth_from_url(self.url)
auth = url_auth if any(url_auth) else None
if auth:
if isinstance(auth, tuple) and len(auth) == 2:
# special-case basic HTTP auth
auth = HTTPBasicAuth(*auth)
# Allow auth to make its changes.
r = auth(self)
# Update self to reflect the auth changes.
self.__dict__.update(r.__dict__)
# Recompute Content-Length
self.prepare_content_length(self.body) | python | def prepare_auth(self, auth, url=''):
"""Prepares the given HTTP auth data."""
# If no Auth is explicitly provided, extract it from the URL first.
if auth is None:
url_auth = get_auth_from_url(self.url)
auth = url_auth if any(url_auth) else None
if auth:
if isinstance(auth, tuple) and len(auth) == 2:
# special-case basic HTTP auth
auth = HTTPBasicAuth(*auth)
# Allow auth to make its changes.
r = auth(self)
# Update self to reflect the auth changes.
self.__dict__.update(r.__dict__)
# Recompute Content-Length
self.prepare_content_length(self.body) | [
"def",
"prepare_auth",
"(",
"self",
",",
"auth",
",",
"url",
"=",
"''",
")",
":",
"# If no Auth is explicitly provided, extract it from the URL first.",
"if",
"auth",
"is",
"None",
":",
"url_auth",
"=",
"get_auth_from_url",
"(",
"self",
".",
"url",
")",
"auth",
"=",
"url_auth",
"if",
"any",
"(",
"url_auth",
")",
"else",
"None",
"if",
"auth",
":",
"if",
"isinstance",
"(",
"auth",
",",
"tuple",
")",
"and",
"len",
"(",
"auth",
")",
"==",
"2",
":",
"# special-case basic HTTP auth",
"auth",
"=",
"HTTPBasicAuth",
"(",
"*",
"auth",
")",
"# Allow auth to make its changes.",
"r",
"=",
"auth",
"(",
"self",
")",
"# Update self to reflect the auth changes.",
"self",
".",
"__dict__",
".",
"update",
"(",
"r",
".",
"__dict__",
")",
"# Recompute Content-Length",
"self",
".",
"prepare_content_length",
"(",
"self",
".",
"body",
")"
] | Prepares the given HTTP auth data. | [
"Prepares",
"the",
"given",
"HTTP",
"auth",
"data",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/models.py#L534-L554 |
25,310 | pypa/pipenv | pipenv/vendor/requests/models.py | PreparedRequest.prepare_cookies | def prepare_cookies(self, cookies):
"""Prepares the given HTTP cookie data.
This function eventually generates a ``Cookie`` header from the
given cookies using cookielib. Due to cookielib's design, the header
will not be regenerated if it already exists, meaning this function
can only be called once for the life of the
:class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls
to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
header is removed beforehand.
"""
if isinstance(cookies, cookielib.CookieJar):
self._cookies = cookies
else:
self._cookies = cookiejar_from_dict(cookies)
cookie_header = get_cookie_header(self._cookies, self)
if cookie_header is not None:
self.headers['Cookie'] = cookie_header | python | def prepare_cookies(self, cookies):
"""Prepares the given HTTP cookie data.
This function eventually generates a ``Cookie`` header from the
given cookies using cookielib. Due to cookielib's design, the header
will not be regenerated if it already exists, meaning this function
can only be called once for the life of the
:class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls
to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
header is removed beforehand.
"""
if isinstance(cookies, cookielib.CookieJar):
self._cookies = cookies
else:
self._cookies = cookiejar_from_dict(cookies)
cookie_header = get_cookie_header(self._cookies, self)
if cookie_header is not None:
self.headers['Cookie'] = cookie_header | [
"def",
"prepare_cookies",
"(",
"self",
",",
"cookies",
")",
":",
"if",
"isinstance",
"(",
"cookies",
",",
"cookielib",
".",
"CookieJar",
")",
":",
"self",
".",
"_cookies",
"=",
"cookies",
"else",
":",
"self",
".",
"_cookies",
"=",
"cookiejar_from_dict",
"(",
"cookies",
")",
"cookie_header",
"=",
"get_cookie_header",
"(",
"self",
".",
"_cookies",
",",
"self",
")",
"if",
"cookie_header",
"is",
"not",
"None",
":",
"self",
".",
"headers",
"[",
"'Cookie'",
"]",
"=",
"cookie_header"
] | Prepares the given HTTP cookie data.
This function eventually generates a ``Cookie`` header from the
given cookies using cookielib. Due to cookielib's design, the header
will not be regenerated if it already exists, meaning this function
can only be called once for the life of the
:class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls
to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
header is removed beforehand. | [
"Prepares",
"the",
"given",
"HTTP",
"cookie",
"data",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/models.py#L556-L574 |
25,311 | pypa/pipenv | pipenv/vendor/requests/models.py | PreparedRequest.prepare_hooks | def prepare_hooks(self, hooks):
"""Prepares the given hooks."""
# hooks can be passed as None to the prepare method and to this
# method. To prevent iterating over None, simply use an empty list
# if hooks is False-y
hooks = hooks or []
for event in hooks:
self.register_hook(event, hooks[event]) | python | def prepare_hooks(self, hooks):
"""Prepares the given hooks."""
# hooks can be passed as None to the prepare method and to this
# method. To prevent iterating over None, simply use an empty list
# if hooks is False-y
hooks = hooks or []
for event in hooks:
self.register_hook(event, hooks[event]) | [
"def",
"prepare_hooks",
"(",
"self",
",",
"hooks",
")",
":",
"# hooks can be passed as None to the prepare method and to this",
"# method. To prevent iterating over None, simply use an empty list",
"# if hooks is False-y",
"hooks",
"=",
"hooks",
"or",
"[",
"]",
"for",
"event",
"in",
"hooks",
":",
"self",
".",
"register_hook",
"(",
"event",
",",
"hooks",
"[",
"event",
"]",
")"
] | Prepares the given hooks. | [
"Prepares",
"the",
"given",
"hooks",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/models.py#L576-L583 |
25,312 | pypa/pipenv | pipenv/vendor/requests/models.py | Response.is_permanent_redirect | def is_permanent_redirect(self):
"""True if this Response one of the permanent versions of redirect."""
return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect)) | python | def is_permanent_redirect(self):
"""True if this Response one of the permanent versions of redirect."""
return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect)) | [
"def",
"is_permanent_redirect",
"(",
"self",
")",
":",
"return",
"(",
"'location'",
"in",
"self",
".",
"headers",
"and",
"self",
".",
"status_code",
"in",
"(",
"codes",
".",
"moved_permanently",
",",
"codes",
".",
"permanent_redirect",
")",
")"
] | True if this Response one of the permanent versions of redirect. | [
"True",
"if",
"this",
"Response",
"one",
"of",
"the",
"permanent",
"versions",
"of",
"redirect",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/models.py#L715-L717 |
25,313 | pypa/pipenv | pipenv/vendor/requests/models.py | Response.close | def close(self):
"""Releases the connection back to the pool. Once this method has been
called the underlying ``raw`` object must not be accessed again.
*Note: Should not normally need to be called explicitly.*
"""
if not self._content_consumed:
self.raw.close()
release_conn = getattr(self.raw, 'release_conn', None)
if release_conn is not None:
release_conn() | python | def close(self):
"""Releases the connection back to the pool. Once this method has been
called the underlying ``raw`` object must not be accessed again.
*Note: Should not normally need to be called explicitly.*
"""
if not self._content_consumed:
self.raw.close()
release_conn = getattr(self.raw, 'release_conn', None)
if release_conn is not None:
release_conn() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_content_consumed",
":",
"self",
".",
"raw",
".",
"close",
"(",
")",
"release_conn",
"=",
"getattr",
"(",
"self",
".",
"raw",
",",
"'release_conn'",
",",
"None",
")",
"if",
"release_conn",
"is",
"not",
"None",
":",
"release_conn",
"(",
")"
] | Releases the connection back to the pool. Once this method has been
called the underlying ``raw`` object must not be accessed again.
*Note: Should not normally need to be called explicitly.* | [
"Releases",
"the",
"connection",
"back",
"to",
"the",
"pool",
".",
"Once",
"this",
"method",
"has",
"been",
"called",
"the",
"underlying",
"raw",
"object",
"must",
"not",
"be",
"accessed",
"again",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/models.py#L942-L953 |
25,314 | pypa/pipenv | pipenv/patched/notpip/_internal/commands/install.py | create_env_error_message | def create_env_error_message(error, show_traceback, using_user_site):
"""Format an error message for an EnvironmentError
It may occur anytime during the execution of the install command.
"""
parts = []
# Mention the error if we are not going to show a traceback
parts.append("Could not install packages due to an EnvironmentError")
if not show_traceback:
parts.append(": ")
parts.append(str(error))
else:
parts.append(".")
# Spilt the error indication from a helper message (if any)
parts[-1] += "\n"
# Suggest useful actions to the user:
# (1) using user site-packages or (2) verifying the permissions
if error.errno == errno.EACCES:
user_option_part = "Consider using the `--user` option"
permissions_part = "Check the permissions"
if not using_user_site:
parts.extend([
user_option_part, " or ",
permissions_part.lower(),
])
else:
parts.append(permissions_part)
parts.append(".\n")
return "".join(parts).strip() + "\n" | python | def create_env_error_message(error, show_traceback, using_user_site):
"""Format an error message for an EnvironmentError
It may occur anytime during the execution of the install command.
"""
parts = []
# Mention the error if we are not going to show a traceback
parts.append("Could not install packages due to an EnvironmentError")
if not show_traceback:
parts.append(": ")
parts.append(str(error))
else:
parts.append(".")
# Spilt the error indication from a helper message (if any)
parts[-1] += "\n"
# Suggest useful actions to the user:
# (1) using user site-packages or (2) verifying the permissions
if error.errno == errno.EACCES:
user_option_part = "Consider using the `--user` option"
permissions_part = "Check the permissions"
if not using_user_site:
parts.extend([
user_option_part, " or ",
permissions_part.lower(),
])
else:
parts.append(permissions_part)
parts.append(".\n")
return "".join(parts).strip() + "\n" | [
"def",
"create_env_error_message",
"(",
"error",
",",
"show_traceback",
",",
"using_user_site",
")",
":",
"parts",
"=",
"[",
"]",
"# Mention the error if we are not going to show a traceback",
"parts",
".",
"append",
"(",
"\"Could not install packages due to an EnvironmentError\"",
")",
"if",
"not",
"show_traceback",
":",
"parts",
".",
"append",
"(",
"\": \"",
")",
"parts",
".",
"append",
"(",
"str",
"(",
"error",
")",
")",
"else",
":",
"parts",
".",
"append",
"(",
"\".\"",
")",
"# Spilt the error indication from a helper message (if any)",
"parts",
"[",
"-",
"1",
"]",
"+=",
"\"\\n\"",
"# Suggest useful actions to the user:",
"# (1) using user site-packages or (2) verifying the permissions",
"if",
"error",
".",
"errno",
"==",
"errno",
".",
"EACCES",
":",
"user_option_part",
"=",
"\"Consider using the `--user` option\"",
"permissions_part",
"=",
"\"Check the permissions\"",
"if",
"not",
"using_user_site",
":",
"parts",
".",
"extend",
"(",
"[",
"user_option_part",
",",
"\" or \"",
",",
"permissions_part",
".",
"lower",
"(",
")",
",",
"]",
")",
"else",
":",
"parts",
".",
"append",
"(",
"permissions_part",
")",
"parts",
".",
"append",
"(",
"\".\\n\"",
")",
"return",
"\"\"",
".",
"join",
"(",
"parts",
")",
".",
"strip",
"(",
")",
"+",
"\"\\n\""
] | Format an error message for an EnvironmentError
It may occur anytime during the execution of the install command. | [
"Format",
"an",
"error",
"message",
"for",
"an",
"EnvironmentError"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/commands/install.py#L533-L566 |
25,315 | pypa/pipenv | pipenv/vendor/urllib3/connectionpool.py | HTTPConnectionPool._raise_timeout | def _raise_timeout(self, err, url, timeout_value):
"""Is the error actually a timeout? Will raise a ReadTimeout or pass"""
if isinstance(err, SocketTimeout):
raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
# See the above comment about EAGAIN in Python 3. In Python 2 we have
# to specifically catch it and throw the timeout error
if hasattr(err, 'errno') and err.errno in _blocking_errnos:
raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
# Catch possible read timeouts thrown as SSL errors. If not the
# case, rethrow the original. We need to do this because of:
# http://bugs.python.org/issue10272
if 'timed out' in str(err) or 'did not complete (read)' in str(err): # Python < 2.7.4
raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) | python | def _raise_timeout(self, err, url, timeout_value):
"""Is the error actually a timeout? Will raise a ReadTimeout or pass"""
if isinstance(err, SocketTimeout):
raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
# See the above comment about EAGAIN in Python 3. In Python 2 we have
# to specifically catch it and throw the timeout error
if hasattr(err, 'errno') and err.errno in _blocking_errnos:
raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
# Catch possible read timeouts thrown as SSL errors. If not the
# case, rethrow the original. We need to do this because of:
# http://bugs.python.org/issue10272
if 'timed out' in str(err) or 'did not complete (read)' in str(err): # Python < 2.7.4
raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) | [
"def",
"_raise_timeout",
"(",
"self",
",",
"err",
",",
"url",
",",
"timeout_value",
")",
":",
"if",
"isinstance",
"(",
"err",
",",
"SocketTimeout",
")",
":",
"raise",
"ReadTimeoutError",
"(",
"self",
",",
"url",
",",
"\"Read timed out. (read timeout=%s)\"",
"%",
"timeout_value",
")",
"# See the above comment about EAGAIN in Python 3. In Python 2 we have",
"# to specifically catch it and throw the timeout error",
"if",
"hasattr",
"(",
"err",
",",
"'errno'",
")",
"and",
"err",
".",
"errno",
"in",
"_blocking_errnos",
":",
"raise",
"ReadTimeoutError",
"(",
"self",
",",
"url",
",",
"\"Read timed out. (read timeout=%s)\"",
"%",
"timeout_value",
")",
"# Catch possible read timeouts thrown as SSL errors. If not the",
"# case, rethrow the original. We need to do this because of:",
"# http://bugs.python.org/issue10272",
"if",
"'timed out'",
"in",
"str",
"(",
"err",
")",
"or",
"'did not complete (read)'",
"in",
"str",
"(",
"err",
")",
":",
"# Python < 2.7.4",
"raise",
"ReadTimeoutError",
"(",
"self",
",",
"url",
",",
"\"Read timed out. (read timeout=%s)\"",
"%",
"timeout_value",
")"
] | Is the error actually a timeout? Will raise a ReadTimeout or pass | [
"Is",
"the",
"error",
"actually",
"a",
"timeout?",
"Will",
"raise",
"a",
"ReadTimeout",
"or",
"pass"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/connectionpool.py#L302-L317 |
25,316 | pypa/pipenv | pipenv/vendor/pythonfinder/pythonfinder.py | Finder.reload_system_path | def reload_system_path(self):
# type: () -> None
"""
Rebuilds the base system path and all of the contained finders within it.
This will re-apply any changes to the environment or any version changes on the system.
"""
if self._system_path is not None:
self._system_path.clear_caches()
self._system_path = None
six.moves.reload_module(pyfinder_path)
self._system_path = self.create_system_path() | python | def reload_system_path(self):
# type: () -> None
"""
Rebuilds the base system path and all of the contained finders within it.
This will re-apply any changes to the environment or any version changes on the system.
"""
if self._system_path is not None:
self._system_path.clear_caches()
self._system_path = None
six.moves.reload_module(pyfinder_path)
self._system_path = self.create_system_path() | [
"def",
"reload_system_path",
"(",
"self",
")",
":",
"# type: () -> None",
"if",
"self",
".",
"_system_path",
"is",
"not",
"None",
":",
"self",
".",
"_system_path",
".",
"clear_caches",
"(",
")",
"self",
".",
"_system_path",
"=",
"None",
"six",
".",
"moves",
".",
"reload_module",
"(",
"pyfinder_path",
")",
"self",
".",
"_system_path",
"=",
"self",
".",
"create_system_path",
"(",
")"
] | Rebuilds the base system path and all of the contained finders within it.
This will re-apply any changes to the environment or any version changes on the system. | [
"Rebuilds",
"the",
"base",
"system",
"path",
"and",
"all",
"of",
"the",
"contained",
"finders",
"within",
"it",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pythonfinder/pythonfinder.py#L78-L90 |
25,317 | pypa/pipenv | pipenv/vendor/backports/enum/__init__.py | _convert | def _convert(cls, name, module, filter, source=None):
"""
Create a new Enum subclass that replaces a collection of global constants
"""
# convert all constants from source (or module) that pass filter() to
# a new Enum called name, and export the enum and its members back to
# module;
# also, replace the __reduce_ex__ method so unpickling works in
# previous Python versions
module_globals = vars(_sys.modules[module])
if source:
source = vars(source)
else:
source = module_globals
members = dict((name, value) for name, value in source.items() if filter(name))
cls = cls(name, members, module=module)
cls.__reduce_ex__ = _reduce_ex_by_name
module_globals.update(cls.__members__)
module_globals[name] = cls
return cls | python | def _convert(cls, name, module, filter, source=None):
"""
Create a new Enum subclass that replaces a collection of global constants
"""
# convert all constants from source (or module) that pass filter() to
# a new Enum called name, and export the enum and its members back to
# module;
# also, replace the __reduce_ex__ method so unpickling works in
# previous Python versions
module_globals = vars(_sys.modules[module])
if source:
source = vars(source)
else:
source = module_globals
members = dict((name, value) for name, value in source.items() if filter(name))
cls = cls(name, members, module=module)
cls.__reduce_ex__ = _reduce_ex_by_name
module_globals.update(cls.__members__)
module_globals[name] = cls
return cls | [
"def",
"_convert",
"(",
"cls",
",",
"name",
",",
"module",
",",
"filter",
",",
"source",
"=",
"None",
")",
":",
"# convert all constants from source (or module) that pass filter() to",
"# a new Enum called name, and export the enum and its members back to",
"# module;",
"# also, replace the __reduce_ex__ method so unpickling works in",
"# previous Python versions",
"module_globals",
"=",
"vars",
"(",
"_sys",
".",
"modules",
"[",
"module",
"]",
")",
"if",
"source",
":",
"source",
"=",
"vars",
"(",
"source",
")",
"else",
":",
"source",
"=",
"module_globals",
"members",
"=",
"dict",
"(",
"(",
"name",
",",
"value",
")",
"for",
"name",
",",
"value",
"in",
"source",
".",
"items",
"(",
")",
"if",
"filter",
"(",
"name",
")",
")",
"cls",
"=",
"cls",
"(",
"name",
",",
"members",
",",
"module",
"=",
"module",
")",
"cls",
".",
"__reduce_ex__",
"=",
"_reduce_ex_by_name",
"module_globals",
".",
"update",
"(",
"cls",
".",
"__members__",
")",
"module_globals",
"[",
"name",
"]",
"=",
"cls",
"return",
"cls"
] | Create a new Enum subclass that replaces a collection of global constants | [
"Create",
"a",
"new",
"Enum",
"subclass",
"that",
"replaces",
"a",
"collection",
"of",
"global",
"constants"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/backports/enum/__init__.py#L789-L808 |
25,318 | pypa/pipenv | pipenv/vendor/backports/enum/__init__.py | unique | def unique(enumeration):
"""Class decorator that ensures only unique members exist in an enumeration."""
duplicates = []
for name, member in enumeration.__members__.items():
if name != member.name:
duplicates.append((name, member.name))
if duplicates:
duplicate_names = ', '.join(
["%s -> %s" % (alias, name) for (alias, name) in duplicates]
)
raise ValueError('duplicate names found in %r: %s' %
(enumeration, duplicate_names)
)
return enumeration | python | def unique(enumeration):
"""Class decorator that ensures only unique members exist in an enumeration."""
duplicates = []
for name, member in enumeration.__members__.items():
if name != member.name:
duplicates.append((name, member.name))
if duplicates:
duplicate_names = ', '.join(
["%s -> %s" % (alias, name) for (alias, name) in duplicates]
)
raise ValueError('duplicate names found in %r: %s' %
(enumeration, duplicate_names)
)
return enumeration | [
"def",
"unique",
"(",
"enumeration",
")",
":",
"duplicates",
"=",
"[",
"]",
"for",
"name",
",",
"member",
"in",
"enumeration",
".",
"__members__",
".",
"items",
"(",
")",
":",
"if",
"name",
"!=",
"member",
".",
"name",
":",
"duplicates",
".",
"append",
"(",
"(",
"name",
",",
"member",
".",
"name",
")",
")",
"if",
"duplicates",
":",
"duplicate_names",
"=",
"', '",
".",
"join",
"(",
"[",
"\"%s -> %s\"",
"%",
"(",
"alias",
",",
"name",
")",
"for",
"(",
"alias",
",",
"name",
")",
"in",
"duplicates",
"]",
")",
"raise",
"ValueError",
"(",
"'duplicate names found in %r: %s'",
"%",
"(",
"enumeration",
",",
"duplicate_names",
")",
")",
"return",
"enumeration"
] | Class decorator that ensures only unique members exist in an enumeration. | [
"Class",
"decorator",
"that",
"ensures",
"only",
"unique",
"members",
"exist",
"in",
"an",
"enumeration",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/backports/enum/__init__.py#L824-L837 |
25,319 | pypa/pipenv | pipenv/vendor/backports/enum/__init__.py | EnumMeta._create_ | def _create_(cls, class_name, names=None, module=None, type=None, start=1):
"""Convenience method to create a new Enum class.
`names` can be:
* A string containing member names, separated either with spaces or
commas. Values are auto-numbered from 1.
* An iterable of member names. Values are auto-numbered from 1.
* An iterable of (member name, value) pairs.
* A mapping of member name -> value.
"""
if pyver < 3.0:
# if class_name is unicode, attempt a conversion to ASCII
if isinstance(class_name, unicode):
try:
class_name = class_name.encode('ascii')
except UnicodeEncodeError:
raise TypeError('%r is not representable in ASCII' % class_name)
metacls = cls.__class__
if type is None:
bases = (cls, )
else:
bases = (type, cls)
classdict = metacls.__prepare__(class_name, bases)
_order_ = []
# special processing needed for names?
if isinstance(names, basestring):
names = names.replace(',', ' ').split()
if isinstance(names, (tuple, list)) and isinstance(names[0], basestring):
names = [(e, i+start) for (i, e) in enumerate(names)]
# Here, names is either an iterable of (name, value) or a mapping.
item = None # in case names is empty
for item in names:
if isinstance(item, basestring):
member_name, member_value = item, names[item]
else:
member_name, member_value = item
classdict[member_name] = member_value
_order_.append(member_name)
# only set _order_ in classdict if name/value was not from a mapping
if not isinstance(item, basestring):
classdict['_order_'] = ' '.join(_order_)
enum_class = metacls.__new__(metacls, class_name, bases, classdict)
# TODO: replace the frame hack if a blessed way to know the calling
# module is ever developed
if module is None:
try:
module = _sys._getframe(2).f_globals['__name__']
except (AttributeError, ValueError):
pass
if module is None:
_make_class_unpicklable(enum_class)
else:
enum_class.__module__ = module
return enum_class | python | def _create_(cls, class_name, names=None, module=None, type=None, start=1):
"""Convenience method to create a new Enum class.
`names` can be:
* A string containing member names, separated either with spaces or
commas. Values are auto-numbered from 1.
* An iterable of member names. Values are auto-numbered from 1.
* An iterable of (member name, value) pairs.
* A mapping of member name -> value.
"""
if pyver < 3.0:
# if class_name is unicode, attempt a conversion to ASCII
if isinstance(class_name, unicode):
try:
class_name = class_name.encode('ascii')
except UnicodeEncodeError:
raise TypeError('%r is not representable in ASCII' % class_name)
metacls = cls.__class__
if type is None:
bases = (cls, )
else:
bases = (type, cls)
classdict = metacls.__prepare__(class_name, bases)
_order_ = []
# special processing needed for names?
if isinstance(names, basestring):
names = names.replace(',', ' ').split()
if isinstance(names, (tuple, list)) and isinstance(names[0], basestring):
names = [(e, i+start) for (i, e) in enumerate(names)]
# Here, names is either an iterable of (name, value) or a mapping.
item = None # in case names is empty
for item in names:
if isinstance(item, basestring):
member_name, member_value = item, names[item]
else:
member_name, member_value = item
classdict[member_name] = member_value
_order_.append(member_name)
# only set _order_ in classdict if name/value was not from a mapping
if not isinstance(item, basestring):
classdict['_order_'] = ' '.join(_order_)
enum_class = metacls.__new__(metacls, class_name, bases, classdict)
# TODO: replace the frame hack if a blessed way to know the calling
# module is ever developed
if module is None:
try:
module = _sys._getframe(2).f_globals['__name__']
except (AttributeError, ValueError):
pass
if module is None:
_make_class_unpicklable(enum_class)
else:
enum_class.__module__ = module
return enum_class | [
"def",
"_create_",
"(",
"cls",
",",
"class_name",
",",
"names",
"=",
"None",
",",
"module",
"=",
"None",
",",
"type",
"=",
"None",
",",
"start",
"=",
"1",
")",
":",
"if",
"pyver",
"<",
"3.0",
":",
"# if class_name is unicode, attempt a conversion to ASCII",
"if",
"isinstance",
"(",
"class_name",
",",
"unicode",
")",
":",
"try",
":",
"class_name",
"=",
"class_name",
".",
"encode",
"(",
"'ascii'",
")",
"except",
"UnicodeEncodeError",
":",
"raise",
"TypeError",
"(",
"'%r is not representable in ASCII'",
"%",
"class_name",
")",
"metacls",
"=",
"cls",
".",
"__class__",
"if",
"type",
"is",
"None",
":",
"bases",
"=",
"(",
"cls",
",",
")",
"else",
":",
"bases",
"=",
"(",
"type",
",",
"cls",
")",
"classdict",
"=",
"metacls",
".",
"__prepare__",
"(",
"class_name",
",",
"bases",
")",
"_order_",
"=",
"[",
"]",
"# special processing needed for names?",
"if",
"isinstance",
"(",
"names",
",",
"basestring",
")",
":",
"names",
"=",
"names",
".",
"replace",
"(",
"','",
",",
"' '",
")",
".",
"split",
"(",
")",
"if",
"isinstance",
"(",
"names",
",",
"(",
"tuple",
",",
"list",
")",
")",
"and",
"isinstance",
"(",
"names",
"[",
"0",
"]",
",",
"basestring",
")",
":",
"names",
"=",
"[",
"(",
"e",
",",
"i",
"+",
"start",
")",
"for",
"(",
"i",
",",
"e",
")",
"in",
"enumerate",
"(",
"names",
")",
"]",
"# Here, names is either an iterable of (name, value) or a mapping.",
"item",
"=",
"None",
"# in case names is empty",
"for",
"item",
"in",
"names",
":",
"if",
"isinstance",
"(",
"item",
",",
"basestring",
")",
":",
"member_name",
",",
"member_value",
"=",
"item",
",",
"names",
"[",
"item",
"]",
"else",
":",
"member_name",
",",
"member_value",
"=",
"item",
"classdict",
"[",
"member_name",
"]",
"=",
"member_value",
"_order_",
".",
"append",
"(",
"member_name",
")",
"# only set _order_ in classdict if name/value was not from a mapping",
"if",
"not",
"isinstance",
"(",
"item",
",",
"basestring",
")",
":",
"classdict",
"[",
"'_order_'",
"]",
"=",
"' '",
".",
"join",
"(",
"_order_",
")",
"enum_class",
"=",
"metacls",
".",
"__new__",
"(",
"metacls",
",",
"class_name",
",",
"bases",
",",
"classdict",
")",
"# TODO: replace the frame hack if a blessed way to know the calling",
"# module is ever developed",
"if",
"module",
"is",
"None",
":",
"try",
":",
"module",
"=",
"_sys",
".",
"_getframe",
"(",
"2",
")",
".",
"f_globals",
"[",
"'__name__'",
"]",
"except",
"(",
"AttributeError",
",",
"ValueError",
")",
":",
"pass",
"if",
"module",
"is",
"None",
":",
"_make_class_unpicklable",
"(",
"enum_class",
")",
"else",
":",
"enum_class",
".",
"__module__",
"=",
"module",
"return",
"enum_class"
] | Convenience method to create a new Enum class.
`names` can be:
* A string containing member names, separated either with spaces or
commas. Values are auto-numbered from 1.
* An iterable of member names. Values are auto-numbered from 1.
* An iterable of (member name, value) pairs.
* A mapping of member name -> value. | [
"Convenience",
"method",
"to",
"create",
"a",
"new",
"Enum",
"class",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/backports/enum/__init__.py#L422-L481 |
25,320 | pypa/pipenv | pipenv/vendor/backports/enum/__init__.py | EnumMeta._get_mixins_ | def _get_mixins_(bases):
"""Returns the type for creating enum members, and the first inherited
enum class.
bases: the tuple of bases that was given to __new__
"""
if not bases or Enum is None:
return object, Enum
# double check that we are not subclassing a class with existing
# enumeration members; while we're at it, see if any other data
# type has been mixed in so we can use the correct __new__
member_type = first_enum = None
for base in bases:
if (base is not Enum and
issubclass(base, Enum) and
base._member_names_):
raise TypeError("Cannot extend enumerations")
# base is now the last base in bases
if not issubclass(base, Enum):
raise TypeError("new enumerations must be created as "
"`ClassName([mixin_type,] enum_type)`")
# get correct mix-in type (either mix-in type of Enum subclass, or
# first base if last base is Enum)
if not issubclass(bases[0], Enum):
member_type = bases[0] # first data type
first_enum = bases[-1] # enum type
else:
for base in bases[0].__mro__:
# most common: (IntEnum, int, Enum, object)
# possible: (<Enum 'AutoIntEnum'>, <Enum 'IntEnum'>,
# <class 'int'>, <Enum 'Enum'>,
# <class 'object'>)
if issubclass(base, Enum):
if first_enum is None:
first_enum = base
else:
if member_type is None:
member_type = base
return member_type, first_enum | python | def _get_mixins_(bases):
"""Returns the type for creating enum members, and the first inherited
enum class.
bases: the tuple of bases that was given to __new__
"""
if not bases or Enum is None:
return object, Enum
# double check that we are not subclassing a class with existing
# enumeration members; while we're at it, see if any other data
# type has been mixed in so we can use the correct __new__
member_type = first_enum = None
for base in bases:
if (base is not Enum and
issubclass(base, Enum) and
base._member_names_):
raise TypeError("Cannot extend enumerations")
# base is now the last base in bases
if not issubclass(base, Enum):
raise TypeError("new enumerations must be created as "
"`ClassName([mixin_type,] enum_type)`")
# get correct mix-in type (either mix-in type of Enum subclass, or
# first base if last base is Enum)
if not issubclass(bases[0], Enum):
member_type = bases[0] # first data type
first_enum = bases[-1] # enum type
else:
for base in bases[0].__mro__:
# most common: (IntEnum, int, Enum, object)
# possible: (<Enum 'AutoIntEnum'>, <Enum 'IntEnum'>,
# <class 'int'>, <Enum 'Enum'>,
# <class 'object'>)
if issubclass(base, Enum):
if first_enum is None:
first_enum = base
else:
if member_type is None:
member_type = base
return member_type, first_enum | [
"def",
"_get_mixins_",
"(",
"bases",
")",
":",
"if",
"not",
"bases",
"or",
"Enum",
"is",
"None",
":",
"return",
"object",
",",
"Enum",
"# double check that we are not subclassing a class with existing",
"# enumeration members; while we're at it, see if any other data",
"# type has been mixed in so we can use the correct __new__",
"member_type",
"=",
"first_enum",
"=",
"None",
"for",
"base",
"in",
"bases",
":",
"if",
"(",
"base",
"is",
"not",
"Enum",
"and",
"issubclass",
"(",
"base",
",",
"Enum",
")",
"and",
"base",
".",
"_member_names_",
")",
":",
"raise",
"TypeError",
"(",
"\"Cannot extend enumerations\"",
")",
"# base is now the last base in bases",
"if",
"not",
"issubclass",
"(",
"base",
",",
"Enum",
")",
":",
"raise",
"TypeError",
"(",
"\"new enumerations must be created as \"",
"\"`ClassName([mixin_type,] enum_type)`\"",
")",
"# get correct mix-in type (either mix-in type of Enum subclass, or",
"# first base if last base is Enum)",
"if",
"not",
"issubclass",
"(",
"bases",
"[",
"0",
"]",
",",
"Enum",
")",
":",
"member_type",
"=",
"bases",
"[",
"0",
"]",
"# first data type",
"first_enum",
"=",
"bases",
"[",
"-",
"1",
"]",
"# enum type",
"else",
":",
"for",
"base",
"in",
"bases",
"[",
"0",
"]",
".",
"__mro__",
":",
"# most common: (IntEnum, int, Enum, object)",
"# possible: (<Enum 'AutoIntEnum'>, <Enum 'IntEnum'>,",
"# <class 'int'>, <Enum 'Enum'>,",
"# <class 'object'>)",
"if",
"issubclass",
"(",
"base",
",",
"Enum",
")",
":",
"if",
"first_enum",
"is",
"None",
":",
"first_enum",
"=",
"base",
"else",
":",
"if",
"member_type",
"is",
"None",
":",
"member_type",
"=",
"base",
"return",
"member_type",
",",
"first_enum"
] | Returns the type for creating enum members, and the first inherited
enum class.
bases: the tuple of bases that was given to __new__ | [
"Returns",
"the",
"type",
"for",
"creating",
"enum",
"members",
"and",
"the",
"first",
"inherited",
"enum",
"class",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/backports/enum/__init__.py#L484-L527 |
25,321 | pypa/pipenv | pipenv/patched/notpip/_internal/commands/list.py | format_for_columns | def format_for_columns(pkgs, options):
"""
Convert the package data into something usable
by output_package_listing_columns.
"""
running_outdated = options.outdated
# Adjust the header for the `pip list --outdated` case.
if running_outdated:
header = ["Package", "Version", "Latest", "Type"]
else:
header = ["Package", "Version"]
data = []
if options.verbose >= 1 or any(dist_is_editable(x) for x in pkgs):
header.append("Location")
if options.verbose >= 1:
header.append("Installer")
for proj in pkgs:
# if we're working on the 'outdated' list, separate out the
# latest_version and type
row = [proj.project_name, proj.version]
if running_outdated:
row.append(proj.latest_version)
row.append(proj.latest_filetype)
if options.verbose >= 1 or dist_is_editable(proj):
row.append(proj.location)
if options.verbose >= 1:
row.append(get_installer(proj))
data.append(row)
return data, header | python | def format_for_columns(pkgs, options):
"""
Convert the package data into something usable
by output_package_listing_columns.
"""
running_outdated = options.outdated
# Adjust the header for the `pip list --outdated` case.
if running_outdated:
header = ["Package", "Version", "Latest", "Type"]
else:
header = ["Package", "Version"]
data = []
if options.verbose >= 1 or any(dist_is_editable(x) for x in pkgs):
header.append("Location")
if options.verbose >= 1:
header.append("Installer")
for proj in pkgs:
# if we're working on the 'outdated' list, separate out the
# latest_version and type
row = [proj.project_name, proj.version]
if running_outdated:
row.append(proj.latest_version)
row.append(proj.latest_filetype)
if options.verbose >= 1 or dist_is_editable(proj):
row.append(proj.location)
if options.verbose >= 1:
row.append(get_installer(proj))
data.append(row)
return data, header | [
"def",
"format_for_columns",
"(",
"pkgs",
",",
"options",
")",
":",
"running_outdated",
"=",
"options",
".",
"outdated",
"# Adjust the header for the `pip list --outdated` case.",
"if",
"running_outdated",
":",
"header",
"=",
"[",
"\"Package\"",
",",
"\"Version\"",
",",
"\"Latest\"",
",",
"\"Type\"",
"]",
"else",
":",
"header",
"=",
"[",
"\"Package\"",
",",
"\"Version\"",
"]",
"data",
"=",
"[",
"]",
"if",
"options",
".",
"verbose",
">=",
"1",
"or",
"any",
"(",
"dist_is_editable",
"(",
"x",
")",
"for",
"x",
"in",
"pkgs",
")",
":",
"header",
".",
"append",
"(",
"\"Location\"",
")",
"if",
"options",
".",
"verbose",
">=",
"1",
":",
"header",
".",
"append",
"(",
"\"Installer\"",
")",
"for",
"proj",
"in",
"pkgs",
":",
"# if we're working on the 'outdated' list, separate out the",
"# latest_version and type",
"row",
"=",
"[",
"proj",
".",
"project_name",
",",
"proj",
".",
"version",
"]",
"if",
"running_outdated",
":",
"row",
".",
"append",
"(",
"proj",
".",
"latest_version",
")",
"row",
".",
"append",
"(",
"proj",
".",
"latest_filetype",
")",
"if",
"options",
".",
"verbose",
">=",
"1",
"or",
"dist_is_editable",
"(",
"proj",
")",
":",
"row",
".",
"append",
"(",
"proj",
".",
"location",
")",
"if",
"options",
".",
"verbose",
">=",
"1",
":",
"row",
".",
"append",
"(",
"get_installer",
"(",
"proj",
")",
")",
"data",
".",
"append",
"(",
"row",
")",
"return",
"data",
",",
"header"
] | Convert the package data into something usable
by output_package_listing_columns. | [
"Convert",
"the",
"package",
"data",
"into",
"something",
"usable",
"by",
"output_package_listing_columns",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/commands/list.py#L250-L284 |
25,322 | pypa/pipenv | pipenv/vendor/distlib/scripts.py | ScriptMaker.make | def make(self, specification, options=None):
"""
Make a script.
:param specification: The specification, which is either a valid export
entry specification (to make a script from a
callable) or a filename (to make a script by
copying from a source location).
:param options: A dictionary of options controlling script generation.
:return: A list of all absolute pathnames written to.
"""
filenames = []
entry = get_export_entry(specification)
if entry is None:
self._copy_script(specification, filenames)
else:
self._make_script(entry, filenames, options=options)
return filenames | python | def make(self, specification, options=None):
"""
Make a script.
:param specification: The specification, which is either a valid export
entry specification (to make a script from a
callable) or a filename (to make a script by
copying from a source location).
:param options: A dictionary of options controlling script generation.
:return: A list of all absolute pathnames written to.
"""
filenames = []
entry = get_export_entry(specification)
if entry is None:
self._copy_script(specification, filenames)
else:
self._make_script(entry, filenames, options=options)
return filenames | [
"def",
"make",
"(",
"self",
",",
"specification",
",",
"options",
"=",
"None",
")",
":",
"filenames",
"=",
"[",
"]",
"entry",
"=",
"get_export_entry",
"(",
"specification",
")",
"if",
"entry",
"is",
"None",
":",
"self",
".",
"_copy_script",
"(",
"specification",
",",
"filenames",
")",
"else",
":",
"self",
".",
"_make_script",
"(",
"entry",
",",
"filenames",
",",
"options",
"=",
"options",
")",
"return",
"filenames"
] | Make a script.
:param specification: The specification, which is either a valid export
entry specification (to make a script from a
callable) or a filename (to make a script by
copying from a source location).
:param options: A dictionary of options controlling script generation.
:return: A list of all absolute pathnames written to. | [
"Make",
"a",
"script",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/scripts.py#L389-L406 |
25,323 | pypa/pipenv | pipenv/patched/pipfile/api.py | load | def load(pipfile_path=None, inject_env=True):
"""Loads a pipfile from a given path.
If none is provided, one will try to be found.
"""
if pipfile_path is None:
pipfile_path = Pipfile.find()
return Pipfile.load(filename=pipfile_path, inject_env=inject_env) | python | def load(pipfile_path=None, inject_env=True):
"""Loads a pipfile from a given path.
If none is provided, one will try to be found.
"""
if pipfile_path is None:
pipfile_path = Pipfile.find()
return Pipfile.load(filename=pipfile_path, inject_env=inject_env) | [
"def",
"load",
"(",
"pipfile_path",
"=",
"None",
",",
"inject_env",
"=",
"True",
")",
":",
"if",
"pipfile_path",
"is",
"None",
":",
"pipfile_path",
"=",
"Pipfile",
".",
"find",
"(",
")",
"return",
"Pipfile",
".",
"load",
"(",
"filename",
"=",
"pipfile_path",
",",
"inject_env",
"=",
"inject_env",
")"
] | Loads a pipfile from a given path.
If none is provided, one will try to be found. | [
"Loads",
"a",
"pipfile",
"from",
"a",
"given",
"path",
".",
"If",
"none",
"is",
"provided",
"one",
"will",
"try",
"to",
"be",
"found",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/pipfile/api.py#L222-L230 |
25,324 | pypa/pipenv | pipenv/patched/pipfile/api.py | PipfileParser.inject_environment_variables | def inject_environment_variables(self, d):
"""
Recursively injects environment variables into TOML values
"""
if not d:
return d
if isinstance(d, six.string_types):
return os.path.expandvars(d)
for k, v in d.items():
if isinstance(v, six.string_types):
d[k] = os.path.expandvars(v)
elif isinstance(v, dict):
d[k] = self.inject_environment_variables(v)
elif isinstance(v, list):
d[k] = [self.inject_environment_variables(e) for e in v]
return d | python | def inject_environment_variables(self, d):
"""
Recursively injects environment variables into TOML values
"""
if not d:
return d
if isinstance(d, six.string_types):
return os.path.expandvars(d)
for k, v in d.items():
if isinstance(v, six.string_types):
d[k] = os.path.expandvars(v)
elif isinstance(v, dict):
d[k] = self.inject_environment_variables(v)
elif isinstance(v, list):
d[k] = [self.inject_environment_variables(e) for e in v]
return d | [
"def",
"inject_environment_variables",
"(",
"self",
",",
"d",
")",
":",
"if",
"not",
"d",
":",
"return",
"d",
"if",
"isinstance",
"(",
"d",
",",
"six",
".",
"string_types",
")",
":",
"return",
"os",
".",
"path",
".",
"expandvars",
"(",
"d",
")",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"six",
".",
"string_types",
")",
":",
"d",
"[",
"k",
"]",
"=",
"os",
".",
"path",
".",
"expandvars",
"(",
"v",
")",
"elif",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"d",
"[",
"k",
"]",
"=",
"self",
".",
"inject_environment_variables",
"(",
"v",
")",
"elif",
"isinstance",
"(",
"v",
",",
"list",
")",
":",
"d",
"[",
"k",
"]",
"=",
"[",
"self",
".",
"inject_environment_variables",
"(",
"e",
")",
"for",
"e",
"in",
"v",
"]",
"return",
"d"
] | Recursively injects environment variables into TOML values | [
"Recursively",
"injects",
"environment",
"variables",
"into",
"TOML",
"values"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/pipfile/api.py#L73-L90 |
25,325 | pypa/pipenv | pipenv/patched/pipfile/api.py | Pipfile.load | def load(klass, filename, inject_env=True):
"""Load a Pipfile from a given filename."""
p = PipfileParser(filename=filename)
pipfile = klass(filename=filename)
pipfile.data = p.parse(inject_env=inject_env)
return pipfile | python | def load(klass, filename, inject_env=True):
"""Load a Pipfile from a given filename."""
p = PipfileParser(filename=filename)
pipfile = klass(filename=filename)
pipfile.data = p.parse(inject_env=inject_env)
return pipfile | [
"def",
"load",
"(",
"klass",
",",
"filename",
",",
"inject_env",
"=",
"True",
")",
":",
"p",
"=",
"PipfileParser",
"(",
"filename",
"=",
"filename",
")",
"pipfile",
"=",
"klass",
"(",
"filename",
"=",
"filename",
")",
"pipfile",
".",
"data",
"=",
"p",
".",
"parse",
"(",
"inject_env",
"=",
"inject_env",
")",
"return",
"pipfile"
] | Load a Pipfile from a given filename. | [
"Load",
"a",
"Pipfile",
"from",
"a",
"given",
"filename",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/pipfile/api.py#L157-L162 |
25,326 | pypa/pipenv | pipenv/patched/pipfile/api.py | Pipfile.hash | def hash(self):
"""Returns the SHA256 of the pipfile's data."""
content = json.dumps(self.data, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(content.encode("utf8")).hexdigest() | python | def hash(self):
"""Returns the SHA256 of the pipfile's data."""
content = json.dumps(self.data, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(content.encode("utf8")).hexdigest() | [
"def",
"hash",
"(",
"self",
")",
":",
"content",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"data",
",",
"sort_keys",
"=",
"True",
",",
"separators",
"=",
"(",
"\",\"",
",",
"\":\"",
")",
")",
"return",
"hashlib",
".",
"sha256",
"(",
"content",
".",
"encode",
"(",
"\"utf8\"",
")",
")",
".",
"hexdigest",
"(",
")"
] | Returns the SHA256 of the pipfile's data. | [
"Returns",
"the",
"SHA256",
"of",
"the",
"pipfile",
"s",
"data",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/pipfile/api.py#L165-L168 |
25,327 | pypa/pipenv | pipenv/patched/pipfile/api.py | Pipfile.lock | def lock(self):
"""Returns a JSON representation of the Pipfile."""
data = self.data
data['_meta']['hash'] = {"sha256": self.hash}
data['_meta']['pipfile-spec'] = 6
return json.dumps(data, indent=4, separators=(',', ': ')) | python | def lock(self):
"""Returns a JSON representation of the Pipfile."""
data = self.data
data['_meta']['hash'] = {"sha256": self.hash}
data['_meta']['pipfile-spec'] = 6
return json.dumps(data, indent=4, separators=(',', ': ')) | [
"def",
"lock",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"data",
"data",
"[",
"'_meta'",
"]",
"[",
"'hash'",
"]",
"=",
"{",
"\"sha256\"",
":",
"self",
".",
"hash",
"}",
"data",
"[",
"'_meta'",
"]",
"[",
"'pipfile-spec'",
"]",
"=",
"6",
"return",
"json",
".",
"dumps",
"(",
"data",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
")"
] | Returns a JSON representation of the Pipfile. | [
"Returns",
"a",
"JSON",
"representation",
"of",
"the",
"Pipfile",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/pipfile/api.py#L176-L181 |
25,328 | pypa/pipenv | pipenv/patched/pipfile/api.py | Pipfile.assert_requirements | def assert_requirements(self):
""""Asserts PEP 508 specifiers."""
# Support for 508's implementation_version.
if hasattr(sys, 'implementation'):
implementation_version = format_full_version(sys.implementation.version)
else:
implementation_version = "0"
# Default to cpython for 2.7.
if hasattr(sys, 'implementation'):
implementation_name = sys.implementation.name
else:
implementation_name = 'cpython'
lookup = {
'os_name': os.name,
'sys_platform': sys.platform,
'platform_machine': platform.machine(),
'platform_python_implementation': platform.python_implementation(),
'platform_release': platform.release(),
'platform_system': platform.system(),
'platform_version': platform.version(),
'python_version': platform.python_version()[:3],
'python_full_version': platform.python_version(),
'implementation_name': implementation_name,
'implementation_version': implementation_version
}
# Assert each specified requirement.
for marker, specifier in self.data['_meta']['requires'].items():
if marker in lookup:
try:
assert lookup[marker] == specifier
except AssertionError:
raise AssertionError('Specifier {!r} does not match {!r}.'.format(marker, specifier)) | python | def assert_requirements(self):
""""Asserts PEP 508 specifiers."""
# Support for 508's implementation_version.
if hasattr(sys, 'implementation'):
implementation_version = format_full_version(sys.implementation.version)
else:
implementation_version = "0"
# Default to cpython for 2.7.
if hasattr(sys, 'implementation'):
implementation_name = sys.implementation.name
else:
implementation_name = 'cpython'
lookup = {
'os_name': os.name,
'sys_platform': sys.platform,
'platform_machine': platform.machine(),
'platform_python_implementation': platform.python_implementation(),
'platform_release': platform.release(),
'platform_system': platform.system(),
'platform_version': platform.version(),
'python_version': platform.python_version()[:3],
'python_full_version': platform.python_version(),
'implementation_name': implementation_name,
'implementation_version': implementation_version
}
# Assert each specified requirement.
for marker, specifier in self.data['_meta']['requires'].items():
if marker in lookup:
try:
assert lookup[marker] == specifier
except AssertionError:
raise AssertionError('Specifier {!r} does not match {!r}.'.format(marker, specifier)) | [
"def",
"assert_requirements",
"(",
"self",
")",
":",
"# Support for 508's implementation_version.",
"if",
"hasattr",
"(",
"sys",
",",
"'implementation'",
")",
":",
"implementation_version",
"=",
"format_full_version",
"(",
"sys",
".",
"implementation",
".",
"version",
")",
"else",
":",
"implementation_version",
"=",
"\"0\"",
"# Default to cpython for 2.7.",
"if",
"hasattr",
"(",
"sys",
",",
"'implementation'",
")",
":",
"implementation_name",
"=",
"sys",
".",
"implementation",
".",
"name",
"else",
":",
"implementation_name",
"=",
"'cpython'",
"lookup",
"=",
"{",
"'os_name'",
":",
"os",
".",
"name",
",",
"'sys_platform'",
":",
"sys",
".",
"platform",
",",
"'platform_machine'",
":",
"platform",
".",
"machine",
"(",
")",
",",
"'platform_python_implementation'",
":",
"platform",
".",
"python_implementation",
"(",
")",
",",
"'platform_release'",
":",
"platform",
".",
"release",
"(",
")",
",",
"'platform_system'",
":",
"platform",
".",
"system",
"(",
")",
",",
"'platform_version'",
":",
"platform",
".",
"version",
"(",
")",
",",
"'python_version'",
":",
"platform",
".",
"python_version",
"(",
")",
"[",
":",
"3",
"]",
",",
"'python_full_version'",
":",
"platform",
".",
"python_version",
"(",
")",
",",
"'implementation_name'",
":",
"implementation_name",
",",
"'implementation_version'",
":",
"implementation_version",
"}",
"# Assert each specified requirement.",
"for",
"marker",
",",
"specifier",
"in",
"self",
".",
"data",
"[",
"'_meta'",
"]",
"[",
"'requires'",
"]",
".",
"items",
"(",
")",
":",
"if",
"marker",
"in",
"lookup",
":",
"try",
":",
"assert",
"lookup",
"[",
"marker",
"]",
"==",
"specifier",
"except",
"AssertionError",
":",
"raise",
"AssertionError",
"(",
"'Specifier {!r} does not match {!r}.'",
".",
"format",
"(",
"marker",
",",
"specifier",
")",
")"
] | Asserts PEP 508 specifiers. | [
"Asserts",
"PEP",
"508",
"specifiers",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/pipfile/api.py#L183-L219 |
25,329 | pypa/pipenv | pipenv/vendor/distlib/_backport/shutil.py | copyfileobj | def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf) | python | def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf) | [
"def",
"copyfileobj",
"(",
"fsrc",
",",
"fdst",
",",
"length",
"=",
"16",
"*",
"1024",
")",
":",
"while",
"1",
":",
"buf",
"=",
"fsrc",
".",
"read",
"(",
"length",
")",
"if",
"not",
"buf",
":",
"break",
"fdst",
".",
"write",
"(",
"buf",
")"
] | copy data from file-like object fsrc to file-like object fdst | [
"copy",
"data",
"from",
"file",
"-",
"like",
"object",
"fsrc",
"to",
"file",
"-",
"like",
"object",
"fdst"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L67-L73 |
25,330 | pypa/pipenv | pipenv/vendor/distlib/_backport/shutil.py | copyfile | def copyfile(src, dst):
"""Copy data from src to dst"""
if _samefile(src, dst):
raise Error("`%s` and `%s` are the same file" % (src, dst))
for fn in [src, dst]:
try:
st = os.stat(fn)
except OSError:
# File most likely does not exist
pass
else:
# XXX What about other special files? (sockets, devices...)
if stat.S_ISFIFO(st.st_mode):
raise SpecialFileError("`%s` is a named pipe" % fn)
with open(src, 'rb') as fsrc:
with open(dst, 'wb') as fdst:
copyfileobj(fsrc, fdst) | python | def copyfile(src, dst):
"""Copy data from src to dst"""
if _samefile(src, dst):
raise Error("`%s` and `%s` are the same file" % (src, dst))
for fn in [src, dst]:
try:
st = os.stat(fn)
except OSError:
# File most likely does not exist
pass
else:
# XXX What about other special files? (sockets, devices...)
if stat.S_ISFIFO(st.st_mode):
raise SpecialFileError("`%s` is a named pipe" % fn)
with open(src, 'rb') as fsrc:
with open(dst, 'wb') as fdst:
copyfileobj(fsrc, fdst) | [
"def",
"copyfile",
"(",
"src",
",",
"dst",
")",
":",
"if",
"_samefile",
"(",
"src",
",",
"dst",
")",
":",
"raise",
"Error",
"(",
"\"`%s` and `%s` are the same file\"",
"%",
"(",
"src",
",",
"dst",
")",
")",
"for",
"fn",
"in",
"[",
"src",
",",
"dst",
"]",
":",
"try",
":",
"st",
"=",
"os",
".",
"stat",
"(",
"fn",
")",
"except",
"OSError",
":",
"# File most likely does not exist",
"pass",
"else",
":",
"# XXX What about other special files? (sockets, devices...)",
"if",
"stat",
".",
"S_ISFIFO",
"(",
"st",
".",
"st_mode",
")",
":",
"raise",
"SpecialFileError",
"(",
"\"`%s` is a named pipe\"",
"%",
"fn",
")",
"with",
"open",
"(",
"src",
",",
"'rb'",
")",
"as",
"fsrc",
":",
"with",
"open",
"(",
"dst",
",",
"'wb'",
")",
"as",
"fdst",
":",
"copyfileobj",
"(",
"fsrc",
",",
"fdst",
")"
] | Copy data from src to dst | [
"Copy",
"data",
"from",
"src",
"to",
"dst"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L87-L105 |
25,331 | pypa/pipenv | pipenv/vendor/distlib/_backport/shutil.py | copymode | def copymode(src, dst):
"""Copy mode bits from src to dst"""
if hasattr(os, 'chmod'):
st = os.stat(src)
mode = stat.S_IMODE(st.st_mode)
os.chmod(dst, mode) | python | def copymode(src, dst):
"""Copy mode bits from src to dst"""
if hasattr(os, 'chmod'):
st = os.stat(src)
mode = stat.S_IMODE(st.st_mode)
os.chmod(dst, mode) | [
"def",
"copymode",
"(",
"src",
",",
"dst",
")",
":",
"if",
"hasattr",
"(",
"os",
",",
"'chmod'",
")",
":",
"st",
"=",
"os",
".",
"stat",
"(",
"src",
")",
"mode",
"=",
"stat",
".",
"S_IMODE",
"(",
"st",
".",
"st_mode",
")",
"os",
".",
"chmod",
"(",
"dst",
",",
"mode",
")"
] | Copy mode bits from src to dst | [
"Copy",
"mode",
"bits",
"from",
"src",
"to",
"dst"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L107-L112 |
25,332 | pypa/pipenv | pipenv/vendor/distlib/_backport/shutil.py | move | def move(src, dst):
"""Recursively move a file or directory to another location. This is
similar to the Unix "mv" command.
If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not already
exist.
If the destination already exists but is not a directory, it may be
overwritten depending on os.rename() semantics.
If the destination is on our current filesystem, then rename() is used.
Otherwise, src is copied to the destination and then removed.
A lot more could be done here... A look at a mv.c shows a lot of
the issues this implementation glosses over.
"""
real_dst = dst
if os.path.isdir(dst):
if _samefile(src, dst):
# We might be on a case insensitive filesystem,
# perform the rename anyway.
os.rename(src, dst)
return
real_dst = os.path.join(dst, _basename(src))
if os.path.exists(real_dst):
raise Error("Destination path '%s' already exists" % real_dst)
try:
os.rename(src, real_dst)
except OSError:
if os.path.isdir(src):
if _destinsrc(src, dst):
raise Error("Cannot move a directory '%s' into itself '%s'." % (src, dst))
copytree(src, real_dst, symlinks=True)
rmtree(src)
else:
copy2(src, real_dst)
os.unlink(src) | python | def move(src, dst):
"""Recursively move a file or directory to another location. This is
similar to the Unix "mv" command.
If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not already
exist.
If the destination already exists but is not a directory, it may be
overwritten depending on os.rename() semantics.
If the destination is on our current filesystem, then rename() is used.
Otherwise, src is copied to the destination and then removed.
A lot more could be done here... A look at a mv.c shows a lot of
the issues this implementation glosses over.
"""
real_dst = dst
if os.path.isdir(dst):
if _samefile(src, dst):
# We might be on a case insensitive filesystem,
# perform the rename anyway.
os.rename(src, dst)
return
real_dst = os.path.join(dst, _basename(src))
if os.path.exists(real_dst):
raise Error("Destination path '%s' already exists" % real_dst)
try:
os.rename(src, real_dst)
except OSError:
if os.path.isdir(src):
if _destinsrc(src, dst):
raise Error("Cannot move a directory '%s' into itself '%s'." % (src, dst))
copytree(src, real_dst, symlinks=True)
rmtree(src)
else:
copy2(src, real_dst)
os.unlink(src) | [
"def",
"move",
"(",
"src",
",",
"dst",
")",
":",
"real_dst",
"=",
"dst",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dst",
")",
":",
"if",
"_samefile",
"(",
"src",
",",
"dst",
")",
":",
"# We might be on a case insensitive filesystem,",
"# perform the rename anyway.",
"os",
".",
"rename",
"(",
"src",
",",
"dst",
")",
"return",
"real_dst",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"_basename",
"(",
"src",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"real_dst",
")",
":",
"raise",
"Error",
"(",
"\"Destination path '%s' already exists\"",
"%",
"real_dst",
")",
"try",
":",
"os",
".",
"rename",
"(",
"src",
",",
"real_dst",
")",
"except",
"OSError",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"src",
")",
":",
"if",
"_destinsrc",
"(",
"src",
",",
"dst",
")",
":",
"raise",
"Error",
"(",
"\"Cannot move a directory '%s' into itself '%s'.\"",
"%",
"(",
"src",
",",
"dst",
")",
")",
"copytree",
"(",
"src",
",",
"real_dst",
",",
"symlinks",
"=",
"True",
")",
"rmtree",
"(",
"src",
")",
"else",
":",
"copy2",
"(",
"src",
",",
"real_dst",
")",
"os",
".",
"unlink",
"(",
"src",
")"
] | Recursively move a file or directory to another location. This is
similar to the Unix "mv" command.
If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not already
exist.
If the destination already exists but is not a directory, it may be
overwritten depending on os.rename() semantics.
If the destination is on our current filesystem, then rename() is used.
Otherwise, src is copied to the destination and then removed.
A lot more could be done here... A look at a mv.c shows a lot of
the issues this implementation glosses over. | [
"Recursively",
"move",
"a",
"file",
"or",
"directory",
"to",
"another",
"location",
".",
"This",
"is",
"similar",
"to",
"the",
"Unix",
"mv",
"command",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L300-L338 |
25,333 | pypa/pipenv | pipenv/vendor/distlib/_backport/shutil.py | _get_gid | def _get_gid(name):
"""Returns a gid, given a group name."""
if getgrnam is None or name is None:
return None
try:
result = getgrnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None | python | def _get_gid(name):
"""Returns a gid, given a group name."""
if getgrnam is None or name is None:
return None
try:
result = getgrnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None | [
"def",
"_get_gid",
"(",
"name",
")",
":",
"if",
"getgrnam",
"is",
"None",
"or",
"name",
"is",
"None",
":",
"return",
"None",
"try",
":",
"result",
"=",
"getgrnam",
"(",
"name",
")",
"except",
"KeyError",
":",
"result",
"=",
"None",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
"[",
"2",
"]",
"return",
"None"
] | Returns a gid, given a group name. | [
"Returns",
"a",
"gid",
"given",
"a",
"group",
"name",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L349-L359 |
25,334 | pypa/pipenv | pipenv/vendor/distlib/_backport/shutil.py | _get_uid | def _get_uid(name):
"""Returns an uid, given a user name."""
if getpwnam is None or name is None:
return None
try:
result = getpwnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None | python | def _get_uid(name):
"""Returns an uid, given a user name."""
if getpwnam is None or name is None:
return None
try:
result = getpwnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None | [
"def",
"_get_uid",
"(",
"name",
")",
":",
"if",
"getpwnam",
"is",
"None",
"or",
"name",
"is",
"None",
":",
"return",
"None",
"try",
":",
"result",
"=",
"getpwnam",
"(",
"name",
")",
"except",
"KeyError",
":",
"result",
"=",
"None",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
"[",
"2",
"]",
"return",
"None"
] | Returns an uid, given a user name. | [
"Returns",
"an",
"uid",
"given",
"a",
"user",
"name",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L361-L371 |
25,335 | pypa/pipenv | pipenv/vendor/distlib/_backport/shutil.py | _make_zipfile | def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
"""Create a zip file from all the files under 'base_dir'.
The output zip file will be named 'base_name' + ".zip". Uses either the
"zipfile" Python module (if available) or the InfoZIP "zip" utility
(if installed and found on the default search path). If neither tool is
available, raises ExecError. Returns the name of the output zip
file.
"""
zip_filename = base_name + ".zip"
archive_dir = os.path.dirname(base_name)
if not os.path.exists(archive_dir):
if logger is not None:
logger.info("creating %s", archive_dir)
if not dry_run:
os.makedirs(archive_dir)
# If zipfile module is not available, try spawning an external 'zip'
# command.
try:
import zipfile
except ImportError:
zipfile = None
if zipfile is None:
_call_external_zip(base_dir, zip_filename, verbose, dry_run)
else:
if logger is not None:
logger.info("creating '%s' and adding '%s' to it",
zip_filename, base_dir)
if not dry_run:
zip = zipfile.ZipFile(zip_filename, "w",
compression=zipfile.ZIP_DEFLATED)
for dirpath, dirnames, filenames in os.walk(base_dir):
for name in filenames:
path = os.path.normpath(os.path.join(dirpath, name))
if os.path.isfile(path):
zip.write(path, path)
if logger is not None:
logger.info("adding '%s'", path)
zip.close()
return zip_filename | python | def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
"""Create a zip file from all the files under 'base_dir'.
The output zip file will be named 'base_name' + ".zip". Uses either the
"zipfile" Python module (if available) or the InfoZIP "zip" utility
(if installed and found on the default search path). If neither tool is
available, raises ExecError. Returns the name of the output zip
file.
"""
zip_filename = base_name + ".zip"
archive_dir = os.path.dirname(base_name)
if not os.path.exists(archive_dir):
if logger is not None:
logger.info("creating %s", archive_dir)
if not dry_run:
os.makedirs(archive_dir)
# If zipfile module is not available, try spawning an external 'zip'
# command.
try:
import zipfile
except ImportError:
zipfile = None
if zipfile is None:
_call_external_zip(base_dir, zip_filename, verbose, dry_run)
else:
if logger is not None:
logger.info("creating '%s' and adding '%s' to it",
zip_filename, base_dir)
if not dry_run:
zip = zipfile.ZipFile(zip_filename, "w",
compression=zipfile.ZIP_DEFLATED)
for dirpath, dirnames, filenames in os.walk(base_dir):
for name in filenames:
path = os.path.normpath(os.path.join(dirpath, name))
if os.path.isfile(path):
zip.write(path, path)
if logger is not None:
logger.info("adding '%s'", path)
zip.close()
return zip_filename | [
"def",
"_make_zipfile",
"(",
"base_name",
",",
"base_dir",
",",
"verbose",
"=",
"0",
",",
"dry_run",
"=",
"0",
",",
"logger",
"=",
"None",
")",
":",
"zip_filename",
"=",
"base_name",
"+",
"\".zip\"",
"archive_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"base_name",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"archive_dir",
")",
":",
"if",
"logger",
"is",
"not",
"None",
":",
"logger",
".",
"info",
"(",
"\"creating %s\"",
",",
"archive_dir",
")",
"if",
"not",
"dry_run",
":",
"os",
".",
"makedirs",
"(",
"archive_dir",
")",
"# If zipfile module is not available, try spawning an external 'zip'",
"# command.",
"try",
":",
"import",
"zipfile",
"except",
"ImportError",
":",
"zipfile",
"=",
"None",
"if",
"zipfile",
"is",
"None",
":",
"_call_external_zip",
"(",
"base_dir",
",",
"zip_filename",
",",
"verbose",
",",
"dry_run",
")",
"else",
":",
"if",
"logger",
"is",
"not",
"None",
":",
"logger",
".",
"info",
"(",
"\"creating '%s' and adding '%s' to it\"",
",",
"zip_filename",
",",
"base_dir",
")",
"if",
"not",
"dry_run",
":",
"zip",
"=",
"zipfile",
".",
"ZipFile",
"(",
"zip_filename",
",",
"\"w\"",
",",
"compression",
"=",
"zipfile",
".",
"ZIP_DEFLATED",
")",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"base_dir",
")",
":",
"for",
"name",
"in",
"filenames",
":",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"name",
")",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"zip",
".",
"write",
"(",
"path",
",",
"path",
")",
"if",
"logger",
"is",
"not",
"None",
":",
"logger",
".",
"info",
"(",
"\"adding '%s'\"",
",",
"path",
")",
"zip",
".",
"close",
"(",
")",
"return",
"zip_filename"
] | Create a zip file from all the files under 'base_dir'.
The output zip file will be named 'base_name' + ".zip". Uses either the
"zipfile" Python module (if available) or the InfoZIP "zip" utility
(if installed and found on the default search path). If neither tool is
available, raises ExecError. Returns the name of the output zip
file. | [
"Create",
"a",
"zip",
"file",
"from",
"all",
"the",
"files",
"under",
"base_dir",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L452-L497 |
25,336 | pypa/pipenv | pipenv/vendor/distlib/_backport/shutil.py | get_archive_formats | def get_archive_formats():
"""Returns a list of supported formats for archiving and unarchiving.
Each element of the returned sequence is a tuple (name, description)
"""
formats = [(name, registry[2]) for name, registry in
_ARCHIVE_FORMATS.items()]
formats.sort()
return formats | python | def get_archive_formats():
"""Returns a list of supported formats for archiving and unarchiving.
Each element of the returned sequence is a tuple (name, description)
"""
formats = [(name, registry[2]) for name, registry in
_ARCHIVE_FORMATS.items()]
formats.sort()
return formats | [
"def",
"get_archive_formats",
"(",
")",
":",
"formats",
"=",
"[",
"(",
"name",
",",
"registry",
"[",
"2",
"]",
")",
"for",
"name",
",",
"registry",
"in",
"_ARCHIVE_FORMATS",
".",
"items",
"(",
")",
"]",
"formats",
".",
"sort",
"(",
")",
"return",
"formats"
] | Returns a list of supported formats for archiving and unarchiving.
Each element of the returned sequence is a tuple (name, description) | [
"Returns",
"a",
"list",
"of",
"supported",
"formats",
"for",
"archiving",
"and",
"unarchiving",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L510-L518 |
25,337 | pypa/pipenv | pipenv/vendor/distlib/_backport/shutil.py | register_archive_format | def register_archive_format(name, function, extra_args=None, description=''):
"""Registers an archive format.
name is the name of the format. function is the callable that will be
used to create archives. If provided, extra_args is a sequence of
(name, value) tuples that will be passed as arguments to the callable.
description can be provided to describe the format, and will be returned
by the get_archive_formats() function.
"""
if extra_args is None:
extra_args = []
if not isinstance(function, collections.Callable):
raise TypeError('The %s object is not callable' % function)
if not isinstance(extra_args, (tuple, list)):
raise TypeError('extra_args needs to be a sequence')
for element in extra_args:
if not isinstance(element, (tuple, list)) or len(element) !=2:
raise TypeError('extra_args elements are : (arg_name, value)')
_ARCHIVE_FORMATS[name] = (function, extra_args, description) | python | def register_archive_format(name, function, extra_args=None, description=''):
"""Registers an archive format.
name is the name of the format. function is the callable that will be
used to create archives. If provided, extra_args is a sequence of
(name, value) tuples that will be passed as arguments to the callable.
description can be provided to describe the format, and will be returned
by the get_archive_formats() function.
"""
if extra_args is None:
extra_args = []
if not isinstance(function, collections.Callable):
raise TypeError('The %s object is not callable' % function)
if not isinstance(extra_args, (tuple, list)):
raise TypeError('extra_args needs to be a sequence')
for element in extra_args:
if not isinstance(element, (tuple, list)) or len(element) !=2:
raise TypeError('extra_args elements are : (arg_name, value)')
_ARCHIVE_FORMATS[name] = (function, extra_args, description) | [
"def",
"register_archive_format",
"(",
"name",
",",
"function",
",",
"extra_args",
"=",
"None",
",",
"description",
"=",
"''",
")",
":",
"if",
"extra_args",
"is",
"None",
":",
"extra_args",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"function",
",",
"collections",
".",
"Callable",
")",
":",
"raise",
"TypeError",
"(",
"'The %s object is not callable'",
"%",
"function",
")",
"if",
"not",
"isinstance",
"(",
"extra_args",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"raise",
"TypeError",
"(",
"'extra_args needs to be a sequence'",
")",
"for",
"element",
"in",
"extra_args",
":",
"if",
"not",
"isinstance",
"(",
"element",
",",
"(",
"tuple",
",",
"list",
")",
")",
"or",
"len",
"(",
"element",
")",
"!=",
"2",
":",
"raise",
"TypeError",
"(",
"'extra_args elements are : (arg_name, value)'",
")",
"_ARCHIVE_FORMATS",
"[",
"name",
"]",
"=",
"(",
"function",
",",
"extra_args",
",",
"description",
")"
] | Registers an archive format.
name is the name of the format. function is the callable that will be
used to create archives. If provided, extra_args is a sequence of
(name, value) tuples that will be passed as arguments to the callable.
description can be provided to describe the format, and will be returned
by the get_archive_formats() function. | [
"Registers",
"an",
"archive",
"format",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L520-L539 |
25,338 | pypa/pipenv | pipenv/vendor/distlib/_backport/shutil.py | get_unpack_formats | def get_unpack_formats():
"""Returns a list of supported formats for unpacking.
Each element of the returned sequence is a tuple
(name, extensions, description)
"""
formats = [(name, info[0], info[3]) for name, info in
_UNPACK_FORMATS.items()]
formats.sort()
return formats | python | def get_unpack_formats():
"""Returns a list of supported formats for unpacking.
Each element of the returned sequence is a tuple
(name, extensions, description)
"""
formats = [(name, info[0], info[3]) for name, info in
_UNPACK_FORMATS.items()]
formats.sort()
return formats | [
"def",
"get_unpack_formats",
"(",
")",
":",
"formats",
"=",
"[",
"(",
"name",
",",
"info",
"[",
"0",
"]",
",",
"info",
"[",
"3",
"]",
")",
"for",
"name",
",",
"info",
"in",
"_UNPACK_FORMATS",
".",
"items",
"(",
")",
"]",
"formats",
".",
"sort",
"(",
")",
"return",
"formats"
] | Returns a list of supported formats for unpacking.
Each element of the returned sequence is a tuple
(name, extensions, description) | [
"Returns",
"a",
"list",
"of",
"supported",
"formats",
"for",
"unpacking",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L599-L608 |
25,339 | pypa/pipenv | pipenv/vendor/distlib/_backport/shutil.py | _check_unpack_options | def _check_unpack_options(extensions, function, extra_args):
"""Checks what gets registered as an unpacker."""
# first make sure no other unpacker is registered for this extension
existing_extensions = {}
for name, info in _UNPACK_FORMATS.items():
for ext in info[0]:
existing_extensions[ext] = name
for extension in extensions:
if extension in existing_extensions:
msg = '%s is already registered for "%s"'
raise RegistryError(msg % (extension,
existing_extensions[extension]))
if not isinstance(function, collections.Callable):
raise TypeError('The registered function must be a callable') | python | def _check_unpack_options(extensions, function, extra_args):
"""Checks what gets registered as an unpacker."""
# first make sure no other unpacker is registered for this extension
existing_extensions = {}
for name, info in _UNPACK_FORMATS.items():
for ext in info[0]:
existing_extensions[ext] = name
for extension in extensions:
if extension in existing_extensions:
msg = '%s is already registered for "%s"'
raise RegistryError(msg % (extension,
existing_extensions[extension]))
if not isinstance(function, collections.Callable):
raise TypeError('The registered function must be a callable') | [
"def",
"_check_unpack_options",
"(",
"extensions",
",",
"function",
",",
"extra_args",
")",
":",
"# first make sure no other unpacker is registered for this extension",
"existing_extensions",
"=",
"{",
"}",
"for",
"name",
",",
"info",
"in",
"_UNPACK_FORMATS",
".",
"items",
"(",
")",
":",
"for",
"ext",
"in",
"info",
"[",
"0",
"]",
":",
"existing_extensions",
"[",
"ext",
"]",
"=",
"name",
"for",
"extension",
"in",
"extensions",
":",
"if",
"extension",
"in",
"existing_extensions",
":",
"msg",
"=",
"'%s is already registered for \"%s\"'",
"raise",
"RegistryError",
"(",
"msg",
"%",
"(",
"extension",
",",
"existing_extensions",
"[",
"extension",
"]",
")",
")",
"if",
"not",
"isinstance",
"(",
"function",
",",
"collections",
".",
"Callable",
")",
":",
"raise",
"TypeError",
"(",
"'The registered function must be a callable'",
")"
] | Checks what gets registered as an unpacker. | [
"Checks",
"what",
"gets",
"registered",
"as",
"an",
"unpacker",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L610-L625 |
25,340 | pypa/pipenv | pipenv/vendor/distlib/_backport/shutil.py | register_unpack_format | def register_unpack_format(name, extensions, function, extra_args=None,
description=''):
"""Registers an unpack format.
`name` is the name of the format. `extensions` is a list of extensions
corresponding to the format.
`function` is the callable that will be
used to unpack archives. The callable will receive archives to unpack.
If it's unable to handle an archive, it needs to raise a ReadError
exception.
If provided, `extra_args` is a sequence of
(name, value) tuples that will be passed as arguments to the callable.
description can be provided to describe the format, and will be returned
by the get_unpack_formats() function.
"""
if extra_args is None:
extra_args = []
_check_unpack_options(extensions, function, extra_args)
_UNPACK_FORMATS[name] = extensions, function, extra_args, description | python | def register_unpack_format(name, extensions, function, extra_args=None,
description=''):
"""Registers an unpack format.
`name` is the name of the format. `extensions` is a list of extensions
corresponding to the format.
`function` is the callable that will be
used to unpack archives. The callable will receive archives to unpack.
If it's unable to handle an archive, it needs to raise a ReadError
exception.
If provided, `extra_args` is a sequence of
(name, value) tuples that will be passed as arguments to the callable.
description can be provided to describe the format, and will be returned
by the get_unpack_formats() function.
"""
if extra_args is None:
extra_args = []
_check_unpack_options(extensions, function, extra_args)
_UNPACK_FORMATS[name] = extensions, function, extra_args, description | [
"def",
"register_unpack_format",
"(",
"name",
",",
"extensions",
",",
"function",
",",
"extra_args",
"=",
"None",
",",
"description",
"=",
"''",
")",
":",
"if",
"extra_args",
"is",
"None",
":",
"extra_args",
"=",
"[",
"]",
"_check_unpack_options",
"(",
"extensions",
",",
"function",
",",
"extra_args",
")",
"_UNPACK_FORMATS",
"[",
"name",
"]",
"=",
"extensions",
",",
"function",
",",
"extra_args",
",",
"description"
] | Registers an unpack format.
`name` is the name of the format. `extensions` is a list of extensions
corresponding to the format.
`function` is the callable that will be
used to unpack archives. The callable will receive archives to unpack.
If it's unable to handle an archive, it needs to raise a ReadError
exception.
If provided, `extra_args` is a sequence of
(name, value) tuples that will be passed as arguments to the callable.
description can be provided to describe the format, and will be returned
by the get_unpack_formats() function. | [
"Registers",
"an",
"unpack",
"format",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L628-L648 |
25,341 | pypa/pipenv | pipenv/vendor/distlib/_backport/shutil.py | unpack_archive | def unpack_archive(filename, extract_dir=None, format=None):
"""Unpack an archive.
`filename` is the name of the archive.
`extract_dir` is the name of the target directory, where the archive
is unpacked. If not provided, the current working directory is used.
`format` is the archive format: one of "zip", "tar", or "gztar". Or any
other registered format. If not provided, unpack_archive will use the
filename extension and see if an unpacker was registered for that
extension.
In case none is found, a ValueError is raised.
"""
if extract_dir is None:
extract_dir = os.getcwd()
if format is not None:
try:
format_info = _UNPACK_FORMATS[format]
except KeyError:
raise ValueError("Unknown unpack format '{0}'".format(format))
func = format_info[1]
func(filename, extract_dir, **dict(format_info[2]))
else:
# we need to look at the registered unpackers supported extensions
format = _find_unpack_format(filename)
if format is None:
raise ReadError("Unknown archive format '{0}'".format(filename))
func = _UNPACK_FORMATS[format][1]
kwargs = dict(_UNPACK_FORMATS[format][2])
func(filename, extract_dir, **kwargs) | python | def unpack_archive(filename, extract_dir=None, format=None):
"""Unpack an archive.
`filename` is the name of the archive.
`extract_dir` is the name of the target directory, where the archive
is unpacked. If not provided, the current working directory is used.
`format` is the archive format: one of "zip", "tar", or "gztar". Or any
other registered format. If not provided, unpack_archive will use the
filename extension and see if an unpacker was registered for that
extension.
In case none is found, a ValueError is raised.
"""
if extract_dir is None:
extract_dir = os.getcwd()
if format is not None:
try:
format_info = _UNPACK_FORMATS[format]
except KeyError:
raise ValueError("Unknown unpack format '{0}'".format(format))
func = format_info[1]
func(filename, extract_dir, **dict(format_info[2]))
else:
# we need to look at the registered unpackers supported extensions
format = _find_unpack_format(filename)
if format is None:
raise ReadError("Unknown archive format '{0}'".format(filename))
func = _UNPACK_FORMATS[format][1]
kwargs = dict(_UNPACK_FORMATS[format][2])
func(filename, extract_dir, **kwargs) | [
"def",
"unpack_archive",
"(",
"filename",
",",
"extract_dir",
"=",
"None",
",",
"format",
"=",
"None",
")",
":",
"if",
"extract_dir",
"is",
"None",
":",
"extract_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"if",
"format",
"is",
"not",
"None",
":",
"try",
":",
"format_info",
"=",
"_UNPACK_FORMATS",
"[",
"format",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"Unknown unpack format '{0}'\"",
".",
"format",
"(",
"format",
")",
")",
"func",
"=",
"format_info",
"[",
"1",
"]",
"func",
"(",
"filename",
",",
"extract_dir",
",",
"*",
"*",
"dict",
"(",
"format_info",
"[",
"2",
"]",
")",
")",
"else",
":",
"# we need to look at the registered unpackers supported extensions",
"format",
"=",
"_find_unpack_format",
"(",
"filename",
")",
"if",
"format",
"is",
"None",
":",
"raise",
"ReadError",
"(",
"\"Unknown archive format '{0}'\"",
".",
"format",
"(",
"filename",
")",
")",
"func",
"=",
"_UNPACK_FORMATS",
"[",
"format",
"]",
"[",
"1",
"]",
"kwargs",
"=",
"dict",
"(",
"_UNPACK_FORMATS",
"[",
"format",
"]",
"[",
"2",
"]",
")",
"func",
"(",
"filename",
",",
"extract_dir",
",",
"*",
"*",
"kwargs",
")"
] | Unpack an archive.
`filename` is the name of the archive.
`extract_dir` is the name of the target directory, where the archive
is unpacked. If not provided, the current working directory is used.
`format` is the archive format: one of "zip", "tar", or "gztar". Or any
other registered format. If not provided, unpack_archive will use the
filename extension and see if an unpacker was registered for that
extension.
In case none is found, a ValueError is raised. | [
"Unpack",
"an",
"archive",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L727-L761 |
25,342 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/html5parser.py | parseFragment | def parseFragment(doc, container="div", treebuilder="etree", namespaceHTMLElements=True, **kwargs):
"""Parse an HTML fragment as a string or file-like object into a tree
:arg doc: the fragment to parse as a string or file-like object
:arg container: the container context to parse the fragment in
:arg treebuilder: the treebuilder to use when parsing
:arg namespaceHTMLElements: whether or not to namespace HTML elements
:returns: parsed tree
Example:
>>> from html5lib.html5libparser import parseFragment
>>> parseFragment('<b>this is a fragment</b>')
<Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090>
"""
tb = treebuilders.getTreeBuilder(treebuilder)
p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements)
return p.parseFragment(doc, container=container, **kwargs) | python | def parseFragment(doc, container="div", treebuilder="etree", namespaceHTMLElements=True, **kwargs):
"""Parse an HTML fragment as a string or file-like object into a tree
:arg doc: the fragment to parse as a string or file-like object
:arg container: the container context to parse the fragment in
:arg treebuilder: the treebuilder to use when parsing
:arg namespaceHTMLElements: whether or not to namespace HTML elements
:returns: parsed tree
Example:
>>> from html5lib.html5libparser import parseFragment
>>> parseFragment('<b>this is a fragment</b>')
<Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090>
"""
tb = treebuilders.getTreeBuilder(treebuilder)
p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements)
return p.parseFragment(doc, container=container, **kwargs) | [
"def",
"parseFragment",
"(",
"doc",
",",
"container",
"=",
"\"div\"",
",",
"treebuilder",
"=",
"\"etree\"",
",",
"namespaceHTMLElements",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"tb",
"=",
"treebuilders",
".",
"getTreeBuilder",
"(",
"treebuilder",
")",
"p",
"=",
"HTMLParser",
"(",
"tb",
",",
"namespaceHTMLElements",
"=",
"namespaceHTMLElements",
")",
"return",
"p",
".",
"parseFragment",
"(",
"doc",
",",
"container",
"=",
"container",
",",
"*",
"*",
"kwargs",
")"
] | Parse an HTML fragment as a string or file-like object into a tree
:arg doc: the fragment to parse as a string or file-like object
:arg container: the container context to parse the fragment in
:arg treebuilder: the treebuilder to use when parsing
:arg namespaceHTMLElements: whether or not to namespace HTML elements
:returns: parsed tree
Example:
>>> from html5lib.html5libparser import parseFragment
>>> parseFragment('<b>this is a fragment</b>')
<Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090> | [
"Parse",
"an",
"HTML",
"fragment",
"as",
"a",
"string",
"or",
"file",
"-",
"like",
"object",
"into",
"a",
"tree"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/html5parser.py#L50-L72 |
25,343 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/html5parser.py | HTMLParser.parse | def parse(self, stream, *args, **kwargs):
"""Parse a HTML document into a well-formed tree
:arg stream: a file-like object or string containing the HTML to be parsed
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element).
:arg scripting: treat noscript elements as if JavaScript was turned on
:returns: parsed tree
Example:
>>> from html5lib.html5parser import HTMLParser
>>> parser = HTMLParser()
>>> parser.parse('<html><body><p>This is a doc</p></body></html>')
<Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0>
"""
self._parse(stream, False, None, *args, **kwargs)
return self.tree.getDocument() | python | def parse(self, stream, *args, **kwargs):
"""Parse a HTML document into a well-formed tree
:arg stream: a file-like object or string containing the HTML to be parsed
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element).
:arg scripting: treat noscript elements as if JavaScript was turned on
:returns: parsed tree
Example:
>>> from html5lib.html5parser import HTMLParser
>>> parser = HTMLParser()
>>> parser.parse('<html><body><p>This is a doc</p></body></html>')
<Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0>
"""
self._parse(stream, False, None, *args, **kwargs)
return self.tree.getDocument() | [
"def",
"parse",
"(",
"self",
",",
"stream",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_parse",
"(",
"stream",
",",
"False",
",",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"tree",
".",
"getDocument",
"(",
")"
] | Parse a HTML document into a well-formed tree
:arg stream: a file-like object or string containing the HTML to be parsed
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element).
:arg scripting: treat noscript elements as if JavaScript was turned on
:returns: parsed tree
Example:
>>> from html5lib.html5parser import HTMLParser
>>> parser = HTMLParser()
>>> parser.parse('<html><body><p>This is a doc</p></body></html>')
<Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0> | [
"Parse",
"a",
"HTML",
"document",
"into",
"a",
"well",
"-",
"formed",
"tree"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/html5parser.py#L267-L290 |
25,344 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/html5parser.py | HTMLParser.parseFragment | def parseFragment(self, stream, *args, **kwargs):
"""Parse a HTML fragment into a well-formed tree fragment
:arg container: name of the element we're setting the innerHTML
property if set to None, default to 'div'
:arg stream: a file-like object or string containing the HTML to be parsed
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element)
:arg scripting: treat noscript elements as if JavaScript was turned on
:returns: parsed tree
Example:
>>> from html5lib.html5libparser import HTMLParser
>>> parser = HTMLParser()
>>> parser.parseFragment('<b>this is a fragment</b>')
<Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090>
"""
self._parse(stream, True, *args, **kwargs)
return self.tree.getFragment() | python | def parseFragment(self, stream, *args, **kwargs):
"""Parse a HTML fragment into a well-formed tree fragment
:arg container: name of the element we're setting the innerHTML
property if set to None, default to 'div'
:arg stream: a file-like object or string containing the HTML to be parsed
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element)
:arg scripting: treat noscript elements as if JavaScript was turned on
:returns: parsed tree
Example:
>>> from html5lib.html5libparser import HTMLParser
>>> parser = HTMLParser()
>>> parser.parseFragment('<b>this is a fragment</b>')
<Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090>
"""
self._parse(stream, True, *args, **kwargs)
return self.tree.getFragment() | [
"def",
"parseFragment",
"(",
"self",
",",
"stream",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_parse",
"(",
"stream",
",",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"tree",
".",
"getFragment",
"(",
")"
] | Parse a HTML fragment into a well-formed tree fragment
:arg container: name of the element we're setting the innerHTML
property if set to None, default to 'div'
:arg stream: a file-like object or string containing the HTML to be parsed
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element)
:arg scripting: treat noscript elements as if JavaScript was turned on
:returns: parsed tree
Example:
>>> from html5lib.html5libparser import HTMLParser
>>> parser = HTMLParser()
>>> parser.parseFragment('<b>this is a fragment</b>')
<Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090> | [
"Parse",
"a",
"HTML",
"fragment",
"into",
"a",
"well",
"-",
"formed",
"tree",
"fragment"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/html5parser.py#L292-L318 |
25,345 | pypa/pipenv | pipenv/vendor/pipdeptree.py | construct_tree | def construct_tree(index):
"""Construct tree representation of the pkgs from the index.
The keys of the dict representing the tree will be objects of type
DistPackage and the values will be list of ReqPackage objects.
:param dict index: dist index ie. index of pkgs by their keys
:returns: tree of pkgs and their dependencies
:rtype: dict
"""
return dict((p, [ReqPackage(r, index.get(r.key))
for r in p.requires()])
for p in index.values()) | python | def construct_tree(index):
"""Construct tree representation of the pkgs from the index.
The keys of the dict representing the tree will be objects of type
DistPackage and the values will be list of ReqPackage objects.
:param dict index: dist index ie. index of pkgs by their keys
:returns: tree of pkgs and their dependencies
:rtype: dict
"""
return dict((p, [ReqPackage(r, index.get(r.key))
for r in p.requires()])
for p in index.values()) | [
"def",
"construct_tree",
"(",
"index",
")",
":",
"return",
"dict",
"(",
"(",
"p",
",",
"[",
"ReqPackage",
"(",
"r",
",",
"index",
".",
"get",
"(",
"r",
".",
"key",
")",
")",
"for",
"r",
"in",
"p",
".",
"requires",
"(",
")",
"]",
")",
"for",
"p",
"in",
"index",
".",
"values",
"(",
")",
")"
] | Construct tree representation of the pkgs from the index.
The keys of the dict representing the tree will be objects of type
DistPackage and the values will be list of ReqPackage objects.
:param dict index: dist index ie. index of pkgs by their keys
:returns: tree of pkgs and their dependencies
:rtype: dict | [
"Construct",
"tree",
"representation",
"of",
"the",
"pkgs",
"from",
"the",
"index",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L42-L55 |
25,346 | pypa/pipenv | pipenv/vendor/pipdeptree.py | sorted_tree | def sorted_tree(tree):
"""Sorts the dict representation of the tree
The root packages as well as the intermediate packages are sorted
in the alphabetical order of the package names.
:param dict tree: the pkg dependency tree obtained by calling
`construct_tree` function
:returns: sorted tree
:rtype: collections.OrderedDict
"""
return OrderedDict(sorted([(k, sorted(v, key=attrgetter('key')))
for k, v in tree.items()],
key=lambda kv: kv[0].key)) | python | def sorted_tree(tree):
"""Sorts the dict representation of the tree
The root packages as well as the intermediate packages are sorted
in the alphabetical order of the package names.
:param dict tree: the pkg dependency tree obtained by calling
`construct_tree` function
:returns: sorted tree
:rtype: collections.OrderedDict
"""
return OrderedDict(sorted([(k, sorted(v, key=attrgetter('key')))
for k, v in tree.items()],
key=lambda kv: kv[0].key)) | [
"def",
"sorted_tree",
"(",
"tree",
")",
":",
"return",
"OrderedDict",
"(",
"sorted",
"(",
"[",
"(",
"k",
",",
"sorted",
"(",
"v",
",",
"key",
"=",
"attrgetter",
"(",
"'key'",
")",
")",
")",
"for",
"k",
",",
"v",
"in",
"tree",
".",
"items",
"(",
")",
"]",
",",
"key",
"=",
"lambda",
"kv",
":",
"kv",
"[",
"0",
"]",
".",
"key",
")",
")"
] | Sorts the dict representation of the tree
The root packages as well as the intermediate packages are sorted
in the alphabetical order of the package names.
:param dict tree: the pkg dependency tree obtained by calling
`construct_tree` function
:returns: sorted tree
:rtype: collections.OrderedDict | [
"Sorts",
"the",
"dict",
"representation",
"of",
"the",
"tree"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L58-L72 |
25,347 | pypa/pipenv | pipenv/vendor/pipdeptree.py | find_tree_root | def find_tree_root(tree, key):
"""Find a root in a tree by it's key
:param dict tree: the pkg dependency tree obtained by calling
`construct_tree` function
:param str key: key of the root node to find
:returns: a root node if found else None
:rtype: mixed
"""
result = [p for p in tree.keys() if p.key == key]
assert len(result) in [0, 1]
return None if len(result) == 0 else result[0] | python | def find_tree_root(tree, key):
"""Find a root in a tree by it's key
:param dict tree: the pkg dependency tree obtained by calling
`construct_tree` function
:param str key: key of the root node to find
:returns: a root node if found else None
:rtype: mixed
"""
result = [p for p in tree.keys() if p.key == key]
assert len(result) in [0, 1]
return None if len(result) == 0 else result[0] | [
"def",
"find_tree_root",
"(",
"tree",
",",
"key",
")",
":",
"result",
"=",
"[",
"p",
"for",
"p",
"in",
"tree",
".",
"keys",
"(",
")",
"if",
"p",
".",
"key",
"==",
"key",
"]",
"assert",
"len",
"(",
"result",
")",
"in",
"[",
"0",
",",
"1",
"]",
"return",
"None",
"if",
"len",
"(",
"result",
")",
"==",
"0",
"else",
"result",
"[",
"0",
"]"
] | Find a root in a tree by it's key
:param dict tree: the pkg dependency tree obtained by calling
`construct_tree` function
:param str key: key of the root node to find
:returns: a root node if found else None
:rtype: mixed | [
"Find",
"a",
"root",
"in",
"a",
"tree",
"by",
"it",
"s",
"key"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L75-L87 |
25,348 | pypa/pipenv | pipenv/vendor/pipdeptree.py | reverse_tree | def reverse_tree(tree):
"""Reverse the dependency tree.
ie. the keys of the resulting dict are objects of type
ReqPackage and the values are lists of DistPackage objects.
:param dict tree: the pkg dependency tree obtained by calling
`construct_tree` function
:returns: reversed tree
:rtype: dict
"""
rtree = defaultdict(list)
child_keys = set(c.key for c in flatten(tree.values()))
for k, vs in tree.items():
for v in vs:
node = find_tree_root(rtree, v.key) or v
rtree[node].append(k.as_required_by(v))
if k.key not in child_keys:
rtree[k.as_requirement()] = []
return rtree | python | def reverse_tree(tree):
"""Reverse the dependency tree.
ie. the keys of the resulting dict are objects of type
ReqPackage and the values are lists of DistPackage objects.
:param dict tree: the pkg dependency tree obtained by calling
`construct_tree` function
:returns: reversed tree
:rtype: dict
"""
rtree = defaultdict(list)
child_keys = set(c.key for c in flatten(tree.values()))
for k, vs in tree.items():
for v in vs:
node = find_tree_root(rtree, v.key) or v
rtree[node].append(k.as_required_by(v))
if k.key not in child_keys:
rtree[k.as_requirement()] = []
return rtree | [
"def",
"reverse_tree",
"(",
"tree",
")",
":",
"rtree",
"=",
"defaultdict",
"(",
"list",
")",
"child_keys",
"=",
"set",
"(",
"c",
".",
"key",
"for",
"c",
"in",
"flatten",
"(",
"tree",
".",
"values",
"(",
")",
")",
")",
"for",
"k",
",",
"vs",
"in",
"tree",
".",
"items",
"(",
")",
":",
"for",
"v",
"in",
"vs",
":",
"node",
"=",
"find_tree_root",
"(",
"rtree",
",",
"v",
".",
"key",
")",
"or",
"v",
"rtree",
"[",
"node",
"]",
".",
"append",
"(",
"k",
".",
"as_required_by",
"(",
"v",
")",
")",
"if",
"k",
".",
"key",
"not",
"in",
"child_keys",
":",
"rtree",
"[",
"k",
".",
"as_requirement",
"(",
")",
"]",
"=",
"[",
"]",
"return",
"rtree"
] | Reverse the dependency tree.
ie. the keys of the resulting dict are objects of type
ReqPackage and the values are lists of DistPackage objects.
:param dict tree: the pkg dependency tree obtained by calling
`construct_tree` function
:returns: reversed tree
:rtype: dict | [
"Reverse",
"the",
"dependency",
"tree",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L90-L110 |
25,349 | pypa/pipenv | pipenv/vendor/pipdeptree.py | guess_version | def guess_version(pkg_key, default='?'):
"""Guess the version of a pkg when pip doesn't provide it
:param str pkg_key: key of the package
:param str default: default version to return if unable to find
:returns: version
:rtype: string
"""
try:
m = import_module(pkg_key)
except ImportError:
return default
else:
return getattr(m, '__version__', default) | python | def guess_version(pkg_key, default='?'):
"""Guess the version of a pkg when pip doesn't provide it
:param str pkg_key: key of the package
:param str default: default version to return if unable to find
:returns: version
:rtype: string
"""
try:
m = import_module(pkg_key)
except ImportError:
return default
else:
return getattr(m, '__version__', default) | [
"def",
"guess_version",
"(",
"pkg_key",
",",
"default",
"=",
"'?'",
")",
":",
"try",
":",
"m",
"=",
"import_module",
"(",
"pkg_key",
")",
"except",
"ImportError",
":",
"return",
"default",
"else",
":",
"return",
"getattr",
"(",
"m",
",",
"'__version__'",
",",
"default",
")"
] | Guess the version of a pkg when pip doesn't provide it
:param str pkg_key: key of the package
:param str default: default version to return if unable to find
:returns: version
:rtype: string | [
"Guess",
"the",
"version",
"of",
"a",
"pkg",
"when",
"pip",
"doesn",
"t",
"provide",
"it"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L113-L127 |
25,350 | pypa/pipenv | pipenv/vendor/pipdeptree.py | render_tree | def render_tree(tree, list_all=True, show_only=None, frozen=False, exclude=None):
"""Convert tree to string representation
:param dict tree: the package tree
:param bool list_all: whether to list all the pgks at the root
level or only those that are the
sub-dependencies
:param set show_only: set of select packages to be shown in the
output. This is optional arg, default: None.
:param bool frozen: whether or not show the names of the pkgs in
the output that's favourable to pip --freeze
:param set exclude: set of select packages to be excluded from the
output. This is optional arg, default: None.
:returns: string representation of the tree
:rtype: str
"""
tree = sorted_tree(tree)
branch_keys = set(r.key for r in flatten(tree.values()))
nodes = tree.keys()
use_bullets = not frozen
key_tree = dict((k.key, v) for k, v in tree.items())
get_children = lambda n: key_tree.get(n.key, [])
if show_only:
nodes = [p for p in nodes
if p.key in show_only or p.project_name in show_only]
elif not list_all:
nodes = [p for p in nodes if p.key not in branch_keys]
def aux(node, parent=None, indent=0, chain=None):
if exclude and (node.key in exclude or node.project_name in exclude):
return []
if chain is None:
chain = [node.project_name]
node_str = node.render(parent, frozen)
if parent:
prefix = ' '*indent + ('- ' if use_bullets else '')
node_str = prefix + node_str
result = [node_str]
children = [aux(c, node, indent=indent+2,
chain=chain+[c.project_name])
for c in get_children(node)
if c.project_name not in chain]
result += list(flatten(children))
return result
lines = flatten([aux(p) for p in nodes])
return '\n'.join(lines) | python | def render_tree(tree, list_all=True, show_only=None, frozen=False, exclude=None):
"""Convert tree to string representation
:param dict tree: the package tree
:param bool list_all: whether to list all the pgks at the root
level or only those that are the
sub-dependencies
:param set show_only: set of select packages to be shown in the
output. This is optional arg, default: None.
:param bool frozen: whether or not show the names of the pkgs in
the output that's favourable to pip --freeze
:param set exclude: set of select packages to be excluded from the
output. This is optional arg, default: None.
:returns: string representation of the tree
:rtype: str
"""
tree = sorted_tree(tree)
branch_keys = set(r.key for r in flatten(tree.values()))
nodes = tree.keys()
use_bullets = not frozen
key_tree = dict((k.key, v) for k, v in tree.items())
get_children = lambda n: key_tree.get(n.key, [])
if show_only:
nodes = [p for p in nodes
if p.key in show_only or p.project_name in show_only]
elif not list_all:
nodes = [p for p in nodes if p.key not in branch_keys]
def aux(node, parent=None, indent=0, chain=None):
if exclude and (node.key in exclude or node.project_name in exclude):
return []
if chain is None:
chain = [node.project_name]
node_str = node.render(parent, frozen)
if parent:
prefix = ' '*indent + ('- ' if use_bullets else '')
node_str = prefix + node_str
result = [node_str]
children = [aux(c, node, indent=indent+2,
chain=chain+[c.project_name])
for c in get_children(node)
if c.project_name not in chain]
result += list(flatten(children))
return result
lines = flatten([aux(p) for p in nodes])
return '\n'.join(lines) | [
"def",
"render_tree",
"(",
"tree",
",",
"list_all",
"=",
"True",
",",
"show_only",
"=",
"None",
",",
"frozen",
"=",
"False",
",",
"exclude",
"=",
"None",
")",
":",
"tree",
"=",
"sorted_tree",
"(",
"tree",
")",
"branch_keys",
"=",
"set",
"(",
"r",
".",
"key",
"for",
"r",
"in",
"flatten",
"(",
"tree",
".",
"values",
"(",
")",
")",
")",
"nodes",
"=",
"tree",
".",
"keys",
"(",
")",
"use_bullets",
"=",
"not",
"frozen",
"key_tree",
"=",
"dict",
"(",
"(",
"k",
".",
"key",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"tree",
".",
"items",
"(",
")",
")",
"get_children",
"=",
"lambda",
"n",
":",
"key_tree",
".",
"get",
"(",
"n",
".",
"key",
",",
"[",
"]",
")",
"if",
"show_only",
":",
"nodes",
"=",
"[",
"p",
"for",
"p",
"in",
"nodes",
"if",
"p",
".",
"key",
"in",
"show_only",
"or",
"p",
".",
"project_name",
"in",
"show_only",
"]",
"elif",
"not",
"list_all",
":",
"nodes",
"=",
"[",
"p",
"for",
"p",
"in",
"nodes",
"if",
"p",
".",
"key",
"not",
"in",
"branch_keys",
"]",
"def",
"aux",
"(",
"node",
",",
"parent",
"=",
"None",
",",
"indent",
"=",
"0",
",",
"chain",
"=",
"None",
")",
":",
"if",
"exclude",
"and",
"(",
"node",
".",
"key",
"in",
"exclude",
"or",
"node",
".",
"project_name",
"in",
"exclude",
")",
":",
"return",
"[",
"]",
"if",
"chain",
"is",
"None",
":",
"chain",
"=",
"[",
"node",
".",
"project_name",
"]",
"node_str",
"=",
"node",
".",
"render",
"(",
"parent",
",",
"frozen",
")",
"if",
"parent",
":",
"prefix",
"=",
"' '",
"*",
"indent",
"+",
"(",
"'- '",
"if",
"use_bullets",
"else",
"''",
")",
"node_str",
"=",
"prefix",
"+",
"node_str",
"result",
"=",
"[",
"node_str",
"]",
"children",
"=",
"[",
"aux",
"(",
"c",
",",
"node",
",",
"indent",
"=",
"indent",
"+",
"2",
",",
"chain",
"=",
"chain",
"+",
"[",
"c",
".",
"project_name",
"]",
")",
"for",
"c",
"in",
"get_children",
"(",
"node",
")",
"if",
"c",
".",
"project_name",
"not",
"in",
"chain",
"]",
"result",
"+=",
"list",
"(",
"flatten",
"(",
"children",
")",
")",
"return",
"result",
"lines",
"=",
"flatten",
"(",
"[",
"aux",
"(",
"p",
")",
"for",
"p",
"in",
"nodes",
"]",
")",
"return",
"'\\n'",
".",
"join",
"(",
"lines",
")"
] | Convert tree to string representation
:param dict tree: the package tree
:param bool list_all: whether to list all the pgks at the root
level or only those that are the
sub-dependencies
:param set show_only: set of select packages to be shown in the
output. This is optional arg, default: None.
:param bool frozen: whether or not show the names of the pkgs in
the output that's favourable to pip --freeze
:param set exclude: set of select packages to be excluded from the
output. This is optional arg, default: None.
:returns: string representation of the tree
:rtype: str | [
"Convert",
"tree",
"to",
"string",
"representation"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L288-L337 |
25,351 | pypa/pipenv | pipenv/vendor/pipdeptree.py | render_json | def render_json(tree, indent):
"""Converts the tree into a flat json representation.
The json repr will be a list of hashes, each hash having 2 fields:
- package
- dependencies: list of dependencies
:param dict tree: dependency tree
:param int indent: no. of spaces to indent json
:returns: json representation of the tree
:rtype: str
"""
return json.dumps([{'package': k.as_dict(),
'dependencies': [v.as_dict() for v in vs]}
for k, vs in tree.items()],
indent=indent) | python | def render_json(tree, indent):
"""Converts the tree into a flat json representation.
The json repr will be a list of hashes, each hash having 2 fields:
- package
- dependencies: list of dependencies
:param dict tree: dependency tree
:param int indent: no. of spaces to indent json
:returns: json representation of the tree
:rtype: str
"""
return json.dumps([{'package': k.as_dict(),
'dependencies': [v.as_dict() for v in vs]}
for k, vs in tree.items()],
indent=indent) | [
"def",
"render_json",
"(",
"tree",
",",
"indent",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"[",
"{",
"'package'",
":",
"k",
".",
"as_dict",
"(",
")",
",",
"'dependencies'",
":",
"[",
"v",
".",
"as_dict",
"(",
")",
"for",
"v",
"in",
"vs",
"]",
"}",
"for",
"k",
",",
"vs",
"in",
"tree",
".",
"items",
"(",
")",
"]",
",",
"indent",
"=",
"indent",
")"
] | Converts the tree into a flat json representation.
The json repr will be a list of hashes, each hash having 2 fields:
- package
- dependencies: list of dependencies
:param dict tree: dependency tree
:param int indent: no. of spaces to indent json
:returns: json representation of the tree
:rtype: str | [
"Converts",
"the",
"tree",
"into",
"a",
"flat",
"json",
"representation",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L340-L356 |
25,352 | pypa/pipenv | pipenv/vendor/pipdeptree.py | render_json_tree | def render_json_tree(tree, indent):
"""Converts the tree into a nested json representation.
The json repr will be a list of hashes, each hash having the following fields:
- package_name
- key
- required_version
- installed_version
- dependencies: list of dependencies
:param dict tree: dependency tree
:param int indent: no. of spaces to indent json
:returns: json representation of the tree
:rtype: str
"""
tree = sorted_tree(tree)
branch_keys = set(r.key for r in flatten(tree.values()))
nodes = [p for p in tree.keys() if p.key not in branch_keys]
key_tree = dict((k.key, v) for k, v in tree.items())
get_children = lambda n: key_tree.get(n.key, [])
def aux(node, parent=None, chain=None):
if chain is None:
chain = [node.project_name]
d = node.as_dict()
if parent:
d['required_version'] = node.version_spec if node.version_spec else 'Any'
else:
d['required_version'] = d['installed_version']
d['dependencies'] = [
aux(c, parent=node, chain=chain+[c.project_name])
for c in get_children(node)
if c.project_name not in chain
]
return d
return json.dumps([aux(p) for p in nodes], indent=indent) | python | def render_json_tree(tree, indent):
"""Converts the tree into a nested json representation.
The json repr will be a list of hashes, each hash having the following fields:
- package_name
- key
- required_version
- installed_version
- dependencies: list of dependencies
:param dict tree: dependency tree
:param int indent: no. of spaces to indent json
:returns: json representation of the tree
:rtype: str
"""
tree = sorted_tree(tree)
branch_keys = set(r.key for r in flatten(tree.values()))
nodes = [p for p in tree.keys() if p.key not in branch_keys]
key_tree = dict((k.key, v) for k, v in tree.items())
get_children = lambda n: key_tree.get(n.key, [])
def aux(node, parent=None, chain=None):
if chain is None:
chain = [node.project_name]
d = node.as_dict()
if parent:
d['required_version'] = node.version_spec if node.version_spec else 'Any'
else:
d['required_version'] = d['installed_version']
d['dependencies'] = [
aux(c, parent=node, chain=chain+[c.project_name])
for c in get_children(node)
if c.project_name not in chain
]
return d
return json.dumps([aux(p) for p in nodes], indent=indent) | [
"def",
"render_json_tree",
"(",
"tree",
",",
"indent",
")",
":",
"tree",
"=",
"sorted_tree",
"(",
"tree",
")",
"branch_keys",
"=",
"set",
"(",
"r",
".",
"key",
"for",
"r",
"in",
"flatten",
"(",
"tree",
".",
"values",
"(",
")",
")",
")",
"nodes",
"=",
"[",
"p",
"for",
"p",
"in",
"tree",
".",
"keys",
"(",
")",
"if",
"p",
".",
"key",
"not",
"in",
"branch_keys",
"]",
"key_tree",
"=",
"dict",
"(",
"(",
"k",
".",
"key",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"tree",
".",
"items",
"(",
")",
")",
"get_children",
"=",
"lambda",
"n",
":",
"key_tree",
".",
"get",
"(",
"n",
".",
"key",
",",
"[",
"]",
")",
"def",
"aux",
"(",
"node",
",",
"parent",
"=",
"None",
",",
"chain",
"=",
"None",
")",
":",
"if",
"chain",
"is",
"None",
":",
"chain",
"=",
"[",
"node",
".",
"project_name",
"]",
"d",
"=",
"node",
".",
"as_dict",
"(",
")",
"if",
"parent",
":",
"d",
"[",
"'required_version'",
"]",
"=",
"node",
".",
"version_spec",
"if",
"node",
".",
"version_spec",
"else",
"'Any'",
"else",
":",
"d",
"[",
"'required_version'",
"]",
"=",
"d",
"[",
"'installed_version'",
"]",
"d",
"[",
"'dependencies'",
"]",
"=",
"[",
"aux",
"(",
"c",
",",
"parent",
"=",
"node",
",",
"chain",
"=",
"chain",
"+",
"[",
"c",
".",
"project_name",
"]",
")",
"for",
"c",
"in",
"get_children",
"(",
"node",
")",
"if",
"c",
".",
"project_name",
"not",
"in",
"chain",
"]",
"return",
"d",
"return",
"json",
".",
"dumps",
"(",
"[",
"aux",
"(",
"p",
")",
"for",
"p",
"in",
"nodes",
"]",
",",
"indent",
"=",
"indent",
")"
] | Converts the tree into a nested json representation.
The json repr will be a list of hashes, each hash having the following fields:
- package_name
- key
- required_version
- installed_version
- dependencies: list of dependencies
:param dict tree: dependency tree
:param int indent: no. of spaces to indent json
:returns: json representation of the tree
:rtype: str | [
"Converts",
"the",
"tree",
"into",
"a",
"nested",
"json",
"representation",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L359-L399 |
25,353 | pypa/pipenv | pipenv/vendor/pipdeptree.py | dump_graphviz | def dump_graphviz(tree, output_format='dot'):
"""Output dependency graph as one of the supported GraphViz output formats.
:param dict tree: dependency graph
:param string output_format: output format
:returns: representation of tree in the specified output format
:rtype: str or binary representation depending on the output format
"""
try:
from graphviz import backend, Digraph
except ImportError:
print('graphviz is not available, but necessary for the output '
'option. Please install it.', file=sys.stderr)
sys.exit(1)
if output_format not in backend.FORMATS:
print('{0} is not a supported output format.'.format(output_format),
file=sys.stderr)
print('Supported formats are: {0}'.format(
', '.join(sorted(backend.FORMATS))), file=sys.stderr)
sys.exit(1)
graph = Digraph(format=output_format)
for package, deps in tree.items():
project_name = package.project_name
label = '{0}\n{1}'.format(project_name, package.version)
graph.node(project_name, label=label)
for dep in deps:
label = dep.version_spec
if not label:
label = 'any'
graph.edge(project_name, dep.project_name, label=label)
# Allow output of dot format, even if GraphViz isn't installed.
if output_format == 'dot':
return graph.source
# As it's unknown if the selected output format is binary or not, try to
# decode it as UTF8 and only print it out in binary if that's not possible.
try:
return graph.pipe().decode('utf-8')
except UnicodeDecodeError:
return graph.pipe() | python | def dump_graphviz(tree, output_format='dot'):
"""Output dependency graph as one of the supported GraphViz output formats.
:param dict tree: dependency graph
:param string output_format: output format
:returns: representation of tree in the specified output format
:rtype: str or binary representation depending on the output format
"""
try:
from graphviz import backend, Digraph
except ImportError:
print('graphviz is not available, but necessary for the output '
'option. Please install it.', file=sys.stderr)
sys.exit(1)
if output_format not in backend.FORMATS:
print('{0} is not a supported output format.'.format(output_format),
file=sys.stderr)
print('Supported formats are: {0}'.format(
', '.join(sorted(backend.FORMATS))), file=sys.stderr)
sys.exit(1)
graph = Digraph(format=output_format)
for package, deps in tree.items():
project_name = package.project_name
label = '{0}\n{1}'.format(project_name, package.version)
graph.node(project_name, label=label)
for dep in deps:
label = dep.version_spec
if not label:
label = 'any'
graph.edge(project_name, dep.project_name, label=label)
# Allow output of dot format, even if GraphViz isn't installed.
if output_format == 'dot':
return graph.source
# As it's unknown if the selected output format is binary or not, try to
# decode it as UTF8 and only print it out in binary if that's not possible.
try:
return graph.pipe().decode('utf-8')
except UnicodeDecodeError:
return graph.pipe() | [
"def",
"dump_graphviz",
"(",
"tree",
",",
"output_format",
"=",
"'dot'",
")",
":",
"try",
":",
"from",
"graphviz",
"import",
"backend",
",",
"Digraph",
"except",
"ImportError",
":",
"print",
"(",
"'graphviz is not available, but necessary for the output '",
"'option. Please install it.'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"output_format",
"not",
"in",
"backend",
".",
"FORMATS",
":",
"print",
"(",
"'{0} is not a supported output format.'",
".",
"format",
"(",
"output_format",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"'Supported formats are: {0}'",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"sorted",
"(",
"backend",
".",
"FORMATS",
")",
")",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"graph",
"=",
"Digraph",
"(",
"format",
"=",
"output_format",
")",
"for",
"package",
",",
"deps",
"in",
"tree",
".",
"items",
"(",
")",
":",
"project_name",
"=",
"package",
".",
"project_name",
"label",
"=",
"'{0}\\n{1}'",
".",
"format",
"(",
"project_name",
",",
"package",
".",
"version",
")",
"graph",
".",
"node",
"(",
"project_name",
",",
"label",
"=",
"label",
")",
"for",
"dep",
"in",
"deps",
":",
"label",
"=",
"dep",
".",
"version_spec",
"if",
"not",
"label",
":",
"label",
"=",
"'any'",
"graph",
".",
"edge",
"(",
"project_name",
",",
"dep",
".",
"project_name",
",",
"label",
"=",
"label",
")",
"# Allow output of dot format, even if GraphViz isn't installed.",
"if",
"output_format",
"==",
"'dot'",
":",
"return",
"graph",
".",
"source",
"# As it's unknown if the selected output format is binary or not, try to",
"# decode it as UTF8 and only print it out in binary if that's not possible.",
"try",
":",
"return",
"graph",
".",
"pipe",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"UnicodeDecodeError",
":",
"return",
"graph",
".",
"pipe",
"(",
")"
] | Output dependency graph as one of the supported GraphViz output formats.
:param dict tree: dependency graph
:param string output_format: output format
:returns: representation of tree in the specified output format
:rtype: str or binary representation depending on the output format | [
"Output",
"dependency",
"graph",
"as",
"one",
"of",
"the",
"supported",
"GraphViz",
"output",
"formats",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L402-L445 |
25,354 | pypa/pipenv | pipenv/vendor/pipdeptree.py | print_graphviz | def print_graphviz(dump_output):
"""Dump the data generated by GraphViz to stdout.
:param dump_output: The output from dump_graphviz
"""
if hasattr(dump_output, 'encode'):
print(dump_output)
else:
with os.fdopen(sys.stdout.fileno(), 'wb') as bytestream:
bytestream.write(dump_output) | python | def print_graphviz(dump_output):
"""Dump the data generated by GraphViz to stdout.
:param dump_output: The output from dump_graphviz
"""
if hasattr(dump_output, 'encode'):
print(dump_output)
else:
with os.fdopen(sys.stdout.fileno(), 'wb') as bytestream:
bytestream.write(dump_output) | [
"def",
"print_graphviz",
"(",
"dump_output",
")",
":",
"if",
"hasattr",
"(",
"dump_output",
",",
"'encode'",
")",
":",
"print",
"(",
"dump_output",
")",
"else",
":",
"with",
"os",
".",
"fdopen",
"(",
"sys",
".",
"stdout",
".",
"fileno",
"(",
")",
",",
"'wb'",
")",
"as",
"bytestream",
":",
"bytestream",
".",
"write",
"(",
"dump_output",
")"
] | Dump the data generated by GraphViz to stdout.
:param dump_output: The output from dump_graphviz | [
"Dump",
"the",
"data",
"generated",
"by",
"GraphViz",
"to",
"stdout",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L448-L457 |
25,355 | pypa/pipenv | pipenv/vendor/pipdeptree.py | conflicting_deps | def conflicting_deps(tree):
"""Returns dependencies which are not present or conflict with the
requirements of other packages.
e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed
:param tree: the requirements tree (dict)
:returns: dict of DistPackage -> list of unsatisfied/unknown ReqPackage
:rtype: dict
"""
conflicting = defaultdict(list)
for p, rs in tree.items():
for req in rs:
if req.is_conflicting():
conflicting[p].append(req)
return conflicting | python | def conflicting_deps(tree):
"""Returns dependencies which are not present or conflict with the
requirements of other packages.
e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed
:param tree: the requirements tree (dict)
:returns: dict of DistPackage -> list of unsatisfied/unknown ReqPackage
:rtype: dict
"""
conflicting = defaultdict(list)
for p, rs in tree.items():
for req in rs:
if req.is_conflicting():
conflicting[p].append(req)
return conflicting | [
"def",
"conflicting_deps",
"(",
"tree",
")",
":",
"conflicting",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"p",
",",
"rs",
"in",
"tree",
".",
"items",
"(",
")",
":",
"for",
"req",
"in",
"rs",
":",
"if",
"req",
".",
"is_conflicting",
"(",
")",
":",
"conflicting",
"[",
"p",
"]",
".",
"append",
"(",
"req",
")",
"return",
"conflicting"
] | Returns dependencies which are not present or conflict with the
requirements of other packages.
e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed
:param tree: the requirements tree (dict)
:returns: dict of DistPackage -> list of unsatisfied/unknown ReqPackage
:rtype: dict | [
"Returns",
"dependencies",
"which",
"are",
"not",
"present",
"or",
"conflict",
"with",
"the",
"requirements",
"of",
"other",
"packages",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L460-L476 |
25,356 | pypa/pipenv | pipenv/vendor/pipdeptree.py | cyclic_deps | def cyclic_deps(tree):
"""Return cyclic dependencies as list of tuples
:param list pkgs: pkg_resources.Distribution instances
:param dict pkg_index: mapping of pkgs with their respective keys
:returns: list of tuples representing cyclic dependencies
:rtype: generator
"""
key_tree = dict((k.key, v) for k, v in tree.items())
get_children = lambda n: key_tree.get(n.key, [])
cyclic = []
for p, rs in tree.items():
for req in rs:
if p.key in map(attrgetter('key'), get_children(req)):
cyclic.append((p, req, p))
return cyclic | python | def cyclic_deps(tree):
"""Return cyclic dependencies as list of tuples
:param list pkgs: pkg_resources.Distribution instances
:param dict pkg_index: mapping of pkgs with their respective keys
:returns: list of tuples representing cyclic dependencies
:rtype: generator
"""
key_tree = dict((k.key, v) for k, v in tree.items())
get_children = lambda n: key_tree.get(n.key, [])
cyclic = []
for p, rs in tree.items():
for req in rs:
if p.key in map(attrgetter('key'), get_children(req)):
cyclic.append((p, req, p))
return cyclic | [
"def",
"cyclic_deps",
"(",
"tree",
")",
":",
"key_tree",
"=",
"dict",
"(",
"(",
"k",
".",
"key",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"tree",
".",
"items",
"(",
")",
")",
"get_children",
"=",
"lambda",
"n",
":",
"key_tree",
".",
"get",
"(",
"n",
".",
"key",
",",
"[",
"]",
")",
"cyclic",
"=",
"[",
"]",
"for",
"p",
",",
"rs",
"in",
"tree",
".",
"items",
"(",
")",
":",
"for",
"req",
"in",
"rs",
":",
"if",
"p",
".",
"key",
"in",
"map",
"(",
"attrgetter",
"(",
"'key'",
")",
",",
"get_children",
"(",
"req",
")",
")",
":",
"cyclic",
".",
"append",
"(",
"(",
"p",
",",
"req",
",",
"p",
")",
")",
"return",
"cyclic"
] | Return cyclic dependencies as list of tuples
:param list pkgs: pkg_resources.Distribution instances
:param dict pkg_index: mapping of pkgs with their respective keys
:returns: list of tuples representing cyclic dependencies
:rtype: generator | [
"Return",
"cyclic",
"dependencies",
"as",
"list",
"of",
"tuples"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L479-L495 |
25,357 | pypa/pipenv | pipenv/vendor/pipdeptree.py | ReqPackage.is_conflicting | def is_conflicting(self):
"""If installed version conflicts with required version"""
# unknown installed version is also considered conflicting
if self.installed_version == self.UNKNOWN_VERSION:
return True
ver_spec = (self.version_spec if self.version_spec else '')
req_version_str = '{0}{1}'.format(self.project_name, ver_spec)
req_obj = pkg_resources.Requirement.parse(req_version_str)
return self.installed_version not in req_obj | python | def is_conflicting(self):
"""If installed version conflicts with required version"""
# unknown installed version is also considered conflicting
if self.installed_version == self.UNKNOWN_VERSION:
return True
ver_spec = (self.version_spec if self.version_spec else '')
req_version_str = '{0}{1}'.format(self.project_name, ver_spec)
req_obj = pkg_resources.Requirement.parse(req_version_str)
return self.installed_version not in req_obj | [
"def",
"is_conflicting",
"(",
"self",
")",
":",
"# unknown installed version is also considered conflicting",
"if",
"self",
".",
"installed_version",
"==",
"self",
".",
"UNKNOWN_VERSION",
":",
"return",
"True",
"ver_spec",
"=",
"(",
"self",
".",
"version_spec",
"if",
"self",
".",
"version_spec",
"else",
"''",
")",
"req_version_str",
"=",
"'{0}{1}'",
".",
"format",
"(",
"self",
".",
"project_name",
",",
"ver_spec",
")",
"req_obj",
"=",
"pkg_resources",
".",
"Requirement",
".",
"parse",
"(",
"req_version_str",
")",
"return",
"self",
".",
"installed_version",
"not",
"in",
"req_obj"
] | If installed version conflicts with required version | [
"If",
"installed",
"version",
"conflicts",
"with",
"required",
"version"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L254-L262 |
25,358 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/hashes.py | Hashes.check_against_chunks | def check_against_chunks(self, chunks):
# type: (Iterator[bytes]) -> None
"""Check good hashes against ones built from iterable of chunks of
data.
Raise HashMismatch if none match.
"""
gots = {}
for hash_name in iterkeys(self._allowed):
try:
gots[hash_name] = hashlib.new(hash_name)
except (ValueError, TypeError):
raise InstallationError('Unknown hash name: %s' % hash_name)
for chunk in chunks:
for hash in itervalues(gots):
hash.update(chunk)
for hash_name, got in iteritems(gots):
if got.hexdigest() in self._allowed[hash_name]:
return
self._raise(gots) | python | def check_against_chunks(self, chunks):
# type: (Iterator[bytes]) -> None
"""Check good hashes against ones built from iterable of chunks of
data.
Raise HashMismatch if none match.
"""
gots = {}
for hash_name in iterkeys(self._allowed):
try:
gots[hash_name] = hashlib.new(hash_name)
except (ValueError, TypeError):
raise InstallationError('Unknown hash name: %s' % hash_name)
for chunk in chunks:
for hash in itervalues(gots):
hash.update(chunk)
for hash_name, got in iteritems(gots):
if got.hexdigest() in self._allowed[hash_name]:
return
self._raise(gots) | [
"def",
"check_against_chunks",
"(",
"self",
",",
"chunks",
")",
":",
"# type: (Iterator[bytes]) -> None",
"gots",
"=",
"{",
"}",
"for",
"hash_name",
"in",
"iterkeys",
"(",
"self",
".",
"_allowed",
")",
":",
"try",
":",
"gots",
"[",
"hash_name",
"]",
"=",
"hashlib",
".",
"new",
"(",
"hash_name",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"raise",
"InstallationError",
"(",
"'Unknown hash name: %s'",
"%",
"hash_name",
")",
"for",
"chunk",
"in",
"chunks",
":",
"for",
"hash",
"in",
"itervalues",
"(",
"gots",
")",
":",
"hash",
".",
"update",
"(",
"chunk",
")",
"for",
"hash_name",
",",
"got",
"in",
"iteritems",
"(",
"gots",
")",
":",
"if",
"got",
".",
"hexdigest",
"(",
")",
"in",
"self",
".",
"_allowed",
"[",
"hash_name",
"]",
":",
"return",
"self",
".",
"_raise",
"(",
"gots",
")"
] | Check good hashes against ones built from iterable of chunks of
data.
Raise HashMismatch if none match. | [
"Check",
"good",
"hashes",
"against",
"ones",
"built",
"from",
"iterable",
"of",
"chunks",
"of",
"data",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/hashes.py#L47-L69 |
25,359 | pypa/pipenv | pipenv/vendor/cerberus/validator.py | BareValidator._drop_nodes_from_errorpaths | def _drop_nodes_from_errorpaths(self, _errors, dp_items, sp_items):
""" Removes nodes by index from an errorpath, relatively to the
basepaths of self.
:param errors: A list of :class:`errors.ValidationError` instances.
:param dp_items: A list of integers, pointing at the nodes to drop from
the :attr:`document_path`.
:param sp_items: Alike ``dp_items``, but for :attr:`schema_path`.
"""
dp_basedepth = len(self.document_path)
sp_basedepth = len(self.schema_path)
for error in _errors:
for i in sorted(dp_items, reverse=True):
error.document_path = \
drop_item_from_tuple(error.document_path, dp_basedepth + i)
for i in sorted(sp_items, reverse=True):
error.schema_path = \
drop_item_from_tuple(error.schema_path, sp_basedepth + i)
if error.child_errors:
self._drop_nodes_from_errorpaths(error.child_errors,
dp_items, sp_items) | python | def _drop_nodes_from_errorpaths(self, _errors, dp_items, sp_items):
""" Removes nodes by index from an errorpath, relatively to the
basepaths of self.
:param errors: A list of :class:`errors.ValidationError` instances.
:param dp_items: A list of integers, pointing at the nodes to drop from
the :attr:`document_path`.
:param sp_items: Alike ``dp_items``, but for :attr:`schema_path`.
"""
dp_basedepth = len(self.document_path)
sp_basedepth = len(self.schema_path)
for error in _errors:
for i in sorted(dp_items, reverse=True):
error.document_path = \
drop_item_from_tuple(error.document_path, dp_basedepth + i)
for i in sorted(sp_items, reverse=True):
error.schema_path = \
drop_item_from_tuple(error.schema_path, sp_basedepth + i)
if error.child_errors:
self._drop_nodes_from_errorpaths(error.child_errors,
dp_items, sp_items) | [
"def",
"_drop_nodes_from_errorpaths",
"(",
"self",
",",
"_errors",
",",
"dp_items",
",",
"sp_items",
")",
":",
"dp_basedepth",
"=",
"len",
"(",
"self",
".",
"document_path",
")",
"sp_basedepth",
"=",
"len",
"(",
"self",
".",
"schema_path",
")",
"for",
"error",
"in",
"_errors",
":",
"for",
"i",
"in",
"sorted",
"(",
"dp_items",
",",
"reverse",
"=",
"True",
")",
":",
"error",
".",
"document_path",
"=",
"drop_item_from_tuple",
"(",
"error",
".",
"document_path",
",",
"dp_basedepth",
"+",
"i",
")",
"for",
"i",
"in",
"sorted",
"(",
"sp_items",
",",
"reverse",
"=",
"True",
")",
":",
"error",
".",
"schema_path",
"=",
"drop_item_from_tuple",
"(",
"error",
".",
"schema_path",
",",
"sp_basedepth",
"+",
"i",
")",
"if",
"error",
".",
"child_errors",
":",
"self",
".",
"_drop_nodes_from_errorpaths",
"(",
"error",
".",
"child_errors",
",",
"dp_items",
",",
"sp_items",
")"
] | Removes nodes by index from an errorpath, relatively to the
basepaths of self.
:param errors: A list of :class:`errors.ValidationError` instances.
:param dp_items: A list of integers, pointing at the nodes to drop from
the :attr:`document_path`.
:param sp_items: Alike ``dp_items``, but for :attr:`schema_path`. | [
"Removes",
"nodes",
"by",
"index",
"from",
"an",
"errorpath",
"relatively",
"to",
"the",
"basepaths",
"of",
"self",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L341-L361 |
25,360 | pypa/pipenv | pipenv/vendor/cerberus/validator.py | BareValidator._lookup_field | def _lookup_field(self, path):
""" Searches for a field as defined by path. This method is used by the
``dependency`` evaluation logic.
:param path: Path elements are separated by a ``.``. A leading ``^``
indicates that the path relates to the document root,
otherwise it relates to the currently evaluated document,
which is possibly a subdocument.
The sequence ``^^`` at the start will be interpreted as a
literal ``^``.
:type path: :class:`str`
:returns: Either the found field name and its value or :obj:`None` for
both.
:rtype: A two-value :class:`tuple`.
"""
if path.startswith('^'):
path = path[1:]
context = self.document if path.startswith('^') \
else self.root_document
else:
context = self.document
parts = path.split('.')
for part in parts:
if part not in context:
return None, None
context = context.get(part)
return parts[-1], context | python | def _lookup_field(self, path):
""" Searches for a field as defined by path. This method is used by the
``dependency`` evaluation logic.
:param path: Path elements are separated by a ``.``. A leading ``^``
indicates that the path relates to the document root,
otherwise it relates to the currently evaluated document,
which is possibly a subdocument.
The sequence ``^^`` at the start will be interpreted as a
literal ``^``.
:type path: :class:`str`
:returns: Either the found field name and its value or :obj:`None` for
both.
:rtype: A two-value :class:`tuple`.
"""
if path.startswith('^'):
path = path[1:]
context = self.document if path.startswith('^') \
else self.root_document
else:
context = self.document
parts = path.split('.')
for part in parts:
if part not in context:
return None, None
context = context.get(part)
return parts[-1], context | [
"def",
"_lookup_field",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"'^'",
")",
":",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"context",
"=",
"self",
".",
"document",
"if",
"path",
".",
"startswith",
"(",
"'^'",
")",
"else",
"self",
".",
"root_document",
"else",
":",
"context",
"=",
"self",
".",
"document",
"parts",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"for",
"part",
"in",
"parts",
":",
"if",
"part",
"not",
"in",
"context",
":",
"return",
"None",
",",
"None",
"context",
"=",
"context",
".",
"get",
"(",
"part",
")",
"return",
"parts",
"[",
"-",
"1",
"]",
",",
"context"
] | Searches for a field as defined by path. This method is used by the
``dependency`` evaluation logic.
:param path: Path elements are separated by a ``.``. A leading ``^``
indicates that the path relates to the document root,
otherwise it relates to the currently evaluated document,
which is possibly a subdocument.
The sequence ``^^`` at the start will be interpreted as a
literal ``^``.
:type path: :class:`str`
:returns: Either the found field name and its value or :obj:`None` for
both.
:rtype: A two-value :class:`tuple`. | [
"Searches",
"for",
"a",
"field",
"as",
"defined",
"by",
"path",
".",
"This",
"method",
"is",
"used",
"by",
"the",
"dependency",
"evaluation",
"logic",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L363-L391 |
25,361 | pypa/pipenv | pipenv/vendor/cerberus/validator.py | BareValidator._drop_remaining_rules | def _drop_remaining_rules(self, *rules):
""" Drops rules from the queue of the rules that still need to be
evaluated for the currently processed field.
If no arguments are given, the whole queue is emptied.
"""
if rules:
for rule in rules:
try:
self._remaining_rules.remove(rule)
except ValueError:
pass
else:
self._remaining_rules = [] | python | def _drop_remaining_rules(self, *rules):
""" Drops rules from the queue of the rules that still need to be
evaluated for the currently processed field.
If no arguments are given, the whole queue is emptied.
"""
if rules:
for rule in rules:
try:
self._remaining_rules.remove(rule)
except ValueError:
pass
else:
self._remaining_rules = [] | [
"def",
"_drop_remaining_rules",
"(",
"self",
",",
"*",
"rules",
")",
":",
"if",
"rules",
":",
"for",
"rule",
"in",
"rules",
":",
"try",
":",
"self",
".",
"_remaining_rules",
".",
"remove",
"(",
"rule",
")",
"except",
"ValueError",
":",
"pass",
"else",
":",
"self",
".",
"_remaining_rules",
"=",
"[",
"]"
] | Drops rules from the queue of the rules that still need to be
evaluated for the currently processed field.
If no arguments are given, the whole queue is emptied. | [
"Drops",
"rules",
"from",
"the",
"queue",
"of",
"the",
"rules",
"that",
"still",
"need",
"to",
"be",
"evaluated",
"for",
"the",
"currently",
"processed",
"field",
".",
"If",
"no",
"arguments",
"are",
"given",
"the",
"whole",
"queue",
"is",
"emptied",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L561-L573 |
25,362 | pypa/pipenv | pipenv/vendor/cerberus/validator.py | BareValidator.normalized | def normalized(self, document, schema=None, always_return_document=False):
""" Returns the document normalized according to the specified rules
of a schema.
:param document: The document to normalize.
:type document: any :term:`mapping`
:param schema: The validation schema. Defaults to :obj:`None`. If not
provided here, the schema must have been provided at
class instantiation.
:type schema: any :term:`mapping`
:param always_return_document: Return the document, even if an error
occurred. Defaults to: ``False``.
:type always_return_document: :class:`bool`
:return: A normalized copy of the provided mapping or :obj:`None` if an
error occurred during normalization.
"""
self.__init_processing(document, schema)
self.__normalize_mapping(self.document, self.schema)
self.error_handler.end(self)
if self._errors and not always_return_document:
return None
else:
return self.document | python | def normalized(self, document, schema=None, always_return_document=False):
""" Returns the document normalized according to the specified rules
of a schema.
:param document: The document to normalize.
:type document: any :term:`mapping`
:param schema: The validation schema. Defaults to :obj:`None`. If not
provided here, the schema must have been provided at
class instantiation.
:type schema: any :term:`mapping`
:param always_return_document: Return the document, even if an error
occurred. Defaults to: ``False``.
:type always_return_document: :class:`bool`
:return: A normalized copy of the provided mapping or :obj:`None` if an
error occurred during normalization.
"""
self.__init_processing(document, schema)
self.__normalize_mapping(self.document, self.schema)
self.error_handler.end(self)
if self._errors and not always_return_document:
return None
else:
return self.document | [
"def",
"normalized",
"(",
"self",
",",
"document",
",",
"schema",
"=",
"None",
",",
"always_return_document",
"=",
"False",
")",
":",
"self",
".",
"__init_processing",
"(",
"document",
",",
"schema",
")",
"self",
".",
"__normalize_mapping",
"(",
"self",
".",
"document",
",",
"self",
".",
"schema",
")",
"self",
".",
"error_handler",
".",
"end",
"(",
"self",
")",
"if",
"self",
".",
"_errors",
"and",
"not",
"always_return_document",
":",
"return",
"None",
"else",
":",
"return",
"self",
".",
"document"
] | Returns the document normalized according to the specified rules
of a schema.
:param document: The document to normalize.
:type document: any :term:`mapping`
:param schema: The validation schema. Defaults to :obj:`None`. If not
provided here, the schema must have been provided at
class instantiation.
:type schema: any :term:`mapping`
:param always_return_document: Return the document, even if an error
occurred. Defaults to: ``False``.
:type always_return_document: :class:`bool`
:return: A normalized copy of the provided mapping or :obj:`None` if an
error occurred during normalization. | [
"Returns",
"the",
"document",
"normalized",
"according",
"to",
"the",
"specified",
"rules",
"of",
"a",
"schema",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L577-L599 |
25,363 | pypa/pipenv | pipenv/vendor/cerberus/validator.py | BareValidator.validate | def validate(self, document, schema=None, update=False, normalize=True):
""" Normalizes and validates a mapping against a validation-schema of
defined rules.
:param document: The document to normalize.
:type document: any :term:`mapping`
:param schema: The validation schema. Defaults to :obj:`None`. If not
provided here, the schema must have been provided at
class instantiation.
:type schema: any :term:`mapping`
:param update: If ``True``, required fields won't be checked.
:type update: :class:`bool`
:param normalize: If ``True``, normalize the document before validation.
:type normalize: :class:`bool`
:return: ``True`` if validation succeeds, otherwise ``False``. Check
the :func:`errors` property for a list of processing errors.
:rtype: :class:`bool`
"""
self.update = update
self._unrequired_by_excludes = set()
self.__init_processing(document, schema)
if normalize:
self.__normalize_mapping(self.document, self.schema)
for field in self.document:
if self.ignore_none_values and self.document[field] is None:
continue
definitions = self.schema.get(field)
if definitions is not None:
self.__validate_definitions(definitions, field)
else:
self.__validate_unknown_fields(field)
if not self.update:
self.__validate_required_fields(self.document)
self.error_handler.end(self)
return not bool(self._errors) | python | def validate(self, document, schema=None, update=False, normalize=True):
""" Normalizes and validates a mapping against a validation-schema of
defined rules.
:param document: The document to normalize.
:type document: any :term:`mapping`
:param schema: The validation schema. Defaults to :obj:`None`. If not
provided here, the schema must have been provided at
class instantiation.
:type schema: any :term:`mapping`
:param update: If ``True``, required fields won't be checked.
:type update: :class:`bool`
:param normalize: If ``True``, normalize the document before validation.
:type normalize: :class:`bool`
:return: ``True`` if validation succeeds, otherwise ``False``. Check
the :func:`errors` property for a list of processing errors.
:rtype: :class:`bool`
"""
self.update = update
self._unrequired_by_excludes = set()
self.__init_processing(document, schema)
if normalize:
self.__normalize_mapping(self.document, self.schema)
for field in self.document:
if self.ignore_none_values and self.document[field] is None:
continue
definitions = self.schema.get(field)
if definitions is not None:
self.__validate_definitions(definitions, field)
else:
self.__validate_unknown_fields(field)
if not self.update:
self.__validate_required_fields(self.document)
self.error_handler.end(self)
return not bool(self._errors) | [
"def",
"validate",
"(",
"self",
",",
"document",
",",
"schema",
"=",
"None",
",",
"update",
"=",
"False",
",",
"normalize",
"=",
"True",
")",
":",
"self",
".",
"update",
"=",
"update",
"self",
".",
"_unrequired_by_excludes",
"=",
"set",
"(",
")",
"self",
".",
"__init_processing",
"(",
"document",
",",
"schema",
")",
"if",
"normalize",
":",
"self",
".",
"__normalize_mapping",
"(",
"self",
".",
"document",
",",
"self",
".",
"schema",
")",
"for",
"field",
"in",
"self",
".",
"document",
":",
"if",
"self",
".",
"ignore_none_values",
"and",
"self",
".",
"document",
"[",
"field",
"]",
"is",
"None",
":",
"continue",
"definitions",
"=",
"self",
".",
"schema",
".",
"get",
"(",
"field",
")",
"if",
"definitions",
"is",
"not",
"None",
":",
"self",
".",
"__validate_definitions",
"(",
"definitions",
",",
"field",
")",
"else",
":",
"self",
".",
"__validate_unknown_fields",
"(",
"field",
")",
"if",
"not",
"self",
".",
"update",
":",
"self",
".",
"__validate_required_fields",
"(",
"self",
".",
"document",
")",
"self",
".",
"error_handler",
".",
"end",
"(",
"self",
")",
"return",
"not",
"bool",
"(",
"self",
".",
"_errors",
")"
] | Normalizes and validates a mapping against a validation-schema of
defined rules.
:param document: The document to normalize.
:type document: any :term:`mapping`
:param schema: The validation schema. Defaults to :obj:`None`. If not
provided here, the schema must have been provided at
class instantiation.
:type schema: any :term:`mapping`
:param update: If ``True``, required fields won't be checked.
:type update: :class:`bool`
:param normalize: If ``True``, normalize the document before validation.
:type normalize: :class:`bool`
:return: ``True`` if validation succeeds, otherwise ``False``. Check
the :func:`errors` property for a list of processing errors.
:rtype: :class:`bool` | [
"Normalizes",
"and",
"validates",
"a",
"mapping",
"against",
"a",
"validation",
"-",
"schema",
"of",
"defined",
"rules",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L846-L886 |
25,364 | pypa/pipenv | pipenv/vendor/cerberus/validator.py | BareValidator.__validate_logical | def __validate_logical(self, operator, definitions, field, value):
""" Validates value against all definitions and logs errors according
to the operator. """
valid_counter = 0
_errors = errors.ErrorList()
for i, definition in enumerate(definitions):
schema = {field: definition.copy()}
for rule in ('allow_unknown', 'type'):
if rule not in schema[field] and rule in self.schema[field]:
schema[field][rule] = self.schema[field][rule]
if 'allow_unknown' not in schema[field]:
schema[field]['allow_unknown'] = self.allow_unknown
validator = self._get_child_validator(
schema_crumb=(field, operator, i),
schema=schema, allow_unknown=True)
if validator(self.document, update=self.update, normalize=False):
valid_counter += 1
else:
self._drop_nodes_from_errorpaths(validator._errors, [], [3])
_errors.extend(validator._errors)
return valid_counter, _errors | python | def __validate_logical(self, operator, definitions, field, value):
""" Validates value against all definitions and logs errors according
to the operator. """
valid_counter = 0
_errors = errors.ErrorList()
for i, definition in enumerate(definitions):
schema = {field: definition.copy()}
for rule in ('allow_unknown', 'type'):
if rule not in schema[field] and rule in self.schema[field]:
schema[field][rule] = self.schema[field][rule]
if 'allow_unknown' not in schema[field]:
schema[field]['allow_unknown'] = self.allow_unknown
validator = self._get_child_validator(
schema_crumb=(field, operator, i),
schema=schema, allow_unknown=True)
if validator(self.document, update=self.update, normalize=False):
valid_counter += 1
else:
self._drop_nodes_from_errorpaths(validator._errors, [], [3])
_errors.extend(validator._errors)
return valid_counter, _errors | [
"def",
"__validate_logical",
"(",
"self",
",",
"operator",
",",
"definitions",
",",
"field",
",",
"value",
")",
":",
"valid_counter",
"=",
"0",
"_errors",
"=",
"errors",
".",
"ErrorList",
"(",
")",
"for",
"i",
",",
"definition",
"in",
"enumerate",
"(",
"definitions",
")",
":",
"schema",
"=",
"{",
"field",
":",
"definition",
".",
"copy",
"(",
")",
"}",
"for",
"rule",
"in",
"(",
"'allow_unknown'",
",",
"'type'",
")",
":",
"if",
"rule",
"not",
"in",
"schema",
"[",
"field",
"]",
"and",
"rule",
"in",
"self",
".",
"schema",
"[",
"field",
"]",
":",
"schema",
"[",
"field",
"]",
"[",
"rule",
"]",
"=",
"self",
".",
"schema",
"[",
"field",
"]",
"[",
"rule",
"]",
"if",
"'allow_unknown'",
"not",
"in",
"schema",
"[",
"field",
"]",
":",
"schema",
"[",
"field",
"]",
"[",
"'allow_unknown'",
"]",
"=",
"self",
".",
"allow_unknown",
"validator",
"=",
"self",
".",
"_get_child_validator",
"(",
"schema_crumb",
"=",
"(",
"field",
",",
"operator",
",",
"i",
")",
",",
"schema",
"=",
"schema",
",",
"allow_unknown",
"=",
"True",
")",
"if",
"validator",
"(",
"self",
".",
"document",
",",
"update",
"=",
"self",
".",
"update",
",",
"normalize",
"=",
"False",
")",
":",
"valid_counter",
"+=",
"1",
"else",
":",
"self",
".",
"_drop_nodes_from_errorpaths",
"(",
"validator",
".",
"_errors",
",",
"[",
"]",
",",
"[",
"3",
"]",
")",
"_errors",
".",
"extend",
"(",
"validator",
".",
"_errors",
")",
"return",
"valid_counter",
",",
"_errors"
] | Validates value against all definitions and logs errors according
to the operator. | [
"Validates",
"value",
"against",
"all",
"definitions",
"and",
"logs",
"errors",
"according",
"to",
"the",
"operator",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1062-L1085 |
25,365 | pypa/pipenv | pipenv/vendor/cerberus/validator.py | BareValidator.__validate_required_fields | def __validate_required_fields(self, document):
""" Validates that required fields are not missing.
:param document: The document being validated.
"""
try:
required = set(field for field, definition in self.schema.items()
if self._resolve_rules_set(definition).
get('required') is True)
except AttributeError:
if self.is_child and self.schema_path[-1] == 'schema':
raise _SchemaRuleTypeError
else:
raise
required -= self._unrequired_by_excludes
missing = required - set(field for field in document
if document.get(field) is not None or
not self.ignore_none_values)
for field in missing:
self._error(field, errors.REQUIRED_FIELD)
# At least on field from self._unrequired_by_excludes should be
# present in document
if self._unrequired_by_excludes:
fields = set(field for field in document
if document.get(field) is not None)
if self._unrequired_by_excludes.isdisjoint(fields):
for field in self._unrequired_by_excludes - fields:
self._error(field, errors.REQUIRED_FIELD) | python | def __validate_required_fields(self, document):
""" Validates that required fields are not missing.
:param document: The document being validated.
"""
try:
required = set(field for field, definition in self.schema.items()
if self._resolve_rules_set(definition).
get('required') is True)
except AttributeError:
if self.is_child and self.schema_path[-1] == 'schema':
raise _SchemaRuleTypeError
else:
raise
required -= self._unrequired_by_excludes
missing = required - set(field for field in document
if document.get(field) is not None or
not self.ignore_none_values)
for field in missing:
self._error(field, errors.REQUIRED_FIELD)
# At least on field from self._unrequired_by_excludes should be
# present in document
if self._unrequired_by_excludes:
fields = set(field for field in document
if document.get(field) is not None)
if self._unrequired_by_excludes.isdisjoint(fields):
for field in self._unrequired_by_excludes - fields:
self._error(field, errors.REQUIRED_FIELD) | [
"def",
"__validate_required_fields",
"(",
"self",
",",
"document",
")",
":",
"try",
":",
"required",
"=",
"set",
"(",
"field",
"for",
"field",
",",
"definition",
"in",
"self",
".",
"schema",
".",
"items",
"(",
")",
"if",
"self",
".",
"_resolve_rules_set",
"(",
"definition",
")",
".",
"get",
"(",
"'required'",
")",
"is",
"True",
")",
"except",
"AttributeError",
":",
"if",
"self",
".",
"is_child",
"and",
"self",
".",
"schema_path",
"[",
"-",
"1",
"]",
"==",
"'schema'",
":",
"raise",
"_SchemaRuleTypeError",
"else",
":",
"raise",
"required",
"-=",
"self",
".",
"_unrequired_by_excludes",
"missing",
"=",
"required",
"-",
"set",
"(",
"field",
"for",
"field",
"in",
"document",
"if",
"document",
".",
"get",
"(",
"field",
")",
"is",
"not",
"None",
"or",
"not",
"self",
".",
"ignore_none_values",
")",
"for",
"field",
"in",
"missing",
":",
"self",
".",
"_error",
"(",
"field",
",",
"errors",
".",
"REQUIRED_FIELD",
")",
"# At least on field from self._unrequired_by_excludes should be",
"# present in document",
"if",
"self",
".",
"_unrequired_by_excludes",
":",
"fields",
"=",
"set",
"(",
"field",
"for",
"field",
"in",
"document",
"if",
"document",
".",
"get",
"(",
"field",
")",
"is",
"not",
"None",
")",
"if",
"self",
".",
"_unrequired_by_excludes",
".",
"isdisjoint",
"(",
"fields",
")",
":",
"for",
"field",
"in",
"self",
".",
"_unrequired_by_excludes",
"-",
"fields",
":",
"self",
".",
"_error",
"(",
"field",
",",
"errors",
".",
"REQUIRED_FIELD",
")"
] | Validates that required fields are not missing.
:param document: The document being validated. | [
"Validates",
"that",
"required",
"fields",
"are",
"not",
"missing",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1195-L1224 |
25,366 | pypa/pipenv | pipenv/vendor/jinja2/filters.py | make_attrgetter | def make_attrgetter(environment, attribute, postprocess=None):
"""Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers.
"""
if attribute is None:
attribute = []
elif isinstance(attribute, string_types):
attribute = [int(x) if x.isdigit() else x for x in attribute.split('.')]
else:
attribute = [attribute]
def attrgetter(item):
for part in attribute:
item = environment.getitem(item, part)
if postprocess is not None:
item = postprocess(item)
return item
return attrgetter | python | def make_attrgetter(environment, attribute, postprocess=None):
"""Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers.
"""
if attribute is None:
attribute = []
elif isinstance(attribute, string_types):
attribute = [int(x) if x.isdigit() else x for x in attribute.split('.')]
else:
attribute = [attribute]
def attrgetter(item):
for part in attribute:
item = environment.getitem(item, part)
if postprocess is not None:
item = postprocess(item)
return item
return attrgetter | [
"def",
"make_attrgetter",
"(",
"environment",
",",
"attribute",
",",
"postprocess",
"=",
"None",
")",
":",
"if",
"attribute",
"is",
"None",
":",
"attribute",
"=",
"[",
"]",
"elif",
"isinstance",
"(",
"attribute",
",",
"string_types",
")",
":",
"attribute",
"=",
"[",
"int",
"(",
"x",
")",
"if",
"x",
".",
"isdigit",
"(",
")",
"else",
"x",
"for",
"x",
"in",
"attribute",
".",
"split",
"(",
"'.'",
")",
"]",
"else",
":",
"attribute",
"=",
"[",
"attribute",
"]",
"def",
"attrgetter",
"(",
"item",
")",
":",
"for",
"part",
"in",
"attribute",
":",
"item",
"=",
"environment",
".",
"getitem",
"(",
"item",
",",
"part",
")",
"if",
"postprocess",
"is",
"not",
"None",
":",
"item",
"=",
"postprocess",
"(",
"item",
")",
"return",
"item",
"return",
"attrgetter"
] | Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers. | [
"Returns",
"a",
"callable",
"that",
"looks",
"up",
"the",
"given",
"attribute",
"from",
"a",
"passed",
"object",
"with",
"the",
"rules",
"of",
"the",
"environment",
".",
"Dots",
"are",
"allowed",
"to",
"access",
"attributes",
"of",
"attributes",
".",
"Integer",
"parts",
"in",
"paths",
"are",
"looked",
"up",
"as",
"integers",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L62-L84 |
25,367 | pypa/pipenv | pipenv/vendor/jinja2/filters.py | do_title | def do_title(s):
"""Return a titlecased version of the value. I.e. words will start with
uppercase letters, all remaining characters are lowercase.
"""
return ''.join(
[item[0].upper() + item[1:].lower()
for item in _word_beginning_split_re.split(soft_unicode(s))
if item]) | python | def do_title(s):
"""Return a titlecased version of the value. I.e. words will start with
uppercase letters, all remaining characters are lowercase.
"""
return ''.join(
[item[0].upper() + item[1:].lower()
for item in _word_beginning_split_re.split(soft_unicode(s))
if item]) | [
"def",
"do_title",
"(",
"s",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"item",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"item",
"[",
"1",
":",
"]",
".",
"lower",
"(",
")",
"for",
"item",
"in",
"_word_beginning_split_re",
".",
"split",
"(",
"soft_unicode",
"(",
"s",
")",
")",
"if",
"item",
"]",
")"
] | Return a titlecased version of the value. I.e. words will start with
uppercase letters, all remaining characters are lowercase. | [
"Return",
"a",
"titlecased",
"version",
"of",
"the",
"value",
".",
"I",
".",
"e",
".",
"words",
"will",
"start",
"with",
"uppercase",
"letters",
"all",
"remaining",
"characters",
"are",
"lowercase",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L196-L203 |
25,368 | pypa/pipenv | pipenv/vendor/jinja2/filters.py | do_sort | def do_sort(
environment, value, reverse=False, case_sensitive=False, attribute=None
):
"""Sort an iterable. Per default it sorts ascending, if you pass it
true as first argument it will reverse the sorting.
If the iterable is made of strings the third parameter can be used to
control the case sensitiveness of the comparison which is disabled by
default.
.. sourcecode:: jinja
{% for item in iterable|sort %}
...
{% endfor %}
It is also possible to sort by an attribute (for example to sort
by the date of an object) by specifying the `attribute` parameter:
.. sourcecode:: jinja
{% for item in iterable|sort(attribute='date') %}
...
{% endfor %}
.. versionchanged:: 2.6
The `attribute` parameter was added.
"""
key_func = make_attrgetter(
environment, attribute,
postprocess=ignore_case if not case_sensitive else None
)
return sorted(value, key=key_func, reverse=reverse) | python | def do_sort(
environment, value, reverse=False, case_sensitive=False, attribute=None
):
"""Sort an iterable. Per default it sorts ascending, if you pass it
true as first argument it will reverse the sorting.
If the iterable is made of strings the third parameter can be used to
control the case sensitiveness of the comparison which is disabled by
default.
.. sourcecode:: jinja
{% for item in iterable|sort %}
...
{% endfor %}
It is also possible to sort by an attribute (for example to sort
by the date of an object) by specifying the `attribute` parameter:
.. sourcecode:: jinja
{% for item in iterable|sort(attribute='date') %}
...
{% endfor %}
.. versionchanged:: 2.6
The `attribute` parameter was added.
"""
key_func = make_attrgetter(
environment, attribute,
postprocess=ignore_case if not case_sensitive else None
)
return sorted(value, key=key_func, reverse=reverse) | [
"def",
"do_sort",
"(",
"environment",
",",
"value",
",",
"reverse",
"=",
"False",
",",
"case_sensitive",
"=",
"False",
",",
"attribute",
"=",
"None",
")",
":",
"key_func",
"=",
"make_attrgetter",
"(",
"environment",
",",
"attribute",
",",
"postprocess",
"=",
"ignore_case",
"if",
"not",
"case_sensitive",
"else",
"None",
")",
"return",
"sorted",
"(",
"value",
",",
"key",
"=",
"key_func",
",",
"reverse",
"=",
"reverse",
")"
] | Sort an iterable. Per default it sorts ascending, if you pass it
true as first argument it will reverse the sorting.
If the iterable is made of strings the third parameter can be used to
control the case sensitiveness of the comparison which is disabled by
default.
.. sourcecode:: jinja
{% for item in iterable|sort %}
...
{% endfor %}
It is also possible to sort by an attribute (for example to sort
by the date of an object) by specifying the `attribute` parameter:
.. sourcecode:: jinja
{% for item in iterable|sort(attribute='date') %}
...
{% endfor %}
.. versionchanged:: 2.6
The `attribute` parameter was added. | [
"Sort",
"an",
"iterable",
".",
"Per",
"default",
"it",
"sorts",
"ascending",
"if",
"you",
"pass",
"it",
"true",
"as",
"first",
"argument",
"it",
"will",
"reverse",
"the",
"sorting",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L246-L278 |
25,369 | pypa/pipenv | pipenv/vendor/jinja2/filters.py | do_unique | def do_unique(environment, value, case_sensitive=False, attribute=None):
"""Returns a list of unique items from the the given iterable.
.. sourcecode:: jinja
{{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}
-> ['foo', 'bar', 'foobar']
The unique items are yielded in the same order as their first occurrence in
the iterable passed to the filter.
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Filter objects with unique values for this attribute.
"""
getter = make_attrgetter(
environment, attribute,
postprocess=ignore_case if not case_sensitive else None
)
seen = set()
for item in value:
key = getter(item)
if key not in seen:
seen.add(key)
yield item | python | def do_unique(environment, value, case_sensitive=False, attribute=None):
"""Returns a list of unique items from the the given iterable.
.. sourcecode:: jinja
{{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}
-> ['foo', 'bar', 'foobar']
The unique items are yielded in the same order as their first occurrence in
the iterable passed to the filter.
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Filter objects with unique values for this attribute.
"""
getter = make_attrgetter(
environment, attribute,
postprocess=ignore_case if not case_sensitive else None
)
seen = set()
for item in value:
key = getter(item)
if key not in seen:
seen.add(key)
yield item | [
"def",
"do_unique",
"(",
"environment",
",",
"value",
",",
"case_sensitive",
"=",
"False",
",",
"attribute",
"=",
"None",
")",
":",
"getter",
"=",
"make_attrgetter",
"(",
"environment",
",",
"attribute",
",",
"postprocess",
"=",
"ignore_case",
"if",
"not",
"case_sensitive",
"else",
"None",
")",
"seen",
"=",
"set",
"(",
")",
"for",
"item",
"in",
"value",
":",
"key",
"=",
"getter",
"(",
"item",
")",
"if",
"key",
"not",
"in",
"seen",
":",
"seen",
".",
"add",
"(",
"key",
")",
"yield",
"item"
] | Returns a list of unique items from the the given iterable.
.. sourcecode:: jinja
{{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}
-> ['foo', 'bar', 'foobar']
The unique items are yielded in the same order as their first occurrence in
the iterable passed to the filter.
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Filter objects with unique values for this attribute. | [
"Returns",
"a",
"list",
"of",
"unique",
"items",
"from",
"the",
"the",
"given",
"iterable",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L282-L307 |
25,370 | pypa/pipenv | pipenv/vendor/jinja2/filters.py | do_min | def do_min(environment, value, case_sensitive=False, attribute=None):
"""Return the smallest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|min }}
-> 1
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute.
"""
return _min_or_max(environment, value, min, case_sensitive, attribute) | python | def do_min(environment, value, case_sensitive=False, attribute=None):
"""Return the smallest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|min }}
-> 1
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute.
"""
return _min_or_max(environment, value, min, case_sensitive, attribute) | [
"def",
"do_min",
"(",
"environment",
",",
"value",
",",
"case_sensitive",
"=",
"False",
",",
"attribute",
"=",
"None",
")",
":",
"return",
"_min_or_max",
"(",
"environment",
",",
"value",
",",
"min",
",",
"case_sensitive",
",",
"attribute",
")"
] | Return the smallest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|min }}
-> 1
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute. | [
"Return",
"the",
"smallest",
"item",
"from",
"the",
"sequence",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L326-L337 |
25,371 | pypa/pipenv | pipenv/vendor/jinja2/filters.py | do_max | def do_max(environment, value, case_sensitive=False, attribute=None):
"""Return the largest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|max }}
-> 3
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute.
"""
return _min_or_max(environment, value, max, case_sensitive, attribute) | python | def do_max(environment, value, case_sensitive=False, attribute=None):
"""Return the largest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|max }}
-> 3
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute.
"""
return _min_or_max(environment, value, max, case_sensitive, attribute) | [
"def",
"do_max",
"(",
"environment",
",",
"value",
",",
"case_sensitive",
"=",
"False",
",",
"attribute",
"=",
"None",
")",
":",
"return",
"_min_or_max",
"(",
"environment",
",",
"value",
",",
"max",
",",
"case_sensitive",
",",
"attribute",
")"
] | Return the largest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|max }}
-> 3
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute. | [
"Return",
"the",
"largest",
"item",
"from",
"the",
"sequence",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L341-L352 |
25,372 | pypa/pipenv | pipenv/vendor/jinja2/filters.py | do_last | def do_last(environment, seq):
"""Return the last item of a sequence."""
try:
return next(iter(reversed(seq)))
except StopIteration:
return environment.undefined('No last item, sequence was empty.') | python | def do_last(environment, seq):
"""Return the last item of a sequence."""
try:
return next(iter(reversed(seq)))
except StopIteration:
return environment.undefined('No last item, sequence was empty.') | [
"def",
"do_last",
"(",
"environment",
",",
"seq",
")",
":",
"try",
":",
"return",
"next",
"(",
"iter",
"(",
"reversed",
"(",
"seq",
")",
")",
")",
"except",
"StopIteration",
":",
"return",
"environment",
".",
"undefined",
"(",
"'No last item, sequence was empty.'",
")"
] | Return the last item of a sequence. | [
"Return",
"the",
"last",
"item",
"of",
"a",
"sequence",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L442-L447 |
25,373 | pypa/pipenv | pipenv/vendor/jinja2/filters.py | do_random | def do_random(context, seq):
"""Return a random item from the sequence."""
try:
return random.choice(seq)
except IndexError:
return context.environment.undefined('No random item, sequence was empty.') | python | def do_random(context, seq):
"""Return a random item from the sequence."""
try:
return random.choice(seq)
except IndexError:
return context.environment.undefined('No random item, sequence was empty.') | [
"def",
"do_random",
"(",
"context",
",",
"seq",
")",
":",
"try",
":",
"return",
"random",
".",
"choice",
"(",
"seq",
")",
"except",
"IndexError",
":",
"return",
"context",
".",
"environment",
".",
"undefined",
"(",
"'No random item, sequence was empty.'",
")"
] | Return a random item from the sequence. | [
"Return",
"a",
"random",
"item",
"from",
"the",
"sequence",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L451-L456 |
25,374 | pypa/pipenv | pipenv/vendor/jinja2/filters.py | do_indent | def do_indent(
s, width=4, first=False, blank=False, indentfirst=None
):
"""Return a copy of the string with each line indented by 4 spaces. The
first line and blank lines are not indented by default.
:param width: Number of spaces to indent by.
:param first: Don't skip indenting the first line.
:param blank: Don't skip indenting empty lines.
.. versionchanged:: 2.10
Blank lines are not indented by default.
Rename the ``indentfirst`` argument to ``first``.
"""
if indentfirst is not None:
warnings.warn(DeprecationWarning(
'The "indentfirst" argument is renamed to "first".'
), stacklevel=2)
first = indentfirst
s += u'\n' # this quirk is necessary for splitlines method
indention = u' ' * width
if blank:
rv = (u'\n' + indention).join(s.splitlines())
else:
lines = s.splitlines()
rv = lines.pop(0)
if lines:
rv += u'\n' + u'\n'.join(
indention + line if line else line for line in lines
)
if first:
rv = indention + rv
return rv | python | def do_indent(
s, width=4, first=False, blank=False, indentfirst=None
):
"""Return a copy of the string with each line indented by 4 spaces. The
first line and blank lines are not indented by default.
:param width: Number of spaces to indent by.
:param first: Don't skip indenting the first line.
:param blank: Don't skip indenting empty lines.
.. versionchanged:: 2.10
Blank lines are not indented by default.
Rename the ``indentfirst`` argument to ``first``.
"""
if indentfirst is not None:
warnings.warn(DeprecationWarning(
'The "indentfirst" argument is renamed to "first".'
), stacklevel=2)
first = indentfirst
s += u'\n' # this quirk is necessary for splitlines method
indention = u' ' * width
if blank:
rv = (u'\n' + indention).join(s.splitlines())
else:
lines = s.splitlines()
rv = lines.pop(0)
if lines:
rv += u'\n' + u'\n'.join(
indention + line if line else line for line in lines
)
if first:
rv = indention + rv
return rv | [
"def",
"do_indent",
"(",
"s",
",",
"width",
"=",
"4",
",",
"first",
"=",
"False",
",",
"blank",
"=",
"False",
",",
"indentfirst",
"=",
"None",
")",
":",
"if",
"indentfirst",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"DeprecationWarning",
"(",
"'The \"indentfirst\" argument is renamed to \"first\".'",
")",
",",
"stacklevel",
"=",
"2",
")",
"first",
"=",
"indentfirst",
"s",
"+=",
"u'\\n'",
"# this quirk is necessary for splitlines method",
"indention",
"=",
"u' '",
"*",
"width",
"if",
"blank",
":",
"rv",
"=",
"(",
"u'\\n'",
"+",
"indention",
")",
".",
"join",
"(",
"s",
".",
"splitlines",
"(",
")",
")",
"else",
":",
"lines",
"=",
"s",
".",
"splitlines",
"(",
")",
"rv",
"=",
"lines",
".",
"pop",
"(",
"0",
")",
"if",
"lines",
":",
"rv",
"+=",
"u'\\n'",
"+",
"u'\\n'",
".",
"join",
"(",
"indention",
"+",
"line",
"if",
"line",
"else",
"line",
"for",
"line",
"in",
"lines",
")",
"if",
"first",
":",
"rv",
"=",
"indention",
"+",
"rv",
"return",
"rv"
] | Return a copy of the string with each line indented by 4 spaces. The
first line and blank lines are not indented by default.
:param width: Number of spaces to indent by.
:param first: Don't skip indenting the first line.
:param blank: Don't skip indenting empty lines.
.. versionchanged:: 2.10
Blank lines are not indented by default.
Rename the ``indentfirst`` argument to ``first``. | [
"Return",
"a",
"copy",
"of",
"the",
"string",
"with",
"each",
"line",
"indented",
"by",
"4",
"spaces",
".",
"The",
"first",
"line",
"and",
"blank",
"lines",
"are",
"not",
"indented",
"by",
"default",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L536-L574 |
25,375 | pypa/pipenv | pipenv/vendor/jinja2/filters.py | do_wordwrap | def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words)) | python | def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words)) | [
"def",
"do_wordwrap",
"(",
"environment",
",",
"s",
",",
"width",
"=",
"79",
",",
"break_long_words",
"=",
"True",
",",
"wrapstring",
"=",
"None",
")",
":",
"if",
"not",
"wrapstring",
":",
"wrapstring",
"=",
"environment",
".",
"newline_sequence",
"import",
"textwrap",
"return",
"wrapstring",
".",
"join",
"(",
"textwrap",
".",
"wrap",
"(",
"s",
",",
"width",
"=",
"width",
",",
"expand_tabs",
"=",
"False",
",",
"replace_whitespace",
"=",
"False",
",",
"break_long_words",
"=",
"break_long_words",
")",
")"
] | Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter. | [
"Return",
"a",
"copy",
"of",
"the",
"string",
"passed",
"to",
"the",
"filter",
"wrapped",
"after",
"79",
"characters",
".",
"You",
"can",
"override",
"this",
"default",
"using",
"the",
"first",
"parameter",
".",
"If",
"you",
"set",
"the",
"second",
"parameter",
"to",
"false",
"Jinja",
"will",
"not",
"split",
"words",
"apart",
"if",
"they",
"are",
"longer",
"than",
"width",
".",
"By",
"default",
"the",
"newlines",
"will",
"be",
"the",
"default",
"newlines",
"for",
"the",
"environment",
"but",
"this",
"can",
"be",
"changed",
"using",
"the",
"wrapstring",
"keyword",
"argument",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L615-L633 |
25,376 | pypa/pipenv | pipenv/vendor/jinja2/filters.py | do_reverse | def do_reverse(value):
"""Reverse the object or return an iterator that iterates over it the other
way round.
"""
if isinstance(value, string_types):
return value[::-1]
try:
return reversed(value)
except TypeError:
try:
rv = list(value)
rv.reverse()
return rv
except TypeError:
raise FilterArgumentError('argument must be iterable') | python | def do_reverse(value):
"""Reverse the object or return an iterator that iterates over it the other
way round.
"""
if isinstance(value, string_types):
return value[::-1]
try:
return reversed(value)
except TypeError:
try:
rv = list(value)
rv.reverse()
return rv
except TypeError:
raise FilterArgumentError('argument must be iterable') | [
"def",
"do_reverse",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"return",
"value",
"[",
":",
":",
"-",
"1",
"]",
"try",
":",
"return",
"reversed",
"(",
"value",
")",
"except",
"TypeError",
":",
"try",
":",
"rv",
"=",
"list",
"(",
"value",
")",
"rv",
".",
"reverse",
"(",
")",
"return",
"rv",
"except",
"TypeError",
":",
"raise",
"FilterArgumentError",
"(",
"'argument must be iterable'",
")"
] | Reverse the object or return an iterator that iterates over it the other
way round. | [
"Reverse",
"the",
"object",
"or",
"return",
"an",
"iterator",
"that",
"iterates",
"over",
"it",
"the",
"other",
"way",
"round",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L895-L909 |
25,377 | pypa/pipenv | pipenv/vendor/jinja2/filters.py | do_map | def do_map(*args, **kwargs):
"""Applies a filter on a sequence of objects or looks up an attribute.
This is useful when dealing with lists of objects but you are really
only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list
of users but you are only interested in a list of usernames:
.. sourcecode:: jinja
Users on this page: {{ users|map(attribute='username')|join(', ') }}
Alternatively you can let it invoke a filter by passing the name of the
filter and the arguments afterwards. A good example would be applying a
text conversion filter on a sequence:
.. sourcecode:: jinja
Users on this page: {{ titles|map('lower')|join(', ') }}
.. versionadded:: 2.7
"""
seq, func = prepare_map(args, kwargs)
if seq:
for item in seq:
yield func(item) | python | def do_map(*args, **kwargs):
"""Applies a filter on a sequence of objects or looks up an attribute.
This is useful when dealing with lists of objects but you are really
only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list
of users but you are only interested in a list of usernames:
.. sourcecode:: jinja
Users on this page: {{ users|map(attribute='username')|join(', ') }}
Alternatively you can let it invoke a filter by passing the name of the
filter and the arguments afterwards. A good example would be applying a
text conversion filter on a sequence:
.. sourcecode:: jinja
Users on this page: {{ titles|map('lower')|join(', ') }}
.. versionadded:: 2.7
"""
seq, func = prepare_map(args, kwargs)
if seq:
for item in seq:
yield func(item) | [
"def",
"do_map",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"seq",
",",
"func",
"=",
"prepare_map",
"(",
"args",
",",
"kwargs",
")",
"if",
"seq",
":",
"for",
"item",
"in",
"seq",
":",
"yield",
"func",
"(",
"item",
")"
] | Applies a filter on a sequence of objects or looks up an attribute.
This is useful when dealing with lists of objects but you are really
only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list
of users but you are only interested in a list of usernames:
.. sourcecode:: jinja
Users on this page: {{ users|map(attribute='username')|join(', ') }}
Alternatively you can let it invoke a filter by passing the name of the
filter and the arguments afterwards. A good example would be applying a
text conversion filter on a sequence:
.. sourcecode:: jinja
Users on this page: {{ titles|map('lower')|join(', ') }}
.. versionadded:: 2.7 | [
"Applies",
"a",
"filter",
"on",
"a",
"sequence",
"of",
"objects",
"or",
"looks",
"up",
"an",
"attribute",
".",
"This",
"is",
"useful",
"when",
"dealing",
"with",
"lists",
"of",
"objects",
"but",
"you",
"are",
"really",
"only",
"interested",
"in",
"a",
"certain",
"value",
"of",
"it",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L938-L963 |
25,378 | pypa/pipenv | pipenv/patched/notpip/_internal/cli/autocompletion.py | auto_complete_paths | def auto_complete_paths(current, completion_type):
"""If ``completion_type`` is ``file`` or ``path``, list all regular files
and directories starting with ``current``; otherwise only list directories
starting with ``current``.
:param current: The word to be completed
:param completion_type: path completion type(`file`, `path` or `dir`)i
:return: A generator of regular files and/or directories
"""
directory, filename = os.path.split(current)
current_path = os.path.abspath(directory)
# Don't complete paths if they can't be accessed
if not os.access(current_path, os.R_OK):
return
filename = os.path.normcase(filename)
# list all files that start with ``filename``
file_list = (x for x in os.listdir(current_path)
if os.path.normcase(x).startswith(filename))
for f in file_list:
opt = os.path.join(current_path, f)
comp_file = os.path.normcase(os.path.join(directory, f))
# complete regular files when there is not ``<dir>`` after option
# complete directories when there is ``<file>``, ``<path>`` or
# ``<dir>``after option
if completion_type != 'dir' and os.path.isfile(opt):
yield comp_file
elif os.path.isdir(opt):
yield os.path.join(comp_file, '') | python | def auto_complete_paths(current, completion_type):
"""If ``completion_type`` is ``file`` or ``path``, list all regular files
and directories starting with ``current``; otherwise only list directories
starting with ``current``.
:param current: The word to be completed
:param completion_type: path completion type(`file`, `path` or `dir`)i
:return: A generator of regular files and/or directories
"""
directory, filename = os.path.split(current)
current_path = os.path.abspath(directory)
# Don't complete paths if they can't be accessed
if not os.access(current_path, os.R_OK):
return
filename = os.path.normcase(filename)
# list all files that start with ``filename``
file_list = (x for x in os.listdir(current_path)
if os.path.normcase(x).startswith(filename))
for f in file_list:
opt = os.path.join(current_path, f)
comp_file = os.path.normcase(os.path.join(directory, f))
# complete regular files when there is not ``<dir>`` after option
# complete directories when there is ``<file>``, ``<path>`` or
# ``<dir>``after option
if completion_type != 'dir' and os.path.isfile(opt):
yield comp_file
elif os.path.isdir(opt):
yield os.path.join(comp_file, '') | [
"def",
"auto_complete_paths",
"(",
"current",
",",
"completion_type",
")",
":",
"directory",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"current",
")",
"current_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")",
"# Don't complete paths if they can't be accessed",
"if",
"not",
"os",
".",
"access",
"(",
"current_path",
",",
"os",
".",
"R_OK",
")",
":",
"return",
"filename",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"filename",
")",
"# list all files that start with ``filename``",
"file_list",
"=",
"(",
"x",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"current_path",
")",
"if",
"os",
".",
"path",
".",
"normcase",
"(",
"x",
")",
".",
"startswith",
"(",
"filename",
")",
")",
"for",
"f",
"in",
"file_list",
":",
"opt",
"=",
"os",
".",
"path",
".",
"join",
"(",
"current_path",
",",
"f",
")",
"comp_file",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"f",
")",
")",
"# complete regular files when there is not ``<dir>`` after option",
"# complete directories when there is ``<file>``, ``<path>`` or",
"# ``<dir>``after option",
"if",
"completion_type",
"!=",
"'dir'",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"opt",
")",
":",
"yield",
"comp_file",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"opt",
")",
":",
"yield",
"os",
".",
"path",
".",
"join",
"(",
"comp_file",
",",
"''",
")"
] | If ``completion_type`` is ``file`` or ``path``, list all regular files
and directories starting with ``current``; otherwise only list directories
starting with ``current``.
:param current: The word to be completed
:param completion_type: path completion type(`file`, `path` or `dir`)i
:return: A generator of regular files and/or directories | [
"If",
"completion_type",
"is",
"file",
"or",
"path",
"list",
"all",
"regular",
"files",
"and",
"directories",
"starting",
"with",
"current",
";",
"otherwise",
"only",
"list",
"directories",
"starting",
"with",
"current",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/autocompletion.py#L125-L152 |
25,379 | pypa/pipenv | pipenv/vendor/passa/internals/_pip_shims.py | _build_wheel_modern | def _build_wheel_modern(ireq, output_dir, finder, wheel_cache, kwargs):
"""Build a wheel.
* ireq: The InstallRequirement object to build
* output_dir: The directory to build the wheel in.
* finder: pip's internal Finder object to find the source out of ireq.
* kwargs: Various keyword arguments from `_prepare_wheel_building_kwargs`.
"""
kwargs.update({"progress_bar": "off", "build_isolation": False})
with pip_shims.RequirementTracker() as req_tracker:
if req_tracker:
kwargs["req_tracker"] = req_tracker
preparer = pip_shims.RequirementPreparer(**kwargs)
builder = pip_shims.WheelBuilder(finder, preparer, wheel_cache)
return builder._build_one(ireq, output_dir) | python | def _build_wheel_modern(ireq, output_dir, finder, wheel_cache, kwargs):
"""Build a wheel.
* ireq: The InstallRequirement object to build
* output_dir: The directory to build the wheel in.
* finder: pip's internal Finder object to find the source out of ireq.
* kwargs: Various keyword arguments from `_prepare_wheel_building_kwargs`.
"""
kwargs.update({"progress_bar": "off", "build_isolation": False})
with pip_shims.RequirementTracker() as req_tracker:
if req_tracker:
kwargs["req_tracker"] = req_tracker
preparer = pip_shims.RequirementPreparer(**kwargs)
builder = pip_shims.WheelBuilder(finder, preparer, wheel_cache)
return builder._build_one(ireq, output_dir) | [
"def",
"_build_wheel_modern",
"(",
"ireq",
",",
"output_dir",
",",
"finder",
",",
"wheel_cache",
",",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"\"progress_bar\"",
":",
"\"off\"",
",",
"\"build_isolation\"",
":",
"False",
"}",
")",
"with",
"pip_shims",
".",
"RequirementTracker",
"(",
")",
"as",
"req_tracker",
":",
"if",
"req_tracker",
":",
"kwargs",
"[",
"\"req_tracker\"",
"]",
"=",
"req_tracker",
"preparer",
"=",
"pip_shims",
".",
"RequirementPreparer",
"(",
"*",
"*",
"kwargs",
")",
"builder",
"=",
"pip_shims",
".",
"WheelBuilder",
"(",
"finder",
",",
"preparer",
",",
"wheel_cache",
")",
"return",
"builder",
".",
"_build_one",
"(",
"ireq",
",",
"output_dir",
")"
] | Build a wheel.
* ireq: The InstallRequirement object to build
* output_dir: The directory to build the wheel in.
* finder: pip's internal Finder object to find the source out of ireq.
* kwargs: Various keyword arguments from `_prepare_wheel_building_kwargs`. | [
"Build",
"a",
"wheel",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/_pip_shims.py#L24-L38 |
25,380 | pypa/pipenv | pipenv/vendor/pythonfinder/utils.py | get_python_version | def get_python_version(path):
# type: (str) -> str
"""Get python version string using subprocess from a given path."""
version_cmd = [path, "-c", "import sys; print(sys.version.split()[0])"]
try:
c = vistir.misc.run(
version_cmd,
block=True,
nospin=True,
return_object=True,
combine_stderr=False,
write_to_stdout=False,
)
except OSError:
raise InvalidPythonVersion("%s is not a valid python path" % path)
if not c.out:
raise InvalidPythonVersion("%s is not a valid python path" % path)
return c.out.strip() | python | def get_python_version(path):
# type: (str) -> str
"""Get python version string using subprocess from a given path."""
version_cmd = [path, "-c", "import sys; print(sys.version.split()[0])"]
try:
c = vistir.misc.run(
version_cmd,
block=True,
nospin=True,
return_object=True,
combine_stderr=False,
write_to_stdout=False,
)
except OSError:
raise InvalidPythonVersion("%s is not a valid python path" % path)
if not c.out:
raise InvalidPythonVersion("%s is not a valid python path" % path)
return c.out.strip() | [
"def",
"get_python_version",
"(",
"path",
")",
":",
"# type: (str) -> str",
"version_cmd",
"=",
"[",
"path",
",",
"\"-c\"",
",",
"\"import sys; print(sys.version.split()[0])\"",
"]",
"try",
":",
"c",
"=",
"vistir",
".",
"misc",
".",
"run",
"(",
"version_cmd",
",",
"block",
"=",
"True",
",",
"nospin",
"=",
"True",
",",
"return_object",
"=",
"True",
",",
"combine_stderr",
"=",
"False",
",",
"write_to_stdout",
"=",
"False",
",",
")",
"except",
"OSError",
":",
"raise",
"InvalidPythonVersion",
"(",
"\"%s is not a valid python path\"",
"%",
"path",
")",
"if",
"not",
"c",
".",
"out",
":",
"raise",
"InvalidPythonVersion",
"(",
"\"%s is not a valid python path\"",
"%",
"path",
")",
"return",
"c",
".",
"out",
".",
"strip",
"(",
")"
] | Get python version string using subprocess from a given path. | [
"Get",
"python",
"version",
"string",
"using",
"subprocess",
"from",
"a",
"given",
"path",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pythonfinder/utils.py#L87-L104 |
25,381 | pypa/pipenv | pipenv/vendor/pythonfinder/utils.py | path_is_known_executable | def path_is_known_executable(path):
# type: (vistir.compat.Path) -> bool
"""
Returns whether a given path is a known executable from known executable extensions
or has the executable bit toggled.
:param path: The path to the target executable.
:type path: :class:`~vistir.compat.Path`
:return: True if the path has chmod +x, or is a readable, known executable extension.
:rtype: bool
"""
return (
path_is_executable(path)
or os.access(str(path), os.R_OK)
and path.suffix in KNOWN_EXTS
) | python | def path_is_known_executable(path):
# type: (vistir.compat.Path) -> bool
"""
Returns whether a given path is a known executable from known executable extensions
or has the executable bit toggled.
:param path: The path to the target executable.
:type path: :class:`~vistir.compat.Path`
:return: True if the path has chmod +x, or is a readable, known executable extension.
:rtype: bool
"""
return (
path_is_executable(path)
or os.access(str(path), os.R_OK)
and path.suffix in KNOWN_EXTS
) | [
"def",
"path_is_known_executable",
"(",
"path",
")",
":",
"# type: (vistir.compat.Path) -> bool",
"return",
"(",
"path_is_executable",
"(",
"path",
")",
"or",
"os",
".",
"access",
"(",
"str",
"(",
"path",
")",
",",
"os",
".",
"R_OK",
")",
"and",
"path",
".",
"suffix",
"in",
"KNOWN_EXTS",
")"
] | Returns whether a given path is a known executable from known executable extensions
or has the executable bit toggled.
:param path: The path to the target executable.
:type path: :class:`~vistir.compat.Path`
:return: True if the path has chmod +x, or is a readable, known executable extension.
:rtype: bool | [
"Returns",
"whether",
"a",
"given",
"path",
"is",
"a",
"known",
"executable",
"from",
"known",
"executable",
"extensions",
"or",
"has",
"the",
"executable",
"bit",
"toggled",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pythonfinder/utils.py#L181-L197 |
25,382 | pypa/pipenv | pipenv/vendor/pythonfinder/utils.py | looks_like_python | def looks_like_python(name):
# type: (str) -> bool
"""
Determine whether the supplied filename looks like a possible name of python.
:param str name: The name of the provided file.
:return: Whether the provided name looks like python.
:rtype: bool
"""
if not any(name.lower().startswith(py_name) for py_name in PYTHON_IMPLEMENTATIONS):
return False
match = RE_MATCHER.match(name)
if match:
return any(fnmatch(name, rule) for rule in MATCH_RULES)
return False | python | def looks_like_python(name):
# type: (str) -> bool
"""
Determine whether the supplied filename looks like a possible name of python.
:param str name: The name of the provided file.
:return: Whether the provided name looks like python.
:rtype: bool
"""
if not any(name.lower().startswith(py_name) for py_name in PYTHON_IMPLEMENTATIONS):
return False
match = RE_MATCHER.match(name)
if match:
return any(fnmatch(name, rule) for rule in MATCH_RULES)
return False | [
"def",
"looks_like_python",
"(",
"name",
")",
":",
"# type: (str) -> bool",
"if",
"not",
"any",
"(",
"name",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"py_name",
")",
"for",
"py_name",
"in",
"PYTHON_IMPLEMENTATIONS",
")",
":",
"return",
"False",
"match",
"=",
"RE_MATCHER",
".",
"match",
"(",
"name",
")",
"if",
"match",
":",
"return",
"any",
"(",
"fnmatch",
"(",
"name",
",",
"rule",
")",
"for",
"rule",
"in",
"MATCH_RULES",
")",
"return",
"False"
] | Determine whether the supplied filename looks like a possible name of python.
:param str name: The name of the provided file.
:return: Whether the provided name looks like python.
:rtype: bool | [
"Determine",
"whether",
"the",
"supplied",
"filename",
"looks",
"like",
"a",
"possible",
"name",
"of",
"python",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pythonfinder/utils.py#L201-L216 |
25,383 | pypa/pipenv | pipenv/vendor/pythonfinder/utils.py | filter_pythons | def filter_pythons(path):
# type: (Union[str, vistir.compat.Path]) -> Iterable
"""Return all valid pythons in a given path"""
if not isinstance(path, vistir.compat.Path):
path = vistir.compat.Path(str(path))
if not path.is_dir():
return path if path_is_python(path) else None
return filter(path_is_python, path.iterdir()) | python | def filter_pythons(path):
# type: (Union[str, vistir.compat.Path]) -> Iterable
"""Return all valid pythons in a given path"""
if not isinstance(path, vistir.compat.Path):
path = vistir.compat.Path(str(path))
if not path.is_dir():
return path if path_is_python(path) else None
return filter(path_is_python, path.iterdir()) | [
"def",
"filter_pythons",
"(",
"path",
")",
":",
"# type: (Union[str, vistir.compat.Path]) -> Iterable",
"if",
"not",
"isinstance",
"(",
"path",
",",
"vistir",
".",
"compat",
".",
"Path",
")",
":",
"path",
"=",
"vistir",
".",
"compat",
".",
"Path",
"(",
"str",
"(",
"path",
")",
")",
"if",
"not",
"path",
".",
"is_dir",
"(",
")",
":",
"return",
"path",
"if",
"path_is_python",
"(",
"path",
")",
"else",
"None",
"return",
"filter",
"(",
"path_is_python",
",",
"path",
".",
"iterdir",
"(",
")",
")"
] | Return all valid pythons in a given path | [
"Return",
"all",
"valid",
"pythons",
"in",
"a",
"given",
"path"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pythonfinder/utils.py#L270-L277 |
25,384 | pypa/pipenv | pipenv/patched/notpip/_internal/cache.py | Cache._get_cache_path_parts | def _get_cache_path_parts(self, link):
# type: (Link) -> List[str]
"""Get parts of part that must be os.path.joined with cache_dir
"""
# We want to generate an url to use as our cache key, we don't want to
# just re-use the URL because it might have other items in the fragment
# and we don't care about those.
key_parts = [link.url_without_fragment]
if link.hash_name is not None and link.hash is not None:
key_parts.append("=".join([link.hash_name, link.hash]))
key_url = "#".join(key_parts)
# Encode our key url with sha224, we'll use this because it has similar
# security properties to sha256, but with a shorter total output (and
# thus less secure). However the differences don't make a lot of
# difference for our use case here.
hashed = hashlib.sha224(key_url.encode()).hexdigest()
# We want to nest the directories some to prevent having a ton of top
# level directories where we might run out of sub directories on some
# FS.
parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
return parts | python | def _get_cache_path_parts(self, link):
# type: (Link) -> List[str]
"""Get parts of part that must be os.path.joined with cache_dir
"""
# We want to generate an url to use as our cache key, we don't want to
# just re-use the URL because it might have other items in the fragment
# and we don't care about those.
key_parts = [link.url_without_fragment]
if link.hash_name is not None and link.hash is not None:
key_parts.append("=".join([link.hash_name, link.hash]))
key_url = "#".join(key_parts)
# Encode our key url with sha224, we'll use this because it has similar
# security properties to sha256, but with a shorter total output (and
# thus less secure). However the differences don't make a lot of
# difference for our use case here.
hashed = hashlib.sha224(key_url.encode()).hexdigest()
# We want to nest the directories some to prevent having a ton of top
# level directories where we might run out of sub directories on some
# FS.
parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
return parts | [
"def",
"_get_cache_path_parts",
"(",
"self",
",",
"link",
")",
":",
"# type: (Link) -> List[str]",
"# We want to generate an url to use as our cache key, we don't want to",
"# just re-use the URL because it might have other items in the fragment",
"# and we don't care about those.",
"key_parts",
"=",
"[",
"link",
".",
"url_without_fragment",
"]",
"if",
"link",
".",
"hash_name",
"is",
"not",
"None",
"and",
"link",
".",
"hash",
"is",
"not",
"None",
":",
"key_parts",
".",
"append",
"(",
"\"=\"",
".",
"join",
"(",
"[",
"link",
".",
"hash_name",
",",
"link",
".",
"hash",
"]",
")",
")",
"key_url",
"=",
"\"#\"",
".",
"join",
"(",
"key_parts",
")",
"# Encode our key url with sha224, we'll use this because it has similar",
"# security properties to sha256, but with a shorter total output (and",
"# thus less secure). However the differences don't make a lot of",
"# difference for our use case here.",
"hashed",
"=",
"hashlib",
".",
"sha224",
"(",
"key_url",
".",
"encode",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"# We want to nest the directories some to prevent having a ton of top",
"# level directories where we might run out of sub directories on some",
"# FS.",
"parts",
"=",
"[",
"hashed",
"[",
":",
"2",
"]",
",",
"hashed",
"[",
"2",
":",
"4",
"]",
",",
"hashed",
"[",
"4",
":",
"6",
"]",
",",
"hashed",
"[",
"6",
":",
"]",
"]",
"return",
"parts"
] | Get parts of part that must be os.path.joined with cache_dir | [
"Get",
"parts",
"of",
"part",
"that",
"must",
"be",
"os",
".",
"path",
".",
"joined",
"with",
"cache_dir"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cache.py#L46-L70 |
25,385 | pypa/pipenv | pipenv/patched/notpip/_internal/cache.py | SimpleWheelCache.get_path_for_link | def get_path_for_link(self, link):
# type: (Link) -> str
"""Return a directory to store cached wheels for link
Because there are M wheels for any one sdist, we provide a directory
to cache them in, and then consult that directory when looking up
cache hits.
We only insert things into the cache if they have plausible version
numbers, so that we don't contaminate the cache with things that were
not unique. E.g. ./package might have dozens of installs done for it
and build a version of 0.0...and if we built and cached a wheel, we'd
end up using the same wheel even if the source has been edited.
:param link: The link of the sdist for which this will cache wheels.
"""
parts = self._get_cache_path_parts(link)
# Store wheels within the root cache_dir
return os.path.join(self.cache_dir, "wheels", *parts) | python | def get_path_for_link(self, link):
# type: (Link) -> str
"""Return a directory to store cached wheels for link
Because there are M wheels for any one sdist, we provide a directory
to cache them in, and then consult that directory when looking up
cache hits.
We only insert things into the cache if they have plausible version
numbers, so that we don't contaminate the cache with things that were
not unique. E.g. ./package might have dozens of installs done for it
and build a version of 0.0...and if we built and cached a wheel, we'd
end up using the same wheel even if the source has been edited.
:param link: The link of the sdist for which this will cache wheels.
"""
parts = self._get_cache_path_parts(link)
# Store wheels within the root cache_dir
return os.path.join(self.cache_dir, "wheels", *parts) | [
"def",
"get_path_for_link",
"(",
"self",
",",
"link",
")",
":",
"# type: (Link) -> str",
"parts",
"=",
"self",
".",
"_get_cache_path_parts",
"(",
"link",
")",
"# Store wheels within the root cache_dir",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cache_dir",
",",
"\"wheels\"",
",",
"*",
"parts",
")"
] | Return a directory to store cached wheels for link
Because there are M wheels for any one sdist, we provide a directory
to cache them in, and then consult that directory when looking up
cache hits.
We only insert things into the cache if they have plausible version
numbers, so that we don't contaminate the cache with things that were
not unique. E.g. ./package might have dozens of installs done for it
and build a version of 0.0...and if we built and cached a wheel, we'd
end up using the same wheel even if the source has been edited.
:param link: The link of the sdist for which this will cache wheels. | [
"Return",
"a",
"directory",
"to",
"store",
"cached",
"wheels",
"for",
"link"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cache.py#L132-L151 |
25,386 | pypa/pipenv | pipenv/vendor/passa/internals/dependencies.py | _get_dependencies_from_cache | def _get_dependencies_from_cache(ireq):
"""Retrieves dependencies for the requirement from the dependency cache.
"""
if os.environ.get("PASSA_IGNORE_LOCAL_CACHE"):
return
if ireq.editable:
return
try:
deps = DEPENDENCY_CACHE[ireq]
pyrq = REQUIRES_PYTHON_CACHE[ireq]
except KeyError:
return
# Preserving sanity: Run through the cache and make sure every entry if
# valid. If this fails, something is wrong with the cache. Drop it.
try:
packaging.specifiers.SpecifierSet(pyrq)
ireq_name = packaging.utils.canonicalize_name(ireq.name)
if any(_is_cache_broken(line, ireq_name) for line in deps):
broken = True
else:
broken = False
except Exception:
broken = True
if broken:
print("dropping broken cache for {0}".format(ireq.name))
del DEPENDENCY_CACHE[ireq]
del REQUIRES_PYTHON_CACHE[ireq]
return
return deps, pyrq | python | def _get_dependencies_from_cache(ireq):
"""Retrieves dependencies for the requirement from the dependency cache.
"""
if os.environ.get("PASSA_IGNORE_LOCAL_CACHE"):
return
if ireq.editable:
return
try:
deps = DEPENDENCY_CACHE[ireq]
pyrq = REQUIRES_PYTHON_CACHE[ireq]
except KeyError:
return
# Preserving sanity: Run through the cache and make sure every entry if
# valid. If this fails, something is wrong with the cache. Drop it.
try:
packaging.specifiers.SpecifierSet(pyrq)
ireq_name = packaging.utils.canonicalize_name(ireq.name)
if any(_is_cache_broken(line, ireq_name) for line in deps):
broken = True
else:
broken = False
except Exception:
broken = True
if broken:
print("dropping broken cache for {0}".format(ireq.name))
del DEPENDENCY_CACHE[ireq]
del REQUIRES_PYTHON_CACHE[ireq]
return
return deps, pyrq | [
"def",
"_get_dependencies_from_cache",
"(",
"ireq",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"PASSA_IGNORE_LOCAL_CACHE\"",
")",
":",
"return",
"if",
"ireq",
".",
"editable",
":",
"return",
"try",
":",
"deps",
"=",
"DEPENDENCY_CACHE",
"[",
"ireq",
"]",
"pyrq",
"=",
"REQUIRES_PYTHON_CACHE",
"[",
"ireq",
"]",
"except",
"KeyError",
":",
"return",
"# Preserving sanity: Run through the cache and make sure every entry if",
"# valid. If this fails, something is wrong with the cache. Drop it.",
"try",
":",
"packaging",
".",
"specifiers",
".",
"SpecifierSet",
"(",
"pyrq",
")",
"ireq_name",
"=",
"packaging",
".",
"utils",
".",
"canonicalize_name",
"(",
"ireq",
".",
"name",
")",
"if",
"any",
"(",
"_is_cache_broken",
"(",
"line",
",",
"ireq_name",
")",
"for",
"line",
"in",
"deps",
")",
":",
"broken",
"=",
"True",
"else",
":",
"broken",
"=",
"False",
"except",
"Exception",
":",
"broken",
"=",
"True",
"if",
"broken",
":",
"print",
"(",
"\"dropping broken cache for {0}\"",
".",
"format",
"(",
"ireq",
".",
"name",
")",
")",
"del",
"DEPENDENCY_CACHE",
"[",
"ireq",
"]",
"del",
"REQUIRES_PYTHON_CACHE",
"[",
"ireq",
"]",
"return",
"return",
"deps",
",",
"pyrq"
] | Retrieves dependencies for the requirement from the dependency cache. | [
"Retrieves",
"dependencies",
"for",
"the",
"requirement",
"from",
"the",
"dependency",
"cache",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/dependencies.py#L49-L80 |
25,387 | pypa/pipenv | pipenv/vendor/passa/internals/dependencies.py | _get_dependencies_from_json | def _get_dependencies_from_json(ireq, sources):
"""Retrieves dependencies for the install requirement from the JSON API.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallRequirements.
:rtype: set(str) or None
"""
if os.environ.get("PASSA_IGNORE_JSON_API"):
return
# It is technically possible to parse extras out of the JSON API's
# requirement format, but it is such a chore let's just use the simple API.
if ireq.extras:
return
try:
version = get_pinned_version(ireq)
except ValueError:
return
url_prefixes = [
proc_url[:-7] # Strip "/simple".
for proc_url in (
raw_url.rstrip("/")
for raw_url in (source.get("url", "") for source in sources)
)
if proc_url.endswith("/simple")
]
session = requests.session()
for prefix in url_prefixes:
url = "{prefix}/pypi/{name}/{version}/json".format(
prefix=prefix,
name=packaging.utils.canonicalize_name(ireq.name),
version=version,
)
try:
dependencies = _get_dependencies_from_json_url(url, session)
if dependencies is not None:
return dependencies
except Exception as e:
print("unable to read dependencies via {0} ({1})".format(url, e))
session.close()
return | python | def _get_dependencies_from_json(ireq, sources):
"""Retrieves dependencies for the install requirement from the JSON API.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallRequirements.
:rtype: set(str) or None
"""
if os.environ.get("PASSA_IGNORE_JSON_API"):
return
# It is technically possible to parse extras out of the JSON API's
# requirement format, but it is such a chore let's just use the simple API.
if ireq.extras:
return
try:
version = get_pinned_version(ireq)
except ValueError:
return
url_prefixes = [
proc_url[:-7] # Strip "/simple".
for proc_url in (
raw_url.rstrip("/")
for raw_url in (source.get("url", "") for source in sources)
)
if proc_url.endswith("/simple")
]
session = requests.session()
for prefix in url_prefixes:
url = "{prefix}/pypi/{name}/{version}/json".format(
prefix=prefix,
name=packaging.utils.canonicalize_name(ireq.name),
version=version,
)
try:
dependencies = _get_dependencies_from_json_url(url, session)
if dependencies is not None:
return dependencies
except Exception as e:
print("unable to read dependencies via {0} ({1})".format(url, e))
session.close()
return | [
"def",
"_get_dependencies_from_json",
"(",
"ireq",
",",
"sources",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"PASSA_IGNORE_JSON_API\"",
")",
":",
"return",
"# It is technically possible to parse extras out of the JSON API's",
"# requirement format, but it is such a chore let's just use the simple API.",
"if",
"ireq",
".",
"extras",
":",
"return",
"try",
":",
"version",
"=",
"get_pinned_version",
"(",
"ireq",
")",
"except",
"ValueError",
":",
"return",
"url_prefixes",
"=",
"[",
"proc_url",
"[",
":",
"-",
"7",
"]",
"# Strip \"/simple\".",
"for",
"proc_url",
"in",
"(",
"raw_url",
".",
"rstrip",
"(",
"\"/\"",
")",
"for",
"raw_url",
"in",
"(",
"source",
".",
"get",
"(",
"\"url\"",
",",
"\"\"",
")",
"for",
"source",
"in",
"sources",
")",
")",
"if",
"proc_url",
".",
"endswith",
"(",
"\"/simple\"",
")",
"]",
"session",
"=",
"requests",
".",
"session",
"(",
")",
"for",
"prefix",
"in",
"url_prefixes",
":",
"url",
"=",
"\"{prefix}/pypi/{name}/{version}/json\"",
".",
"format",
"(",
"prefix",
"=",
"prefix",
",",
"name",
"=",
"packaging",
".",
"utils",
".",
"canonicalize_name",
"(",
"ireq",
".",
"name",
")",
",",
"version",
"=",
"version",
",",
")",
"try",
":",
"dependencies",
"=",
"_get_dependencies_from_json_url",
"(",
"url",
",",
"session",
")",
"if",
"dependencies",
"is",
"not",
"None",
":",
"return",
"dependencies",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\"unable to read dependencies via {0} ({1})\"",
".",
"format",
"(",
"url",
",",
"e",
")",
")",
"session",
".",
"close",
"(",
")",
"return"
] | Retrieves dependencies for the install requirement from the JSON API.
: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 | [
"Retrieves",
"dependencies",
"for",
"the",
"install",
"requirement",
"from",
"the",
"JSON",
"API",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/dependencies.py#L113-L158 |
25,388 | pypa/pipenv | pipenv/vendor/passa/internals/dependencies.py | _read_requirements | def _read_requirements(metadata, extras):
"""Read wheel metadata to know what it depends on.
The `run_requires` attribute contains a list of dict or str specifying
requirements. For dicts, it may contain an "extra" key to specify these
requirements are for a specific extra. Unfortunately, not all fields are
specificed like this (I don't know why); some are specified with markers.
So we jump though these terrible hoops to know exactly what we need.
The extra extraction is not comprehensive. Tt assumes the marker is NEVER
something like `extra == "foo" and extra == "bar"`. I guess this never
makes sense anyway? Markers are just terrible.
"""
extras = extras or ()
requirements = []
for entry in metadata.run_requires:
if isinstance(entry, six.text_type):
entry = {"requires": [entry]}
extra = None
else:
extra = entry.get("extra")
if extra is not None and extra not in extras:
continue
for line in entry.get("requires", []):
r = requirementslib.Requirement.from_line(line)
if r.markers:
contained = get_contained_extras(r.markers)
if (contained and not any(e in contained for e in extras)):
continue
marker = get_without_extra(r.markers)
r.markers = str(marker) if marker else None
line = r.as_line(include_hashes=False)
requirements.append(line)
return requirements | python | def _read_requirements(metadata, extras):
"""Read wheel metadata to know what it depends on.
The `run_requires` attribute contains a list of dict or str specifying
requirements. For dicts, it may contain an "extra" key to specify these
requirements are for a specific extra. Unfortunately, not all fields are
specificed like this (I don't know why); some are specified with markers.
So we jump though these terrible hoops to know exactly what we need.
The extra extraction is not comprehensive. Tt assumes the marker is NEVER
something like `extra == "foo" and extra == "bar"`. I guess this never
makes sense anyway? Markers are just terrible.
"""
extras = extras or ()
requirements = []
for entry in metadata.run_requires:
if isinstance(entry, six.text_type):
entry = {"requires": [entry]}
extra = None
else:
extra = entry.get("extra")
if extra is not None and extra not in extras:
continue
for line in entry.get("requires", []):
r = requirementslib.Requirement.from_line(line)
if r.markers:
contained = get_contained_extras(r.markers)
if (contained and not any(e in contained for e in extras)):
continue
marker = get_without_extra(r.markers)
r.markers = str(marker) if marker else None
line = r.as_line(include_hashes=False)
requirements.append(line)
return requirements | [
"def",
"_read_requirements",
"(",
"metadata",
",",
"extras",
")",
":",
"extras",
"=",
"extras",
"or",
"(",
")",
"requirements",
"=",
"[",
"]",
"for",
"entry",
"in",
"metadata",
".",
"run_requires",
":",
"if",
"isinstance",
"(",
"entry",
",",
"six",
".",
"text_type",
")",
":",
"entry",
"=",
"{",
"\"requires\"",
":",
"[",
"entry",
"]",
"}",
"extra",
"=",
"None",
"else",
":",
"extra",
"=",
"entry",
".",
"get",
"(",
"\"extra\"",
")",
"if",
"extra",
"is",
"not",
"None",
"and",
"extra",
"not",
"in",
"extras",
":",
"continue",
"for",
"line",
"in",
"entry",
".",
"get",
"(",
"\"requires\"",
",",
"[",
"]",
")",
":",
"r",
"=",
"requirementslib",
".",
"Requirement",
".",
"from_line",
"(",
"line",
")",
"if",
"r",
".",
"markers",
":",
"contained",
"=",
"get_contained_extras",
"(",
"r",
".",
"markers",
")",
"if",
"(",
"contained",
"and",
"not",
"any",
"(",
"e",
"in",
"contained",
"for",
"e",
"in",
"extras",
")",
")",
":",
"continue",
"marker",
"=",
"get_without_extra",
"(",
"r",
".",
"markers",
")",
"r",
".",
"markers",
"=",
"str",
"(",
"marker",
")",
"if",
"marker",
"else",
"None",
"line",
"=",
"r",
".",
"as_line",
"(",
"include_hashes",
"=",
"False",
")",
"requirements",
".",
"append",
"(",
"line",
")",
"return",
"requirements"
] | Read wheel metadata to know what it depends on.
The `run_requires` attribute contains a list of dict or str specifying
requirements. For dicts, it may contain an "extra" key to specify these
requirements are for a specific extra. Unfortunately, not all fields are
specificed like this (I don't know why); some are specified with markers.
So we jump though these terrible hoops to know exactly what we need.
The extra extraction is not comprehensive. Tt assumes the marker is NEVER
something like `extra == "foo" and extra == "bar"`. I guess this never
makes sense anyway? Markers are just terrible. | [
"Read",
"wheel",
"metadata",
"to",
"know",
"what",
"it",
"depends",
"on",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/dependencies.py#L161-L194 |
25,389 | pypa/pipenv | pipenv/vendor/passa/internals/dependencies.py | _read_requires_python | def _read_requires_python(metadata):
"""Read wheel metadata to know the value of Requires-Python.
This is surprisingly poorly supported in Distlib. This function tries
several ways to get this information:
* Metadata 2.0: metadata.dictionary.get("requires_python") is not None
* Metadata 2.1: metadata._legacy.get("Requires-Python") is not None
* Metadata 1.2: metadata._legacy.get("Requires-Python") != "UNKNOWN"
"""
# TODO: Support more metadata formats.
value = metadata.dictionary.get("requires_python")
if value is not None:
return value
if metadata._legacy:
value = metadata._legacy.get("Requires-Python")
if value is not None and value != "UNKNOWN":
return value
return "" | python | def _read_requires_python(metadata):
"""Read wheel metadata to know the value of Requires-Python.
This is surprisingly poorly supported in Distlib. This function tries
several ways to get this information:
* Metadata 2.0: metadata.dictionary.get("requires_python") is not None
* Metadata 2.1: metadata._legacy.get("Requires-Python") is not None
* Metadata 1.2: metadata._legacy.get("Requires-Python") != "UNKNOWN"
"""
# TODO: Support more metadata formats.
value = metadata.dictionary.get("requires_python")
if value is not None:
return value
if metadata._legacy:
value = metadata._legacy.get("Requires-Python")
if value is not None and value != "UNKNOWN":
return value
return "" | [
"def",
"_read_requires_python",
"(",
"metadata",
")",
":",
"# TODO: Support more metadata formats.",
"value",
"=",
"metadata",
".",
"dictionary",
".",
"get",
"(",
"\"requires_python\"",
")",
"if",
"value",
"is",
"not",
"None",
":",
"return",
"value",
"if",
"metadata",
".",
"_legacy",
":",
"value",
"=",
"metadata",
".",
"_legacy",
".",
"get",
"(",
"\"Requires-Python\"",
")",
"if",
"value",
"is",
"not",
"None",
"and",
"value",
"!=",
"\"UNKNOWN\"",
":",
"return",
"value",
"return",
"\"\""
] | Read wheel metadata to know the value of Requires-Python.
This is surprisingly poorly supported in Distlib. This function tries
several ways to get this information:
* Metadata 2.0: metadata.dictionary.get("requires_python") is not None
* Metadata 2.1: metadata._legacy.get("Requires-Python") is not None
* Metadata 1.2: metadata._legacy.get("Requires-Python") != "UNKNOWN" | [
"Read",
"wheel",
"metadata",
"to",
"know",
"the",
"value",
"of",
"Requires",
"-",
"Python",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/dependencies.py#L197-L215 |
25,390 | pypa/pipenv | pipenv/vendor/passa/internals/dependencies.py | _get_dependencies_from_pip | def _get_dependencies_from_pip(ireq, sources):
"""Retrieves dependencies for the requirement from pipenv.patched.notpip internals.
The current strategy is to try the followings in order, returning the
first successful result.
1. Try to build a wheel out of the ireq, and read metadata out of it.
2. Read metadata out of the egg-info directory if it is present.
"""
extras = ireq.extras or ()
try:
wheel = build_wheel(ireq, sources)
except WheelBuildError:
# XXX: This depends on a side effect of `build_wheel`. This block is
# reached when it fails to build an sdist, where the sdist would have
# been downloaded, extracted into `ireq.source_dir`, and partially
# built (hopefully containing .egg-info).
metadata = read_sdist_metadata(ireq)
if not metadata:
raise
else:
metadata = wheel.metadata
requirements = _read_requirements(metadata, extras)
requires_python = _read_requires_python(metadata)
return requirements, requires_python | python | def _get_dependencies_from_pip(ireq, sources):
"""Retrieves dependencies for the requirement from pipenv.patched.notpip internals.
The current strategy is to try the followings in order, returning the
first successful result.
1. Try to build a wheel out of the ireq, and read metadata out of it.
2. Read metadata out of the egg-info directory if it is present.
"""
extras = ireq.extras or ()
try:
wheel = build_wheel(ireq, sources)
except WheelBuildError:
# XXX: This depends on a side effect of `build_wheel`. This block is
# reached when it fails to build an sdist, where the sdist would have
# been downloaded, extracted into `ireq.source_dir`, and partially
# built (hopefully containing .egg-info).
metadata = read_sdist_metadata(ireq)
if not metadata:
raise
else:
metadata = wheel.metadata
requirements = _read_requirements(metadata, extras)
requires_python = _read_requires_python(metadata)
return requirements, requires_python | [
"def",
"_get_dependencies_from_pip",
"(",
"ireq",
",",
"sources",
")",
":",
"extras",
"=",
"ireq",
".",
"extras",
"or",
"(",
")",
"try",
":",
"wheel",
"=",
"build_wheel",
"(",
"ireq",
",",
"sources",
")",
"except",
"WheelBuildError",
":",
"# XXX: This depends on a side effect of `build_wheel`. This block is",
"# reached when it fails to build an sdist, where the sdist would have",
"# been downloaded, extracted into `ireq.source_dir`, and partially",
"# built (hopefully containing .egg-info).",
"metadata",
"=",
"read_sdist_metadata",
"(",
"ireq",
")",
"if",
"not",
"metadata",
":",
"raise",
"else",
":",
"metadata",
"=",
"wheel",
".",
"metadata",
"requirements",
"=",
"_read_requirements",
"(",
"metadata",
",",
"extras",
")",
"requires_python",
"=",
"_read_requires_python",
"(",
"metadata",
")",
"return",
"requirements",
",",
"requires_python"
] | Retrieves dependencies for the requirement from pipenv.patched.notpip internals.
The current strategy is to try the followings in order, returning the
first successful result.
1. Try to build a wheel out of the ireq, and read metadata out of it.
2. Read metadata out of the egg-info directory if it is present. | [
"Retrieves",
"dependencies",
"for",
"the",
"requirement",
"from",
"pipenv",
".",
"patched",
".",
"notpip",
"internals",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/dependencies.py#L218-L242 |
25,391 | pypa/pipenv | pipenv/vendor/urllib3/fields.py | format_header_param | def format_header_param(name, value):
"""
Helper function to format and quote a single header parameter.
Particularly useful for header parameters which might contain
non-ASCII values, like file names. This follows RFC 2231, as
suggested by RFC 2388 Section 4.4.
:param name:
The name of the parameter, a string expected to be ASCII only.
:param value:
The value of the parameter, provided as a unicode string.
"""
if not any(ch in value for ch in '"\\\r\n'):
result = '%s="%s"' % (name, value)
try:
result.encode('ascii')
except (UnicodeEncodeError, UnicodeDecodeError):
pass
else:
return result
if not six.PY3 and isinstance(value, six.text_type): # Python 2:
value = value.encode('utf-8')
value = email.utils.encode_rfc2231(value, 'utf-8')
value = '%s*=%s' % (name, value)
return value | python | def format_header_param(name, value):
"""
Helper function to format and quote a single header parameter.
Particularly useful for header parameters which might contain
non-ASCII values, like file names. This follows RFC 2231, as
suggested by RFC 2388 Section 4.4.
:param name:
The name of the parameter, a string expected to be ASCII only.
:param value:
The value of the parameter, provided as a unicode string.
"""
if not any(ch in value for ch in '"\\\r\n'):
result = '%s="%s"' % (name, value)
try:
result.encode('ascii')
except (UnicodeEncodeError, UnicodeDecodeError):
pass
else:
return result
if not six.PY3 and isinstance(value, six.text_type): # Python 2:
value = value.encode('utf-8')
value = email.utils.encode_rfc2231(value, 'utf-8')
value = '%s*=%s' % (name, value)
return value | [
"def",
"format_header_param",
"(",
"name",
",",
"value",
")",
":",
"if",
"not",
"any",
"(",
"ch",
"in",
"value",
"for",
"ch",
"in",
"'\"\\\\\\r\\n'",
")",
":",
"result",
"=",
"'%s=\"%s\"'",
"%",
"(",
"name",
",",
"value",
")",
"try",
":",
"result",
".",
"encode",
"(",
"'ascii'",
")",
"except",
"(",
"UnicodeEncodeError",
",",
"UnicodeDecodeError",
")",
":",
"pass",
"else",
":",
"return",
"result",
"if",
"not",
"six",
".",
"PY3",
"and",
"isinstance",
"(",
"value",
",",
"six",
".",
"text_type",
")",
":",
"# Python 2:",
"value",
"=",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
"value",
"=",
"email",
".",
"utils",
".",
"encode_rfc2231",
"(",
"value",
",",
"'utf-8'",
")",
"value",
"=",
"'%s*=%s'",
"%",
"(",
"name",
",",
"value",
")",
"return",
"value"
] | Helper function to format and quote a single header parameter.
Particularly useful for header parameters which might contain
non-ASCII values, like file names. This follows RFC 2231, as
suggested by RFC 2388 Section 4.4.
:param name:
The name of the parameter, a string expected to be ASCII only.
:param value:
The value of the parameter, provided as a unicode string. | [
"Helper",
"function",
"to",
"format",
"and",
"quote",
"a",
"single",
"header",
"parameter",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/fields.py#L22-L47 |
25,392 | pypa/pipenv | pipenv/vendor/urllib3/fields.py | RequestField._render_parts | def _render_parts(self, header_parts):
"""
Helper function to format and quote a single header.
Useful for single headers that are composed of multiple items. E.g.,
'Content-Disposition' fields.
:param header_parts:
A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format
as `k1="v1"; k2="v2"; ...`.
"""
parts = []
iterable = header_parts
if isinstance(header_parts, dict):
iterable = header_parts.items()
for name, value in iterable:
if value is not None:
parts.append(self._render_part(name, value))
return '; '.join(parts) | python | def _render_parts(self, header_parts):
"""
Helper function to format and quote a single header.
Useful for single headers that are composed of multiple items. E.g.,
'Content-Disposition' fields.
:param header_parts:
A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format
as `k1="v1"; k2="v2"; ...`.
"""
parts = []
iterable = header_parts
if isinstance(header_parts, dict):
iterable = header_parts.items()
for name, value in iterable:
if value is not None:
parts.append(self._render_part(name, value))
return '; '.join(parts) | [
"def",
"_render_parts",
"(",
"self",
",",
"header_parts",
")",
":",
"parts",
"=",
"[",
"]",
"iterable",
"=",
"header_parts",
"if",
"isinstance",
"(",
"header_parts",
",",
"dict",
")",
":",
"iterable",
"=",
"header_parts",
".",
"items",
"(",
")",
"for",
"name",
",",
"value",
"in",
"iterable",
":",
"if",
"value",
"is",
"not",
"None",
":",
"parts",
".",
"append",
"(",
"self",
".",
"_render_part",
"(",
"name",
",",
"value",
")",
")",
"return",
"'; '",
".",
"join",
"(",
"parts",
")"
] | Helper function to format and quote a single header.
Useful for single headers that are composed of multiple items. E.g.,
'Content-Disposition' fields.
:param header_parts:
A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format
as `k1="v1"; k2="v2"; ...`. | [
"Helper",
"function",
"to",
"format",
"and",
"quote",
"a",
"single",
"header",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/fields.py#L116-L136 |
25,393 | pypa/pipenv | pipenv/vendor/urllib3/fields.py | RequestField.render_headers | def render_headers(self):
"""
Renders the headers for this request field.
"""
lines = []
sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location']
for sort_key in sort_keys:
if self.headers.get(sort_key, False):
lines.append('%s: %s' % (sort_key, self.headers[sort_key]))
for header_name, header_value in self.headers.items():
if header_name not in sort_keys:
if header_value:
lines.append('%s: %s' % (header_name, header_value))
lines.append('\r\n')
return '\r\n'.join(lines) | python | def render_headers(self):
"""
Renders the headers for this request field.
"""
lines = []
sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location']
for sort_key in sort_keys:
if self.headers.get(sort_key, False):
lines.append('%s: %s' % (sort_key, self.headers[sort_key]))
for header_name, header_value in self.headers.items():
if header_name not in sort_keys:
if header_value:
lines.append('%s: %s' % (header_name, header_value))
lines.append('\r\n')
return '\r\n'.join(lines) | [
"def",
"render_headers",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"]",
"sort_keys",
"=",
"[",
"'Content-Disposition'",
",",
"'Content-Type'",
",",
"'Content-Location'",
"]",
"for",
"sort_key",
"in",
"sort_keys",
":",
"if",
"self",
".",
"headers",
".",
"get",
"(",
"sort_key",
",",
"False",
")",
":",
"lines",
".",
"append",
"(",
"'%s: %s'",
"%",
"(",
"sort_key",
",",
"self",
".",
"headers",
"[",
"sort_key",
"]",
")",
")",
"for",
"header_name",
",",
"header_value",
"in",
"self",
".",
"headers",
".",
"items",
"(",
")",
":",
"if",
"header_name",
"not",
"in",
"sort_keys",
":",
"if",
"header_value",
":",
"lines",
".",
"append",
"(",
"'%s: %s'",
"%",
"(",
"header_name",
",",
"header_value",
")",
")",
"lines",
".",
"append",
"(",
"'\\r\\n'",
")",
"return",
"'\\r\\n'",
".",
"join",
"(",
"lines",
")"
] | Renders the headers for this request field. | [
"Renders",
"the",
"headers",
"for",
"this",
"request",
"field",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/fields.py#L138-L155 |
25,394 | pypa/pipenv | pipenv/vendor/urllib3/fields.py | RequestField.make_multipart | def make_multipart(self, content_disposition=None, content_type=None,
content_location=None):
"""
Makes this request field into a multipart request field.
This method overrides "Content-Disposition", "Content-Type" and
"Content-Location" headers to the request parameter.
:param content_type:
The 'Content-Type' of the request body.
:param content_location:
The 'Content-Location' of the request body.
"""
self.headers['Content-Disposition'] = content_disposition or 'form-data'
self.headers['Content-Disposition'] += '; '.join([
'', self._render_parts(
(('name', self._name), ('filename', self._filename))
)
])
self.headers['Content-Type'] = content_type
self.headers['Content-Location'] = content_location | python | def make_multipart(self, content_disposition=None, content_type=None,
content_location=None):
"""
Makes this request field into a multipart request field.
This method overrides "Content-Disposition", "Content-Type" and
"Content-Location" headers to the request parameter.
:param content_type:
The 'Content-Type' of the request body.
:param content_location:
The 'Content-Location' of the request body.
"""
self.headers['Content-Disposition'] = content_disposition or 'form-data'
self.headers['Content-Disposition'] += '; '.join([
'', self._render_parts(
(('name', self._name), ('filename', self._filename))
)
])
self.headers['Content-Type'] = content_type
self.headers['Content-Location'] = content_location | [
"def",
"make_multipart",
"(",
"self",
",",
"content_disposition",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"content_location",
"=",
"None",
")",
":",
"self",
".",
"headers",
"[",
"'Content-Disposition'",
"]",
"=",
"content_disposition",
"or",
"'form-data'",
"self",
".",
"headers",
"[",
"'Content-Disposition'",
"]",
"+=",
"'; '",
".",
"join",
"(",
"[",
"''",
",",
"self",
".",
"_render_parts",
"(",
"(",
"(",
"'name'",
",",
"self",
".",
"_name",
")",
",",
"(",
"'filename'",
",",
"self",
".",
"_filename",
")",
")",
")",
"]",
")",
"self",
".",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"content_type",
"self",
".",
"headers",
"[",
"'Content-Location'",
"]",
"=",
"content_location"
] | Makes this request field into a multipart request field.
This method overrides "Content-Disposition", "Content-Type" and
"Content-Location" headers to the request parameter.
:param content_type:
The 'Content-Type' of the request body.
:param content_location:
The 'Content-Location' of the request body. | [
"Makes",
"this",
"request",
"field",
"into",
"a",
"multipart",
"request",
"field",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/fields.py#L157-L178 |
25,395 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/treewalkers/base.py | TreeWalker.emptyTag | def emptyTag(self, namespace, name, attrs, hasChildren=False):
"""Generates an EmptyTag token
:arg namespace: the namespace of the token--can be ``None``
:arg name: the name of the element
:arg attrs: the attributes of the element as a dict
:arg hasChildren: whether or not to yield a SerializationError because
this tag shouldn't have children
:returns: EmptyTag token
"""
yield {"type": "EmptyTag", "name": name,
"namespace": namespace,
"data": attrs}
if hasChildren:
yield self.error("Void element has children") | python | def emptyTag(self, namespace, name, attrs, hasChildren=False):
"""Generates an EmptyTag token
:arg namespace: the namespace of the token--can be ``None``
:arg name: the name of the element
:arg attrs: the attributes of the element as a dict
:arg hasChildren: whether or not to yield a SerializationError because
this tag shouldn't have children
:returns: EmptyTag token
"""
yield {"type": "EmptyTag", "name": name,
"namespace": namespace,
"data": attrs}
if hasChildren:
yield self.error("Void element has children") | [
"def",
"emptyTag",
"(",
"self",
",",
"namespace",
",",
"name",
",",
"attrs",
",",
"hasChildren",
"=",
"False",
")",
":",
"yield",
"{",
"\"type\"",
":",
"\"EmptyTag\"",
",",
"\"name\"",
":",
"name",
",",
"\"namespace\"",
":",
"namespace",
",",
"\"data\"",
":",
"attrs",
"}",
"if",
"hasChildren",
":",
"yield",
"self",
".",
"error",
"(",
"\"Void element has children\"",
")"
] | Generates an EmptyTag token
:arg namespace: the namespace of the token--can be ``None``
:arg name: the name of the element
:arg attrs: the attributes of the element as a dict
:arg hasChildren: whether or not to yield a SerializationError because
this tag shouldn't have children
:returns: EmptyTag token | [
"Generates",
"an",
"EmptyTag",
"token"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treewalkers/base.py#L48-L67 |
25,396 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/treewalkers/base.py | TreeWalker.text | def text(self, data):
"""Generates SpaceCharacters and Characters tokens
Depending on what's in the data, this generates one or more
``SpaceCharacters`` and ``Characters`` tokens.
For example:
>>> from html5lib.treewalkers.base import TreeWalker
>>> # Give it an empty tree just so it instantiates
>>> walker = TreeWalker([])
>>> list(walker.text(''))
[]
>>> list(walker.text(' '))
[{u'data': ' ', u'type': u'SpaceCharacters'}]
>>> list(walker.text(' abc ')) # doctest: +NORMALIZE_WHITESPACE
[{u'data': ' ', u'type': u'SpaceCharacters'},
{u'data': u'abc', u'type': u'Characters'},
{u'data': u' ', u'type': u'SpaceCharacters'}]
:arg data: the text data
:returns: one or more ``SpaceCharacters`` and ``Characters`` tokens
"""
data = data
middle = data.lstrip(spaceCharacters)
left = data[:len(data) - len(middle)]
if left:
yield {"type": "SpaceCharacters", "data": left}
data = middle
middle = data.rstrip(spaceCharacters)
right = data[len(middle):]
if middle:
yield {"type": "Characters", "data": middle}
if right:
yield {"type": "SpaceCharacters", "data": right} | python | def text(self, data):
"""Generates SpaceCharacters and Characters tokens
Depending on what's in the data, this generates one or more
``SpaceCharacters`` and ``Characters`` tokens.
For example:
>>> from html5lib.treewalkers.base import TreeWalker
>>> # Give it an empty tree just so it instantiates
>>> walker = TreeWalker([])
>>> list(walker.text(''))
[]
>>> list(walker.text(' '))
[{u'data': ' ', u'type': u'SpaceCharacters'}]
>>> list(walker.text(' abc ')) # doctest: +NORMALIZE_WHITESPACE
[{u'data': ' ', u'type': u'SpaceCharacters'},
{u'data': u'abc', u'type': u'Characters'},
{u'data': u' ', u'type': u'SpaceCharacters'}]
:arg data: the text data
:returns: one or more ``SpaceCharacters`` and ``Characters`` tokens
"""
data = data
middle = data.lstrip(spaceCharacters)
left = data[:len(data) - len(middle)]
if left:
yield {"type": "SpaceCharacters", "data": left}
data = middle
middle = data.rstrip(spaceCharacters)
right = data[len(middle):]
if middle:
yield {"type": "Characters", "data": middle}
if right:
yield {"type": "SpaceCharacters", "data": right} | [
"def",
"text",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"data",
"middle",
"=",
"data",
".",
"lstrip",
"(",
"spaceCharacters",
")",
"left",
"=",
"data",
"[",
":",
"len",
"(",
"data",
")",
"-",
"len",
"(",
"middle",
")",
"]",
"if",
"left",
":",
"yield",
"{",
"\"type\"",
":",
"\"SpaceCharacters\"",
",",
"\"data\"",
":",
"left",
"}",
"data",
"=",
"middle",
"middle",
"=",
"data",
".",
"rstrip",
"(",
"spaceCharacters",
")",
"right",
"=",
"data",
"[",
"len",
"(",
"middle",
")",
":",
"]",
"if",
"middle",
":",
"yield",
"{",
"\"type\"",
":",
"\"Characters\"",
",",
"\"data\"",
":",
"middle",
"}",
"if",
"right",
":",
"yield",
"{",
"\"type\"",
":",
"\"SpaceCharacters\"",
",",
"\"data\"",
":",
"right",
"}"
] | Generates SpaceCharacters and Characters tokens
Depending on what's in the data, this generates one or more
``SpaceCharacters`` and ``Characters`` tokens.
For example:
>>> from html5lib.treewalkers.base import TreeWalker
>>> # Give it an empty tree just so it instantiates
>>> walker = TreeWalker([])
>>> list(walker.text(''))
[]
>>> list(walker.text(' '))
[{u'data': ' ', u'type': u'SpaceCharacters'}]
>>> list(walker.text(' abc ')) # doctest: +NORMALIZE_WHITESPACE
[{u'data': ' ', u'type': u'SpaceCharacters'},
{u'data': u'abc', u'type': u'Characters'},
{u'data': u' ', u'type': u'SpaceCharacters'}]
:arg data: the text data
:returns: one or more ``SpaceCharacters`` and ``Characters`` tokens | [
"Generates",
"SpaceCharacters",
"and",
"Characters",
"tokens"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treewalkers/base.py#L100-L136 |
25,397 | pypa/pipenv | pipenv/shells.py | _get_activate_script | def _get_activate_script(cmd, venv):
"""Returns the string to activate a virtualenv.
This is POSIX-only at the moment since the compat (pexpect-based) shell
does not work elsewhere anyway.
"""
# Suffix and source command for other shells.
# Support for fish shell.
if "fish" in cmd:
suffix = ".fish"
command = "source"
# Support for csh shell.
elif "csh" in cmd:
suffix = ".csh"
command = "source"
else:
suffix = ""
command = "."
# Escape any spaces located within the virtualenv path to allow
# for proper activation.
venv_location = str(venv).replace(" ", r"\ ")
# The leading space can make history cleaner in some shells.
return " {2} {0}/bin/activate{1}".format(venv_location, suffix, command) | python | def _get_activate_script(cmd, venv):
"""Returns the string to activate a virtualenv.
This is POSIX-only at the moment since the compat (pexpect-based) shell
does not work elsewhere anyway.
"""
# Suffix and source command for other shells.
# Support for fish shell.
if "fish" in cmd:
suffix = ".fish"
command = "source"
# Support for csh shell.
elif "csh" in cmd:
suffix = ".csh"
command = "source"
else:
suffix = ""
command = "."
# Escape any spaces located within the virtualenv path to allow
# for proper activation.
venv_location = str(venv).replace(" ", r"\ ")
# The leading space can make history cleaner in some shells.
return " {2} {0}/bin/activate{1}".format(venv_location, suffix, command) | [
"def",
"_get_activate_script",
"(",
"cmd",
",",
"venv",
")",
":",
"# Suffix and source command for other shells.",
"# Support for fish shell.",
"if",
"\"fish\"",
"in",
"cmd",
":",
"suffix",
"=",
"\".fish\"",
"command",
"=",
"\"source\"",
"# Support for csh shell.",
"elif",
"\"csh\"",
"in",
"cmd",
":",
"suffix",
"=",
"\".csh\"",
"command",
"=",
"\"source\"",
"else",
":",
"suffix",
"=",
"\"\"",
"command",
"=",
"\".\"",
"# Escape any spaces located within the virtualenv path to allow",
"# for proper activation.",
"venv_location",
"=",
"str",
"(",
"venv",
")",
".",
"replace",
"(",
"\" \"",
",",
"r\"\\ \"",
")",
"# The leading space can make history cleaner in some shells.",
"return",
"\" {2} {0}/bin/activate{1}\"",
".",
"format",
"(",
"venv_location",
",",
"suffix",
",",
"command",
")"
] | Returns the string to activate a virtualenv.
This is POSIX-only at the moment since the compat (pexpect-based) shell
does not work elsewhere anyway. | [
"Returns",
"the",
"string",
"to",
"activate",
"a",
"virtualenv",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/shells.py#L32-L54 |
25,398 | pypa/pipenv | pipenv/vendor/distlib/wheel.py | Wheel.filename | def filename(self):
"""
Build and return a filename from the various components.
"""
if self.buildver:
buildver = '-' + self.buildver
else:
buildver = ''
pyver = '.'.join(self.pyver)
abi = '.'.join(self.abi)
arch = '.'.join(self.arch)
# replace - with _ as a local version separator
version = self.version.replace('-', '_')
return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver,
pyver, abi, arch) | python | def filename(self):
"""
Build and return a filename from the various components.
"""
if self.buildver:
buildver = '-' + self.buildver
else:
buildver = ''
pyver = '.'.join(self.pyver)
abi = '.'.join(self.abi)
arch = '.'.join(self.arch)
# replace - with _ as a local version separator
version = self.version.replace('-', '_')
return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver,
pyver, abi, arch) | [
"def",
"filename",
"(",
"self",
")",
":",
"if",
"self",
".",
"buildver",
":",
"buildver",
"=",
"'-'",
"+",
"self",
".",
"buildver",
"else",
":",
"buildver",
"=",
"''",
"pyver",
"=",
"'.'",
".",
"join",
"(",
"self",
".",
"pyver",
")",
"abi",
"=",
"'.'",
".",
"join",
"(",
"self",
".",
"abi",
")",
"arch",
"=",
"'.'",
".",
"join",
"(",
"self",
".",
"arch",
")",
"# replace - with _ as a local version separator",
"version",
"=",
"self",
".",
"version",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"return",
"'%s-%s%s-%s-%s-%s.whl'",
"%",
"(",
"self",
".",
"name",
",",
"version",
",",
"buildver",
",",
"pyver",
",",
"abi",
",",
"arch",
")"
] | Build and return a filename from the various components. | [
"Build",
"and",
"return",
"a",
"filename",
"from",
"the",
"various",
"components",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/wheel.py#L186-L200 |
25,399 | pypa/pipenv | pipenv/core.py | add_to_path | def add_to_path(p):
"""Adds a given path to the PATH."""
if p not in os.environ["PATH"]:
os.environ["PATH"] = "{0}{1}{2}".format(p, os.pathsep, os.environ["PATH"]) | python | def add_to_path(p):
"""Adds a given path to the PATH."""
if p not in os.environ["PATH"]:
os.environ["PATH"] = "{0}{1}{2}".format(p, os.pathsep, os.environ["PATH"]) | [
"def",
"add_to_path",
"(",
"p",
")",
":",
"if",
"p",
"not",
"in",
"os",
".",
"environ",
"[",
"\"PATH\"",
"]",
":",
"os",
".",
"environ",
"[",
"\"PATH\"",
"]",
"=",
"\"{0}{1}{2}\"",
".",
"format",
"(",
"p",
",",
"os",
".",
"pathsep",
",",
"os",
".",
"environ",
"[",
"\"PATH\"",
"]",
")"
] | Adds a given path to the PATH. | [
"Adds",
"a",
"given",
"path",
"to",
"the",
"PATH",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/core.py#L159-L162 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.