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,200 | pypa/pipenv | pipenv/vendor/pep517/envbuild.py | BuildEnvironment.pip_install | def pip_install(self, reqs):
"""Install dependencies into this env by calling pip in a subprocess"""
if not reqs:
return
log.info('Calling pip to install %s', reqs)
check_call([
sys.executable, '-m', 'pip', 'install', '--ignore-installed',
'--prefix', self.path] + list(reqs)) | python | def pip_install(self, reqs):
"""Install dependencies into this env by calling pip in a subprocess"""
if not reqs:
return
log.info('Calling pip to install %s', reqs)
check_call([
sys.executable, '-m', 'pip', 'install', '--ignore-installed',
'--prefix', self.path] + list(reqs)) | [
"def",
"pip_install",
"(",
"self",
",",
"reqs",
")",
":",
"if",
"not",
"reqs",
":",
"return",
"log",
".",
"info",
"(",
"'Calling pip to install %s'",
",",
"reqs",
")",
"check_call",
"(",
"[",
"sys",
".",
"executable",
",",
"'-m'",
",",
"'pip'",
",",
"'install'",
",",
"'--ignore-installed'",
",",
"'--prefix'",
",",
"self",
".",
"path",
"]",
"+",
"list",
"(",
"reqs",
")",
")"
] | Install dependencies into this env by calling pip in a subprocess | [
"Install",
"dependencies",
"into",
"this",
"env",
"by",
"calling",
"pip",
"in",
"a",
"subprocess"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/envbuild.py#L88-L95 |
25,201 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/treebuilders/base.py | Node.reparentChildren | def reparentChildren(self, newParent):
"""Move all the children of the current node to newParent.
This is needed so that trees that don't store text as nodes move the
text in the correct way
:arg newParent: the node to move all this node's children to
"""
# XXX - should this method be made more general?
for child in self.childNodes:
newParent.appendChild(child)
self.childNodes = [] | python | def reparentChildren(self, newParent):
"""Move all the children of the current node to newParent.
This is needed so that trees that don't store text as nodes move the
text in the correct way
:arg newParent: the node to move all this node's children to
"""
# XXX - should this method be made more general?
for child in self.childNodes:
newParent.appendChild(child)
self.childNodes = [] | [
"def",
"reparentChildren",
"(",
"self",
",",
"newParent",
")",
":",
"# XXX - should this method be made more general?",
"for",
"child",
"in",
"self",
".",
"childNodes",
":",
"newParent",
".",
"appendChild",
"(",
"child",
")",
"self",
".",
"childNodes",
"=",
"[",
"]"
] | Move all the children of the current node to newParent.
This is needed so that trees that don't store text as nodes move the
text in the correct way
:arg newParent: the node to move all this node's children to | [
"Move",
"all",
"the",
"children",
"of",
"the",
"current",
"node",
"to",
"newParent",
".",
"This",
"is",
"needed",
"so",
"that",
"trees",
"that",
"don",
"t",
"store",
"text",
"as",
"nodes",
"move",
"the",
"text",
"in",
"the",
"correct",
"way"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treebuilders/base.py#L97-L108 |
25,202 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/treebuilders/base.py | TreeBuilder.elementInActiveFormattingElements | def elementInActiveFormattingElements(self, name):
"""Check if an element exists between the end of the active
formatting elements and the last marker. If it does, return it, else
return false"""
for item in self.activeFormattingElements[::-1]:
# Check for Marker first because if it's a Marker it doesn't have a
# name attribute.
if item == Marker:
break
elif item.name == name:
return item
return False | python | def elementInActiveFormattingElements(self, name):
"""Check if an element exists between the end of the active
formatting elements and the last marker. If it does, return it, else
return false"""
for item in self.activeFormattingElements[::-1]:
# Check for Marker first because if it's a Marker it doesn't have a
# name attribute.
if item == Marker:
break
elif item.name == name:
return item
return False | [
"def",
"elementInActiveFormattingElements",
"(",
"self",
",",
"name",
")",
":",
"for",
"item",
"in",
"self",
".",
"activeFormattingElements",
"[",
":",
":",
"-",
"1",
"]",
":",
"# Check for Marker first because if it's a Marker it doesn't have a",
"# name attribute.",
"if",
"item",
"==",
"Marker",
":",
"break",
"elif",
"item",
".",
"name",
"==",
"name",
":",
"return",
"item",
"return",
"False"
] | Check if an element exists between the end of the active
formatting elements and the last marker. If it does, return it, else
return false | [
"Check",
"if",
"an",
"element",
"exists",
"between",
"the",
"end",
"of",
"the",
"active",
"formatting",
"elements",
"and",
"the",
"last",
"marker",
".",
"If",
"it",
"does",
"return",
"it",
"else",
"return",
"false"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treebuilders/base.py#L269-L281 |
25,203 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/treebuilders/base.py | TreeBuilder.createElement | def createElement(self, token):
"""Create an element but don't insert it anywhere"""
name = token["name"]
namespace = token.get("namespace", self.defaultNamespace)
element = self.elementClass(name, namespace)
element.attributes = token["data"]
return element | python | def createElement(self, token):
"""Create an element but don't insert it anywhere"""
name = token["name"]
namespace = token.get("namespace", self.defaultNamespace)
element = self.elementClass(name, namespace)
element.attributes = token["data"]
return element | [
"def",
"createElement",
"(",
"self",
",",
"token",
")",
":",
"name",
"=",
"token",
"[",
"\"name\"",
"]",
"namespace",
"=",
"token",
".",
"get",
"(",
"\"namespace\"",
",",
"self",
".",
"defaultNamespace",
")",
"element",
"=",
"self",
".",
"elementClass",
"(",
"name",
",",
"namespace",
")",
"element",
".",
"attributes",
"=",
"token",
"[",
"\"data\"",
"]",
"return",
"element"
] | Create an element but don't insert it anywhere | [
"Create",
"an",
"element",
"but",
"don",
"t",
"insert",
"it",
"anywhere"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treebuilders/base.py#L301-L307 |
25,204 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/treebuilders/base.py | TreeBuilder._setInsertFromTable | def _setInsertFromTable(self, value):
"""Switch the function used to insert an element from the
normal one to the misnested table one and back again"""
self._insertFromTable = value
if value:
self.insertElement = self.insertElementTable
else:
self.insertElement = self.insertElementNormal | python | def _setInsertFromTable(self, value):
"""Switch the function used to insert an element from the
normal one to the misnested table one and back again"""
self._insertFromTable = value
if value:
self.insertElement = self.insertElementTable
else:
self.insertElement = self.insertElementNormal | [
"def",
"_setInsertFromTable",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_insertFromTable",
"=",
"value",
"if",
"value",
":",
"self",
".",
"insertElement",
"=",
"self",
".",
"insertElementTable",
"else",
":",
"self",
".",
"insertElement",
"=",
"self",
".",
"insertElementNormal"
] | Switch the function used to insert an element from the
normal one to the misnested table one and back again | [
"Switch",
"the",
"function",
"used",
"to",
"insert",
"an",
"element",
"from",
"the",
"normal",
"one",
"to",
"the",
"misnested",
"table",
"one",
"and",
"back",
"again"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treebuilders/base.py#L312-L319 |
25,205 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/treebuilders/base.py | TreeBuilder.insertElementTable | def insertElementTable(self, token):
"""Create an element and insert it into the tree"""
element = self.createElement(token)
if self.openElements[-1].name not in tableInsertModeElements:
return self.insertElementNormal(token)
else:
# We should be in the InTable mode. This means we want to do
# special magic element rearranging
parent, insertBefore = self.getTableMisnestedNodePosition()
if insertBefore is None:
parent.appendChild(element)
else:
parent.insertBefore(element, insertBefore)
self.openElements.append(element)
return element | python | def insertElementTable(self, token):
"""Create an element and insert it into the tree"""
element = self.createElement(token)
if self.openElements[-1].name not in tableInsertModeElements:
return self.insertElementNormal(token)
else:
# We should be in the InTable mode. This means we want to do
# special magic element rearranging
parent, insertBefore = self.getTableMisnestedNodePosition()
if insertBefore is None:
parent.appendChild(element)
else:
parent.insertBefore(element, insertBefore)
self.openElements.append(element)
return element | [
"def",
"insertElementTable",
"(",
"self",
",",
"token",
")",
":",
"element",
"=",
"self",
".",
"createElement",
"(",
"token",
")",
"if",
"self",
".",
"openElements",
"[",
"-",
"1",
"]",
".",
"name",
"not",
"in",
"tableInsertModeElements",
":",
"return",
"self",
".",
"insertElementNormal",
"(",
"token",
")",
"else",
":",
"# We should be in the InTable mode. This means we want to do",
"# special magic element rearranging",
"parent",
",",
"insertBefore",
"=",
"self",
".",
"getTableMisnestedNodePosition",
"(",
")",
"if",
"insertBefore",
"is",
"None",
":",
"parent",
".",
"appendChild",
"(",
"element",
")",
"else",
":",
"parent",
".",
"insertBefore",
"(",
"element",
",",
"insertBefore",
")",
"self",
".",
"openElements",
".",
"append",
"(",
"element",
")",
"return",
"element"
] | Create an element and insert it into the tree | [
"Create",
"an",
"element",
"and",
"insert",
"it",
"into",
"the",
"tree"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treebuilders/base.py#L333-L347 |
25,206 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/treebuilders/base.py | TreeBuilder.insertText | def insertText(self, data, parent=None):
"""Insert text data."""
if parent is None:
parent = self.openElements[-1]
if (not self.insertFromTable or (self.insertFromTable and
self.openElements[-1].name
not in tableInsertModeElements)):
parent.insertText(data)
else:
# We should be in the InTable mode. This means we want to do
# special magic element rearranging
parent, insertBefore = self.getTableMisnestedNodePosition()
parent.insertText(data, insertBefore) | python | def insertText(self, data, parent=None):
"""Insert text data."""
if parent is None:
parent = self.openElements[-1]
if (not self.insertFromTable or (self.insertFromTable and
self.openElements[-1].name
not in tableInsertModeElements)):
parent.insertText(data)
else:
# We should be in the InTable mode. This means we want to do
# special magic element rearranging
parent, insertBefore = self.getTableMisnestedNodePosition()
parent.insertText(data, insertBefore) | [
"def",
"insertText",
"(",
"self",
",",
"data",
",",
"parent",
"=",
"None",
")",
":",
"if",
"parent",
"is",
"None",
":",
"parent",
"=",
"self",
".",
"openElements",
"[",
"-",
"1",
"]",
"if",
"(",
"not",
"self",
".",
"insertFromTable",
"or",
"(",
"self",
".",
"insertFromTable",
"and",
"self",
".",
"openElements",
"[",
"-",
"1",
"]",
".",
"name",
"not",
"in",
"tableInsertModeElements",
")",
")",
":",
"parent",
".",
"insertText",
"(",
"data",
")",
"else",
":",
"# We should be in the InTable mode. This means we want to do",
"# special magic element rearranging",
"parent",
",",
"insertBefore",
"=",
"self",
".",
"getTableMisnestedNodePosition",
"(",
")",
"parent",
".",
"insertText",
"(",
"data",
",",
"insertBefore",
")"
] | Insert text data. | [
"Insert",
"text",
"data",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treebuilders/base.py#L349-L362 |
25,207 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/treebuilders/base.py | TreeBuilder.getFragment | def getFragment(self):
"""Return the final fragment"""
# assert self.innerHTML
fragment = self.fragmentClass()
self.openElements[0].reparentChildren(fragment)
return fragment | python | def getFragment(self):
"""Return the final fragment"""
# assert self.innerHTML
fragment = self.fragmentClass()
self.openElements[0].reparentChildren(fragment)
return fragment | [
"def",
"getFragment",
"(",
"self",
")",
":",
"# assert self.innerHTML",
"fragment",
"=",
"self",
".",
"fragmentClass",
"(",
")",
"self",
".",
"openElements",
"[",
"0",
"]",
".",
"reparentChildren",
"(",
"fragment",
")",
"return",
"fragment"
] | Return the final fragment | [
"Return",
"the",
"final",
"fragment"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treebuilders/base.py#L404-L409 |
25,208 | pypa/pipenv | pipenv/vendor/packaging/markers.py | Marker.evaluate | def evaluate(self, environment=None):
"""Evaluate a marker.
Return the boolean from evaluating the given marker against the
environment. environment is an optional argument to override all or
part of the determined environment.
The environment is determined from the current Python process.
"""
current_environment = default_environment()
if environment is not None:
current_environment.update(environment)
return _evaluate_markers(self._markers, current_environment) | python | def evaluate(self, environment=None):
"""Evaluate a marker.
Return the boolean from evaluating the given marker against the
environment. environment is an optional argument to override all or
part of the determined environment.
The environment is determined from the current Python process.
"""
current_environment = default_environment()
if environment is not None:
current_environment.update(environment)
return _evaluate_markers(self._markers, current_environment) | [
"def",
"evaluate",
"(",
"self",
",",
"environment",
"=",
"None",
")",
":",
"current_environment",
"=",
"default_environment",
"(",
")",
"if",
"environment",
"is",
"not",
"None",
":",
"current_environment",
".",
"update",
"(",
"environment",
")",
"return",
"_evaluate_markers",
"(",
"self",
".",
"_markers",
",",
"current_environment",
")"
] | Evaluate a marker.
Return the boolean from evaluating the given marker against the
environment. environment is an optional argument to override all or
part of the determined environment.
The environment is determined from the current Python process. | [
"Evaluate",
"a",
"marker",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/packaging/markers.py#L283-L296 |
25,209 | pypa/pipenv | pipenv/vendor/passa/internals/hashes.py | _allow_all_wheels | def _allow_all_wheels():
"""Monkey patch pip.Wheel to allow all wheels
The usual checks against platforms and Python versions are ignored to allow
fetching all available entries in PyPI. This also saves the candidate cache
and set a new one, or else the results from the previous non-patched calls
will interfere.
"""
original_wheel_supported = Wheel.supported
original_support_index_min = Wheel.support_index_min
Wheel.supported = _wheel_supported
Wheel.support_index_min = _wheel_support_index_min
yield
Wheel.supported = original_wheel_supported
Wheel.support_index_min = original_support_index_min | python | def _allow_all_wheels():
"""Monkey patch pip.Wheel to allow all wheels
The usual checks against platforms and Python versions are ignored to allow
fetching all available entries in PyPI. This also saves the candidate cache
and set a new one, or else the results from the previous non-patched calls
will interfere.
"""
original_wheel_supported = Wheel.supported
original_support_index_min = Wheel.support_index_min
Wheel.supported = _wheel_supported
Wheel.support_index_min = _wheel_support_index_min
yield
Wheel.supported = original_wheel_supported
Wheel.support_index_min = original_support_index_min | [
"def",
"_allow_all_wheels",
"(",
")",
":",
"original_wheel_supported",
"=",
"Wheel",
".",
"supported",
"original_support_index_min",
"=",
"Wheel",
".",
"support_index_min",
"Wheel",
".",
"supported",
"=",
"_wheel_supported",
"Wheel",
".",
"support_index_min",
"=",
"_wheel_support_index_min",
"yield",
"Wheel",
".",
"supported",
"=",
"original_wheel_supported",
"Wheel",
".",
"support_index_min",
"=",
"original_support_index_min"
] | Monkey patch pip.Wheel to allow all wheels
The usual checks against platforms and Python versions are ignored to allow
fetching all available entries in PyPI. This also saves the candidate cache
and set a new one, or else the results from the previous non-patched calls
will interfere. | [
"Monkey",
"patch",
"pip",
".",
"Wheel",
"to",
"allow",
"all",
"wheels"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/hashes.py#L21-L36 |
25,210 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/temp_dir.py | TempDirectory.create | def create(self):
"""Create a temporary directory and store its path in self.path
"""
if self.path is not None:
logger.debug(
"Skipped creation of temporary directory: {}".format(self.path)
)
return
# We realpath here because some systems have their default tmpdir
# symlinked to another directory. This tends to confuse build
# scripts, so we canonicalize the path by traversing potential
# symlinks here.
self.path = os.path.realpath(
tempfile.mkdtemp(prefix="pip-{}-".format(self.kind))
)
self._register_finalizer()
logger.debug("Created temporary directory: {}".format(self.path)) | python | def create(self):
"""Create a temporary directory and store its path in self.path
"""
if self.path is not None:
logger.debug(
"Skipped creation of temporary directory: {}".format(self.path)
)
return
# We realpath here because some systems have their default tmpdir
# symlinked to another directory. This tends to confuse build
# scripts, so we canonicalize the path by traversing potential
# symlinks here.
self.path = os.path.realpath(
tempfile.mkdtemp(prefix="pip-{}-".format(self.kind))
)
self._register_finalizer()
logger.debug("Created temporary directory: {}".format(self.path)) | [
"def",
"create",
"(",
"self",
")",
":",
"if",
"self",
".",
"path",
"is",
"not",
"None",
":",
"logger",
".",
"debug",
"(",
"\"Skipped creation of temporary directory: {}\"",
".",
"format",
"(",
"self",
".",
"path",
")",
")",
"return",
"# We realpath here because some systems have their default tmpdir",
"# symlinked to another directory. This tends to confuse build",
"# scripts, so we canonicalize the path by traversing potential",
"# symlinks here.",
"self",
".",
"path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"\"pip-{}-\"",
".",
"format",
"(",
"self",
".",
"kind",
")",
")",
")",
"self",
".",
"_register_finalizer",
"(",
")",
"logger",
".",
"debug",
"(",
"\"Created temporary directory: {}\"",
".",
"format",
"(",
"self",
".",
"path",
")",
")"
] | Create a temporary directory and store its path in self.path | [
"Create",
"a",
"temporary",
"directory",
"and",
"store",
"its",
"path",
"in",
"self",
".",
"path"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/temp_dir.py#L78-L94 |
25,211 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/temp_dir.py | TempDirectory.cleanup | def cleanup(self):
"""Remove the temporary directory created and reset state
"""
if getattr(self._finalizer, "detach", None) and self._finalizer.detach():
if os.path.exists(self.path):
try:
rmtree(self.path)
except OSError:
pass
else:
self.path = None | python | def cleanup(self):
"""Remove the temporary directory created and reset state
"""
if getattr(self._finalizer, "detach", None) and self._finalizer.detach():
if os.path.exists(self.path):
try:
rmtree(self.path)
except OSError:
pass
else:
self.path = None | [
"def",
"cleanup",
"(",
"self",
")",
":",
"if",
"getattr",
"(",
"self",
".",
"_finalizer",
",",
"\"detach\"",
",",
"None",
")",
"and",
"self",
".",
"_finalizer",
".",
"detach",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
":",
"try",
":",
"rmtree",
"(",
"self",
".",
"path",
")",
"except",
"OSError",
":",
"pass",
"else",
":",
"self",
".",
"path",
"=",
"None"
] | Remove the temporary directory created and reset state | [
"Remove",
"the",
"temporary",
"directory",
"created",
"and",
"reset",
"state"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/temp_dir.py#L106-L116 |
25,212 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/temp_dir.py | AdjacentTempDirectory._generate_names | def _generate_names(cls, name):
"""Generates a series of temporary names.
The algorithm replaces the leading characters in the name
with ones that are valid filesystem characters, but are not
valid package names (for both Python and pip definitions of
package).
"""
for i in range(1, len(name)):
for candidate in itertools.combinations_with_replacement(
cls.LEADING_CHARS, i - 1):
new_name = '~' + ''.join(candidate) + name[i:]
if new_name != name:
yield new_name
# If we make it this far, we will have to make a longer name
for i in range(len(cls.LEADING_CHARS)):
for candidate in itertools.combinations_with_replacement(
cls.LEADING_CHARS, i):
new_name = '~' + ''.join(candidate) + name
if new_name != name:
yield new_name | python | def _generate_names(cls, name):
"""Generates a series of temporary names.
The algorithm replaces the leading characters in the name
with ones that are valid filesystem characters, but are not
valid package names (for both Python and pip definitions of
package).
"""
for i in range(1, len(name)):
for candidate in itertools.combinations_with_replacement(
cls.LEADING_CHARS, i - 1):
new_name = '~' + ''.join(candidate) + name[i:]
if new_name != name:
yield new_name
# If we make it this far, we will have to make a longer name
for i in range(len(cls.LEADING_CHARS)):
for candidate in itertools.combinations_with_replacement(
cls.LEADING_CHARS, i):
new_name = '~' + ''.join(candidate) + name
if new_name != name:
yield new_name | [
"def",
"_generate_names",
"(",
"cls",
",",
"name",
")",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"name",
")",
")",
":",
"for",
"candidate",
"in",
"itertools",
".",
"combinations_with_replacement",
"(",
"cls",
".",
"LEADING_CHARS",
",",
"i",
"-",
"1",
")",
":",
"new_name",
"=",
"'~'",
"+",
"''",
".",
"join",
"(",
"candidate",
")",
"+",
"name",
"[",
"i",
":",
"]",
"if",
"new_name",
"!=",
"name",
":",
"yield",
"new_name",
"# If we make it this far, we will have to make a longer name",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"cls",
".",
"LEADING_CHARS",
")",
")",
":",
"for",
"candidate",
"in",
"itertools",
".",
"combinations_with_replacement",
"(",
"cls",
".",
"LEADING_CHARS",
",",
"i",
")",
":",
"new_name",
"=",
"'~'",
"+",
"''",
".",
"join",
"(",
"candidate",
")",
"+",
"name",
"if",
"new_name",
"!=",
"name",
":",
"yield",
"new_name"
] | Generates a series of temporary names.
The algorithm replaces the leading characters in the name
with ones that are valid filesystem characters, but are not
valid package names (for both Python and pip definitions of
package). | [
"Generates",
"a",
"series",
"of",
"temporary",
"names",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/temp_dir.py#L145-L166 |
25,213 | pypa/pipenv | pipenv/vendor/chardet/__init__.py | detect | def detect(byte_str):
"""
Detect the encoding of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray``
"""
if not isinstance(byte_str, bytearray):
if not isinstance(byte_str, bytes):
raise TypeError('Expected object of type bytes or bytearray, got: '
'{0}'.format(type(byte_str)))
else:
byte_str = bytearray(byte_str)
detector = UniversalDetector()
detector.feed(byte_str)
return detector.close() | python | def detect(byte_str):
"""
Detect the encoding of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray``
"""
if not isinstance(byte_str, bytearray):
if not isinstance(byte_str, bytes):
raise TypeError('Expected object of type bytes or bytearray, got: '
'{0}'.format(type(byte_str)))
else:
byte_str = bytearray(byte_str)
detector = UniversalDetector()
detector.feed(byte_str)
return detector.close() | [
"def",
"detect",
"(",
"byte_str",
")",
":",
"if",
"not",
"isinstance",
"(",
"byte_str",
",",
"bytearray",
")",
":",
"if",
"not",
"isinstance",
"(",
"byte_str",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"'Expected object of type bytes or bytearray, got: '",
"'{0}'",
".",
"format",
"(",
"type",
"(",
"byte_str",
")",
")",
")",
"else",
":",
"byte_str",
"=",
"bytearray",
"(",
"byte_str",
")",
"detector",
"=",
"UniversalDetector",
"(",
")",
"detector",
".",
"feed",
"(",
"byte_str",
")",
"return",
"detector",
".",
"close",
"(",
")"
] | Detect the encoding of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray`` | [
"Detect",
"the",
"encoding",
"of",
"the",
"given",
"byte",
"string",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/chardet/__init__.py#L24-L39 |
25,214 | pypa/pipenv | pipenv/vendor/markupsafe/__init__.py | Markup.unescape | def unescape(self):
"""Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
>>> Markup('Main » <em>About</em>').unescape()
'Main » <em>About</em>'
"""
from ._constants import HTML_ENTITIES
def handle_match(m):
name = m.group(1)
if name in HTML_ENTITIES:
return unichr(HTML_ENTITIES[name])
try:
if name[:2] in ("#x", "#X"):
return unichr(int(name[2:], 16))
elif name.startswith("#"):
return unichr(int(name[1:]))
except ValueError:
pass
# Don't modify unexpected input.
return m.group()
return _entity_re.sub(handle_match, text_type(self)) | python | def unescape(self):
"""Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
>>> Markup('Main » <em>About</em>').unescape()
'Main » <em>About</em>'
"""
from ._constants import HTML_ENTITIES
def handle_match(m):
name = m.group(1)
if name in HTML_ENTITIES:
return unichr(HTML_ENTITIES[name])
try:
if name[:2] in ("#x", "#X"):
return unichr(int(name[2:], 16))
elif name.startswith("#"):
return unichr(int(name[1:]))
except ValueError:
pass
# Don't modify unexpected input.
return m.group()
return _entity_re.sub(handle_match, text_type(self)) | [
"def",
"unescape",
"(",
"self",
")",
":",
"from",
".",
"_constants",
"import",
"HTML_ENTITIES",
"def",
"handle_match",
"(",
"m",
")",
":",
"name",
"=",
"m",
".",
"group",
"(",
"1",
")",
"if",
"name",
"in",
"HTML_ENTITIES",
":",
"return",
"unichr",
"(",
"HTML_ENTITIES",
"[",
"name",
"]",
")",
"try",
":",
"if",
"name",
"[",
":",
"2",
"]",
"in",
"(",
"\"#x\"",
",",
"\"#X\"",
")",
":",
"return",
"unichr",
"(",
"int",
"(",
"name",
"[",
"2",
":",
"]",
",",
"16",
")",
")",
"elif",
"name",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"return",
"unichr",
"(",
"int",
"(",
"name",
"[",
"1",
":",
"]",
")",
")",
"except",
"ValueError",
":",
"pass",
"# Don't modify unexpected input.",
"return",
"m",
".",
"group",
"(",
")",
"return",
"_entity_re",
".",
"sub",
"(",
"handle_match",
",",
"text_type",
"(",
"self",
")",
")"
] | Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
>>> Markup('Main » <em>About</em>').unescape()
'Main » <em>About</em>' | [
"Convert",
"escaped",
"markup",
"back",
"into",
"a",
"text",
"string",
".",
"This",
"replaces",
"HTML",
"entities",
"with",
"the",
"characters",
"they",
"represent",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/markupsafe/__init__.py#L127-L150 |
25,215 | pypa/pipenv | pipenv/patched/notpip/_internal/req/req_install.py | InstallRequirement.populate_link | def populate_link(self, finder, upgrade, require_hashes):
# type: (PackageFinder, bool, bool) -> None
"""Ensure that if a link can be found for this, that it is found.
Note that self.link may still be None - if Upgrade is False and the
requirement is already installed.
If require_hashes is True, don't use the wheel cache, because cached
wheels, always built locally, have different hashes than the files
downloaded from the index server and thus throw false hash mismatches.
Furthermore, cached wheels at present have undeterministic contents due
to file modification times.
"""
if self.link is None:
self.link = finder.find_requirement(self, upgrade)
if self._wheel_cache is not None and not require_hashes:
old_link = self.link
self.link = self._wheel_cache.get(self.link, self.name)
if old_link != self.link:
logger.debug('Using cached wheel link: %s', self.link) | python | def populate_link(self, finder, upgrade, require_hashes):
# type: (PackageFinder, bool, bool) -> None
"""Ensure that if a link can be found for this, that it is found.
Note that self.link may still be None - if Upgrade is False and the
requirement is already installed.
If require_hashes is True, don't use the wheel cache, because cached
wheels, always built locally, have different hashes than the files
downloaded from the index server and thus throw false hash mismatches.
Furthermore, cached wheels at present have undeterministic contents due
to file modification times.
"""
if self.link is None:
self.link = finder.find_requirement(self, upgrade)
if self._wheel_cache is not None and not require_hashes:
old_link = self.link
self.link = self._wheel_cache.get(self.link, self.name)
if old_link != self.link:
logger.debug('Using cached wheel link: %s', self.link) | [
"def",
"populate_link",
"(",
"self",
",",
"finder",
",",
"upgrade",
",",
"require_hashes",
")",
":",
"# type: (PackageFinder, bool, bool) -> None",
"if",
"self",
".",
"link",
"is",
"None",
":",
"self",
".",
"link",
"=",
"finder",
".",
"find_requirement",
"(",
"self",
",",
"upgrade",
")",
"if",
"self",
".",
"_wheel_cache",
"is",
"not",
"None",
"and",
"not",
"require_hashes",
":",
"old_link",
"=",
"self",
".",
"link",
"self",
".",
"link",
"=",
"self",
".",
"_wheel_cache",
".",
"get",
"(",
"self",
".",
"link",
",",
"self",
".",
"name",
")",
"if",
"old_link",
"!=",
"self",
".",
"link",
":",
"logger",
".",
"debug",
"(",
"'Using cached wheel link: %s'",
",",
"self",
".",
"link",
")"
] | Ensure that if a link can be found for this, that it is found.
Note that self.link may still be None - if Upgrade is False and the
requirement is already installed.
If require_hashes is True, don't use the wheel cache, because cached
wheels, always built locally, have different hashes than the files
downloaded from the index server and thus throw false hash mismatches.
Furthermore, cached wheels at present have undeterministic contents due
to file modification times. | [
"Ensure",
"that",
"if",
"a",
"link",
"can",
"be",
"found",
"for",
"this",
"that",
"it",
"is",
"found",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_install.py#L182-L201 |
25,216 | pypa/pipenv | pipenv/patched/notpip/_internal/req/req_install.py | InstallRequirement.is_pinned | def is_pinned(self):
# type: () -> bool
"""Return whether I am pinned to an exact version.
For example, some-package==1.2 is pinned; some-package>1.2 is not.
"""
specifiers = self.specifier
return (len(specifiers) == 1 and
next(iter(specifiers)).operator in {'==', '==='}) | python | def is_pinned(self):
# type: () -> bool
"""Return whether I am pinned to an exact version.
For example, some-package==1.2 is pinned; some-package>1.2 is not.
"""
specifiers = self.specifier
return (len(specifiers) == 1 and
next(iter(specifiers)).operator in {'==', '==='}) | [
"def",
"is_pinned",
"(",
"self",
")",
":",
"# type: () -> bool",
"specifiers",
"=",
"self",
".",
"specifier",
"return",
"(",
"len",
"(",
"specifiers",
")",
"==",
"1",
"and",
"next",
"(",
"iter",
"(",
"specifiers",
")",
")",
".",
"operator",
"in",
"{",
"'=='",
",",
"'==='",
"}",
")"
] | Return whether I am pinned to an exact version.
For example, some-package==1.2 is pinned; some-package>1.2 is not. | [
"Return",
"whether",
"I",
"am",
"pinned",
"to",
"an",
"exact",
"version",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_install.py#L217-L225 |
25,217 | pypa/pipenv | pipenv/patched/notpip/_internal/req/req_install.py | InstallRequirement.hashes | def hashes(self, trust_internet=True):
# type: (bool) -> Hashes
"""Return a hash-comparer that considers my option- and URL-based
hashes to be known-good.
Hashes in URLs--ones embedded in the requirements file, not ones
downloaded from an index server--are almost peers with ones from
flags. They satisfy --require-hashes (whether it was implicitly or
explicitly activated) but do not activate it. md5 and sha224 are not
allowed in flags, which should nudge people toward good algos. We
always OR all hashes together, even ones from URLs.
:param trust_internet: Whether to trust URL-based (#md5=...) hashes
downloaded from the internet, as by populate_link()
"""
good_hashes = self.options.get('hashes', {}).copy()
link = self.link if trust_internet else self.original_link
if link and link.hash:
good_hashes.setdefault(link.hash_name, []).append(link.hash)
return Hashes(good_hashes) | python | def hashes(self, trust_internet=True):
# type: (bool) -> Hashes
"""Return a hash-comparer that considers my option- and URL-based
hashes to be known-good.
Hashes in URLs--ones embedded in the requirements file, not ones
downloaded from an index server--are almost peers with ones from
flags. They satisfy --require-hashes (whether it was implicitly or
explicitly activated) but do not activate it. md5 and sha224 are not
allowed in flags, which should nudge people toward good algos. We
always OR all hashes together, even ones from URLs.
:param trust_internet: Whether to trust URL-based (#md5=...) hashes
downloaded from the internet, as by populate_link()
"""
good_hashes = self.options.get('hashes', {}).copy()
link = self.link if trust_internet else self.original_link
if link and link.hash:
good_hashes.setdefault(link.hash_name, []).append(link.hash)
return Hashes(good_hashes) | [
"def",
"hashes",
"(",
"self",
",",
"trust_internet",
"=",
"True",
")",
":",
"# type: (bool) -> Hashes",
"good_hashes",
"=",
"self",
".",
"options",
".",
"get",
"(",
"'hashes'",
",",
"{",
"}",
")",
".",
"copy",
"(",
")",
"link",
"=",
"self",
".",
"link",
"if",
"trust_internet",
"else",
"self",
".",
"original_link",
"if",
"link",
"and",
"link",
".",
"hash",
":",
"good_hashes",
".",
"setdefault",
"(",
"link",
".",
"hash_name",
",",
"[",
"]",
")",
".",
"append",
"(",
"link",
".",
"hash",
")",
"return",
"Hashes",
"(",
"good_hashes",
")"
] | Return a hash-comparer that considers my option- and URL-based
hashes to be known-good.
Hashes in URLs--ones embedded in the requirements file, not ones
downloaded from an index server--are almost peers with ones from
flags. They satisfy --require-hashes (whether it was implicitly or
explicitly activated) but do not activate it. md5 and sha224 are not
allowed in flags, which should nudge people toward good algos. We
always OR all hashes together, even ones from URLs.
:param trust_internet: Whether to trust URL-based (#md5=...) hashes
downloaded from the internet, as by populate_link() | [
"Return",
"a",
"hash",
"-",
"comparer",
"that",
"considers",
"my",
"option",
"-",
"and",
"URL",
"-",
"based",
"hashes",
"to",
"be",
"known",
"-",
"good",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_install.py#L255-L275 |
25,218 | pypa/pipenv | pipenv/patched/notpip/_internal/req/req_install.py | InstallRequirement.prepare_metadata | def prepare_metadata(self):
# type: () -> None
"""Ensure that project metadata is available.
Under PEP 517, call the backend hook to prepare the metadata.
Under legacy processing, call setup.py egg-info.
"""
assert self.source_dir
with indent_log():
if self.use_pep517:
self.prepare_pep517_metadata()
else:
self.run_egg_info()
if not self.req:
if isinstance(parse_version(self.metadata["Version"]), Version):
op = "=="
else:
op = "==="
self.req = Requirement(
"".join([
self.metadata["Name"],
op,
self.metadata["Version"],
])
)
self._correct_build_location()
else:
metadata_name = canonicalize_name(self.metadata["Name"])
if canonicalize_name(self.req.name) != metadata_name:
logger.warning(
'Generating metadata for package %s '
'produced metadata for project name %s. Fix your '
'#egg=%s fragments.',
self.name, metadata_name, self.name
)
self.req = Requirement(metadata_name) | python | def prepare_metadata(self):
# type: () -> None
"""Ensure that project metadata is available.
Under PEP 517, call the backend hook to prepare the metadata.
Under legacy processing, call setup.py egg-info.
"""
assert self.source_dir
with indent_log():
if self.use_pep517:
self.prepare_pep517_metadata()
else:
self.run_egg_info()
if not self.req:
if isinstance(parse_version(self.metadata["Version"]), Version):
op = "=="
else:
op = "==="
self.req = Requirement(
"".join([
self.metadata["Name"],
op,
self.metadata["Version"],
])
)
self._correct_build_location()
else:
metadata_name = canonicalize_name(self.metadata["Name"])
if canonicalize_name(self.req.name) != metadata_name:
logger.warning(
'Generating metadata for package %s '
'produced metadata for project name %s. Fix your '
'#egg=%s fragments.',
self.name, metadata_name, self.name
)
self.req = Requirement(metadata_name) | [
"def",
"prepare_metadata",
"(",
"self",
")",
":",
"# type: () -> None",
"assert",
"self",
".",
"source_dir",
"with",
"indent_log",
"(",
")",
":",
"if",
"self",
".",
"use_pep517",
":",
"self",
".",
"prepare_pep517_metadata",
"(",
")",
"else",
":",
"self",
".",
"run_egg_info",
"(",
")",
"if",
"not",
"self",
".",
"req",
":",
"if",
"isinstance",
"(",
"parse_version",
"(",
"self",
".",
"metadata",
"[",
"\"Version\"",
"]",
")",
",",
"Version",
")",
":",
"op",
"=",
"\"==\"",
"else",
":",
"op",
"=",
"\"===\"",
"self",
".",
"req",
"=",
"Requirement",
"(",
"\"\"",
".",
"join",
"(",
"[",
"self",
".",
"metadata",
"[",
"\"Name\"",
"]",
",",
"op",
",",
"self",
".",
"metadata",
"[",
"\"Version\"",
"]",
",",
"]",
")",
")",
"self",
".",
"_correct_build_location",
"(",
")",
"else",
":",
"metadata_name",
"=",
"canonicalize_name",
"(",
"self",
".",
"metadata",
"[",
"\"Name\"",
"]",
")",
"if",
"canonicalize_name",
"(",
"self",
".",
"req",
".",
"name",
")",
"!=",
"metadata_name",
":",
"logger",
".",
"warning",
"(",
"'Generating metadata for package %s '",
"'produced metadata for project name %s. Fix your '",
"'#egg=%s fragments.'",
",",
"self",
".",
"name",
",",
"metadata_name",
",",
"self",
".",
"name",
")",
"self",
".",
"req",
"=",
"Requirement",
"(",
"metadata_name",
")"
] | Ensure that project metadata is available.
Under PEP 517, call the backend hook to prepare the metadata.
Under legacy processing, call setup.py egg-info. | [
"Ensure",
"that",
"project",
"metadata",
"is",
"available",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_install.py#L517-L554 |
25,219 | pypa/pipenv | pipenv/patched/notpip/_internal/req/req_install.py | InstallRequirement.get_dist | def get_dist(self):
# type: () -> Distribution
"""Return a pkg_resources.Distribution for this requirement"""
if self.metadata_directory:
base_dir, distinfo = os.path.split(self.metadata_directory)
metadata = pkg_resources.PathMetadata(
base_dir, self.metadata_directory
)
dist_name = os.path.splitext(distinfo)[0]
typ = pkg_resources.DistInfoDistribution
else:
egg_info = self.egg_info_path.rstrip(os.path.sep)
base_dir = os.path.dirname(egg_info)
metadata = pkg_resources.PathMetadata(base_dir, egg_info)
dist_name = os.path.splitext(os.path.basename(egg_info))[0]
# https://github.com/python/mypy/issues/1174
typ = pkg_resources.Distribution # type: ignore
return typ(
base_dir,
project_name=dist_name,
metadata=metadata,
) | python | def get_dist(self):
# type: () -> Distribution
"""Return a pkg_resources.Distribution for this requirement"""
if self.metadata_directory:
base_dir, distinfo = os.path.split(self.metadata_directory)
metadata = pkg_resources.PathMetadata(
base_dir, self.metadata_directory
)
dist_name = os.path.splitext(distinfo)[0]
typ = pkg_resources.DistInfoDistribution
else:
egg_info = self.egg_info_path.rstrip(os.path.sep)
base_dir = os.path.dirname(egg_info)
metadata = pkg_resources.PathMetadata(base_dir, egg_info)
dist_name = os.path.splitext(os.path.basename(egg_info))[0]
# https://github.com/python/mypy/issues/1174
typ = pkg_resources.Distribution # type: ignore
return typ(
base_dir,
project_name=dist_name,
metadata=metadata,
) | [
"def",
"get_dist",
"(",
"self",
")",
":",
"# type: () -> Distribution",
"if",
"self",
".",
"metadata_directory",
":",
"base_dir",
",",
"distinfo",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"metadata_directory",
")",
"metadata",
"=",
"pkg_resources",
".",
"PathMetadata",
"(",
"base_dir",
",",
"self",
".",
"metadata_directory",
")",
"dist_name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"distinfo",
")",
"[",
"0",
"]",
"typ",
"=",
"pkg_resources",
".",
"DistInfoDistribution",
"else",
":",
"egg_info",
"=",
"self",
".",
"egg_info_path",
".",
"rstrip",
"(",
"os",
".",
"path",
".",
"sep",
")",
"base_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"egg_info",
")",
"metadata",
"=",
"pkg_resources",
".",
"PathMetadata",
"(",
"base_dir",
",",
"egg_info",
")",
"dist_name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"egg_info",
")",
")",
"[",
"0",
"]",
"# https://github.com/python/mypy/issues/1174",
"typ",
"=",
"pkg_resources",
".",
"Distribution",
"# type: ignore",
"return",
"typ",
"(",
"base_dir",
",",
"project_name",
"=",
"dist_name",
",",
"metadata",
"=",
"metadata",
",",
")"
] | Return a pkg_resources.Distribution for this requirement | [
"Return",
"a",
"pkg_resources",
".",
"Distribution",
"for",
"this",
"requirement"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_install.py#L672-L694 |
25,220 | pypa/pipenv | pipenv/patched/notpip/_internal/req/req_install.py | InstallRequirement.uninstall | def uninstall(self, auto_confirm=False, verbose=False,
use_user_site=False):
# type: (bool, bool, bool) -> Optional[UninstallPathSet]
"""
Uninstall the distribution currently satisfying this requirement.
Prompts before removing or modifying files unless
``auto_confirm`` is True.
Refuses to delete or modify files outside of ``sys.prefix`` -
thus uninstallation within a virtual environment can only
modify that virtual environment, even if the virtualenv is
linked to global site-packages.
"""
if not self.check_if_exists(use_user_site):
logger.warning("Skipping %s as it is not installed.", self.name)
return None
dist = self.satisfied_by or self.conflicts_with
uninstalled_pathset = UninstallPathSet.from_dist(dist)
uninstalled_pathset.remove(auto_confirm, verbose)
return uninstalled_pathset | python | def uninstall(self, auto_confirm=False, verbose=False,
use_user_site=False):
# type: (bool, bool, bool) -> Optional[UninstallPathSet]
"""
Uninstall the distribution currently satisfying this requirement.
Prompts before removing or modifying files unless
``auto_confirm`` is True.
Refuses to delete or modify files outside of ``sys.prefix`` -
thus uninstallation within a virtual environment can only
modify that virtual environment, even if the virtualenv is
linked to global site-packages.
"""
if not self.check_if_exists(use_user_site):
logger.warning("Skipping %s as it is not installed.", self.name)
return None
dist = self.satisfied_by or self.conflicts_with
uninstalled_pathset = UninstallPathSet.from_dist(dist)
uninstalled_pathset.remove(auto_confirm, verbose)
return uninstalled_pathset | [
"def",
"uninstall",
"(",
"self",
",",
"auto_confirm",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
"use_user_site",
"=",
"False",
")",
":",
"# type: (bool, bool, bool) -> Optional[UninstallPathSet]",
"if",
"not",
"self",
".",
"check_if_exists",
"(",
"use_user_site",
")",
":",
"logger",
".",
"warning",
"(",
"\"Skipping %s as it is not installed.\"",
",",
"self",
".",
"name",
")",
"return",
"None",
"dist",
"=",
"self",
".",
"satisfied_by",
"or",
"self",
".",
"conflicts_with",
"uninstalled_pathset",
"=",
"UninstallPathSet",
".",
"from_dist",
"(",
"dist",
")",
"uninstalled_pathset",
".",
"remove",
"(",
"auto_confirm",
",",
"verbose",
")",
"return",
"uninstalled_pathset"
] | Uninstall the distribution currently satisfying this requirement.
Prompts before removing or modifying files unless
``auto_confirm`` is True.
Refuses to delete or modify files outside of ``sys.prefix`` -
thus uninstallation within a virtual environment can only
modify that virtual environment, even if the virtualenv is
linked to global site-packages. | [
"Uninstall",
"the",
"distribution",
"currently",
"satisfying",
"this",
"requirement",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_install.py#L798-L820 |
25,221 | pypa/pipenv | pipenv/patched/notpip/_internal/cli/base_command.py | RequirementCommand.populate_requirement_set | def populate_requirement_set(requirement_set, # type: RequirementSet
args, # type: List[str]
options, # type: Values
finder, # type: PackageFinder
session, # type: PipSession
name, # type: str
wheel_cache # type: Optional[WheelCache]
):
# type: (...) -> None
"""
Marshal cmd line args into a requirement set.
"""
# NOTE: As a side-effect, options.require_hashes and
# requirement_set.require_hashes may be updated
for filename in options.constraints:
for req_to_add in parse_requirements(
filename,
constraint=True, finder=finder, options=options,
session=session, wheel_cache=wheel_cache):
req_to_add.is_direct = True
requirement_set.add_requirement(req_to_add)
for req in args:
req_to_add = install_req_from_line(
req, None, isolated=options.isolated_mode,
use_pep517=options.use_pep517,
wheel_cache=wheel_cache
)
req_to_add.is_direct = True
requirement_set.add_requirement(req_to_add)
for req in options.editables:
req_to_add = install_req_from_editable(
req,
isolated=options.isolated_mode,
use_pep517=options.use_pep517,
wheel_cache=wheel_cache
)
req_to_add.is_direct = True
requirement_set.add_requirement(req_to_add)
for filename in options.requirements:
for req_to_add in parse_requirements(
filename,
finder=finder, options=options, session=session,
wheel_cache=wheel_cache,
use_pep517=options.use_pep517):
req_to_add.is_direct = True
requirement_set.add_requirement(req_to_add)
# If --require-hashes was a line in a requirements file, tell
# RequirementSet about it:
requirement_set.require_hashes = options.require_hashes
if not (args or options.editables or options.requirements):
opts = {'name': name}
if options.find_links:
raise CommandError(
'You must give at least one requirement to %(name)s '
'(maybe you meant "pip %(name)s %(links)s"?)' %
dict(opts, links=' '.join(options.find_links)))
else:
raise CommandError(
'You must give at least one requirement to %(name)s '
'(see "pip help %(name)s")' % opts) | python | def populate_requirement_set(requirement_set, # type: RequirementSet
args, # type: List[str]
options, # type: Values
finder, # type: PackageFinder
session, # type: PipSession
name, # type: str
wheel_cache # type: Optional[WheelCache]
):
# type: (...) -> None
"""
Marshal cmd line args into a requirement set.
"""
# NOTE: As a side-effect, options.require_hashes and
# requirement_set.require_hashes may be updated
for filename in options.constraints:
for req_to_add in parse_requirements(
filename,
constraint=True, finder=finder, options=options,
session=session, wheel_cache=wheel_cache):
req_to_add.is_direct = True
requirement_set.add_requirement(req_to_add)
for req in args:
req_to_add = install_req_from_line(
req, None, isolated=options.isolated_mode,
use_pep517=options.use_pep517,
wheel_cache=wheel_cache
)
req_to_add.is_direct = True
requirement_set.add_requirement(req_to_add)
for req in options.editables:
req_to_add = install_req_from_editable(
req,
isolated=options.isolated_mode,
use_pep517=options.use_pep517,
wheel_cache=wheel_cache
)
req_to_add.is_direct = True
requirement_set.add_requirement(req_to_add)
for filename in options.requirements:
for req_to_add in parse_requirements(
filename,
finder=finder, options=options, session=session,
wheel_cache=wheel_cache,
use_pep517=options.use_pep517):
req_to_add.is_direct = True
requirement_set.add_requirement(req_to_add)
# If --require-hashes was a line in a requirements file, tell
# RequirementSet about it:
requirement_set.require_hashes = options.require_hashes
if not (args or options.editables or options.requirements):
opts = {'name': name}
if options.find_links:
raise CommandError(
'You must give at least one requirement to %(name)s '
'(maybe you meant "pip %(name)s %(links)s"?)' %
dict(opts, links=' '.join(options.find_links)))
else:
raise CommandError(
'You must give at least one requirement to %(name)s '
'(see "pip help %(name)s")' % opts) | [
"def",
"populate_requirement_set",
"(",
"requirement_set",
",",
"# type: RequirementSet",
"args",
",",
"# type: List[str]",
"options",
",",
"# type: Values",
"finder",
",",
"# type: PackageFinder",
"session",
",",
"# type: PipSession",
"name",
",",
"# type: str",
"wheel_cache",
"# type: Optional[WheelCache]",
")",
":",
"# type: (...) -> None",
"# NOTE: As a side-effect, options.require_hashes and",
"# requirement_set.require_hashes may be updated",
"for",
"filename",
"in",
"options",
".",
"constraints",
":",
"for",
"req_to_add",
"in",
"parse_requirements",
"(",
"filename",
",",
"constraint",
"=",
"True",
",",
"finder",
"=",
"finder",
",",
"options",
"=",
"options",
",",
"session",
"=",
"session",
",",
"wheel_cache",
"=",
"wheel_cache",
")",
":",
"req_to_add",
".",
"is_direct",
"=",
"True",
"requirement_set",
".",
"add_requirement",
"(",
"req_to_add",
")",
"for",
"req",
"in",
"args",
":",
"req_to_add",
"=",
"install_req_from_line",
"(",
"req",
",",
"None",
",",
"isolated",
"=",
"options",
".",
"isolated_mode",
",",
"use_pep517",
"=",
"options",
".",
"use_pep517",
",",
"wheel_cache",
"=",
"wheel_cache",
")",
"req_to_add",
".",
"is_direct",
"=",
"True",
"requirement_set",
".",
"add_requirement",
"(",
"req_to_add",
")",
"for",
"req",
"in",
"options",
".",
"editables",
":",
"req_to_add",
"=",
"install_req_from_editable",
"(",
"req",
",",
"isolated",
"=",
"options",
".",
"isolated_mode",
",",
"use_pep517",
"=",
"options",
".",
"use_pep517",
",",
"wheel_cache",
"=",
"wheel_cache",
")",
"req_to_add",
".",
"is_direct",
"=",
"True",
"requirement_set",
".",
"add_requirement",
"(",
"req_to_add",
")",
"for",
"filename",
"in",
"options",
".",
"requirements",
":",
"for",
"req_to_add",
"in",
"parse_requirements",
"(",
"filename",
",",
"finder",
"=",
"finder",
",",
"options",
"=",
"options",
",",
"session",
"=",
"session",
",",
"wheel_cache",
"=",
"wheel_cache",
",",
"use_pep517",
"=",
"options",
".",
"use_pep517",
")",
":",
"req_to_add",
".",
"is_direct",
"=",
"True",
"requirement_set",
".",
"add_requirement",
"(",
"req_to_add",
")",
"# If --require-hashes was a line in a requirements file, tell",
"# RequirementSet about it:",
"requirement_set",
".",
"require_hashes",
"=",
"options",
".",
"require_hashes",
"if",
"not",
"(",
"args",
"or",
"options",
".",
"editables",
"or",
"options",
".",
"requirements",
")",
":",
"opts",
"=",
"{",
"'name'",
":",
"name",
"}",
"if",
"options",
".",
"find_links",
":",
"raise",
"CommandError",
"(",
"'You must give at least one requirement to %(name)s '",
"'(maybe you meant \"pip %(name)s %(links)s\"?)'",
"%",
"dict",
"(",
"opts",
",",
"links",
"=",
"' '",
".",
"join",
"(",
"options",
".",
"find_links",
")",
")",
")",
"else",
":",
"raise",
"CommandError",
"(",
"'You must give at least one requirement to %(name)s '",
"'(see \"pip help %(name)s\")'",
"%",
"opts",
")"
] | Marshal cmd line args into a requirement set. | [
"Marshal",
"cmd",
"line",
"args",
"into",
"a",
"requirement",
"set",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/base_command.py#L242-L306 |
25,222 | pypa/pipenv | pipenv/patched/notpip/_internal/cli/base_command.py | RequirementCommand._build_package_finder | def _build_package_finder(
self,
options, # type: Values
session, # type: PipSession
platform=None, # type: Optional[str]
python_versions=None, # type: Optional[List[str]]
abi=None, # type: Optional[str]
implementation=None # type: Optional[str]
):
# type: (...) -> PackageFinder
"""
Create a package finder appropriate to this requirement command.
"""
index_urls = [options.index_url] + options.extra_index_urls
if options.no_index:
logger.debug(
'Ignoring indexes: %s',
','.join(redact_password_from_url(url) for url in index_urls),
)
index_urls = []
return PackageFinder(
find_links=options.find_links,
format_control=options.format_control,
index_urls=index_urls,
trusted_hosts=options.trusted_hosts,
allow_all_prereleases=options.pre,
session=session,
platform=platform,
versions=python_versions,
abi=abi,
implementation=implementation,
prefer_binary=options.prefer_binary,
) | python | def _build_package_finder(
self,
options, # type: Values
session, # type: PipSession
platform=None, # type: Optional[str]
python_versions=None, # type: Optional[List[str]]
abi=None, # type: Optional[str]
implementation=None # type: Optional[str]
):
# type: (...) -> PackageFinder
"""
Create a package finder appropriate to this requirement command.
"""
index_urls = [options.index_url] + options.extra_index_urls
if options.no_index:
logger.debug(
'Ignoring indexes: %s',
','.join(redact_password_from_url(url) for url in index_urls),
)
index_urls = []
return PackageFinder(
find_links=options.find_links,
format_control=options.format_control,
index_urls=index_urls,
trusted_hosts=options.trusted_hosts,
allow_all_prereleases=options.pre,
session=session,
platform=platform,
versions=python_versions,
abi=abi,
implementation=implementation,
prefer_binary=options.prefer_binary,
) | [
"def",
"_build_package_finder",
"(",
"self",
",",
"options",
",",
"# type: Values",
"session",
",",
"# type: PipSession",
"platform",
"=",
"None",
",",
"# type: Optional[str]",
"python_versions",
"=",
"None",
",",
"# type: Optional[List[str]]",
"abi",
"=",
"None",
",",
"# type: Optional[str]",
"implementation",
"=",
"None",
"# type: Optional[str]",
")",
":",
"# type: (...) -> PackageFinder",
"index_urls",
"=",
"[",
"options",
".",
"index_url",
"]",
"+",
"options",
".",
"extra_index_urls",
"if",
"options",
".",
"no_index",
":",
"logger",
".",
"debug",
"(",
"'Ignoring indexes: %s'",
",",
"','",
".",
"join",
"(",
"redact_password_from_url",
"(",
"url",
")",
"for",
"url",
"in",
"index_urls",
")",
",",
")",
"index_urls",
"=",
"[",
"]",
"return",
"PackageFinder",
"(",
"find_links",
"=",
"options",
".",
"find_links",
",",
"format_control",
"=",
"options",
".",
"format_control",
",",
"index_urls",
"=",
"index_urls",
",",
"trusted_hosts",
"=",
"options",
".",
"trusted_hosts",
",",
"allow_all_prereleases",
"=",
"options",
".",
"pre",
",",
"session",
"=",
"session",
",",
"platform",
"=",
"platform",
",",
"versions",
"=",
"python_versions",
",",
"abi",
"=",
"abi",
",",
"implementation",
"=",
"implementation",
",",
"prefer_binary",
"=",
"options",
".",
"prefer_binary",
",",
")"
] | Create a package finder appropriate to this requirement command. | [
"Create",
"a",
"package",
"finder",
"appropriate",
"to",
"this",
"requirement",
"command",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/base_command.py#L308-L341 |
25,223 | pypa/pipenv | pipenv/vendor/idna/intranges.py | intranges_contain | def intranges_contain(int_, ranges):
"""Determine if `int_` falls into one of the ranges in `ranges`."""
tuple_ = _encode_range(int_, 0)
pos = bisect.bisect_left(ranges, tuple_)
# we could be immediately ahead of a tuple (start, end)
# with start < int_ <= end
if pos > 0:
left, right = _decode_range(ranges[pos-1])
if left <= int_ < right:
return True
# or we could be immediately behind a tuple (int_, end)
if pos < len(ranges):
left, _ = _decode_range(ranges[pos])
if left == int_:
return True
return False | python | def intranges_contain(int_, ranges):
"""Determine if `int_` falls into one of the ranges in `ranges`."""
tuple_ = _encode_range(int_, 0)
pos = bisect.bisect_left(ranges, tuple_)
# we could be immediately ahead of a tuple (start, end)
# with start < int_ <= end
if pos > 0:
left, right = _decode_range(ranges[pos-1])
if left <= int_ < right:
return True
# or we could be immediately behind a tuple (int_, end)
if pos < len(ranges):
left, _ = _decode_range(ranges[pos])
if left == int_:
return True
return False | [
"def",
"intranges_contain",
"(",
"int_",
",",
"ranges",
")",
":",
"tuple_",
"=",
"_encode_range",
"(",
"int_",
",",
"0",
")",
"pos",
"=",
"bisect",
".",
"bisect_left",
"(",
"ranges",
",",
"tuple_",
")",
"# we could be immediately ahead of a tuple (start, end)",
"# with start < int_ <= end",
"if",
"pos",
">",
"0",
":",
"left",
",",
"right",
"=",
"_decode_range",
"(",
"ranges",
"[",
"pos",
"-",
"1",
"]",
")",
"if",
"left",
"<=",
"int_",
"<",
"right",
":",
"return",
"True",
"# or we could be immediately behind a tuple (int_, end)",
"if",
"pos",
"<",
"len",
"(",
"ranges",
")",
":",
"left",
",",
"_",
"=",
"_decode_range",
"(",
"ranges",
"[",
"pos",
"]",
")",
"if",
"left",
"==",
"int_",
":",
"return",
"True",
"return",
"False"
] | Determine if `int_` falls into one of the ranges in `ranges`. | [
"Determine",
"if",
"int_",
"falls",
"into",
"one",
"of",
"the",
"ranges",
"in",
"ranges",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/idna/intranges.py#L38-L53 |
25,224 | pypa/pipenv | pipenv/patched/notpip/_internal/commands/hash.py | _hash_of_file | def _hash_of_file(path, algorithm):
"""Return the hash digest of a file."""
with open(path, 'rb') as archive:
hash = hashlib.new(algorithm)
for chunk in read_chunks(archive):
hash.update(chunk)
return hash.hexdigest() | python | def _hash_of_file(path, algorithm):
"""Return the hash digest of a file."""
with open(path, 'rb') as archive:
hash = hashlib.new(algorithm)
for chunk in read_chunks(archive):
hash.update(chunk)
return hash.hexdigest() | [
"def",
"_hash_of_file",
"(",
"path",
",",
"algorithm",
")",
":",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"archive",
":",
"hash",
"=",
"hashlib",
".",
"new",
"(",
"algorithm",
")",
"for",
"chunk",
"in",
"read_chunks",
"(",
"archive",
")",
":",
"hash",
".",
"update",
"(",
"chunk",
")",
"return",
"hash",
".",
"hexdigest",
"(",
")"
] | Return the hash digest of a file. | [
"Return",
"the",
"hash",
"digest",
"of",
"a",
"file",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/commands/hash.py#L51-L57 |
25,225 | pypa/pipenv | pipenv/patched/notpip/_vendor/distro.py | LinuxDistribution.id | def id(self):
"""Return the distro ID of the OS distribution, as a string.
For details, see :func:`distro.id`.
"""
def normalize(distro_id, table):
distro_id = distro_id.lower().replace(' ', '_')
return table.get(distro_id, distro_id)
distro_id = self.os_release_attr('id')
if distro_id:
return normalize(distro_id, NORMALIZED_OS_ID)
distro_id = self.lsb_release_attr('distributor_id')
if distro_id:
return normalize(distro_id, NORMALIZED_LSB_ID)
distro_id = self.distro_release_attr('id')
if distro_id:
return normalize(distro_id, NORMALIZED_DISTRO_ID)
distro_id = self.uname_attr('id')
if distro_id:
return normalize(distro_id, NORMALIZED_DISTRO_ID)
return '' | python | def id(self):
"""Return the distro ID of the OS distribution, as a string.
For details, see :func:`distro.id`.
"""
def normalize(distro_id, table):
distro_id = distro_id.lower().replace(' ', '_')
return table.get(distro_id, distro_id)
distro_id = self.os_release_attr('id')
if distro_id:
return normalize(distro_id, NORMALIZED_OS_ID)
distro_id = self.lsb_release_attr('distributor_id')
if distro_id:
return normalize(distro_id, NORMALIZED_LSB_ID)
distro_id = self.distro_release_attr('id')
if distro_id:
return normalize(distro_id, NORMALIZED_DISTRO_ID)
distro_id = self.uname_attr('id')
if distro_id:
return normalize(distro_id, NORMALIZED_DISTRO_ID)
return '' | [
"def",
"id",
"(",
"self",
")",
":",
"def",
"normalize",
"(",
"distro_id",
",",
"table",
")",
":",
"distro_id",
"=",
"distro_id",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
"return",
"table",
".",
"get",
"(",
"distro_id",
",",
"distro_id",
")",
"distro_id",
"=",
"self",
".",
"os_release_attr",
"(",
"'id'",
")",
"if",
"distro_id",
":",
"return",
"normalize",
"(",
"distro_id",
",",
"NORMALIZED_OS_ID",
")",
"distro_id",
"=",
"self",
".",
"lsb_release_attr",
"(",
"'distributor_id'",
")",
"if",
"distro_id",
":",
"return",
"normalize",
"(",
"distro_id",
",",
"NORMALIZED_LSB_ID",
")",
"distro_id",
"=",
"self",
".",
"distro_release_attr",
"(",
"'id'",
")",
"if",
"distro_id",
":",
"return",
"normalize",
"(",
"distro_id",
",",
"NORMALIZED_DISTRO_ID",
")",
"distro_id",
"=",
"self",
".",
"uname_attr",
"(",
"'id'",
")",
"if",
"distro_id",
":",
"return",
"normalize",
"(",
"distro_id",
",",
"NORMALIZED_DISTRO_ID",
")",
"return",
"''"
] | Return the distro ID of the OS distribution, as a string.
For details, see :func:`distro.id`. | [
"Return",
"the",
"distro",
"ID",
"of",
"the",
"OS",
"distribution",
"as",
"a",
"string",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/distro.py#L679-L704 |
25,226 | pypa/pipenv | pipenv/patched/notpip/_vendor/distro.py | LinuxDistribution.name | def name(self, pretty=False):
"""
Return the name of the OS distribution, as a string.
For details, see :func:`distro.name`.
"""
name = self.os_release_attr('name') \
or self.lsb_release_attr('distributor_id') \
or self.distro_release_attr('name') \
or self.uname_attr('name')
if pretty:
name = self.os_release_attr('pretty_name') \
or self.lsb_release_attr('description')
if not name:
name = self.distro_release_attr('name') \
or self.uname_attr('name')
version = self.version(pretty=True)
if version:
name = name + ' ' + version
return name or '' | python | def name(self, pretty=False):
"""
Return the name of the OS distribution, as a string.
For details, see :func:`distro.name`.
"""
name = self.os_release_attr('name') \
or self.lsb_release_attr('distributor_id') \
or self.distro_release_attr('name') \
or self.uname_attr('name')
if pretty:
name = self.os_release_attr('pretty_name') \
or self.lsb_release_attr('description')
if not name:
name = self.distro_release_attr('name') \
or self.uname_attr('name')
version = self.version(pretty=True)
if version:
name = name + ' ' + version
return name or '' | [
"def",
"name",
"(",
"self",
",",
"pretty",
"=",
"False",
")",
":",
"name",
"=",
"self",
".",
"os_release_attr",
"(",
"'name'",
")",
"or",
"self",
".",
"lsb_release_attr",
"(",
"'distributor_id'",
")",
"or",
"self",
".",
"distro_release_attr",
"(",
"'name'",
")",
"or",
"self",
".",
"uname_attr",
"(",
"'name'",
")",
"if",
"pretty",
":",
"name",
"=",
"self",
".",
"os_release_attr",
"(",
"'pretty_name'",
")",
"or",
"self",
".",
"lsb_release_attr",
"(",
"'description'",
")",
"if",
"not",
"name",
":",
"name",
"=",
"self",
".",
"distro_release_attr",
"(",
"'name'",
")",
"or",
"self",
".",
"uname_attr",
"(",
"'name'",
")",
"version",
"=",
"self",
".",
"version",
"(",
"pretty",
"=",
"True",
")",
"if",
"version",
":",
"name",
"=",
"name",
"+",
"' '",
"+",
"version",
"return",
"name",
"or",
"''"
] | Return the name of the OS distribution, as a string.
For details, see :func:`distro.name`. | [
"Return",
"the",
"name",
"of",
"the",
"OS",
"distribution",
"as",
"a",
"string",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/distro.py#L706-L725 |
25,227 | pypa/pipenv | pipenv/patched/notpip/_vendor/distro.py | LinuxDistribution.version | def version(self, pretty=False, best=False):
"""
Return the version of the OS distribution, as a string.
For details, see :func:`distro.version`.
"""
versions = [
self.os_release_attr('version_id'),
self.lsb_release_attr('release'),
self.distro_release_attr('version_id'),
self._parse_distro_release_content(
self.os_release_attr('pretty_name')).get('version_id', ''),
self._parse_distro_release_content(
self.lsb_release_attr('description')).get('version_id', ''),
self.uname_attr('release')
]
version = ''
if best:
# This algorithm uses the last version in priority order that has
# the best precision. If the versions are not in conflict, that
# does not matter; otherwise, using the last one instead of the
# first one might be considered a surprise.
for v in versions:
if v.count(".") > version.count(".") or version == '':
version = v
else:
for v in versions:
if v != '':
version = v
break
if pretty and version and self.codename():
version = u'{0} ({1})'.format(version, self.codename())
return version | python | def version(self, pretty=False, best=False):
"""
Return the version of the OS distribution, as a string.
For details, see :func:`distro.version`.
"""
versions = [
self.os_release_attr('version_id'),
self.lsb_release_attr('release'),
self.distro_release_attr('version_id'),
self._parse_distro_release_content(
self.os_release_attr('pretty_name')).get('version_id', ''),
self._parse_distro_release_content(
self.lsb_release_attr('description')).get('version_id', ''),
self.uname_attr('release')
]
version = ''
if best:
# This algorithm uses the last version in priority order that has
# the best precision. If the versions are not in conflict, that
# does not matter; otherwise, using the last one instead of the
# first one might be considered a surprise.
for v in versions:
if v.count(".") > version.count(".") or version == '':
version = v
else:
for v in versions:
if v != '':
version = v
break
if pretty and version and self.codename():
version = u'{0} ({1})'.format(version, self.codename())
return version | [
"def",
"version",
"(",
"self",
",",
"pretty",
"=",
"False",
",",
"best",
"=",
"False",
")",
":",
"versions",
"=",
"[",
"self",
".",
"os_release_attr",
"(",
"'version_id'",
")",
",",
"self",
".",
"lsb_release_attr",
"(",
"'release'",
")",
",",
"self",
".",
"distro_release_attr",
"(",
"'version_id'",
")",
",",
"self",
".",
"_parse_distro_release_content",
"(",
"self",
".",
"os_release_attr",
"(",
"'pretty_name'",
")",
")",
".",
"get",
"(",
"'version_id'",
",",
"''",
")",
",",
"self",
".",
"_parse_distro_release_content",
"(",
"self",
".",
"lsb_release_attr",
"(",
"'description'",
")",
")",
".",
"get",
"(",
"'version_id'",
",",
"''",
")",
",",
"self",
".",
"uname_attr",
"(",
"'release'",
")",
"]",
"version",
"=",
"''",
"if",
"best",
":",
"# This algorithm uses the last version in priority order that has",
"# the best precision. If the versions are not in conflict, that",
"# does not matter; otherwise, using the last one instead of the",
"# first one might be considered a surprise.",
"for",
"v",
"in",
"versions",
":",
"if",
"v",
".",
"count",
"(",
"\".\"",
")",
">",
"version",
".",
"count",
"(",
"\".\"",
")",
"or",
"version",
"==",
"''",
":",
"version",
"=",
"v",
"else",
":",
"for",
"v",
"in",
"versions",
":",
"if",
"v",
"!=",
"''",
":",
"version",
"=",
"v",
"break",
"if",
"pretty",
"and",
"version",
"and",
"self",
".",
"codename",
"(",
")",
":",
"version",
"=",
"u'{0} ({1})'",
".",
"format",
"(",
"version",
",",
"self",
".",
"codename",
"(",
")",
")",
"return",
"version"
] | Return the version of the OS distribution, as a string.
For details, see :func:`distro.version`. | [
"Return",
"the",
"version",
"of",
"the",
"OS",
"distribution",
"as",
"a",
"string",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/distro.py#L727-L759 |
25,228 | pypa/pipenv | pipenv/patched/notpip/_vendor/distro.py | LinuxDistribution.version_parts | def version_parts(self, best=False):
"""
Return the version of the OS distribution, as a tuple of version
numbers.
For details, see :func:`distro.version_parts`.
"""
version_str = self.version(best=best)
if version_str:
version_regex = re.compile(r'(\d+)\.?(\d+)?\.?(\d+)?')
matches = version_regex.match(version_str)
if matches:
major, minor, build_number = matches.groups()
return major, minor or '', build_number or ''
return '', '', '' | python | def version_parts(self, best=False):
"""
Return the version of the OS distribution, as a tuple of version
numbers.
For details, see :func:`distro.version_parts`.
"""
version_str = self.version(best=best)
if version_str:
version_regex = re.compile(r'(\d+)\.?(\d+)?\.?(\d+)?')
matches = version_regex.match(version_str)
if matches:
major, minor, build_number = matches.groups()
return major, minor or '', build_number or ''
return '', '', '' | [
"def",
"version_parts",
"(",
"self",
",",
"best",
"=",
"False",
")",
":",
"version_str",
"=",
"self",
".",
"version",
"(",
"best",
"=",
"best",
")",
"if",
"version_str",
":",
"version_regex",
"=",
"re",
".",
"compile",
"(",
"r'(\\d+)\\.?(\\d+)?\\.?(\\d+)?'",
")",
"matches",
"=",
"version_regex",
".",
"match",
"(",
"version_str",
")",
"if",
"matches",
":",
"major",
",",
"minor",
",",
"build_number",
"=",
"matches",
".",
"groups",
"(",
")",
"return",
"major",
",",
"minor",
"or",
"''",
",",
"build_number",
"or",
"''",
"return",
"''",
",",
"''",
",",
"''"
] | Return the version of the OS distribution, as a tuple of version
numbers.
For details, see :func:`distro.version_parts`. | [
"Return",
"the",
"version",
"of",
"the",
"OS",
"distribution",
"as",
"a",
"tuple",
"of",
"version",
"numbers",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/distro.py#L761-L775 |
25,229 | pypa/pipenv | pipenv/patched/notpip/_vendor/distro.py | LinuxDistribution.info | def info(self, pretty=False, best=False):
"""
Return certain machine-readable information about the OS
distribution.
For details, see :func:`distro.info`.
"""
return dict(
id=self.id(),
version=self.version(pretty, best),
version_parts=dict(
major=self.major_version(best),
minor=self.minor_version(best),
build_number=self.build_number(best)
),
like=self.like(),
codename=self.codename(),
) | python | def info(self, pretty=False, best=False):
"""
Return certain machine-readable information about the OS
distribution.
For details, see :func:`distro.info`.
"""
return dict(
id=self.id(),
version=self.version(pretty, best),
version_parts=dict(
major=self.major_version(best),
minor=self.minor_version(best),
build_number=self.build_number(best)
),
like=self.like(),
codename=self.codename(),
) | [
"def",
"info",
"(",
"self",
",",
"pretty",
"=",
"False",
",",
"best",
"=",
"False",
")",
":",
"return",
"dict",
"(",
"id",
"=",
"self",
".",
"id",
"(",
")",
",",
"version",
"=",
"self",
".",
"version",
"(",
"pretty",
",",
"best",
")",
",",
"version_parts",
"=",
"dict",
"(",
"major",
"=",
"self",
".",
"major_version",
"(",
"best",
")",
",",
"minor",
"=",
"self",
".",
"minor_version",
"(",
"best",
")",
",",
"build_number",
"=",
"self",
".",
"build_number",
"(",
"best",
")",
")",
",",
"like",
"=",
"self",
".",
"like",
"(",
")",
",",
"codename",
"=",
"self",
".",
"codename",
"(",
")",
",",
")"
] | Return certain machine-readable information about the OS
distribution.
For details, see :func:`distro.info`. | [
"Return",
"certain",
"machine",
"-",
"readable",
"information",
"about",
"the",
"OS",
"distribution",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/distro.py#L820-L837 |
25,230 | pypa/pipenv | pipenv/patched/notpip/_vendor/distro.py | LinuxDistribution._os_release_info | def _os_release_info(self):
"""
Get the information items from the specified os-release file.
Returns:
A dictionary containing all information items.
"""
if os.path.isfile(self.os_release_file):
with open(self.os_release_file) as release_file:
return self._parse_os_release_content(release_file)
return {} | python | def _os_release_info(self):
"""
Get the information items from the specified os-release file.
Returns:
A dictionary containing all information items.
"""
if os.path.isfile(self.os_release_file):
with open(self.os_release_file) as release_file:
return self._parse_os_release_content(release_file)
return {} | [
"def",
"_os_release_info",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"os_release_file",
")",
":",
"with",
"open",
"(",
"self",
".",
"os_release_file",
")",
"as",
"release_file",
":",
"return",
"self",
".",
"_parse_os_release_content",
"(",
"release_file",
")",
"return",
"{",
"}"
] | Get the information items from the specified os-release file.
Returns:
A dictionary containing all information items. | [
"Get",
"the",
"information",
"items",
"from",
"the",
"specified",
"os",
"-",
"release",
"file",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/distro.py#L913-L923 |
25,231 | pypa/pipenv | pipenv/patched/notpip/_vendor/distro.py | LinuxDistribution._lsb_release_info | def _lsb_release_info(self):
"""
Get the information items from the lsb_release command output.
Returns:
A dictionary containing all information items.
"""
if not self.include_lsb:
return {}
with open(os.devnull, 'w') as devnull:
try:
cmd = ('lsb_release', '-a')
stdout = subprocess.check_output(cmd, stderr=devnull)
except OSError: # Command not found
return {}
content = stdout.decode(sys.getfilesystemencoding()).splitlines()
return self._parse_lsb_release_content(content) | python | def _lsb_release_info(self):
"""
Get the information items from the lsb_release command output.
Returns:
A dictionary containing all information items.
"""
if not self.include_lsb:
return {}
with open(os.devnull, 'w') as devnull:
try:
cmd = ('lsb_release', '-a')
stdout = subprocess.check_output(cmd, stderr=devnull)
except OSError: # Command not found
return {}
content = stdout.decode(sys.getfilesystemencoding()).splitlines()
return self._parse_lsb_release_content(content) | [
"def",
"_lsb_release_info",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"include_lsb",
":",
"return",
"{",
"}",
"with",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
")",
"as",
"devnull",
":",
"try",
":",
"cmd",
"=",
"(",
"'lsb_release'",
",",
"'-a'",
")",
"stdout",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
",",
"stderr",
"=",
"devnull",
")",
"except",
"OSError",
":",
"# Command not found",
"return",
"{",
"}",
"content",
"=",
"stdout",
".",
"decode",
"(",
"sys",
".",
"getfilesystemencoding",
"(",
")",
")",
".",
"splitlines",
"(",
")",
"return",
"self",
".",
"_parse_lsb_release_content",
"(",
"content",
")"
] | Get the information items from the lsb_release command output.
Returns:
A dictionary containing all information items. | [
"Get",
"the",
"information",
"items",
"from",
"the",
"lsb_release",
"command",
"output",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/distro.py#L986-L1002 |
25,232 | pypa/pipenv | pipenv/patched/notpip/_vendor/distro.py | LinuxDistribution._parse_lsb_release_content | def _parse_lsb_release_content(lines):
"""
Parse the output of the lsb_release command.
Parameters:
* lines: Iterable through the lines of the lsb_release output.
Each line must be a unicode string or a UTF-8 encoded byte
string.
Returns:
A dictionary containing all information items.
"""
props = {}
for line in lines:
kv = line.strip('\n').split(':', 1)
if len(kv) != 2:
# Ignore lines without colon.
continue
k, v = kv
props.update({k.replace(' ', '_').lower(): v.strip()})
return props | python | def _parse_lsb_release_content(lines):
"""
Parse the output of the lsb_release command.
Parameters:
* lines: Iterable through the lines of the lsb_release output.
Each line must be a unicode string or a UTF-8 encoded byte
string.
Returns:
A dictionary containing all information items.
"""
props = {}
for line in lines:
kv = line.strip('\n').split(':', 1)
if len(kv) != 2:
# Ignore lines without colon.
continue
k, v = kv
props.update({k.replace(' ', '_').lower(): v.strip()})
return props | [
"def",
"_parse_lsb_release_content",
"(",
"lines",
")",
":",
"props",
"=",
"{",
"}",
"for",
"line",
"in",
"lines",
":",
"kv",
"=",
"line",
".",
"strip",
"(",
"'\\n'",
")",
".",
"split",
"(",
"':'",
",",
"1",
")",
"if",
"len",
"(",
"kv",
")",
"!=",
"2",
":",
"# Ignore lines without colon.",
"continue",
"k",
",",
"v",
"=",
"kv",
"props",
".",
"update",
"(",
"{",
"k",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
".",
"lower",
"(",
")",
":",
"v",
".",
"strip",
"(",
")",
"}",
")",
"return",
"props"
] | Parse the output of the lsb_release command.
Parameters:
* lines: Iterable through the lines of the lsb_release output.
Each line must be a unicode string or a UTF-8 encoded byte
string.
Returns:
A dictionary containing all information items. | [
"Parse",
"the",
"output",
"of",
"the",
"lsb_release",
"command",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/distro.py#L1005-L1026 |
25,233 | pypa/pipenv | pipenv/patched/notpip/_vendor/distro.py | LinuxDistribution._distro_release_info | def _distro_release_info(self):
"""
Get the information items from the specified distro release file.
Returns:
A dictionary containing all information items.
"""
if self.distro_release_file:
# If it was specified, we use it and parse what we can, even if
# its file name or content does not match the expected pattern.
distro_info = self._parse_distro_release_file(
self.distro_release_file)
basename = os.path.basename(self.distro_release_file)
# The file name pattern for user-specified distro release files
# is somewhat more tolerant (compared to when searching for the
# file), because we want to use what was specified as best as
# possible.
match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
if match:
distro_info['id'] = match.group(1)
return distro_info
else:
try:
basenames = os.listdir(_UNIXCONFDIR)
# We sort for repeatability in cases where there are multiple
# distro specific files; e.g. CentOS, Oracle, Enterprise all
# containing `redhat-release` on top of their own.
basenames.sort()
except OSError:
# This may occur when /etc is not readable but we can't be
# sure about the *-release files. Check common entries of
# /etc for information. If they turn out to not be there the
# error is handled in `_parse_distro_release_file()`.
basenames = ['SuSE-release',
'arch-release',
'base-release',
'centos-release',
'fedora-release',
'gentoo-release',
'mageia-release',
'mandrake-release',
'mandriva-release',
'mandrivalinux-release',
'manjaro-release',
'oracle-release',
'redhat-release',
'sl-release',
'slackware-version']
for basename in basenames:
if basename in _DISTRO_RELEASE_IGNORE_BASENAMES:
continue
match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
if match:
filepath = os.path.join(_UNIXCONFDIR, basename)
distro_info = self._parse_distro_release_file(filepath)
if 'name' in distro_info:
# The name is always present if the pattern matches
self.distro_release_file = filepath
distro_info['id'] = match.group(1)
return distro_info
return {} | python | def _distro_release_info(self):
"""
Get the information items from the specified distro release file.
Returns:
A dictionary containing all information items.
"""
if self.distro_release_file:
# If it was specified, we use it and parse what we can, even if
# its file name or content does not match the expected pattern.
distro_info = self._parse_distro_release_file(
self.distro_release_file)
basename = os.path.basename(self.distro_release_file)
# The file name pattern for user-specified distro release files
# is somewhat more tolerant (compared to when searching for the
# file), because we want to use what was specified as best as
# possible.
match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
if match:
distro_info['id'] = match.group(1)
return distro_info
else:
try:
basenames = os.listdir(_UNIXCONFDIR)
# We sort for repeatability in cases where there are multiple
# distro specific files; e.g. CentOS, Oracle, Enterprise all
# containing `redhat-release` on top of their own.
basenames.sort()
except OSError:
# This may occur when /etc is not readable but we can't be
# sure about the *-release files. Check common entries of
# /etc for information. If they turn out to not be there the
# error is handled in `_parse_distro_release_file()`.
basenames = ['SuSE-release',
'arch-release',
'base-release',
'centos-release',
'fedora-release',
'gentoo-release',
'mageia-release',
'mandrake-release',
'mandriva-release',
'mandrivalinux-release',
'manjaro-release',
'oracle-release',
'redhat-release',
'sl-release',
'slackware-version']
for basename in basenames:
if basename in _DISTRO_RELEASE_IGNORE_BASENAMES:
continue
match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
if match:
filepath = os.path.join(_UNIXCONFDIR, basename)
distro_info = self._parse_distro_release_file(filepath)
if 'name' in distro_info:
# The name is always present if the pattern matches
self.distro_release_file = filepath
distro_info['id'] = match.group(1)
return distro_info
return {} | [
"def",
"_distro_release_info",
"(",
"self",
")",
":",
"if",
"self",
".",
"distro_release_file",
":",
"# If it was specified, we use it and parse what we can, even if",
"# its file name or content does not match the expected pattern.",
"distro_info",
"=",
"self",
".",
"_parse_distro_release_file",
"(",
"self",
".",
"distro_release_file",
")",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"distro_release_file",
")",
"# The file name pattern for user-specified distro release files",
"# is somewhat more tolerant (compared to when searching for the",
"# file), because we want to use what was specified as best as",
"# possible.",
"match",
"=",
"_DISTRO_RELEASE_BASENAME_PATTERN",
".",
"match",
"(",
"basename",
")",
"if",
"match",
":",
"distro_info",
"[",
"'id'",
"]",
"=",
"match",
".",
"group",
"(",
"1",
")",
"return",
"distro_info",
"else",
":",
"try",
":",
"basenames",
"=",
"os",
".",
"listdir",
"(",
"_UNIXCONFDIR",
")",
"# We sort for repeatability in cases where there are multiple",
"# distro specific files; e.g. CentOS, Oracle, Enterprise all",
"# containing `redhat-release` on top of their own.",
"basenames",
".",
"sort",
"(",
")",
"except",
"OSError",
":",
"# This may occur when /etc is not readable but we can't be",
"# sure about the *-release files. Check common entries of",
"# /etc for information. If they turn out to not be there the",
"# error is handled in `_parse_distro_release_file()`.",
"basenames",
"=",
"[",
"'SuSE-release'",
",",
"'arch-release'",
",",
"'base-release'",
",",
"'centos-release'",
",",
"'fedora-release'",
",",
"'gentoo-release'",
",",
"'mageia-release'",
",",
"'mandrake-release'",
",",
"'mandriva-release'",
",",
"'mandrivalinux-release'",
",",
"'manjaro-release'",
",",
"'oracle-release'",
",",
"'redhat-release'",
",",
"'sl-release'",
",",
"'slackware-version'",
"]",
"for",
"basename",
"in",
"basenames",
":",
"if",
"basename",
"in",
"_DISTRO_RELEASE_IGNORE_BASENAMES",
":",
"continue",
"match",
"=",
"_DISTRO_RELEASE_BASENAME_PATTERN",
".",
"match",
"(",
"basename",
")",
"if",
"match",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_UNIXCONFDIR",
",",
"basename",
")",
"distro_info",
"=",
"self",
".",
"_parse_distro_release_file",
"(",
"filepath",
")",
"if",
"'name'",
"in",
"distro_info",
":",
"# The name is always present if the pattern matches",
"self",
".",
"distro_release_file",
"=",
"filepath",
"distro_info",
"[",
"'id'",
"]",
"=",
"match",
".",
"group",
"(",
"1",
")",
"return",
"distro_info",
"return",
"{",
"}"
] | Get the information items from the specified distro release file.
Returns:
A dictionary containing all information items. | [
"Get",
"the",
"information",
"items",
"from",
"the",
"specified",
"distro",
"release",
"file",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/distro.py#L1057-L1117 |
25,234 | pypa/pipenv | pipenv/patched/notpip/_vendor/distro.py | LinuxDistribution._parse_distro_release_file | def _parse_distro_release_file(self, filepath):
"""
Parse a distro release file.
Parameters:
* filepath: Path name of the distro release file.
Returns:
A dictionary containing all information items.
"""
try:
with open(filepath) as fp:
# Only parse the first line. For instance, on SLES there
# are multiple lines. We don't want them...
return self._parse_distro_release_content(fp.readline())
except (OSError, IOError):
# Ignore not being able to read a specific, seemingly version
# related file.
# See https://github.com/nir0s/distro/issues/162
return {} | python | def _parse_distro_release_file(self, filepath):
"""
Parse a distro release file.
Parameters:
* filepath: Path name of the distro release file.
Returns:
A dictionary containing all information items.
"""
try:
with open(filepath) as fp:
# Only parse the first line. For instance, on SLES there
# are multiple lines. We don't want them...
return self._parse_distro_release_content(fp.readline())
except (OSError, IOError):
# Ignore not being able to read a specific, seemingly version
# related file.
# See https://github.com/nir0s/distro/issues/162
return {} | [
"def",
"_parse_distro_release_file",
"(",
"self",
",",
"filepath",
")",
":",
"try",
":",
"with",
"open",
"(",
"filepath",
")",
"as",
"fp",
":",
"# Only parse the first line. For instance, on SLES there",
"# are multiple lines. We don't want them...",
"return",
"self",
".",
"_parse_distro_release_content",
"(",
"fp",
".",
"readline",
"(",
")",
")",
"except",
"(",
"OSError",
",",
"IOError",
")",
":",
"# Ignore not being able to read a specific, seemingly version",
"# related file.",
"# See https://github.com/nir0s/distro/issues/162",
"return",
"{",
"}"
] | Parse a distro release file.
Parameters:
* filepath: Path name of the distro release file.
Returns:
A dictionary containing all information items. | [
"Parse",
"a",
"distro",
"release",
"file",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/distro.py#L1119-L1139 |
25,235 | pypa/pipenv | pipenv/patched/notpip/_vendor/distro.py | LinuxDistribution._parse_distro_release_content | def _parse_distro_release_content(line):
"""
Parse a line from a distro release file.
Parameters:
* line: Line from the distro release file. Must be a unicode string
or a UTF-8 encoded byte string.
Returns:
A dictionary containing all information items.
"""
if isinstance(line, bytes):
line = line.decode('utf-8')
matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match(
line.strip()[::-1])
distro_info = {}
if matches:
# regexp ensures non-None
distro_info['name'] = matches.group(3)[::-1]
if matches.group(2):
distro_info['version_id'] = matches.group(2)[::-1]
if matches.group(1):
distro_info['codename'] = matches.group(1)[::-1]
elif line:
distro_info['name'] = line.strip()
return distro_info | python | def _parse_distro_release_content(line):
"""
Parse a line from a distro release file.
Parameters:
* line: Line from the distro release file. Must be a unicode string
or a UTF-8 encoded byte string.
Returns:
A dictionary containing all information items.
"""
if isinstance(line, bytes):
line = line.decode('utf-8')
matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match(
line.strip()[::-1])
distro_info = {}
if matches:
# regexp ensures non-None
distro_info['name'] = matches.group(3)[::-1]
if matches.group(2):
distro_info['version_id'] = matches.group(2)[::-1]
if matches.group(1):
distro_info['codename'] = matches.group(1)[::-1]
elif line:
distro_info['name'] = line.strip()
return distro_info | [
"def",
"_parse_distro_release_content",
"(",
"line",
")",
":",
"if",
"isinstance",
"(",
"line",
",",
"bytes",
")",
":",
"line",
"=",
"line",
".",
"decode",
"(",
"'utf-8'",
")",
"matches",
"=",
"_DISTRO_RELEASE_CONTENT_REVERSED_PATTERN",
".",
"match",
"(",
"line",
".",
"strip",
"(",
")",
"[",
":",
":",
"-",
"1",
"]",
")",
"distro_info",
"=",
"{",
"}",
"if",
"matches",
":",
"# regexp ensures non-None",
"distro_info",
"[",
"'name'",
"]",
"=",
"matches",
".",
"group",
"(",
"3",
")",
"[",
":",
":",
"-",
"1",
"]",
"if",
"matches",
".",
"group",
"(",
"2",
")",
":",
"distro_info",
"[",
"'version_id'",
"]",
"=",
"matches",
".",
"group",
"(",
"2",
")",
"[",
":",
":",
"-",
"1",
"]",
"if",
"matches",
".",
"group",
"(",
"1",
")",
":",
"distro_info",
"[",
"'codename'",
"]",
"=",
"matches",
".",
"group",
"(",
"1",
")",
"[",
":",
":",
"-",
"1",
"]",
"elif",
"line",
":",
"distro_info",
"[",
"'name'",
"]",
"=",
"line",
".",
"strip",
"(",
")",
"return",
"distro_info"
] | Parse a line from a distro release file.
Parameters:
* line: Line from the distro release file. Must be a unicode string
or a UTF-8 encoded byte string.
Returns:
A dictionary containing all information items. | [
"Parse",
"a",
"line",
"from",
"a",
"distro",
"release",
"file",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/distro.py#L1142-L1167 |
25,236 | pypa/pipenv | pipenv/patched/piptools/sync.py | dependency_tree | def dependency_tree(installed_keys, root_key):
"""
Calculate the dependency tree for the package `root_key` and return
a collection of all its dependencies. Uses a DFS traversal algorithm.
`installed_keys` should be a {key: requirement} mapping, e.g.
{'django': from_line('django==1.8')}
`root_key` should be the key to return the dependency tree for.
"""
dependencies = set()
queue = collections.deque()
if root_key in installed_keys:
dep = installed_keys[root_key]
queue.append(dep)
while queue:
v = queue.popleft()
key = key_from_req(v)
if key in dependencies:
continue
dependencies.add(key)
for dep_specifier in v.requires():
dep_name = key_from_req(dep_specifier)
if dep_name in installed_keys:
dep = installed_keys[dep_name]
if dep_specifier.specifier.contains(dep.version):
queue.append(dep)
return dependencies | python | def dependency_tree(installed_keys, root_key):
"""
Calculate the dependency tree for the package `root_key` and return
a collection of all its dependencies. Uses a DFS traversal algorithm.
`installed_keys` should be a {key: requirement} mapping, e.g.
{'django': from_line('django==1.8')}
`root_key` should be the key to return the dependency tree for.
"""
dependencies = set()
queue = collections.deque()
if root_key in installed_keys:
dep = installed_keys[root_key]
queue.append(dep)
while queue:
v = queue.popleft()
key = key_from_req(v)
if key in dependencies:
continue
dependencies.add(key)
for dep_specifier in v.requires():
dep_name = key_from_req(dep_specifier)
if dep_name in installed_keys:
dep = installed_keys[dep_name]
if dep_specifier.specifier.contains(dep.version):
queue.append(dep)
return dependencies | [
"def",
"dependency_tree",
"(",
"installed_keys",
",",
"root_key",
")",
":",
"dependencies",
"=",
"set",
"(",
")",
"queue",
"=",
"collections",
".",
"deque",
"(",
")",
"if",
"root_key",
"in",
"installed_keys",
":",
"dep",
"=",
"installed_keys",
"[",
"root_key",
"]",
"queue",
".",
"append",
"(",
"dep",
")",
"while",
"queue",
":",
"v",
"=",
"queue",
".",
"popleft",
"(",
")",
"key",
"=",
"key_from_req",
"(",
"v",
")",
"if",
"key",
"in",
"dependencies",
":",
"continue",
"dependencies",
".",
"add",
"(",
"key",
")",
"for",
"dep_specifier",
"in",
"v",
".",
"requires",
"(",
")",
":",
"dep_name",
"=",
"key_from_req",
"(",
"dep_specifier",
")",
"if",
"dep_name",
"in",
"installed_keys",
":",
"dep",
"=",
"installed_keys",
"[",
"dep_name",
"]",
"if",
"dep_specifier",
".",
"specifier",
".",
"contains",
"(",
"dep",
".",
"version",
")",
":",
"queue",
".",
"append",
"(",
"dep",
")",
"return",
"dependencies"
] | Calculate the dependency tree for the package `root_key` and return
a collection of all its dependencies. Uses a DFS traversal algorithm.
`installed_keys` should be a {key: requirement} mapping, e.g.
{'django': from_line('django==1.8')}
`root_key` should be the key to return the dependency tree for. | [
"Calculate",
"the",
"dependency",
"tree",
"for",
"the",
"package",
"root_key",
"and",
"return",
"a",
"collection",
"of",
"all",
"its",
"dependencies",
".",
"Uses",
"a",
"DFS",
"traversal",
"algorithm",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/piptools/sync.py#L21-L53 |
25,237 | pypa/pipenv | pipenv/patched/piptools/sync.py | diff | def diff(compiled_requirements, installed_dists):
"""
Calculate which packages should be installed or uninstalled, given a set
of compiled requirements and a list of currently installed modules.
"""
requirements_lut = {r.link or key_from_req(r.req): r for r in compiled_requirements}
satisfied = set() # holds keys
to_install = set() # holds InstallRequirement objects
to_uninstall = set() # holds keys
pkgs_to_ignore = get_dists_to_ignore(installed_dists)
for dist in installed_dists:
key = key_from_req(dist)
if key not in requirements_lut or not requirements_lut[key].match_markers():
to_uninstall.add(key)
elif requirements_lut[key].specifier.contains(dist.version):
satisfied.add(key)
for key, requirement in requirements_lut.items():
if key not in satisfied and requirement.match_markers():
to_install.add(requirement)
# Make sure to not uninstall any packages that should be ignored
to_uninstall -= set(pkgs_to_ignore)
return (to_install, to_uninstall) | python | def diff(compiled_requirements, installed_dists):
"""
Calculate which packages should be installed or uninstalled, given a set
of compiled requirements and a list of currently installed modules.
"""
requirements_lut = {r.link or key_from_req(r.req): r for r in compiled_requirements}
satisfied = set() # holds keys
to_install = set() # holds InstallRequirement objects
to_uninstall = set() # holds keys
pkgs_to_ignore = get_dists_to_ignore(installed_dists)
for dist in installed_dists:
key = key_from_req(dist)
if key not in requirements_lut or not requirements_lut[key].match_markers():
to_uninstall.add(key)
elif requirements_lut[key].specifier.contains(dist.version):
satisfied.add(key)
for key, requirement in requirements_lut.items():
if key not in satisfied and requirement.match_markers():
to_install.add(requirement)
# Make sure to not uninstall any packages that should be ignored
to_uninstall -= set(pkgs_to_ignore)
return (to_install, to_uninstall) | [
"def",
"diff",
"(",
"compiled_requirements",
",",
"installed_dists",
")",
":",
"requirements_lut",
"=",
"{",
"r",
".",
"link",
"or",
"key_from_req",
"(",
"r",
".",
"req",
")",
":",
"r",
"for",
"r",
"in",
"compiled_requirements",
"}",
"satisfied",
"=",
"set",
"(",
")",
"# holds keys",
"to_install",
"=",
"set",
"(",
")",
"# holds InstallRequirement objects",
"to_uninstall",
"=",
"set",
"(",
")",
"# holds keys",
"pkgs_to_ignore",
"=",
"get_dists_to_ignore",
"(",
"installed_dists",
")",
"for",
"dist",
"in",
"installed_dists",
":",
"key",
"=",
"key_from_req",
"(",
"dist",
")",
"if",
"key",
"not",
"in",
"requirements_lut",
"or",
"not",
"requirements_lut",
"[",
"key",
"]",
".",
"match_markers",
"(",
")",
":",
"to_uninstall",
".",
"add",
"(",
"key",
")",
"elif",
"requirements_lut",
"[",
"key",
"]",
".",
"specifier",
".",
"contains",
"(",
"dist",
".",
"version",
")",
":",
"satisfied",
".",
"add",
"(",
"key",
")",
"for",
"key",
",",
"requirement",
"in",
"requirements_lut",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"satisfied",
"and",
"requirement",
".",
"match_markers",
"(",
")",
":",
"to_install",
".",
"add",
"(",
"requirement",
")",
"# Make sure to not uninstall any packages that should be ignored",
"to_uninstall",
"-=",
"set",
"(",
"pkgs_to_ignore",
")",
"return",
"(",
"to_install",
",",
"to_uninstall",
")"
] | Calculate which packages should be installed or uninstalled, given a set
of compiled requirements and a list of currently installed modules. | [
"Calculate",
"which",
"packages",
"should",
"be",
"installed",
"or",
"uninstalled",
"given",
"a",
"set",
"of",
"compiled",
"requirements",
"and",
"a",
"list",
"of",
"currently",
"installed",
"modules",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/piptools/sync.py#L94-L120 |
25,238 | pypa/pipenv | pipenv/patched/piptools/sync.py | sync | def sync(to_install, to_uninstall, verbose=False, dry_run=False, install_flags=None):
"""
Install and uninstalls the given sets of modules.
"""
if not to_uninstall and not to_install:
click.echo("Everything up-to-date")
pip_flags = []
if not verbose:
pip_flags += ['-q']
if to_uninstall:
if dry_run:
click.echo("Would uninstall:")
for pkg in to_uninstall:
click.echo(" {}".format(pkg))
else:
check_call([sys.executable, '-m', 'pip', 'uninstall', '-y'] + pip_flags + sorted(to_uninstall))
if to_install:
if install_flags is None:
install_flags = []
if dry_run:
click.echo("Would install:")
for ireq in to_install:
click.echo(" {}".format(format_requirement(ireq)))
else:
# prepare requirement lines
req_lines = []
for ireq in sorted(to_install, key=key_from_ireq):
ireq_hashes = get_hashes_from_ireq(ireq)
req_lines.append(format_requirement(ireq, hashes=ireq_hashes))
# save requirement lines to a temporary file
tmp_req_file = tempfile.NamedTemporaryFile(mode='wt', delete=False)
tmp_req_file.write('\n'.join(req_lines))
tmp_req_file.close()
try:
check_call(
[sys.executable, '-m', 'pip', 'install', '-r', tmp_req_file.name] + pip_flags + install_flags
)
finally:
os.unlink(tmp_req_file.name)
return 0 | python | def sync(to_install, to_uninstall, verbose=False, dry_run=False, install_flags=None):
"""
Install and uninstalls the given sets of modules.
"""
if not to_uninstall and not to_install:
click.echo("Everything up-to-date")
pip_flags = []
if not verbose:
pip_flags += ['-q']
if to_uninstall:
if dry_run:
click.echo("Would uninstall:")
for pkg in to_uninstall:
click.echo(" {}".format(pkg))
else:
check_call([sys.executable, '-m', 'pip', 'uninstall', '-y'] + pip_flags + sorted(to_uninstall))
if to_install:
if install_flags is None:
install_flags = []
if dry_run:
click.echo("Would install:")
for ireq in to_install:
click.echo(" {}".format(format_requirement(ireq)))
else:
# prepare requirement lines
req_lines = []
for ireq in sorted(to_install, key=key_from_ireq):
ireq_hashes = get_hashes_from_ireq(ireq)
req_lines.append(format_requirement(ireq, hashes=ireq_hashes))
# save requirement lines to a temporary file
tmp_req_file = tempfile.NamedTemporaryFile(mode='wt', delete=False)
tmp_req_file.write('\n'.join(req_lines))
tmp_req_file.close()
try:
check_call(
[sys.executable, '-m', 'pip', 'install', '-r', tmp_req_file.name] + pip_flags + install_flags
)
finally:
os.unlink(tmp_req_file.name)
return 0 | [
"def",
"sync",
"(",
"to_install",
",",
"to_uninstall",
",",
"verbose",
"=",
"False",
",",
"dry_run",
"=",
"False",
",",
"install_flags",
"=",
"None",
")",
":",
"if",
"not",
"to_uninstall",
"and",
"not",
"to_install",
":",
"click",
".",
"echo",
"(",
"\"Everything up-to-date\"",
")",
"pip_flags",
"=",
"[",
"]",
"if",
"not",
"verbose",
":",
"pip_flags",
"+=",
"[",
"'-q'",
"]",
"if",
"to_uninstall",
":",
"if",
"dry_run",
":",
"click",
".",
"echo",
"(",
"\"Would uninstall:\"",
")",
"for",
"pkg",
"in",
"to_uninstall",
":",
"click",
".",
"echo",
"(",
"\" {}\"",
".",
"format",
"(",
"pkg",
")",
")",
"else",
":",
"check_call",
"(",
"[",
"sys",
".",
"executable",
",",
"'-m'",
",",
"'pip'",
",",
"'uninstall'",
",",
"'-y'",
"]",
"+",
"pip_flags",
"+",
"sorted",
"(",
"to_uninstall",
")",
")",
"if",
"to_install",
":",
"if",
"install_flags",
"is",
"None",
":",
"install_flags",
"=",
"[",
"]",
"if",
"dry_run",
":",
"click",
".",
"echo",
"(",
"\"Would install:\"",
")",
"for",
"ireq",
"in",
"to_install",
":",
"click",
".",
"echo",
"(",
"\" {}\"",
".",
"format",
"(",
"format_requirement",
"(",
"ireq",
")",
")",
")",
"else",
":",
"# prepare requirement lines",
"req_lines",
"=",
"[",
"]",
"for",
"ireq",
"in",
"sorted",
"(",
"to_install",
",",
"key",
"=",
"key_from_ireq",
")",
":",
"ireq_hashes",
"=",
"get_hashes_from_ireq",
"(",
"ireq",
")",
"req_lines",
".",
"append",
"(",
"format_requirement",
"(",
"ireq",
",",
"hashes",
"=",
"ireq_hashes",
")",
")",
"# save requirement lines to a temporary file",
"tmp_req_file",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'wt'",
",",
"delete",
"=",
"False",
")",
"tmp_req_file",
".",
"write",
"(",
"'\\n'",
".",
"join",
"(",
"req_lines",
")",
")",
"tmp_req_file",
".",
"close",
"(",
")",
"try",
":",
"check_call",
"(",
"[",
"sys",
".",
"executable",
",",
"'-m'",
",",
"'pip'",
",",
"'install'",
",",
"'-r'",
",",
"tmp_req_file",
".",
"name",
"]",
"+",
"pip_flags",
"+",
"install_flags",
")",
"finally",
":",
"os",
".",
"unlink",
"(",
"tmp_req_file",
".",
"name",
")",
"return",
"0"
] | Install and uninstalls the given sets of modules. | [
"Install",
"and",
"uninstalls",
"the",
"given",
"sets",
"of",
"modules",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/piptools/sync.py#L123-L168 |
25,239 | pypa/pipenv | pipenv/vendor/jinja2/environment.py | _environment_sanity_check | def _environment_sanity_check(environment):
"""Perform a sanity check on the environment."""
assert issubclass(environment.undefined, Undefined), 'undefined must ' \
'be a subclass of undefined because filters depend on it.'
assert environment.block_start_string != \
environment.variable_start_string != \
environment.comment_start_string, 'block, variable and comment ' \
'start strings must be different'
assert environment.newline_sequence in ('\r', '\r\n', '\n'), \
'newline_sequence set to unknown line ending string.'
return environment | python | def _environment_sanity_check(environment):
"""Perform a sanity check on the environment."""
assert issubclass(environment.undefined, Undefined), 'undefined must ' \
'be a subclass of undefined because filters depend on it.'
assert environment.block_start_string != \
environment.variable_start_string != \
environment.comment_start_string, 'block, variable and comment ' \
'start strings must be different'
assert environment.newline_sequence in ('\r', '\r\n', '\n'), \
'newline_sequence set to unknown line ending string.'
return environment | [
"def",
"_environment_sanity_check",
"(",
"environment",
")",
":",
"assert",
"issubclass",
"(",
"environment",
".",
"undefined",
",",
"Undefined",
")",
",",
"'undefined must '",
"'be a subclass of undefined because filters depend on it.'",
"assert",
"environment",
".",
"block_start_string",
"!=",
"environment",
".",
"variable_start_string",
"!=",
"environment",
".",
"comment_start_string",
",",
"'block, variable and comment '",
"'start strings must be different'",
"assert",
"environment",
".",
"newline_sequence",
"in",
"(",
"'\\r'",
",",
"'\\r\\n'",
",",
"'\\n'",
")",
",",
"'newline_sequence set to unknown line ending string.'",
"return",
"environment"
] | Perform a sanity check on the environment. | [
"Perform",
"a",
"sanity",
"check",
"on",
"the",
"environment",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/environment.py#L100-L110 |
25,240 | pypa/pipenv | pipenv/vendor/jinja2/environment.py | Environment.overlay | def overlay(self, block_start_string=missing, block_end_string=missing,
variable_start_string=missing, variable_end_string=missing,
comment_start_string=missing, comment_end_string=missing,
line_statement_prefix=missing, line_comment_prefix=missing,
trim_blocks=missing, lstrip_blocks=missing,
extensions=missing, optimized=missing,
undefined=missing, finalize=missing, autoescape=missing,
loader=missing, cache_size=missing, auto_reload=missing,
bytecode_cache=missing):
"""Create a new overlay environment that shares all the data with the
current environment except for cache and the overridden attributes.
Extensions cannot be removed for an overlayed environment. An overlayed
environment automatically gets all the extensions of the environment it
is linked to plus optional extra extensions.
Creating overlays should happen after the initial environment was set
up completely. Not all attributes are truly linked, some are just
copied over so modifications on the original environment may not shine
through.
"""
args = dict(locals())
del args['self'], args['cache_size'], args['extensions']
rv = object.__new__(self.__class__)
rv.__dict__.update(self.__dict__)
rv.overlayed = True
rv.linked_to = self
for key, value in iteritems(args):
if value is not missing:
setattr(rv, key, value)
if cache_size is not missing:
rv.cache = create_cache(cache_size)
else:
rv.cache = copy_cache(self.cache)
rv.extensions = {}
for key, value in iteritems(self.extensions):
rv.extensions[key] = value.bind(rv)
if extensions is not missing:
rv.extensions.update(load_extensions(rv, extensions))
return _environment_sanity_check(rv) | python | def overlay(self, block_start_string=missing, block_end_string=missing,
variable_start_string=missing, variable_end_string=missing,
comment_start_string=missing, comment_end_string=missing,
line_statement_prefix=missing, line_comment_prefix=missing,
trim_blocks=missing, lstrip_blocks=missing,
extensions=missing, optimized=missing,
undefined=missing, finalize=missing, autoescape=missing,
loader=missing, cache_size=missing, auto_reload=missing,
bytecode_cache=missing):
"""Create a new overlay environment that shares all the data with the
current environment except for cache and the overridden attributes.
Extensions cannot be removed for an overlayed environment. An overlayed
environment automatically gets all the extensions of the environment it
is linked to plus optional extra extensions.
Creating overlays should happen after the initial environment was set
up completely. Not all attributes are truly linked, some are just
copied over so modifications on the original environment may not shine
through.
"""
args = dict(locals())
del args['self'], args['cache_size'], args['extensions']
rv = object.__new__(self.__class__)
rv.__dict__.update(self.__dict__)
rv.overlayed = True
rv.linked_to = self
for key, value in iteritems(args):
if value is not missing:
setattr(rv, key, value)
if cache_size is not missing:
rv.cache = create_cache(cache_size)
else:
rv.cache = copy_cache(self.cache)
rv.extensions = {}
for key, value in iteritems(self.extensions):
rv.extensions[key] = value.bind(rv)
if extensions is not missing:
rv.extensions.update(load_extensions(rv, extensions))
return _environment_sanity_check(rv) | [
"def",
"overlay",
"(",
"self",
",",
"block_start_string",
"=",
"missing",
",",
"block_end_string",
"=",
"missing",
",",
"variable_start_string",
"=",
"missing",
",",
"variable_end_string",
"=",
"missing",
",",
"comment_start_string",
"=",
"missing",
",",
"comment_end_string",
"=",
"missing",
",",
"line_statement_prefix",
"=",
"missing",
",",
"line_comment_prefix",
"=",
"missing",
",",
"trim_blocks",
"=",
"missing",
",",
"lstrip_blocks",
"=",
"missing",
",",
"extensions",
"=",
"missing",
",",
"optimized",
"=",
"missing",
",",
"undefined",
"=",
"missing",
",",
"finalize",
"=",
"missing",
",",
"autoescape",
"=",
"missing",
",",
"loader",
"=",
"missing",
",",
"cache_size",
"=",
"missing",
",",
"auto_reload",
"=",
"missing",
",",
"bytecode_cache",
"=",
"missing",
")",
":",
"args",
"=",
"dict",
"(",
"locals",
"(",
")",
")",
"del",
"args",
"[",
"'self'",
"]",
",",
"args",
"[",
"'cache_size'",
"]",
",",
"args",
"[",
"'extensions'",
"]",
"rv",
"=",
"object",
".",
"__new__",
"(",
"self",
".",
"__class__",
")",
"rv",
".",
"__dict__",
".",
"update",
"(",
"self",
".",
"__dict__",
")",
"rv",
".",
"overlayed",
"=",
"True",
"rv",
".",
"linked_to",
"=",
"self",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"args",
")",
":",
"if",
"value",
"is",
"not",
"missing",
":",
"setattr",
"(",
"rv",
",",
"key",
",",
"value",
")",
"if",
"cache_size",
"is",
"not",
"missing",
":",
"rv",
".",
"cache",
"=",
"create_cache",
"(",
"cache_size",
")",
"else",
":",
"rv",
".",
"cache",
"=",
"copy_cache",
"(",
"self",
".",
"cache",
")",
"rv",
".",
"extensions",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"self",
".",
"extensions",
")",
":",
"rv",
".",
"extensions",
"[",
"key",
"]",
"=",
"value",
".",
"bind",
"(",
"rv",
")",
"if",
"extensions",
"is",
"not",
"missing",
":",
"rv",
".",
"extensions",
".",
"update",
"(",
"load_extensions",
"(",
"rv",
",",
"extensions",
")",
")",
"return",
"_environment_sanity_check",
"(",
"rv",
")"
] | Create a new overlay environment that shares all the data with the
current environment except for cache and the overridden attributes.
Extensions cannot be removed for an overlayed environment. An overlayed
environment automatically gets all the extensions of the environment it
is linked to plus optional extra extensions.
Creating overlays should happen after the initial environment was set
up completely. Not all attributes are truly linked, some are just
copied over so modifications on the original environment may not shine
through. | [
"Create",
"a",
"new",
"overlay",
"environment",
"that",
"shares",
"all",
"the",
"data",
"with",
"the",
"current",
"environment",
"except",
"for",
"cache",
"and",
"the",
"overridden",
"attributes",
".",
"Extensions",
"cannot",
"be",
"removed",
"for",
"an",
"overlayed",
"environment",
".",
"An",
"overlayed",
"environment",
"automatically",
"gets",
"all",
"the",
"extensions",
"of",
"the",
"environment",
"it",
"is",
"linked",
"to",
"plus",
"optional",
"extra",
"extensions",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/environment.py#L356-L399 |
25,241 | pypa/pipenv | pipenv/vendor/jinja2/environment.py | Environment.iter_extensions | def iter_extensions(self):
"""Iterates over the extensions by priority."""
return iter(sorted(self.extensions.values(),
key=lambda x: x.priority)) | python | def iter_extensions(self):
"""Iterates over the extensions by priority."""
return iter(sorted(self.extensions.values(),
key=lambda x: x.priority)) | [
"def",
"iter_extensions",
"(",
"self",
")",
":",
"return",
"iter",
"(",
"sorted",
"(",
"self",
".",
"extensions",
".",
"values",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"priority",
")",
")"
] | Iterates over the extensions by priority. | [
"Iterates",
"over",
"the",
"extensions",
"by",
"priority",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/environment.py#L403-L406 |
25,242 | pypa/pipenv | pipenv/vendor/jinja2/environment.py | Environment.call_filter | def call_filter(self, name, value, args=None, kwargs=None,
context=None, eval_ctx=None):
"""Invokes a filter on a value the same way the compiler does it.
Note that on Python 3 this might return a coroutine in case the
filter is running from an environment in async mode and the filter
supports async execution. It's your responsibility to await this
if needed.
.. versionadded:: 2.7
"""
func = self.filters.get(name)
if func is None:
fail_for_missing_callable('no filter named %r', name)
args = [value] + list(args or ())
if getattr(func, 'contextfilter', False):
if context is None:
raise TemplateRuntimeError('Attempted to invoke context '
'filter without context')
args.insert(0, context)
elif getattr(func, 'evalcontextfilter', False):
if eval_ctx is None:
if context is not None:
eval_ctx = context.eval_ctx
else:
eval_ctx = EvalContext(self)
args.insert(0, eval_ctx)
elif getattr(func, 'environmentfilter', False):
args.insert(0, self)
return func(*args, **(kwargs or {})) | python | def call_filter(self, name, value, args=None, kwargs=None,
context=None, eval_ctx=None):
"""Invokes a filter on a value the same way the compiler does it.
Note that on Python 3 this might return a coroutine in case the
filter is running from an environment in async mode and the filter
supports async execution. It's your responsibility to await this
if needed.
.. versionadded:: 2.7
"""
func = self.filters.get(name)
if func is None:
fail_for_missing_callable('no filter named %r', name)
args = [value] + list(args or ())
if getattr(func, 'contextfilter', False):
if context is None:
raise TemplateRuntimeError('Attempted to invoke context '
'filter without context')
args.insert(0, context)
elif getattr(func, 'evalcontextfilter', False):
if eval_ctx is None:
if context is not None:
eval_ctx = context.eval_ctx
else:
eval_ctx = EvalContext(self)
args.insert(0, eval_ctx)
elif getattr(func, 'environmentfilter', False):
args.insert(0, self)
return func(*args, **(kwargs or {})) | [
"def",
"call_filter",
"(",
"self",
",",
"name",
",",
"value",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"context",
"=",
"None",
",",
"eval_ctx",
"=",
"None",
")",
":",
"func",
"=",
"self",
".",
"filters",
".",
"get",
"(",
"name",
")",
"if",
"func",
"is",
"None",
":",
"fail_for_missing_callable",
"(",
"'no filter named %r'",
",",
"name",
")",
"args",
"=",
"[",
"value",
"]",
"+",
"list",
"(",
"args",
"or",
"(",
")",
")",
"if",
"getattr",
"(",
"func",
",",
"'contextfilter'",
",",
"False",
")",
":",
"if",
"context",
"is",
"None",
":",
"raise",
"TemplateRuntimeError",
"(",
"'Attempted to invoke context '",
"'filter without context'",
")",
"args",
".",
"insert",
"(",
"0",
",",
"context",
")",
"elif",
"getattr",
"(",
"func",
",",
"'evalcontextfilter'",
",",
"False",
")",
":",
"if",
"eval_ctx",
"is",
"None",
":",
"if",
"context",
"is",
"not",
"None",
":",
"eval_ctx",
"=",
"context",
".",
"eval_ctx",
"else",
":",
"eval_ctx",
"=",
"EvalContext",
"(",
"self",
")",
"args",
".",
"insert",
"(",
"0",
",",
"eval_ctx",
")",
"elif",
"getattr",
"(",
"func",
",",
"'environmentfilter'",
",",
"False",
")",
":",
"args",
".",
"insert",
"(",
"0",
",",
"self",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"(",
"kwargs",
"or",
"{",
"}",
")",
")"
] | Invokes a filter on a value the same way the compiler does it.
Note that on Python 3 this might return a coroutine in case the
filter is running from an environment in async mode and the filter
supports async execution. It's your responsibility to await this
if needed.
.. versionadded:: 2.7 | [
"Invokes",
"a",
"filter",
"on",
"a",
"value",
"the",
"same",
"way",
"the",
"compiler",
"does",
"it",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/environment.py#L438-L467 |
25,243 | pypa/pipenv | pipenv/vendor/jinja2/environment.py | Environment.parse | def parse(self, source, name=None, filename=None):
"""Parse the sourcecode and return the abstract syntax tree. This
tree of nodes is used by the compiler to convert the template into
executable source- or bytecode. This is useful for debugging or to
extract information from templates.
If you are :ref:`developing Jinja2 extensions <writing-extensions>`
this gives you a good overview of the node tree generated.
"""
try:
return self._parse(source, name, filename)
except TemplateSyntaxError:
exc_info = sys.exc_info()
self.handle_exception(exc_info, source_hint=source) | python | def parse(self, source, name=None, filename=None):
"""Parse the sourcecode and return the abstract syntax tree. This
tree of nodes is used by the compiler to convert the template into
executable source- or bytecode. This is useful for debugging or to
extract information from templates.
If you are :ref:`developing Jinja2 extensions <writing-extensions>`
this gives you a good overview of the node tree generated.
"""
try:
return self._parse(source, name, filename)
except TemplateSyntaxError:
exc_info = sys.exc_info()
self.handle_exception(exc_info, source_hint=source) | [
"def",
"parse",
"(",
"self",
",",
"source",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"_parse",
"(",
"source",
",",
"name",
",",
"filename",
")",
"except",
"TemplateSyntaxError",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"self",
".",
"handle_exception",
"(",
"exc_info",
",",
"source_hint",
"=",
"source",
")"
] | Parse the sourcecode and return the abstract syntax tree. This
tree of nodes is used by the compiler to convert the template into
executable source- or bytecode. This is useful for debugging or to
extract information from templates.
If you are :ref:`developing Jinja2 extensions <writing-extensions>`
this gives you a good overview of the node tree generated. | [
"Parse",
"the",
"sourcecode",
"and",
"return",
"the",
"abstract",
"syntax",
"tree",
".",
"This",
"tree",
"of",
"nodes",
"is",
"used",
"by",
"the",
"compiler",
"to",
"convert",
"the",
"template",
"into",
"executable",
"source",
"-",
"or",
"bytecode",
".",
"This",
"is",
"useful",
"for",
"debugging",
"or",
"to",
"extract",
"information",
"from",
"templates",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/environment.py#L480-L493 |
25,244 | pypa/pipenv | pipenv/vendor/jinja2/environment.py | Environment.compile_expression | def compile_expression(self, source, undefined_to_none=True):
"""A handy helper method that returns a callable that accepts keyword
arguments that appear as variables in the expression. If called it
returns the result of the expression.
This is useful if applications want to use the same rules as Jinja
in template "configuration files" or similar situations.
Example usage:
>>> env = Environment()
>>> expr = env.compile_expression('foo == 42')
>>> expr(foo=23)
False
>>> expr(foo=42)
True
Per default the return value is converted to `None` if the
expression returns an undefined value. This can be changed
by setting `undefined_to_none` to `False`.
>>> env.compile_expression('var')() is None
True
>>> env.compile_expression('var', undefined_to_none=False)()
Undefined
.. versionadded:: 2.1
"""
parser = Parser(self, source, state='variable')
exc_info = None
try:
expr = parser.parse_expression()
if not parser.stream.eos:
raise TemplateSyntaxError('chunk after expression',
parser.stream.current.lineno,
None, None)
expr.set_environment(self)
except TemplateSyntaxError:
exc_info = sys.exc_info()
if exc_info is not None:
self.handle_exception(exc_info, source_hint=source)
body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
template = self.from_string(nodes.Template(body, lineno=1))
return TemplateExpression(template, undefined_to_none) | python | def compile_expression(self, source, undefined_to_none=True):
"""A handy helper method that returns a callable that accepts keyword
arguments that appear as variables in the expression. If called it
returns the result of the expression.
This is useful if applications want to use the same rules as Jinja
in template "configuration files" or similar situations.
Example usage:
>>> env = Environment()
>>> expr = env.compile_expression('foo == 42')
>>> expr(foo=23)
False
>>> expr(foo=42)
True
Per default the return value is converted to `None` if the
expression returns an undefined value. This can be changed
by setting `undefined_to_none` to `False`.
>>> env.compile_expression('var')() is None
True
>>> env.compile_expression('var', undefined_to_none=False)()
Undefined
.. versionadded:: 2.1
"""
parser = Parser(self, source, state='variable')
exc_info = None
try:
expr = parser.parse_expression()
if not parser.stream.eos:
raise TemplateSyntaxError('chunk after expression',
parser.stream.current.lineno,
None, None)
expr.set_environment(self)
except TemplateSyntaxError:
exc_info = sys.exc_info()
if exc_info is not None:
self.handle_exception(exc_info, source_hint=source)
body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
template = self.from_string(nodes.Template(body, lineno=1))
return TemplateExpression(template, undefined_to_none) | [
"def",
"compile_expression",
"(",
"self",
",",
"source",
",",
"undefined_to_none",
"=",
"True",
")",
":",
"parser",
"=",
"Parser",
"(",
"self",
",",
"source",
",",
"state",
"=",
"'variable'",
")",
"exc_info",
"=",
"None",
"try",
":",
"expr",
"=",
"parser",
".",
"parse_expression",
"(",
")",
"if",
"not",
"parser",
".",
"stream",
".",
"eos",
":",
"raise",
"TemplateSyntaxError",
"(",
"'chunk after expression'",
",",
"parser",
".",
"stream",
".",
"current",
".",
"lineno",
",",
"None",
",",
"None",
")",
"expr",
".",
"set_environment",
"(",
"self",
")",
"except",
"TemplateSyntaxError",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"exc_info",
"is",
"not",
"None",
":",
"self",
".",
"handle_exception",
"(",
"exc_info",
",",
"source_hint",
"=",
"source",
")",
"body",
"=",
"[",
"nodes",
".",
"Assign",
"(",
"nodes",
".",
"Name",
"(",
"'result'",
",",
"'store'",
")",
",",
"expr",
",",
"lineno",
"=",
"1",
")",
"]",
"template",
"=",
"self",
".",
"from_string",
"(",
"nodes",
".",
"Template",
"(",
"body",
",",
"lineno",
"=",
"1",
")",
")",
"return",
"TemplateExpression",
"(",
"template",
",",
"undefined_to_none",
")"
] | A handy helper method that returns a callable that accepts keyword
arguments that appear as variables in the expression. If called it
returns the result of the expression.
This is useful if applications want to use the same rules as Jinja
in template "configuration files" or similar situations.
Example usage:
>>> env = Environment()
>>> expr = env.compile_expression('foo == 42')
>>> expr(foo=23)
False
>>> expr(foo=42)
True
Per default the return value is converted to `None` if the
expression returns an undefined value. This can be changed
by setting `undefined_to_none` to `False`.
>>> env.compile_expression('var')() is None
True
>>> env.compile_expression('var', undefined_to_none=False)()
Undefined
.. versionadded:: 2.1 | [
"A",
"handy",
"helper",
"method",
"that",
"returns",
"a",
"callable",
"that",
"accepts",
"keyword",
"arguments",
"that",
"appear",
"as",
"variables",
"in",
"the",
"expression",
".",
"If",
"called",
"it",
"returns",
"the",
"result",
"of",
"the",
"expression",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/environment.py#L593-L636 |
25,245 | pypa/pipenv | pipenv/vendor/jinja2/environment.py | Environment.make_globals | def make_globals(self, d):
"""Return a dict for the globals."""
if not d:
return self.globals
return dict(self.globals, **d) | python | def make_globals(self, d):
"""Return a dict for the globals."""
if not d:
return self.globals
return dict(self.globals, **d) | [
"def",
"make_globals",
"(",
"self",
",",
"d",
")",
":",
"if",
"not",
"d",
":",
"return",
"self",
".",
"globals",
"return",
"dict",
"(",
"self",
".",
"globals",
",",
"*",
"*",
"d",
")"
] | Return a dict for the globals. | [
"Return",
"a",
"dict",
"for",
"the",
"globals",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/environment.py#L882-L886 |
25,246 | pypa/pipenv | pipenv/vendor/jinja2/environment.py | Template.from_module_dict | def from_module_dict(cls, environment, module_dict, globals):
"""Creates a template object from a module. This is used by the
module loader to create a template object.
.. versionadded:: 2.4
"""
return cls._from_namespace(environment, module_dict, globals) | python | def from_module_dict(cls, environment, module_dict, globals):
"""Creates a template object from a module. This is used by the
module loader to create a template object.
.. versionadded:: 2.4
"""
return cls._from_namespace(environment, module_dict, globals) | [
"def",
"from_module_dict",
"(",
"cls",
",",
"environment",
",",
"module_dict",
",",
"globals",
")",
":",
"return",
"cls",
".",
"_from_namespace",
"(",
"environment",
",",
"module_dict",
",",
"globals",
")"
] | Creates a template object from a module. This is used by the
module loader to create a template object.
.. versionadded:: 2.4 | [
"Creates",
"a",
"template",
"object",
"from",
"a",
"module",
".",
"This",
"is",
"used",
"by",
"the",
"module",
"loader",
"to",
"create",
"a",
"template",
"object",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/environment.py#L962-L968 |
25,247 | pypa/pipenv | pipenv/vendor/jinja2/environment.py | Template.get_corresponding_lineno | def get_corresponding_lineno(self, lineno):
"""Return the source line number of a line number in the
generated bytecode as they are not in sync.
"""
for template_line, code_line in reversed(self.debug_info):
if code_line <= lineno:
return template_line
return 1 | python | def get_corresponding_lineno(self, lineno):
"""Return the source line number of a line number in the
generated bytecode as they are not in sync.
"""
for template_line, code_line in reversed(self.debug_info):
if code_line <= lineno:
return template_line
return 1 | [
"def",
"get_corresponding_lineno",
"(",
"self",
",",
"lineno",
")",
":",
"for",
"template_line",
",",
"code_line",
"in",
"reversed",
"(",
"self",
".",
"debug_info",
")",
":",
"if",
"code_line",
"<=",
"lineno",
":",
"return",
"template_line",
"return",
"1"
] | Return the source line number of a line number in the
generated bytecode as they are not in sync. | [
"Return",
"the",
"source",
"line",
"number",
"of",
"a",
"line",
"number",
"in",
"the",
"generated",
"bytecode",
"as",
"they",
"are",
"not",
"in",
"sync",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/environment.py#L1108-L1115 |
25,248 | pypa/pipenv | pipenv/vendor/requirementslib/models/url.py | _get_parsed_url | def _get_parsed_url(url):
# type: (S) -> Url
"""
This is a stand-in function for `urllib3.util.parse_url`
The orignal function doesn't handle special characters very well, this simply splits
out the authentication section, creates the parsed url, then puts the authentication
section back in, bypassing validation.
:return: The new, parsed URL object
:rtype: :class:`~urllib3.util.url.Url`
"""
try:
parsed = urllib3_parse(url)
except ValueError:
scheme, _, url = url.partition("://")
auth, _, url = url.rpartition("@")
url = "{scheme}://{url}".format(scheme=scheme, url=url)
parsed = urllib3_parse(url)._replace(auth=auth)
return parsed | python | def _get_parsed_url(url):
# type: (S) -> Url
"""
This is a stand-in function for `urllib3.util.parse_url`
The orignal function doesn't handle special characters very well, this simply splits
out the authentication section, creates the parsed url, then puts the authentication
section back in, bypassing validation.
:return: The new, parsed URL object
:rtype: :class:`~urllib3.util.url.Url`
"""
try:
parsed = urllib3_parse(url)
except ValueError:
scheme, _, url = url.partition("://")
auth, _, url = url.rpartition("@")
url = "{scheme}://{url}".format(scheme=scheme, url=url)
parsed = urllib3_parse(url)._replace(auth=auth)
return parsed | [
"def",
"_get_parsed_url",
"(",
"url",
")",
":",
"# type: (S) -> Url",
"try",
":",
"parsed",
"=",
"urllib3_parse",
"(",
"url",
")",
"except",
"ValueError",
":",
"scheme",
",",
"_",
",",
"url",
"=",
"url",
".",
"partition",
"(",
"\"://\"",
")",
"auth",
",",
"_",
",",
"url",
"=",
"url",
".",
"rpartition",
"(",
"\"@\"",
")",
"url",
"=",
"\"{scheme}://{url}\"",
".",
"format",
"(",
"scheme",
"=",
"scheme",
",",
"url",
"=",
"url",
")",
"parsed",
"=",
"urllib3_parse",
"(",
"url",
")",
".",
"_replace",
"(",
"auth",
"=",
"auth",
")",
"return",
"parsed"
] | This is a stand-in function for `urllib3.util.parse_url`
The orignal function doesn't handle special characters very well, this simply splits
out the authentication section, creates the parsed url, then puts the authentication
section back in, bypassing validation.
:return: The new, parsed URL object
:rtype: :class:`~urllib3.util.url.Url` | [
"This",
"is",
"a",
"stand",
"-",
"in",
"function",
"for",
"urllib3",
".",
"util",
".",
"parse_url"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/url.py#L24-L44 |
25,249 | pypa/pipenv | pipenv/vendor/requirementslib/models/url.py | remove_password_from_url | def remove_password_from_url(url):
# type: (S) -> S
"""
Given a url, remove the password and insert 4 dashes
:param url: The url to replace the authentication in
:type url: S
:return: The new URL without authentication
:rtype: S
"""
parsed = _get_parsed_url(url)
if parsed.auth:
auth, _, _ = parsed.auth.partition(":")
return parsed._replace(auth="{auth}:----".format(auth=auth)).url
return parsed.url | python | def remove_password_from_url(url):
# type: (S) -> S
"""
Given a url, remove the password and insert 4 dashes
:param url: The url to replace the authentication in
:type url: S
:return: The new URL without authentication
:rtype: S
"""
parsed = _get_parsed_url(url)
if parsed.auth:
auth, _, _ = parsed.auth.partition(":")
return parsed._replace(auth="{auth}:----".format(auth=auth)).url
return parsed.url | [
"def",
"remove_password_from_url",
"(",
"url",
")",
":",
"# type: (S) -> S",
"parsed",
"=",
"_get_parsed_url",
"(",
"url",
")",
"if",
"parsed",
".",
"auth",
":",
"auth",
",",
"_",
",",
"_",
"=",
"parsed",
".",
"auth",
".",
"partition",
"(",
"\":\"",
")",
"return",
"parsed",
".",
"_replace",
"(",
"auth",
"=",
"\"{auth}:----\"",
".",
"format",
"(",
"auth",
"=",
"auth",
")",
")",
".",
"url",
"return",
"parsed",
".",
"url"
] | Given a url, remove the password and insert 4 dashes
:param url: The url to replace the authentication in
:type url: S
:return: The new URL without authentication
:rtype: S | [
"Given",
"a",
"url",
"remove",
"the",
"password",
"and",
"insert",
"4",
"dashes"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/url.py#L47-L62 |
25,250 | pypa/pipenv | pipenv/vendor/click/_unicodefun.py | _verify_python3_env | def _verify_python3_env():
"""Ensures that the environment is good for unicode on Python 3."""
if PY2:
return
try:
import locale
fs_enc = codecs.lookup(locale.getpreferredencoding()).name
except Exception:
fs_enc = 'ascii'
if fs_enc != 'ascii':
return
extra = ''
if os.name == 'posix':
import subprocess
try:
rv = subprocess.Popen(['locale', '-a'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()[0]
except OSError:
rv = b''
good_locales = set()
has_c_utf8 = False
# Make sure we're operating on text here.
if isinstance(rv, bytes):
rv = rv.decode('ascii', 'replace')
for line in rv.splitlines():
locale = line.strip()
if locale.lower().endswith(('.utf-8', '.utf8')):
good_locales.add(locale)
if locale.lower() in ('c.utf8', 'c.utf-8'):
has_c_utf8 = True
extra += '\n\n'
if not good_locales:
extra += (
'Additional information: on this system no suitable UTF-8\n'
'locales were discovered. This most likely requires resolving\n'
'by reconfiguring the locale system.'
)
elif has_c_utf8:
extra += (
'This system supports the C.UTF-8 locale which is recommended.\n'
'You might be able to resolve your issue by exporting the\n'
'following environment variables:\n\n'
' export LC_ALL=C.UTF-8\n'
' export LANG=C.UTF-8'
)
else:
extra += (
'This system lists a couple of UTF-8 supporting locales that\n'
'you can pick from. The following suitable locales were\n'
'discovered: %s'
) % ', '.join(sorted(good_locales))
bad_locale = None
for locale in os.environ.get('LC_ALL'), os.environ.get('LANG'):
if locale and locale.lower().endswith(('.utf-8', '.utf8')):
bad_locale = locale
if locale is not None:
break
if bad_locale is not None:
extra += (
'\n\nClick discovered that you exported a UTF-8 locale\n'
'but the locale system could not pick up from it because\n'
'it does not exist. The exported locale is "%s" but it\n'
'is not supported'
) % bad_locale
raise RuntimeError(
'Click will abort further execution because Python 3 was'
' configured to use ASCII as encoding for the environment.'
' Consult https://click.palletsprojects.com/en/7.x/python3/ for'
' mitigation steps.' + extra
) | python | def _verify_python3_env():
"""Ensures that the environment is good for unicode on Python 3."""
if PY2:
return
try:
import locale
fs_enc = codecs.lookup(locale.getpreferredencoding()).name
except Exception:
fs_enc = 'ascii'
if fs_enc != 'ascii':
return
extra = ''
if os.name == 'posix':
import subprocess
try:
rv = subprocess.Popen(['locale', '-a'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()[0]
except OSError:
rv = b''
good_locales = set()
has_c_utf8 = False
# Make sure we're operating on text here.
if isinstance(rv, bytes):
rv = rv.decode('ascii', 'replace')
for line in rv.splitlines():
locale = line.strip()
if locale.lower().endswith(('.utf-8', '.utf8')):
good_locales.add(locale)
if locale.lower() in ('c.utf8', 'c.utf-8'):
has_c_utf8 = True
extra += '\n\n'
if not good_locales:
extra += (
'Additional information: on this system no suitable UTF-8\n'
'locales were discovered. This most likely requires resolving\n'
'by reconfiguring the locale system.'
)
elif has_c_utf8:
extra += (
'This system supports the C.UTF-8 locale which is recommended.\n'
'You might be able to resolve your issue by exporting the\n'
'following environment variables:\n\n'
' export LC_ALL=C.UTF-8\n'
' export LANG=C.UTF-8'
)
else:
extra += (
'This system lists a couple of UTF-8 supporting locales that\n'
'you can pick from. The following suitable locales were\n'
'discovered: %s'
) % ', '.join(sorted(good_locales))
bad_locale = None
for locale in os.environ.get('LC_ALL'), os.environ.get('LANG'):
if locale and locale.lower().endswith(('.utf-8', '.utf8')):
bad_locale = locale
if locale is not None:
break
if bad_locale is not None:
extra += (
'\n\nClick discovered that you exported a UTF-8 locale\n'
'but the locale system could not pick up from it because\n'
'it does not exist. The exported locale is "%s" but it\n'
'is not supported'
) % bad_locale
raise RuntimeError(
'Click will abort further execution because Python 3 was'
' configured to use ASCII as encoding for the environment.'
' Consult https://click.palletsprojects.com/en/7.x/python3/ for'
' mitigation steps.' + extra
) | [
"def",
"_verify_python3_env",
"(",
")",
":",
"if",
"PY2",
":",
"return",
"try",
":",
"import",
"locale",
"fs_enc",
"=",
"codecs",
".",
"lookup",
"(",
"locale",
".",
"getpreferredencoding",
"(",
")",
")",
".",
"name",
"except",
"Exception",
":",
"fs_enc",
"=",
"'ascii'",
"if",
"fs_enc",
"!=",
"'ascii'",
":",
"return",
"extra",
"=",
"''",
"if",
"os",
".",
"name",
"==",
"'posix'",
":",
"import",
"subprocess",
"try",
":",
"rv",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'locale'",
",",
"'-a'",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
"except",
"OSError",
":",
"rv",
"=",
"b''",
"good_locales",
"=",
"set",
"(",
")",
"has_c_utf8",
"=",
"False",
"# Make sure we're operating on text here.",
"if",
"isinstance",
"(",
"rv",
",",
"bytes",
")",
":",
"rv",
"=",
"rv",
".",
"decode",
"(",
"'ascii'",
",",
"'replace'",
")",
"for",
"line",
"in",
"rv",
".",
"splitlines",
"(",
")",
":",
"locale",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"locale",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"(",
"'.utf-8'",
",",
"'.utf8'",
")",
")",
":",
"good_locales",
".",
"add",
"(",
"locale",
")",
"if",
"locale",
".",
"lower",
"(",
")",
"in",
"(",
"'c.utf8'",
",",
"'c.utf-8'",
")",
":",
"has_c_utf8",
"=",
"True",
"extra",
"+=",
"'\\n\\n'",
"if",
"not",
"good_locales",
":",
"extra",
"+=",
"(",
"'Additional information: on this system no suitable UTF-8\\n'",
"'locales were discovered. This most likely requires resolving\\n'",
"'by reconfiguring the locale system.'",
")",
"elif",
"has_c_utf8",
":",
"extra",
"+=",
"(",
"'This system supports the C.UTF-8 locale which is recommended.\\n'",
"'You might be able to resolve your issue by exporting the\\n'",
"'following environment variables:\\n\\n'",
"' export LC_ALL=C.UTF-8\\n'",
"' export LANG=C.UTF-8'",
")",
"else",
":",
"extra",
"+=",
"(",
"'This system lists a couple of UTF-8 supporting locales that\\n'",
"'you can pick from. The following suitable locales were\\n'",
"'discovered: %s'",
")",
"%",
"', '",
".",
"join",
"(",
"sorted",
"(",
"good_locales",
")",
")",
"bad_locale",
"=",
"None",
"for",
"locale",
"in",
"os",
".",
"environ",
".",
"get",
"(",
"'LC_ALL'",
")",
",",
"os",
".",
"environ",
".",
"get",
"(",
"'LANG'",
")",
":",
"if",
"locale",
"and",
"locale",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"(",
"'.utf-8'",
",",
"'.utf8'",
")",
")",
":",
"bad_locale",
"=",
"locale",
"if",
"locale",
"is",
"not",
"None",
":",
"break",
"if",
"bad_locale",
"is",
"not",
"None",
":",
"extra",
"+=",
"(",
"'\\n\\nClick discovered that you exported a UTF-8 locale\\n'",
"'but the locale system could not pick up from it because\\n'",
"'it does not exist. The exported locale is \"%s\" but it\\n'",
"'is not supported'",
")",
"%",
"bad_locale",
"raise",
"RuntimeError",
"(",
"'Click will abort further execution because Python 3 was'",
"' configured to use ASCII as encoding for the environment.'",
"' Consult https://click.palletsprojects.com/en/7.x/python3/ for'",
"' mitigation steps.'",
"+",
"extra",
")"
] | Ensures that the environment is good for unicode on Python 3. | [
"Ensures",
"that",
"the",
"environment",
"is",
"good",
"for",
"unicode",
"on",
"Python",
"3",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/_unicodefun.py#L50-L125 |
25,251 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/misc.py | is_installable_dir | def is_installable_dir(path):
# type: (str) -> bool
"""Is path is a directory containing setup.py or pyproject.toml?
"""
if not os.path.isdir(path):
return False
setup_py = os.path.join(path, 'setup.py')
if os.path.isfile(setup_py):
return True
pyproject_toml = os.path.join(path, 'pyproject.toml')
if os.path.isfile(pyproject_toml):
return True
return False | python | def is_installable_dir(path):
# type: (str) -> bool
"""Is path is a directory containing setup.py or pyproject.toml?
"""
if not os.path.isdir(path):
return False
setup_py = os.path.join(path, 'setup.py')
if os.path.isfile(setup_py):
return True
pyproject_toml = os.path.join(path, 'pyproject.toml')
if os.path.isfile(pyproject_toml):
return True
return False | [
"def",
"is_installable_dir",
"(",
"path",
")",
":",
"# type: (str) -> bool",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"False",
"setup_py",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'setup.py'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"setup_py",
")",
":",
"return",
"True",
"pyproject_toml",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'pyproject.toml'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"pyproject_toml",
")",
":",
"return",
"True",
"return",
"False"
] | Is path is a directory containing setup.py or pyproject.toml? | [
"Is",
"path",
"is",
"a",
"directory",
"containing",
"setup",
".",
"py",
"or",
"pyproject",
".",
"toml?"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/misc.py#L204-L216 |
25,252 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/misc.py | is_svn_page | def is_svn_page(html):
# type: (Union[str, Text]) -> Optional[Match[Union[str, Text]]]
"""
Returns true if the page appears to be the index page of an svn repository
"""
return (re.search(r'<title>[^<]*Revision \d+:', html) and
re.search(r'Powered by (?:<a[^>]*?>)?Subversion', html, re.I)) | python | def is_svn_page(html):
# type: (Union[str, Text]) -> Optional[Match[Union[str, Text]]]
"""
Returns true if the page appears to be the index page of an svn repository
"""
return (re.search(r'<title>[^<]*Revision \d+:', html) and
re.search(r'Powered by (?:<a[^>]*?>)?Subversion', html, re.I)) | [
"def",
"is_svn_page",
"(",
"html",
")",
":",
"# type: (Union[str, Text]) -> Optional[Match[Union[str, Text]]]",
"return",
"(",
"re",
".",
"search",
"(",
"r'<title>[^<]*Revision \\d+:'",
",",
"html",
")",
"and",
"re",
".",
"search",
"(",
"r'Powered by (?:<a[^>]*?>)?Subversion'",
",",
"html",
",",
"re",
".",
"I",
")",
")"
] | Returns true if the page appears to be the index page of an svn repository | [
"Returns",
"true",
"if",
"the",
"page",
"appears",
"to",
"be",
"the",
"index",
"page",
"of",
"an",
"svn",
"repository"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/misc.py#L219-L225 |
25,253 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/misc.py | read_chunks | def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE):
"""Yield pieces of data from a file-like object until EOF."""
while True:
chunk = file.read(size)
if not chunk:
break
yield chunk | python | def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE):
"""Yield pieces of data from a file-like object until EOF."""
while True:
chunk = file.read(size)
if not chunk:
break
yield chunk | [
"def",
"read_chunks",
"(",
"file",
",",
"size",
"=",
"io",
".",
"DEFAULT_BUFFER_SIZE",
")",
":",
"while",
"True",
":",
"chunk",
"=",
"file",
".",
"read",
"(",
"size",
")",
"if",
"not",
"chunk",
":",
"break",
"yield",
"chunk"
] | Yield pieces of data from a file-like object until EOF. | [
"Yield",
"pieces",
"of",
"data",
"from",
"a",
"file",
"-",
"like",
"object",
"until",
"EOF",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/misc.py#L234-L240 |
25,254 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/misc.py | normalize_path | def normalize_path(path, resolve_symlinks=True):
# type: (str, bool) -> str
"""
Convert a path to its canonical, case-normalized, absolute version.
"""
path = expanduser(path)
if resolve_symlinks:
path = os.path.realpath(path)
else:
path = os.path.abspath(path)
return os.path.normcase(path) | python | def normalize_path(path, resolve_symlinks=True):
# type: (str, bool) -> str
"""
Convert a path to its canonical, case-normalized, absolute version.
"""
path = expanduser(path)
if resolve_symlinks:
path = os.path.realpath(path)
else:
path = os.path.abspath(path)
return os.path.normcase(path) | [
"def",
"normalize_path",
"(",
"path",
",",
"resolve_symlinks",
"=",
"True",
")",
":",
"# type: (str, bool) -> str",
"path",
"=",
"expanduser",
"(",
"path",
")",
"if",
"resolve_symlinks",
":",
"path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"path",
")",
"else",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"return",
"os",
".",
"path",
".",
"normcase",
"(",
"path",
")"
] | Convert a path to its canonical, case-normalized, absolute version. | [
"Convert",
"a",
"path",
"to",
"its",
"canonical",
"case",
"-",
"normalized",
"absolute",
"version",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/misc.py#L271-L282 |
25,255 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/misc.py | splitext | def splitext(path):
# type: (str) -> Tuple[str, str]
"""Like os.path.splitext, but take off .tar too"""
base, ext = posixpath.splitext(path)
if base.lower().endswith('.tar'):
ext = base[-4:] + ext
base = base[:-4]
return base, ext | python | def splitext(path):
# type: (str) -> Tuple[str, str]
"""Like os.path.splitext, but take off .tar too"""
base, ext = posixpath.splitext(path)
if base.lower().endswith('.tar'):
ext = base[-4:] + ext
base = base[:-4]
return base, ext | [
"def",
"splitext",
"(",
"path",
")",
":",
"# type: (str) -> Tuple[str, str]",
"base",
",",
"ext",
"=",
"posixpath",
".",
"splitext",
"(",
"path",
")",
"if",
"base",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.tar'",
")",
":",
"ext",
"=",
"base",
"[",
"-",
"4",
":",
"]",
"+",
"ext",
"base",
"=",
"base",
"[",
":",
"-",
"4",
"]",
"return",
"base",
",",
"ext"
] | Like os.path.splitext, but take off .tar too | [
"Like",
"os",
".",
"path",
".",
"splitext",
"but",
"take",
"off",
".",
"tar",
"too"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/misc.py#L285-L292 |
25,256 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/misc.py | is_local | def is_local(path):
# type: (str) -> bool
"""
Return True if path is within sys.prefix, if we're running in a virtualenv.
If we're not in a virtualenv, all paths are considered "local."
"""
if not running_under_virtualenv():
return True
return normalize_path(path).startswith(normalize_path(sys.prefix)) | python | def is_local(path):
# type: (str) -> bool
"""
Return True if path is within sys.prefix, if we're running in a virtualenv.
If we're not in a virtualenv, all paths are considered "local."
"""
if not running_under_virtualenv():
return True
return normalize_path(path).startswith(normalize_path(sys.prefix)) | [
"def",
"is_local",
"(",
"path",
")",
":",
"# type: (str) -> bool",
"if",
"not",
"running_under_virtualenv",
"(",
")",
":",
"return",
"True",
"return",
"normalize_path",
"(",
"path",
")",
".",
"startswith",
"(",
"normalize_path",
"(",
"sys",
".",
"prefix",
")",
")"
] | Return True if path is within sys.prefix, if we're running in a virtualenv.
If we're not in a virtualenv, all paths are considered "local." | [
"Return",
"True",
"if",
"path",
"is",
"within",
"sys",
".",
"prefix",
"if",
"we",
"re",
"running",
"in",
"a",
"virtualenv",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/misc.py#L313-L323 |
25,257 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/misc.py | dist_is_editable | def dist_is_editable(dist):
# type: (Distribution) -> bool
"""
Return True if given Distribution is an editable install.
"""
for path_item in sys.path:
egg_link = os.path.join(path_item, dist.project_name + '.egg-link')
if os.path.isfile(egg_link):
return True
return False | python | def dist_is_editable(dist):
# type: (Distribution) -> bool
"""
Return True if given Distribution is an editable install.
"""
for path_item in sys.path:
egg_link = os.path.join(path_item, dist.project_name + '.egg-link')
if os.path.isfile(egg_link):
return True
return False | [
"def",
"dist_is_editable",
"(",
"dist",
")",
":",
"# type: (Distribution) -> bool",
"for",
"path_item",
"in",
"sys",
".",
"path",
":",
"egg_link",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_item",
",",
"dist",
".",
"project_name",
"+",
"'.egg-link'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"egg_link",
")",
":",
"return",
"True",
"return",
"False"
] | Return True if given Distribution is an editable install. | [
"Return",
"True",
"if",
"given",
"Distribution",
"is",
"an",
"editable",
"install",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/misc.py#L358-L367 |
25,258 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/misc.py | egg_link_path | def egg_link_path(dist):
# type: (Distribution) -> Optional[str]
"""
Return the path for the .egg-link file if it exists, otherwise, None.
There's 3 scenarios:
1) not in a virtualenv
try to find in site.USER_SITE, then site_packages
2) in a no-global virtualenv
try to find in site_packages
3) in a yes-global virtualenv
try to find in site_packages, then site.USER_SITE
(don't look in global location)
For #1 and #3, there could be odd cases, where there's an egg-link in 2
locations.
This method will just return the first one found.
"""
sites = []
if running_under_virtualenv():
if virtualenv_no_global():
sites.append(site_packages)
else:
sites.append(site_packages)
if user_site:
sites.append(user_site)
else:
if user_site:
sites.append(user_site)
sites.append(site_packages)
for site in sites:
egglink = os.path.join(site, dist.project_name) + '.egg-link'
if os.path.isfile(egglink):
return egglink
return None | python | def egg_link_path(dist):
# type: (Distribution) -> Optional[str]
"""
Return the path for the .egg-link file if it exists, otherwise, None.
There's 3 scenarios:
1) not in a virtualenv
try to find in site.USER_SITE, then site_packages
2) in a no-global virtualenv
try to find in site_packages
3) in a yes-global virtualenv
try to find in site_packages, then site.USER_SITE
(don't look in global location)
For #1 and #3, there could be odd cases, where there's an egg-link in 2
locations.
This method will just return the first one found.
"""
sites = []
if running_under_virtualenv():
if virtualenv_no_global():
sites.append(site_packages)
else:
sites.append(site_packages)
if user_site:
sites.append(user_site)
else:
if user_site:
sites.append(user_site)
sites.append(site_packages)
for site in sites:
egglink = os.path.join(site, dist.project_name) + '.egg-link'
if os.path.isfile(egglink):
return egglink
return None | [
"def",
"egg_link_path",
"(",
"dist",
")",
":",
"# type: (Distribution) -> Optional[str]",
"sites",
"=",
"[",
"]",
"if",
"running_under_virtualenv",
"(",
")",
":",
"if",
"virtualenv_no_global",
"(",
")",
":",
"sites",
".",
"append",
"(",
"site_packages",
")",
"else",
":",
"sites",
".",
"append",
"(",
"site_packages",
")",
"if",
"user_site",
":",
"sites",
".",
"append",
"(",
"user_site",
")",
"else",
":",
"if",
"user_site",
":",
"sites",
".",
"append",
"(",
"user_site",
")",
"sites",
".",
"append",
"(",
"site_packages",
")",
"for",
"site",
"in",
"sites",
":",
"egglink",
"=",
"os",
".",
"path",
".",
"join",
"(",
"site",
",",
"dist",
".",
"project_name",
")",
"+",
"'.egg-link'",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"egglink",
")",
":",
"return",
"egglink",
"return",
"None"
] | Return the path for the .egg-link file if it exists, otherwise, None.
There's 3 scenarios:
1) not in a virtualenv
try to find in site.USER_SITE, then site_packages
2) in a no-global virtualenv
try to find in site_packages
3) in a yes-global virtualenv
try to find in site_packages, then site.USER_SITE
(don't look in global location)
For #1 and #3, there could be odd cases, where there's an egg-link in 2
locations.
This method will just return the first one found. | [
"Return",
"the",
"path",
"for",
"the",
".",
"egg",
"-",
"link",
"file",
"if",
"it",
"exists",
"otherwise",
"None",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/misc.py#L429-L465 |
25,259 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/misc.py | get_installed_version | def get_installed_version(dist_name, working_set=None):
"""Get the installed version of dist_name avoiding pkg_resources cache"""
# Create a requirement that we'll look for inside of setuptools.
req = pkg_resources.Requirement.parse(dist_name)
if working_set is None:
# We want to avoid having this cached, so we need to construct a new
# working set each time.
working_set = pkg_resources.WorkingSet()
# Get the installed distribution from our working set
dist = working_set.find(req)
# Check to see if we got an installed distribution or not, if we did
# we want to return it's version.
return dist.version if dist else None | python | def get_installed_version(dist_name, working_set=None):
"""Get the installed version of dist_name avoiding pkg_resources cache"""
# Create a requirement that we'll look for inside of setuptools.
req = pkg_resources.Requirement.parse(dist_name)
if working_set is None:
# We want to avoid having this cached, so we need to construct a new
# working set each time.
working_set = pkg_resources.WorkingSet()
# Get the installed distribution from our working set
dist = working_set.find(req)
# Check to see if we got an installed distribution or not, if we did
# we want to return it's version.
return dist.version if dist else None | [
"def",
"get_installed_version",
"(",
"dist_name",
",",
"working_set",
"=",
"None",
")",
":",
"# Create a requirement that we'll look for inside of setuptools.",
"req",
"=",
"pkg_resources",
".",
"Requirement",
".",
"parse",
"(",
"dist_name",
")",
"if",
"working_set",
"is",
"None",
":",
"# We want to avoid having this cached, so we need to construct a new",
"# working set each time.",
"working_set",
"=",
"pkg_resources",
".",
"WorkingSet",
"(",
")",
"# Get the installed distribution from our working set",
"dist",
"=",
"working_set",
".",
"find",
"(",
"req",
")",
"# Check to see if we got an installed distribution or not, if we did",
"# we want to return it's version.",
"return",
"dist",
".",
"version",
"if",
"dist",
"else",
"None"
] | Get the installed version of dist_name avoiding pkg_resources cache | [
"Get",
"the",
"installed",
"version",
"of",
"dist_name",
"avoiding",
"pkg_resources",
"cache"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/misc.py#L894-L909 |
25,260 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/misc.py | make_vcs_requirement_url | def make_vcs_requirement_url(repo_url, rev, project_name, subdir=None):
"""
Return the URL for a VCS requirement.
Args:
repo_url: the remote VCS url, with any needed VCS prefix (e.g. "git+").
project_name: the (unescaped) project name.
"""
egg_project_name = pkg_resources.to_filename(project_name)
req = '{}@{}#egg={}'.format(repo_url, rev, egg_project_name)
if subdir:
req += '&subdirectory={}'.format(subdir)
return req | python | def make_vcs_requirement_url(repo_url, rev, project_name, subdir=None):
"""
Return the URL for a VCS requirement.
Args:
repo_url: the remote VCS url, with any needed VCS prefix (e.g. "git+").
project_name: the (unescaped) project name.
"""
egg_project_name = pkg_resources.to_filename(project_name)
req = '{}@{}#egg={}'.format(repo_url, rev, egg_project_name)
if subdir:
req += '&subdirectory={}'.format(subdir)
return req | [
"def",
"make_vcs_requirement_url",
"(",
"repo_url",
",",
"rev",
",",
"project_name",
",",
"subdir",
"=",
"None",
")",
":",
"egg_project_name",
"=",
"pkg_resources",
".",
"to_filename",
"(",
"project_name",
")",
"req",
"=",
"'{}@{}#egg={}'",
".",
"format",
"(",
"repo_url",
",",
"rev",
",",
"egg_project_name",
")",
"if",
"subdir",
":",
"req",
"+=",
"'&subdirectory={}'",
".",
"format",
"(",
"subdir",
")",
"return",
"req"
] | Return the URL for a VCS requirement.
Args:
repo_url: the remote VCS url, with any needed VCS prefix (e.g. "git+").
project_name: the (unescaped) project name. | [
"Return",
"the",
"URL",
"for",
"a",
"VCS",
"requirement",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/misc.py#L925-L938 |
25,261 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/misc.py | split_auth_from_netloc | def split_auth_from_netloc(netloc):
"""
Parse out and remove the auth information from a netloc.
Returns: (netloc, (username, password)).
"""
if '@' not in netloc:
return netloc, (None, None)
# Split from the right because that's how urllib.parse.urlsplit()
# behaves if more than one @ is present (which can be checked using
# the password attribute of urlsplit()'s return value).
auth, netloc = netloc.rsplit('@', 1)
if ':' in auth:
# Split from the left because that's how urllib.parse.urlsplit()
# behaves if more than one : is present (which again can be checked
# using the password attribute of the return value)
user_pass = auth.split(':', 1)
else:
user_pass = auth, None
user_pass = tuple(
None if x is None else urllib_unquote(x) for x in user_pass
)
return netloc, user_pass | python | def split_auth_from_netloc(netloc):
"""
Parse out and remove the auth information from a netloc.
Returns: (netloc, (username, password)).
"""
if '@' not in netloc:
return netloc, (None, None)
# Split from the right because that's how urllib.parse.urlsplit()
# behaves if more than one @ is present (which can be checked using
# the password attribute of urlsplit()'s return value).
auth, netloc = netloc.rsplit('@', 1)
if ':' in auth:
# Split from the left because that's how urllib.parse.urlsplit()
# behaves if more than one : is present (which again can be checked
# using the password attribute of the return value)
user_pass = auth.split(':', 1)
else:
user_pass = auth, None
user_pass = tuple(
None if x is None else urllib_unquote(x) for x in user_pass
)
return netloc, user_pass | [
"def",
"split_auth_from_netloc",
"(",
"netloc",
")",
":",
"if",
"'@'",
"not",
"in",
"netloc",
":",
"return",
"netloc",
",",
"(",
"None",
",",
"None",
")",
"# Split from the right because that's how urllib.parse.urlsplit()",
"# behaves if more than one @ is present (which can be checked using",
"# the password attribute of urlsplit()'s return value).",
"auth",
",",
"netloc",
"=",
"netloc",
".",
"rsplit",
"(",
"'@'",
",",
"1",
")",
"if",
"':'",
"in",
"auth",
":",
"# Split from the left because that's how urllib.parse.urlsplit()",
"# behaves if more than one : is present (which again can be checked",
"# using the password attribute of the return value)",
"user_pass",
"=",
"auth",
".",
"split",
"(",
"':'",
",",
"1",
")",
"else",
":",
"user_pass",
"=",
"auth",
",",
"None",
"user_pass",
"=",
"tuple",
"(",
"None",
"if",
"x",
"is",
"None",
"else",
"urllib_unquote",
"(",
"x",
")",
"for",
"x",
"in",
"user_pass",
")",
"return",
"netloc",
",",
"user_pass"
] | Parse out and remove the auth information from a netloc.
Returns: (netloc, (username, password)). | [
"Parse",
"out",
"and",
"remove",
"the",
"auth",
"information",
"from",
"a",
"netloc",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/misc.py#L941-L966 |
25,262 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/misc.py | protect_pip_from_modification_on_windows | def protect_pip_from_modification_on_windows(modifying_pip):
"""Protection of pip.exe from modification on Windows
On Windows, any operation modifying pip should be run as:
python -m pip ...
"""
pip_names = [
"pip.exe",
"pip{}.exe".format(sys.version_info[0]),
"pip{}.{}.exe".format(*sys.version_info[:2])
]
# See https://github.com/pypa/pip/issues/1299 for more discussion
should_show_use_python_msg = (
modifying_pip and
WINDOWS and
os.path.basename(sys.argv[0]) in pip_names
)
if should_show_use_python_msg:
new_command = [
sys.executable, "-m", "pip"
] + sys.argv[1:]
raise CommandError(
'To modify pip, please run the following command:\n{}'
.format(" ".join(new_command))
) | python | def protect_pip_from_modification_on_windows(modifying_pip):
"""Protection of pip.exe from modification on Windows
On Windows, any operation modifying pip should be run as:
python -m pip ...
"""
pip_names = [
"pip.exe",
"pip{}.exe".format(sys.version_info[0]),
"pip{}.{}.exe".format(*sys.version_info[:2])
]
# See https://github.com/pypa/pip/issues/1299 for more discussion
should_show_use_python_msg = (
modifying_pip and
WINDOWS and
os.path.basename(sys.argv[0]) in pip_names
)
if should_show_use_python_msg:
new_command = [
sys.executable, "-m", "pip"
] + sys.argv[1:]
raise CommandError(
'To modify pip, please run the following command:\n{}'
.format(" ".join(new_command))
) | [
"def",
"protect_pip_from_modification_on_windows",
"(",
"modifying_pip",
")",
":",
"pip_names",
"=",
"[",
"\"pip.exe\"",
",",
"\"pip{}.exe\"",
".",
"format",
"(",
"sys",
".",
"version_info",
"[",
"0",
"]",
")",
",",
"\"pip{}.{}.exe\"",
".",
"format",
"(",
"*",
"sys",
".",
"version_info",
"[",
":",
"2",
"]",
")",
"]",
"# See https://github.com/pypa/pip/issues/1299 for more discussion",
"should_show_use_python_msg",
"=",
"(",
"modifying_pip",
"and",
"WINDOWS",
"and",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"in",
"pip_names",
")",
"if",
"should_show_use_python_msg",
":",
"new_command",
"=",
"[",
"sys",
".",
"executable",
",",
"\"-m\"",
",",
"\"pip\"",
"]",
"+",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"raise",
"CommandError",
"(",
"'To modify pip, please run the following command:\\n{}'",
".",
"format",
"(",
"\" \"",
".",
"join",
"(",
"new_command",
")",
")",
")"
] | Protection of pip.exe from modification on Windows
On Windows, any operation modifying pip should be run as:
python -m pip ... | [
"Protection",
"of",
"pip",
".",
"exe",
"from",
"modification",
"on",
"Windows"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/misc.py#L1014-L1040 |
25,263 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/packaging.py | check_requires_python | def check_requires_python(requires_python):
# type: (Optional[str]) -> bool
"""
Check if the python version in use match the `requires_python` specifier.
Returns `True` if the version of python in use matches the requirement.
Returns `False` if the version of python in use does not matches the
requirement.
Raises an InvalidSpecifier if `requires_python` have an invalid format.
"""
if requires_python is None:
# The package provides no information
return True
requires_python_specifier = specifiers.SpecifierSet(requires_python)
# We only use major.minor.micro
python_version = version.parse('{0}.{1}.{2}'.format(*sys.version_info[:3]))
return python_version in requires_python_specifier | python | def check_requires_python(requires_python):
# type: (Optional[str]) -> bool
"""
Check if the python version in use match the `requires_python` specifier.
Returns `True` if the version of python in use matches the requirement.
Returns `False` if the version of python in use does not matches the
requirement.
Raises an InvalidSpecifier if `requires_python` have an invalid format.
"""
if requires_python is None:
# The package provides no information
return True
requires_python_specifier = specifiers.SpecifierSet(requires_python)
# We only use major.minor.micro
python_version = version.parse('{0}.{1}.{2}'.format(*sys.version_info[:3]))
return python_version in requires_python_specifier | [
"def",
"check_requires_python",
"(",
"requires_python",
")",
":",
"# type: (Optional[str]) -> bool",
"if",
"requires_python",
"is",
"None",
":",
"# The package provides no information",
"return",
"True",
"requires_python_specifier",
"=",
"specifiers",
".",
"SpecifierSet",
"(",
"requires_python",
")",
"# We only use major.minor.micro",
"python_version",
"=",
"version",
".",
"parse",
"(",
"'{0}.{1}.{2}'",
".",
"format",
"(",
"*",
"sys",
".",
"version_info",
"[",
":",
"3",
"]",
")",
")",
"return",
"python_version",
"in",
"requires_python_specifier"
] | Check if the python version in use match the `requires_python` specifier.
Returns `True` if the version of python in use matches the requirement.
Returns `False` if the version of python in use does not matches the
requirement.
Raises an InvalidSpecifier if `requires_python` have an invalid format. | [
"Check",
"if",
"the",
"python",
"version",
"in",
"use",
"match",
"the",
"requires_python",
"specifier",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/packaging.py#L23-L41 |
25,264 | pypa/pipenv | pipenv/vendor/click_completion/__init__.py | init | def init(complete_options=False, match_incomplete=None):
"""Initialize the enhanced click completion
Parameters
----------
complete_options : bool
always complete the options, even when the user hasn't typed a first dash (Default value = False)
match_incomplete : func
a function with two parameters choice and incomplete. Must return True
if incomplete is a correct match for choice, False otherwise.
"""
global _initialized
if not _initialized:
_patch()
completion_configuration.complete_options = complete_options
if match_incomplete is not None:
completion_configuration.match_incomplete = match_incomplete
_initialized = True | python | def init(complete_options=False, match_incomplete=None):
"""Initialize the enhanced click completion
Parameters
----------
complete_options : bool
always complete the options, even when the user hasn't typed a first dash (Default value = False)
match_incomplete : func
a function with two parameters choice and incomplete. Must return True
if incomplete is a correct match for choice, False otherwise.
"""
global _initialized
if not _initialized:
_patch()
completion_configuration.complete_options = complete_options
if match_incomplete is not None:
completion_configuration.match_incomplete = match_incomplete
_initialized = True | [
"def",
"init",
"(",
"complete_options",
"=",
"False",
",",
"match_incomplete",
"=",
"None",
")",
":",
"global",
"_initialized",
"if",
"not",
"_initialized",
":",
"_patch",
"(",
")",
"completion_configuration",
".",
"complete_options",
"=",
"complete_options",
"if",
"match_incomplete",
"is",
"not",
"None",
":",
"completion_configuration",
".",
"match_incomplete",
"=",
"match_incomplete",
"_initialized",
"=",
"True"
] | Initialize the enhanced click completion
Parameters
----------
complete_options : bool
always complete the options, even when the user hasn't typed a first dash (Default value = False)
match_incomplete : func
a function with two parameters choice and incomplete. Must return True
if incomplete is a correct match for choice, False otherwise. | [
"Initialize",
"the",
"enhanced",
"click",
"completion"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click_completion/__init__.py#L27-L44 |
25,265 | pypa/pipenv | pipenv/patched/notpip/_internal/commands/search.py | transform_hits | def transform_hits(hits):
"""
The list from pypi is really a list of versions. We want a list of
packages with the list of versions stored inline. This converts the
list from pypi into one we can use.
"""
packages = OrderedDict()
for hit in hits:
name = hit['name']
summary = hit['summary']
version = hit['version']
if name not in packages.keys():
packages[name] = {
'name': name,
'summary': summary,
'versions': [version],
}
else:
packages[name]['versions'].append(version)
# if this is the highest version, replace summary and score
if version == highest_version(packages[name]['versions']):
packages[name]['summary'] = summary
return list(packages.values()) | python | def transform_hits(hits):
"""
The list from pypi is really a list of versions. We want a list of
packages with the list of versions stored inline. This converts the
list from pypi into one we can use.
"""
packages = OrderedDict()
for hit in hits:
name = hit['name']
summary = hit['summary']
version = hit['version']
if name not in packages.keys():
packages[name] = {
'name': name,
'summary': summary,
'versions': [version],
}
else:
packages[name]['versions'].append(version)
# if this is the highest version, replace summary and score
if version == highest_version(packages[name]['versions']):
packages[name]['summary'] = summary
return list(packages.values()) | [
"def",
"transform_hits",
"(",
"hits",
")",
":",
"packages",
"=",
"OrderedDict",
"(",
")",
"for",
"hit",
"in",
"hits",
":",
"name",
"=",
"hit",
"[",
"'name'",
"]",
"summary",
"=",
"hit",
"[",
"'summary'",
"]",
"version",
"=",
"hit",
"[",
"'version'",
"]",
"if",
"name",
"not",
"in",
"packages",
".",
"keys",
"(",
")",
":",
"packages",
"[",
"name",
"]",
"=",
"{",
"'name'",
":",
"name",
",",
"'summary'",
":",
"summary",
",",
"'versions'",
":",
"[",
"version",
"]",
",",
"}",
"else",
":",
"packages",
"[",
"name",
"]",
"[",
"'versions'",
"]",
".",
"append",
"(",
"version",
")",
"# if this is the highest version, replace summary and score",
"if",
"version",
"==",
"highest_version",
"(",
"packages",
"[",
"name",
"]",
"[",
"'versions'",
"]",
")",
":",
"packages",
"[",
"name",
"]",
"[",
"'summary'",
"]",
"=",
"summary",
"return",
"list",
"(",
"packages",
".",
"values",
"(",
")",
")"
] | The list from pypi is really a list of versions. We want a list of
packages with the list of versions stored inline. This converts the
list from pypi into one we can use. | [
"The",
"list",
"from",
"pypi",
"is",
"really",
"a",
"list",
"of",
"versions",
".",
"We",
"want",
"a",
"list",
"of",
"packages",
"with",
"the",
"list",
"of",
"versions",
"stored",
"inline",
".",
"This",
"converts",
"the",
"list",
"from",
"pypi",
"into",
"one",
"we",
"can",
"use",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/commands/search.py#L69-L94 |
25,266 | pypa/pipenv | pipenv/patched/notpip/_internal/req/req_set.py | RequirementSet.add_requirement | def add_requirement(
self,
install_req, # type: InstallRequirement
parent_req_name=None, # type: Optional[str]
extras_requested=None # type: Optional[Iterable[str]]
):
# type: (...) -> Tuple[List[InstallRequirement], Optional[InstallRequirement]] # noqa: E501
"""Add install_req as a requirement to install.
:param parent_req_name: The name of the requirement that needed this
added. The name is used because when multiple unnamed requirements
resolve to the same name, we could otherwise end up with dependency
links that point outside the Requirements set. parent_req must
already be added. Note that None implies that this is a user
supplied requirement, vs an inferred one.
:param extras_requested: an iterable of extras used to evaluate the
environment markers.
:return: Additional requirements to scan. That is either [] if
the requirement is not applicable, or [install_req] if the
requirement is applicable and has just been added.
"""
name = install_req.name
# If the markers do not match, ignore this requirement.
if not install_req.match_markers(extras_requested):
logger.info(
"Ignoring %s: markers '%s' don't match your environment",
name, install_req.markers,
)
return [], None
# If the wheel is not supported, raise an error.
# Should check this after filtering out based on environment markers to
# allow specifying different wheels based on the environment/OS, in a
# single requirements file.
if install_req.link and install_req.link.is_wheel:
wheel = Wheel(install_req.link.filename)
if self.check_supported_wheels and not wheel.supported():
raise InstallationError(
"%s is not a supported wheel on this platform." %
wheel.filename
)
# This next bit is really a sanity check.
assert install_req.is_direct == (parent_req_name is None), (
"a direct req shouldn't have a parent and also, "
"a non direct req should have a parent"
)
# Unnamed requirements are scanned again and the requirement won't be
# added as a dependency until after scanning.
if not name:
# url or path requirement w/o an egg fragment
self.unnamed_requirements.append(install_req)
return [install_req], None
try:
existing_req = self.get_requirement(name)
except KeyError:
existing_req = None
has_conflicting_requirement = (
parent_req_name is None and
existing_req and
not existing_req.constraint and
existing_req.extras == install_req.extras and
existing_req.req.specifier != install_req.req.specifier
)
if has_conflicting_requirement:
raise InstallationError(
"Double requirement given: %s (already in %s, name=%r)"
% (install_req, existing_req, name)
)
# When no existing requirement exists, add the requirement as a
# dependency and it will be scanned again after.
if not existing_req:
self.requirements[name] = install_req
# FIXME: what about other normalizations? E.g., _ vs. -?
if name.lower() != name:
self.requirement_aliases[name.lower()] = name
# We'd want to rescan this requirements later
return [install_req], install_req
# Assume there's no need to scan, and that we've already
# encountered this for scanning.
if install_req.constraint or not existing_req.constraint:
return [], existing_req
does_not_satisfy_constraint = (
install_req.link and
not (
existing_req.link and
install_req.link.path == existing_req.link.path
)
)
if does_not_satisfy_constraint:
self.reqs_to_cleanup.append(install_req)
raise InstallationError(
"Could not satisfy constraints for '%s': "
"installation from path or url cannot be "
"constrained to a version" % name,
)
# If we're now installing a constraint, mark the existing
# object for real installation.
existing_req.constraint = False
existing_req.extras = tuple(sorted(
set(existing_req.extras) | set(install_req.extras)
))
logger.debug(
"Setting %s extras to: %s",
existing_req, existing_req.extras,
)
# Return the existing requirement for addition to the parent and
# scanning again.
return [existing_req], existing_req | python | def add_requirement(
self,
install_req, # type: InstallRequirement
parent_req_name=None, # type: Optional[str]
extras_requested=None # type: Optional[Iterable[str]]
):
# type: (...) -> Tuple[List[InstallRequirement], Optional[InstallRequirement]] # noqa: E501
"""Add install_req as a requirement to install.
:param parent_req_name: The name of the requirement that needed this
added. The name is used because when multiple unnamed requirements
resolve to the same name, we could otherwise end up with dependency
links that point outside the Requirements set. parent_req must
already be added. Note that None implies that this is a user
supplied requirement, vs an inferred one.
:param extras_requested: an iterable of extras used to evaluate the
environment markers.
:return: Additional requirements to scan. That is either [] if
the requirement is not applicable, or [install_req] if the
requirement is applicable and has just been added.
"""
name = install_req.name
# If the markers do not match, ignore this requirement.
if not install_req.match_markers(extras_requested):
logger.info(
"Ignoring %s: markers '%s' don't match your environment",
name, install_req.markers,
)
return [], None
# If the wheel is not supported, raise an error.
# Should check this after filtering out based on environment markers to
# allow specifying different wheels based on the environment/OS, in a
# single requirements file.
if install_req.link and install_req.link.is_wheel:
wheel = Wheel(install_req.link.filename)
if self.check_supported_wheels and not wheel.supported():
raise InstallationError(
"%s is not a supported wheel on this platform." %
wheel.filename
)
# This next bit is really a sanity check.
assert install_req.is_direct == (parent_req_name is None), (
"a direct req shouldn't have a parent and also, "
"a non direct req should have a parent"
)
# Unnamed requirements are scanned again and the requirement won't be
# added as a dependency until after scanning.
if not name:
# url or path requirement w/o an egg fragment
self.unnamed_requirements.append(install_req)
return [install_req], None
try:
existing_req = self.get_requirement(name)
except KeyError:
existing_req = None
has_conflicting_requirement = (
parent_req_name is None and
existing_req and
not existing_req.constraint and
existing_req.extras == install_req.extras and
existing_req.req.specifier != install_req.req.specifier
)
if has_conflicting_requirement:
raise InstallationError(
"Double requirement given: %s (already in %s, name=%r)"
% (install_req, existing_req, name)
)
# When no existing requirement exists, add the requirement as a
# dependency and it will be scanned again after.
if not existing_req:
self.requirements[name] = install_req
# FIXME: what about other normalizations? E.g., _ vs. -?
if name.lower() != name:
self.requirement_aliases[name.lower()] = name
# We'd want to rescan this requirements later
return [install_req], install_req
# Assume there's no need to scan, and that we've already
# encountered this for scanning.
if install_req.constraint or not existing_req.constraint:
return [], existing_req
does_not_satisfy_constraint = (
install_req.link and
not (
existing_req.link and
install_req.link.path == existing_req.link.path
)
)
if does_not_satisfy_constraint:
self.reqs_to_cleanup.append(install_req)
raise InstallationError(
"Could not satisfy constraints for '%s': "
"installation from path or url cannot be "
"constrained to a version" % name,
)
# If we're now installing a constraint, mark the existing
# object for real installation.
existing_req.constraint = False
existing_req.extras = tuple(sorted(
set(existing_req.extras) | set(install_req.extras)
))
logger.debug(
"Setting %s extras to: %s",
existing_req, existing_req.extras,
)
# Return the existing requirement for addition to the parent and
# scanning again.
return [existing_req], existing_req | [
"def",
"add_requirement",
"(",
"self",
",",
"install_req",
",",
"# type: InstallRequirement",
"parent_req_name",
"=",
"None",
",",
"# type: Optional[str]",
"extras_requested",
"=",
"None",
"# type: Optional[Iterable[str]]",
")",
":",
"# type: (...) -> Tuple[List[InstallRequirement], Optional[InstallRequirement]] # noqa: E501",
"name",
"=",
"install_req",
".",
"name",
"# If the markers do not match, ignore this requirement.",
"if",
"not",
"install_req",
".",
"match_markers",
"(",
"extras_requested",
")",
":",
"logger",
".",
"info",
"(",
"\"Ignoring %s: markers '%s' don't match your environment\"",
",",
"name",
",",
"install_req",
".",
"markers",
",",
")",
"return",
"[",
"]",
",",
"None",
"# If the wheel is not supported, raise an error.",
"# Should check this after filtering out based on environment markers to",
"# allow specifying different wheels based on the environment/OS, in a",
"# single requirements file.",
"if",
"install_req",
".",
"link",
"and",
"install_req",
".",
"link",
".",
"is_wheel",
":",
"wheel",
"=",
"Wheel",
"(",
"install_req",
".",
"link",
".",
"filename",
")",
"if",
"self",
".",
"check_supported_wheels",
"and",
"not",
"wheel",
".",
"supported",
"(",
")",
":",
"raise",
"InstallationError",
"(",
"\"%s is not a supported wheel on this platform.\"",
"%",
"wheel",
".",
"filename",
")",
"# This next bit is really a sanity check.",
"assert",
"install_req",
".",
"is_direct",
"==",
"(",
"parent_req_name",
"is",
"None",
")",
",",
"(",
"\"a direct req shouldn't have a parent and also, \"",
"\"a non direct req should have a parent\"",
")",
"# Unnamed requirements are scanned again and the requirement won't be",
"# added as a dependency until after scanning.",
"if",
"not",
"name",
":",
"# url or path requirement w/o an egg fragment",
"self",
".",
"unnamed_requirements",
".",
"append",
"(",
"install_req",
")",
"return",
"[",
"install_req",
"]",
",",
"None",
"try",
":",
"existing_req",
"=",
"self",
".",
"get_requirement",
"(",
"name",
")",
"except",
"KeyError",
":",
"existing_req",
"=",
"None",
"has_conflicting_requirement",
"=",
"(",
"parent_req_name",
"is",
"None",
"and",
"existing_req",
"and",
"not",
"existing_req",
".",
"constraint",
"and",
"existing_req",
".",
"extras",
"==",
"install_req",
".",
"extras",
"and",
"existing_req",
".",
"req",
".",
"specifier",
"!=",
"install_req",
".",
"req",
".",
"specifier",
")",
"if",
"has_conflicting_requirement",
":",
"raise",
"InstallationError",
"(",
"\"Double requirement given: %s (already in %s, name=%r)\"",
"%",
"(",
"install_req",
",",
"existing_req",
",",
"name",
")",
")",
"# When no existing requirement exists, add the requirement as a",
"# dependency and it will be scanned again after.",
"if",
"not",
"existing_req",
":",
"self",
".",
"requirements",
"[",
"name",
"]",
"=",
"install_req",
"# FIXME: what about other normalizations? E.g., _ vs. -?",
"if",
"name",
".",
"lower",
"(",
")",
"!=",
"name",
":",
"self",
".",
"requirement_aliases",
"[",
"name",
".",
"lower",
"(",
")",
"]",
"=",
"name",
"# We'd want to rescan this requirements later",
"return",
"[",
"install_req",
"]",
",",
"install_req",
"# Assume there's no need to scan, and that we've already",
"# encountered this for scanning.",
"if",
"install_req",
".",
"constraint",
"or",
"not",
"existing_req",
".",
"constraint",
":",
"return",
"[",
"]",
",",
"existing_req",
"does_not_satisfy_constraint",
"=",
"(",
"install_req",
".",
"link",
"and",
"not",
"(",
"existing_req",
".",
"link",
"and",
"install_req",
".",
"link",
".",
"path",
"==",
"existing_req",
".",
"link",
".",
"path",
")",
")",
"if",
"does_not_satisfy_constraint",
":",
"self",
".",
"reqs_to_cleanup",
".",
"append",
"(",
"install_req",
")",
"raise",
"InstallationError",
"(",
"\"Could not satisfy constraints for '%s': \"",
"\"installation from path or url cannot be \"",
"\"constrained to a version\"",
"%",
"name",
",",
")",
"# If we're now installing a constraint, mark the existing",
"# object for real installation.",
"existing_req",
".",
"constraint",
"=",
"False",
"existing_req",
".",
"extras",
"=",
"tuple",
"(",
"sorted",
"(",
"set",
"(",
"existing_req",
".",
"extras",
")",
"|",
"set",
"(",
"install_req",
".",
"extras",
")",
")",
")",
"logger",
".",
"debug",
"(",
"\"Setting %s extras to: %s\"",
",",
"existing_req",
",",
"existing_req",
".",
"extras",
",",
")",
"# Return the existing requirement for addition to the parent and",
"# scanning again.",
"return",
"[",
"existing_req",
"]",
",",
"existing_req"
] | Add install_req as a requirement to install.
:param parent_req_name: The name of the requirement that needed this
added. The name is used because when multiple unnamed requirements
resolve to the same name, we could otherwise end up with dependency
links that point outside the Requirements set. parent_req must
already be added. Note that None implies that this is a user
supplied requirement, vs an inferred one.
:param extras_requested: an iterable of extras used to evaluate the
environment markers.
:return: Additional requirements to scan. That is either [] if
the requirement is not applicable, or [install_req] if the
requirement is applicable and has just been added. | [
"Add",
"install_req",
"as",
"a",
"requirement",
"to",
"install",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_set.py#L52-L167 |
25,267 | pypa/pipenv | pipenv/patched/notpip/_internal/resolve.py | Resolver.resolve | def resolve(self, requirement_set):
# type: (RequirementSet) -> None
"""Resolve what operations need to be done
As a side-effect of this method, the packages (and their dependencies)
are downloaded, unpacked and prepared for installation. This
preparation is done by ``pip.operations.prepare``.
Once PyPI has static dependency metadata available, it would be
possible to move the preparation to become a step separated from
dependency resolution.
"""
# make the wheelhouse
if self.preparer.wheel_download_dir:
ensure_dir(self.preparer.wheel_download_dir)
# If any top-level requirement has a hash specified, enter
# hash-checking mode, which requires hashes from all.
root_reqs = (
requirement_set.unnamed_requirements +
list(requirement_set.requirements.values())
)
self.require_hashes = (
requirement_set.require_hashes or
any(req.has_hash_options for req in root_reqs)
)
# Display where finder is looking for packages
locations = self.finder.get_formatted_locations()
if locations:
logger.info(locations)
# Actually prepare the files, and collect any exceptions. Most hash
# exceptions cannot be checked ahead of time, because
# req.populate_link() needs to be called before we can make decisions
# based on link type.
discovered_reqs = [] # type: List[InstallRequirement]
hash_errors = HashErrors()
for req in chain(root_reqs, discovered_reqs):
try:
discovered_reqs.extend(
self._resolve_one(requirement_set, req)
)
except HashError as exc:
exc.req = req
hash_errors.append(exc)
if hash_errors:
raise hash_errors | python | def resolve(self, requirement_set):
# type: (RequirementSet) -> None
"""Resolve what operations need to be done
As a side-effect of this method, the packages (and their dependencies)
are downloaded, unpacked and prepared for installation. This
preparation is done by ``pip.operations.prepare``.
Once PyPI has static dependency metadata available, it would be
possible to move the preparation to become a step separated from
dependency resolution.
"""
# make the wheelhouse
if self.preparer.wheel_download_dir:
ensure_dir(self.preparer.wheel_download_dir)
# If any top-level requirement has a hash specified, enter
# hash-checking mode, which requires hashes from all.
root_reqs = (
requirement_set.unnamed_requirements +
list(requirement_set.requirements.values())
)
self.require_hashes = (
requirement_set.require_hashes or
any(req.has_hash_options for req in root_reqs)
)
# Display where finder is looking for packages
locations = self.finder.get_formatted_locations()
if locations:
logger.info(locations)
# Actually prepare the files, and collect any exceptions. Most hash
# exceptions cannot be checked ahead of time, because
# req.populate_link() needs to be called before we can make decisions
# based on link type.
discovered_reqs = [] # type: List[InstallRequirement]
hash_errors = HashErrors()
for req in chain(root_reqs, discovered_reqs):
try:
discovered_reqs.extend(
self._resolve_one(requirement_set, req)
)
except HashError as exc:
exc.req = req
hash_errors.append(exc)
if hash_errors:
raise hash_errors | [
"def",
"resolve",
"(",
"self",
",",
"requirement_set",
")",
":",
"# type: (RequirementSet) -> None",
"# make the wheelhouse",
"if",
"self",
".",
"preparer",
".",
"wheel_download_dir",
":",
"ensure_dir",
"(",
"self",
".",
"preparer",
".",
"wheel_download_dir",
")",
"# If any top-level requirement has a hash specified, enter",
"# hash-checking mode, which requires hashes from all.",
"root_reqs",
"=",
"(",
"requirement_set",
".",
"unnamed_requirements",
"+",
"list",
"(",
"requirement_set",
".",
"requirements",
".",
"values",
"(",
")",
")",
")",
"self",
".",
"require_hashes",
"=",
"(",
"requirement_set",
".",
"require_hashes",
"or",
"any",
"(",
"req",
".",
"has_hash_options",
"for",
"req",
"in",
"root_reqs",
")",
")",
"# Display where finder is looking for packages",
"locations",
"=",
"self",
".",
"finder",
".",
"get_formatted_locations",
"(",
")",
"if",
"locations",
":",
"logger",
".",
"info",
"(",
"locations",
")",
"# Actually prepare the files, and collect any exceptions. Most hash",
"# exceptions cannot be checked ahead of time, because",
"# req.populate_link() needs to be called before we can make decisions",
"# based on link type.",
"discovered_reqs",
"=",
"[",
"]",
"# type: List[InstallRequirement]",
"hash_errors",
"=",
"HashErrors",
"(",
")",
"for",
"req",
"in",
"chain",
"(",
"root_reqs",
",",
"discovered_reqs",
")",
":",
"try",
":",
"discovered_reqs",
".",
"extend",
"(",
"self",
".",
"_resolve_one",
"(",
"requirement_set",
",",
"req",
")",
")",
"except",
"HashError",
"as",
"exc",
":",
"exc",
".",
"req",
"=",
"req",
"hash_errors",
".",
"append",
"(",
"exc",
")",
"if",
"hash_errors",
":",
"raise",
"hash_errors"
] | Resolve what operations need to be done
As a side-effect of this method, the packages (and their dependencies)
are downloaded, unpacked and prepared for installation. This
preparation is done by ``pip.operations.prepare``.
Once PyPI has static dependency metadata available, it would be
possible to move the preparation to become a step separated from
dependency resolution. | [
"Resolve",
"what",
"operations",
"need",
"to",
"be",
"done"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/resolve.py#L96-L144 |
25,268 | pypa/pipenv | pipenv/patched/notpip/_internal/resolve.py | Resolver._set_req_to_reinstall | def _set_req_to_reinstall(self, req):
# type: (InstallRequirement) -> None
"""
Set a requirement to be installed.
"""
# Don't uninstall the conflict if doing a user install and the
# conflict is not a user install.
if not self.use_user_site or dist_in_usersite(req.satisfied_by):
req.conflicts_with = req.satisfied_by
req.satisfied_by = None | python | def _set_req_to_reinstall(self, req):
# type: (InstallRequirement) -> None
"""
Set a requirement to be installed.
"""
# Don't uninstall the conflict if doing a user install and the
# conflict is not a user install.
if not self.use_user_site or dist_in_usersite(req.satisfied_by):
req.conflicts_with = req.satisfied_by
req.satisfied_by = None | [
"def",
"_set_req_to_reinstall",
"(",
"self",
",",
"req",
")",
":",
"# type: (InstallRequirement) -> None",
"# Don't uninstall the conflict if doing a user install and the",
"# conflict is not a user install.",
"if",
"not",
"self",
".",
"use_user_site",
"or",
"dist_in_usersite",
"(",
"req",
".",
"satisfied_by",
")",
":",
"req",
".",
"conflicts_with",
"=",
"req",
".",
"satisfied_by",
"req",
".",
"satisfied_by",
"=",
"None"
] | Set a requirement to be installed. | [
"Set",
"a",
"requirement",
"to",
"be",
"installed",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/resolve.py#L156-L165 |
25,269 | pypa/pipenv | pipenv/patched/notpip/_internal/resolve.py | Resolver._check_skip_installed | def _check_skip_installed(self, req_to_install):
# type: (InstallRequirement) -> Optional[str]
"""Check if req_to_install should be skipped.
This will check if the req is installed, and whether we should upgrade
or reinstall it, taking into account all the relevant user options.
After calling this req_to_install will only have satisfied_by set to
None if the req_to_install is to be upgraded/reinstalled etc. Any
other value will be a dist recording the current thing installed that
satisfies the requirement.
Note that for vcs urls and the like we can't assess skipping in this
routine - we simply identify that we need to pull the thing down,
then later on it is pulled down and introspected to assess upgrade/
reinstalls etc.
:return: A text reason for why it was skipped, or None.
"""
if self.ignore_installed:
return None
req_to_install.check_if_exists(self.use_user_site)
if not req_to_install.satisfied_by:
return None
if self.force_reinstall:
self._set_req_to_reinstall(req_to_install)
return None
if not self._is_upgrade_allowed(req_to_install):
if self.upgrade_strategy == "only-if-needed":
return 'already satisfied, skipping upgrade'
return 'already satisfied'
# Check for the possibility of an upgrade. For link-based
# requirements we have to pull the tree down and inspect to assess
# the version #, so it's handled way down.
if not req_to_install.link:
try:
self.finder.find_requirement(req_to_install, upgrade=True)
except BestVersionAlreadyInstalled:
# Then the best version is installed.
return 'already up-to-date'
except DistributionNotFound:
# No distribution found, so we squash the error. It will
# be raised later when we re-try later to do the install.
# Why don't we just raise here?
pass
self._set_req_to_reinstall(req_to_install)
return None | python | def _check_skip_installed(self, req_to_install):
# type: (InstallRequirement) -> Optional[str]
"""Check if req_to_install should be skipped.
This will check if the req is installed, and whether we should upgrade
or reinstall it, taking into account all the relevant user options.
After calling this req_to_install will only have satisfied_by set to
None if the req_to_install is to be upgraded/reinstalled etc. Any
other value will be a dist recording the current thing installed that
satisfies the requirement.
Note that for vcs urls and the like we can't assess skipping in this
routine - we simply identify that we need to pull the thing down,
then later on it is pulled down and introspected to assess upgrade/
reinstalls etc.
:return: A text reason for why it was skipped, or None.
"""
if self.ignore_installed:
return None
req_to_install.check_if_exists(self.use_user_site)
if not req_to_install.satisfied_by:
return None
if self.force_reinstall:
self._set_req_to_reinstall(req_to_install)
return None
if not self._is_upgrade_allowed(req_to_install):
if self.upgrade_strategy == "only-if-needed":
return 'already satisfied, skipping upgrade'
return 'already satisfied'
# Check for the possibility of an upgrade. For link-based
# requirements we have to pull the tree down and inspect to assess
# the version #, so it's handled way down.
if not req_to_install.link:
try:
self.finder.find_requirement(req_to_install, upgrade=True)
except BestVersionAlreadyInstalled:
# Then the best version is installed.
return 'already up-to-date'
except DistributionNotFound:
# No distribution found, so we squash the error. It will
# be raised later when we re-try later to do the install.
# Why don't we just raise here?
pass
self._set_req_to_reinstall(req_to_install)
return None | [
"def",
"_check_skip_installed",
"(",
"self",
",",
"req_to_install",
")",
":",
"# type: (InstallRequirement) -> Optional[str]",
"if",
"self",
".",
"ignore_installed",
":",
"return",
"None",
"req_to_install",
".",
"check_if_exists",
"(",
"self",
".",
"use_user_site",
")",
"if",
"not",
"req_to_install",
".",
"satisfied_by",
":",
"return",
"None",
"if",
"self",
".",
"force_reinstall",
":",
"self",
".",
"_set_req_to_reinstall",
"(",
"req_to_install",
")",
"return",
"None",
"if",
"not",
"self",
".",
"_is_upgrade_allowed",
"(",
"req_to_install",
")",
":",
"if",
"self",
".",
"upgrade_strategy",
"==",
"\"only-if-needed\"",
":",
"return",
"'already satisfied, skipping upgrade'",
"return",
"'already satisfied'",
"# Check for the possibility of an upgrade. For link-based",
"# requirements we have to pull the tree down and inspect to assess",
"# the version #, so it's handled way down.",
"if",
"not",
"req_to_install",
".",
"link",
":",
"try",
":",
"self",
".",
"finder",
".",
"find_requirement",
"(",
"req_to_install",
",",
"upgrade",
"=",
"True",
")",
"except",
"BestVersionAlreadyInstalled",
":",
"# Then the best version is installed.",
"return",
"'already up-to-date'",
"except",
"DistributionNotFound",
":",
"# No distribution found, so we squash the error. It will",
"# be raised later when we re-try later to do the install.",
"# Why don't we just raise here?",
"pass",
"self",
".",
"_set_req_to_reinstall",
"(",
"req_to_install",
")",
"return",
"None"
] | Check if req_to_install should be skipped.
This will check if the req is installed, and whether we should upgrade
or reinstall it, taking into account all the relevant user options.
After calling this req_to_install will only have satisfied_by set to
None if the req_to_install is to be upgraded/reinstalled etc. Any
other value will be a dist recording the current thing installed that
satisfies the requirement.
Note that for vcs urls and the like we can't assess skipping in this
routine - we simply identify that we need to pull the thing down,
then later on it is pulled down and introspected to assess upgrade/
reinstalls etc.
:return: A text reason for why it was skipped, or None. | [
"Check",
"if",
"req_to_install",
"should",
"be",
"skipped",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/resolve.py#L168-L219 |
25,270 | pypa/pipenv | pipenv/patched/notpip/_internal/resolve.py | Resolver._get_abstract_dist_for | def _get_abstract_dist_for(self, req):
# type: (InstallRequirement) -> DistAbstraction
"""Takes a InstallRequirement and returns a single AbstractDist \
representing a prepared variant of the same.
"""
assert self.require_hashes is not None, (
"require_hashes should have been set in Resolver.resolve()"
)
if req.editable:
return self.preparer.prepare_editable_requirement(
req, self.require_hashes, self.use_user_site, self.finder,
)
# satisfied_by is only evaluated by calling _check_skip_installed,
# so it must be None here.
assert req.satisfied_by is None
skip_reason = self._check_skip_installed(req)
if req.satisfied_by:
return self.preparer.prepare_installed_requirement(
req, self.require_hashes, skip_reason
)
upgrade_allowed = self._is_upgrade_allowed(req)
abstract_dist = self.preparer.prepare_linked_requirement(
req, self.session, self.finder, upgrade_allowed,
self.require_hashes
)
# NOTE
# The following portion is for determining if a certain package is
# going to be re-installed/upgraded or not and reporting to the user.
# This should probably get cleaned up in a future refactor.
# req.req is only avail after unpack for URL
# pkgs repeat check_if_exists to uninstall-on-upgrade
# (#14)
if not self.ignore_installed:
req.check_if_exists(self.use_user_site)
if req.satisfied_by:
should_modify = (
self.upgrade_strategy != "to-satisfy-only" or
self.force_reinstall or
self.ignore_installed or
req.link.scheme == 'file'
)
if should_modify:
self._set_req_to_reinstall(req)
else:
logger.info(
'Requirement already satisfied (use --upgrade to upgrade):'
' %s', req,
)
return abstract_dist | python | def _get_abstract_dist_for(self, req):
# type: (InstallRequirement) -> DistAbstraction
"""Takes a InstallRequirement and returns a single AbstractDist \
representing a prepared variant of the same.
"""
assert self.require_hashes is not None, (
"require_hashes should have been set in Resolver.resolve()"
)
if req.editable:
return self.preparer.prepare_editable_requirement(
req, self.require_hashes, self.use_user_site, self.finder,
)
# satisfied_by is only evaluated by calling _check_skip_installed,
# so it must be None here.
assert req.satisfied_by is None
skip_reason = self._check_skip_installed(req)
if req.satisfied_by:
return self.preparer.prepare_installed_requirement(
req, self.require_hashes, skip_reason
)
upgrade_allowed = self._is_upgrade_allowed(req)
abstract_dist = self.preparer.prepare_linked_requirement(
req, self.session, self.finder, upgrade_allowed,
self.require_hashes
)
# NOTE
# The following portion is for determining if a certain package is
# going to be re-installed/upgraded or not and reporting to the user.
# This should probably get cleaned up in a future refactor.
# req.req is only avail after unpack for URL
# pkgs repeat check_if_exists to uninstall-on-upgrade
# (#14)
if not self.ignore_installed:
req.check_if_exists(self.use_user_site)
if req.satisfied_by:
should_modify = (
self.upgrade_strategy != "to-satisfy-only" or
self.force_reinstall or
self.ignore_installed or
req.link.scheme == 'file'
)
if should_modify:
self._set_req_to_reinstall(req)
else:
logger.info(
'Requirement already satisfied (use --upgrade to upgrade):'
' %s', req,
)
return abstract_dist | [
"def",
"_get_abstract_dist_for",
"(",
"self",
",",
"req",
")",
":",
"# type: (InstallRequirement) -> DistAbstraction",
"assert",
"self",
".",
"require_hashes",
"is",
"not",
"None",
",",
"(",
"\"require_hashes should have been set in Resolver.resolve()\"",
")",
"if",
"req",
".",
"editable",
":",
"return",
"self",
".",
"preparer",
".",
"prepare_editable_requirement",
"(",
"req",
",",
"self",
".",
"require_hashes",
",",
"self",
".",
"use_user_site",
",",
"self",
".",
"finder",
",",
")",
"# satisfied_by is only evaluated by calling _check_skip_installed,",
"# so it must be None here.",
"assert",
"req",
".",
"satisfied_by",
"is",
"None",
"skip_reason",
"=",
"self",
".",
"_check_skip_installed",
"(",
"req",
")",
"if",
"req",
".",
"satisfied_by",
":",
"return",
"self",
".",
"preparer",
".",
"prepare_installed_requirement",
"(",
"req",
",",
"self",
".",
"require_hashes",
",",
"skip_reason",
")",
"upgrade_allowed",
"=",
"self",
".",
"_is_upgrade_allowed",
"(",
"req",
")",
"abstract_dist",
"=",
"self",
".",
"preparer",
".",
"prepare_linked_requirement",
"(",
"req",
",",
"self",
".",
"session",
",",
"self",
".",
"finder",
",",
"upgrade_allowed",
",",
"self",
".",
"require_hashes",
")",
"# NOTE",
"# The following portion is for determining if a certain package is",
"# going to be re-installed/upgraded or not and reporting to the user.",
"# This should probably get cleaned up in a future refactor.",
"# req.req is only avail after unpack for URL",
"# pkgs repeat check_if_exists to uninstall-on-upgrade",
"# (#14)",
"if",
"not",
"self",
".",
"ignore_installed",
":",
"req",
".",
"check_if_exists",
"(",
"self",
".",
"use_user_site",
")",
"if",
"req",
".",
"satisfied_by",
":",
"should_modify",
"=",
"(",
"self",
".",
"upgrade_strategy",
"!=",
"\"to-satisfy-only\"",
"or",
"self",
".",
"force_reinstall",
"or",
"self",
".",
"ignore_installed",
"or",
"req",
".",
"link",
".",
"scheme",
"==",
"'file'",
")",
"if",
"should_modify",
":",
"self",
".",
"_set_req_to_reinstall",
"(",
"req",
")",
"else",
":",
"logger",
".",
"info",
"(",
"'Requirement already satisfied (use --upgrade to upgrade):'",
"' %s'",
",",
"req",
",",
")",
"return",
"abstract_dist"
] | Takes a InstallRequirement and returns a single AbstractDist \
representing a prepared variant of the same. | [
"Takes",
"a",
"InstallRequirement",
"and",
"returns",
"a",
"single",
"AbstractDist",
"\\",
"representing",
"a",
"prepared",
"variant",
"of",
"the",
"same",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/resolve.py#L221-L277 |
25,271 | pypa/pipenv | pipenv/patched/notpip/_internal/resolve.py | Resolver._resolve_one | def _resolve_one(
self,
requirement_set, # type: RequirementSet
req_to_install, # type: InstallRequirement
ignore_requires_python=False # type: bool
):
# type: (...) -> List[InstallRequirement]
"""Prepare a single requirements file.
:return: A list of additional InstallRequirements to also install.
"""
# Tell user what we are doing for this requirement:
# obtain (editable), skipping, processing (local url), collecting
# (remote url or package name)
if req_to_install.constraint or req_to_install.prepared:
return []
req_to_install.prepared = True
# register tmp src for cleanup in case something goes wrong
requirement_set.reqs_to_cleanup.append(req_to_install)
abstract_dist = self._get_abstract_dist_for(req_to_install)
# Parse and return dependencies
dist = abstract_dist.dist()
try:
check_dist_requires_python(dist)
except UnsupportedPythonVersion as err:
if self.ignore_requires_python or ignore_requires_python or self.ignore_compatibility:
logger.warning(err.args[0])
else:
raise
# A huge hack, by Kenneth Reitz.
try:
self.requires_python = check_dist_requires_python(dist, absorb=False)
except TypeError:
self.requires_python = None
more_reqs = [] # type: List[InstallRequirement]
def add_req(subreq, extras_requested):
sub_install_req = install_req_from_req_string(
str(subreq),
req_to_install,
isolated=self.isolated,
wheel_cache=self.wheel_cache,
use_pep517=self.use_pep517
)
parent_req_name = req_to_install.name
to_scan_again, add_to_parent = requirement_set.add_requirement(
sub_install_req,
parent_req_name=parent_req_name,
extras_requested=extras_requested,
)
if parent_req_name and add_to_parent:
self._discovered_dependencies[parent_req_name].append(
add_to_parent
)
more_reqs.extend(to_scan_again)
with indent_log():
# We add req_to_install before its dependencies, so that we
# can refer to it when adding dependencies.
if not requirement_set.has_requirement(req_to_install.name):
available_requested = sorted(
set(dist.extras) & set(req_to_install.extras)
)
# 'unnamed' requirements will get added here
req_to_install.is_direct = True
requirement_set.add_requirement(
req_to_install, parent_req_name=None,
extras_requested=available_requested,
)
if not self.ignore_dependencies:
if req_to_install.extras:
logger.debug(
"Installing extra requirements: %r",
','.join(req_to_install.extras),
)
missing_requested = sorted(
set(req_to_install.extras) - set(dist.extras)
)
for missing in missing_requested:
logger.warning(
'%s does not provide the extra \'%s\'',
dist, missing
)
available_requested = sorted(
set(dist.extras) & set(req_to_install.extras)
)
for subreq in dist.requires(available_requested):
add_req(subreq, extras_requested=available_requested)
# Hack for deep-resolving extras.
for available in available_requested:
if hasattr(dist, '_DistInfoDistribution__dep_map'):
for req in dist._DistInfoDistribution__dep_map[available]:
req = InstallRequirement(
req,
req_to_install,
isolated=self.isolated,
wheel_cache=self.wheel_cache,
use_pep517=None
)
more_reqs.append(req)
if not req_to_install.editable and not req_to_install.satisfied_by:
# XXX: --no-install leads this to report 'Successfully
# downloaded' for only non-editable reqs, even though we took
# action on them.
requirement_set.successfully_downloaded.append(req_to_install)
return more_reqs | python | def _resolve_one(
self,
requirement_set, # type: RequirementSet
req_to_install, # type: InstallRequirement
ignore_requires_python=False # type: bool
):
# type: (...) -> List[InstallRequirement]
"""Prepare a single requirements file.
:return: A list of additional InstallRequirements to also install.
"""
# Tell user what we are doing for this requirement:
# obtain (editable), skipping, processing (local url), collecting
# (remote url or package name)
if req_to_install.constraint or req_to_install.prepared:
return []
req_to_install.prepared = True
# register tmp src for cleanup in case something goes wrong
requirement_set.reqs_to_cleanup.append(req_to_install)
abstract_dist = self._get_abstract_dist_for(req_to_install)
# Parse and return dependencies
dist = abstract_dist.dist()
try:
check_dist_requires_python(dist)
except UnsupportedPythonVersion as err:
if self.ignore_requires_python or ignore_requires_python or self.ignore_compatibility:
logger.warning(err.args[0])
else:
raise
# A huge hack, by Kenneth Reitz.
try:
self.requires_python = check_dist_requires_python(dist, absorb=False)
except TypeError:
self.requires_python = None
more_reqs = [] # type: List[InstallRequirement]
def add_req(subreq, extras_requested):
sub_install_req = install_req_from_req_string(
str(subreq),
req_to_install,
isolated=self.isolated,
wheel_cache=self.wheel_cache,
use_pep517=self.use_pep517
)
parent_req_name = req_to_install.name
to_scan_again, add_to_parent = requirement_set.add_requirement(
sub_install_req,
parent_req_name=parent_req_name,
extras_requested=extras_requested,
)
if parent_req_name and add_to_parent:
self._discovered_dependencies[parent_req_name].append(
add_to_parent
)
more_reqs.extend(to_scan_again)
with indent_log():
# We add req_to_install before its dependencies, so that we
# can refer to it when adding dependencies.
if not requirement_set.has_requirement(req_to_install.name):
available_requested = sorted(
set(dist.extras) & set(req_to_install.extras)
)
# 'unnamed' requirements will get added here
req_to_install.is_direct = True
requirement_set.add_requirement(
req_to_install, parent_req_name=None,
extras_requested=available_requested,
)
if not self.ignore_dependencies:
if req_to_install.extras:
logger.debug(
"Installing extra requirements: %r",
','.join(req_to_install.extras),
)
missing_requested = sorted(
set(req_to_install.extras) - set(dist.extras)
)
for missing in missing_requested:
logger.warning(
'%s does not provide the extra \'%s\'',
dist, missing
)
available_requested = sorted(
set(dist.extras) & set(req_to_install.extras)
)
for subreq in dist.requires(available_requested):
add_req(subreq, extras_requested=available_requested)
# Hack for deep-resolving extras.
for available in available_requested:
if hasattr(dist, '_DistInfoDistribution__dep_map'):
for req in dist._DistInfoDistribution__dep_map[available]:
req = InstallRequirement(
req,
req_to_install,
isolated=self.isolated,
wheel_cache=self.wheel_cache,
use_pep517=None
)
more_reqs.append(req)
if not req_to_install.editable and not req_to_install.satisfied_by:
# XXX: --no-install leads this to report 'Successfully
# downloaded' for only non-editable reqs, even though we took
# action on them.
requirement_set.successfully_downloaded.append(req_to_install)
return more_reqs | [
"def",
"_resolve_one",
"(",
"self",
",",
"requirement_set",
",",
"# type: RequirementSet",
"req_to_install",
",",
"# type: InstallRequirement",
"ignore_requires_python",
"=",
"False",
"# type: bool",
")",
":",
"# type: (...) -> List[InstallRequirement]",
"# Tell user what we are doing for this requirement:",
"# obtain (editable), skipping, processing (local url), collecting",
"# (remote url or package name)",
"if",
"req_to_install",
".",
"constraint",
"or",
"req_to_install",
".",
"prepared",
":",
"return",
"[",
"]",
"req_to_install",
".",
"prepared",
"=",
"True",
"# register tmp src for cleanup in case something goes wrong",
"requirement_set",
".",
"reqs_to_cleanup",
".",
"append",
"(",
"req_to_install",
")",
"abstract_dist",
"=",
"self",
".",
"_get_abstract_dist_for",
"(",
"req_to_install",
")",
"# Parse and return dependencies",
"dist",
"=",
"abstract_dist",
".",
"dist",
"(",
")",
"try",
":",
"check_dist_requires_python",
"(",
"dist",
")",
"except",
"UnsupportedPythonVersion",
"as",
"err",
":",
"if",
"self",
".",
"ignore_requires_python",
"or",
"ignore_requires_python",
"or",
"self",
".",
"ignore_compatibility",
":",
"logger",
".",
"warning",
"(",
"err",
".",
"args",
"[",
"0",
"]",
")",
"else",
":",
"raise",
"# A huge hack, by Kenneth Reitz.",
"try",
":",
"self",
".",
"requires_python",
"=",
"check_dist_requires_python",
"(",
"dist",
",",
"absorb",
"=",
"False",
")",
"except",
"TypeError",
":",
"self",
".",
"requires_python",
"=",
"None",
"more_reqs",
"=",
"[",
"]",
"# type: List[InstallRequirement]",
"def",
"add_req",
"(",
"subreq",
",",
"extras_requested",
")",
":",
"sub_install_req",
"=",
"install_req_from_req_string",
"(",
"str",
"(",
"subreq",
")",
",",
"req_to_install",
",",
"isolated",
"=",
"self",
".",
"isolated",
",",
"wheel_cache",
"=",
"self",
".",
"wheel_cache",
",",
"use_pep517",
"=",
"self",
".",
"use_pep517",
")",
"parent_req_name",
"=",
"req_to_install",
".",
"name",
"to_scan_again",
",",
"add_to_parent",
"=",
"requirement_set",
".",
"add_requirement",
"(",
"sub_install_req",
",",
"parent_req_name",
"=",
"parent_req_name",
",",
"extras_requested",
"=",
"extras_requested",
",",
")",
"if",
"parent_req_name",
"and",
"add_to_parent",
":",
"self",
".",
"_discovered_dependencies",
"[",
"parent_req_name",
"]",
".",
"append",
"(",
"add_to_parent",
")",
"more_reqs",
".",
"extend",
"(",
"to_scan_again",
")",
"with",
"indent_log",
"(",
")",
":",
"# We add req_to_install before its dependencies, so that we",
"# can refer to it when adding dependencies.",
"if",
"not",
"requirement_set",
".",
"has_requirement",
"(",
"req_to_install",
".",
"name",
")",
":",
"available_requested",
"=",
"sorted",
"(",
"set",
"(",
"dist",
".",
"extras",
")",
"&",
"set",
"(",
"req_to_install",
".",
"extras",
")",
")",
"# 'unnamed' requirements will get added here",
"req_to_install",
".",
"is_direct",
"=",
"True",
"requirement_set",
".",
"add_requirement",
"(",
"req_to_install",
",",
"parent_req_name",
"=",
"None",
",",
"extras_requested",
"=",
"available_requested",
",",
")",
"if",
"not",
"self",
".",
"ignore_dependencies",
":",
"if",
"req_to_install",
".",
"extras",
":",
"logger",
".",
"debug",
"(",
"\"Installing extra requirements: %r\"",
",",
"','",
".",
"join",
"(",
"req_to_install",
".",
"extras",
")",
",",
")",
"missing_requested",
"=",
"sorted",
"(",
"set",
"(",
"req_to_install",
".",
"extras",
")",
"-",
"set",
"(",
"dist",
".",
"extras",
")",
")",
"for",
"missing",
"in",
"missing_requested",
":",
"logger",
".",
"warning",
"(",
"'%s does not provide the extra \\'%s\\''",
",",
"dist",
",",
"missing",
")",
"available_requested",
"=",
"sorted",
"(",
"set",
"(",
"dist",
".",
"extras",
")",
"&",
"set",
"(",
"req_to_install",
".",
"extras",
")",
")",
"for",
"subreq",
"in",
"dist",
".",
"requires",
"(",
"available_requested",
")",
":",
"add_req",
"(",
"subreq",
",",
"extras_requested",
"=",
"available_requested",
")",
"# Hack for deep-resolving extras.",
"for",
"available",
"in",
"available_requested",
":",
"if",
"hasattr",
"(",
"dist",
",",
"'_DistInfoDistribution__dep_map'",
")",
":",
"for",
"req",
"in",
"dist",
".",
"_DistInfoDistribution__dep_map",
"[",
"available",
"]",
":",
"req",
"=",
"InstallRequirement",
"(",
"req",
",",
"req_to_install",
",",
"isolated",
"=",
"self",
".",
"isolated",
",",
"wheel_cache",
"=",
"self",
".",
"wheel_cache",
",",
"use_pep517",
"=",
"None",
")",
"more_reqs",
".",
"append",
"(",
"req",
")",
"if",
"not",
"req_to_install",
".",
"editable",
"and",
"not",
"req_to_install",
".",
"satisfied_by",
":",
"# XXX: --no-install leads this to report 'Successfully",
"# downloaded' for only non-editable reqs, even though we took",
"# action on them.",
"requirement_set",
".",
"successfully_downloaded",
".",
"append",
"(",
"req_to_install",
")",
"return",
"more_reqs"
] | Prepare a single requirements file.
:return: A list of additional InstallRequirements to also install. | [
"Prepare",
"a",
"single",
"requirements",
"file",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/resolve.py#L279-L397 |
25,272 | pypa/pipenv | pipenv/patched/notpip/_internal/resolve.py | Resolver.get_installation_order | def get_installation_order(self, req_set):
# type: (RequirementSet) -> List[InstallRequirement]
"""Create the installation order.
The installation order is topological - requirements are installed
before the requiring thing. We break cycles at an arbitrary point,
and make no other guarantees.
"""
# The current implementation, which we may change at any point
# installs the user specified things in the order given, except when
# dependencies must come earlier to achieve topological order.
order = []
ordered_reqs = set() # type: Set[InstallRequirement]
def schedule(req):
if req.satisfied_by or req in ordered_reqs:
return
if req.constraint:
return
ordered_reqs.add(req)
for dep in self._discovered_dependencies[req.name]:
schedule(dep)
order.append(req)
for install_req in req_set.requirements.values():
schedule(install_req)
return order | python | def get_installation_order(self, req_set):
# type: (RequirementSet) -> List[InstallRequirement]
"""Create the installation order.
The installation order is topological - requirements are installed
before the requiring thing. We break cycles at an arbitrary point,
and make no other guarantees.
"""
# The current implementation, which we may change at any point
# installs the user specified things in the order given, except when
# dependencies must come earlier to achieve topological order.
order = []
ordered_reqs = set() # type: Set[InstallRequirement]
def schedule(req):
if req.satisfied_by or req in ordered_reqs:
return
if req.constraint:
return
ordered_reqs.add(req)
for dep in self._discovered_dependencies[req.name]:
schedule(dep)
order.append(req)
for install_req in req_set.requirements.values():
schedule(install_req)
return order | [
"def",
"get_installation_order",
"(",
"self",
",",
"req_set",
")",
":",
"# type: (RequirementSet) -> List[InstallRequirement]",
"# The current implementation, which we may change at any point",
"# installs the user specified things in the order given, except when",
"# dependencies must come earlier to achieve topological order.",
"order",
"=",
"[",
"]",
"ordered_reqs",
"=",
"set",
"(",
")",
"# type: Set[InstallRequirement]",
"def",
"schedule",
"(",
"req",
")",
":",
"if",
"req",
".",
"satisfied_by",
"or",
"req",
"in",
"ordered_reqs",
":",
"return",
"if",
"req",
".",
"constraint",
":",
"return",
"ordered_reqs",
".",
"add",
"(",
"req",
")",
"for",
"dep",
"in",
"self",
".",
"_discovered_dependencies",
"[",
"req",
".",
"name",
"]",
":",
"schedule",
"(",
"dep",
")",
"order",
".",
"append",
"(",
"req",
")",
"for",
"install_req",
"in",
"req_set",
".",
"requirements",
".",
"values",
"(",
")",
":",
"schedule",
"(",
"install_req",
")",
"return",
"order"
] | Create the installation order.
The installation order is topological - requirements are installed
before the requiring thing. We break cycles at an arbitrary point,
and make no other guarantees. | [
"Create",
"the",
"installation",
"order",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/resolve.py#L399-L425 |
25,273 | pypa/pipenv | pipenv/vendor/pyparsing.py | line | def line( loc, strg ):
"""Returns the line of text containing loc within a string, counting newlines as line separators.
"""
lastCR = strg.rfind("\n", 0, loc)
nextCR = strg.find("\n", loc)
if nextCR >= 0:
return strg[lastCR+1:nextCR]
else:
return strg[lastCR+1:] | python | def line( loc, strg ):
"""Returns the line of text containing loc within a string, counting newlines as line separators.
"""
lastCR = strg.rfind("\n", 0, loc)
nextCR = strg.find("\n", loc)
if nextCR >= 0:
return strg[lastCR+1:nextCR]
else:
return strg[lastCR+1:] | [
"def",
"line",
"(",
"loc",
",",
"strg",
")",
":",
"lastCR",
"=",
"strg",
".",
"rfind",
"(",
"\"\\n\"",
",",
"0",
",",
"loc",
")",
"nextCR",
"=",
"strg",
".",
"find",
"(",
"\"\\n\"",
",",
"loc",
")",
"if",
"nextCR",
">=",
"0",
":",
"return",
"strg",
"[",
"lastCR",
"+",
"1",
":",
"nextCR",
"]",
"else",
":",
"return",
"strg",
"[",
"lastCR",
"+",
"1",
":",
"]"
] | Returns the line of text containing loc within a string, counting newlines as line separators. | [
"Returns",
"the",
"line",
"of",
"text",
"containing",
"loc",
"within",
"a",
"string",
"counting",
"newlines",
"as",
"line",
"separators",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L1124-L1132 |
25,274 | pypa/pipenv | pipenv/vendor/pyparsing.py | traceParseAction | def traceParseAction(f):
"""Decorator for debugging parse actions.
When the parse action is called, this decorator will print
``">> entering method-name(line:<current_source_line>, <parse_location>, <matched_tokens>)"``.
When the parse action completes, the decorator will print
``"<<"`` followed by the returned value, or any exception that the parse action raised.
Example::
wd = Word(alphas)
@traceParseAction
def remove_duplicate_chars(tokens):
return ''.join(sorted(set(''.join(tokens))))
wds = OneOrMore(wd).setParseAction(remove_duplicate_chars)
print(wds.parseString("slkdjs sld sldd sdlf sdljf"))
prints::
>>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {}))
<<leaving remove_duplicate_chars (ret: 'dfjkls')
['dfjkls']
"""
f = _trim_arity(f)
def z(*paArgs):
thisFunc = f.__name__
s,l,t = paArgs[-3:]
if len(paArgs)>3:
thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc
sys.stderr.write( ">>entering %s(line: '%s', %d, %r)\n" % (thisFunc,line(l,s),l,t) )
try:
ret = f(*paArgs)
except Exception as exc:
sys.stderr.write( "<<leaving %s (exception: %s)\n" % (thisFunc,exc) )
raise
sys.stderr.write( "<<leaving %s (ret: %r)\n" % (thisFunc,ret) )
return ret
try:
z.__name__ = f.__name__
except AttributeError:
pass
return z | python | def traceParseAction(f):
"""Decorator for debugging parse actions.
When the parse action is called, this decorator will print
``">> entering method-name(line:<current_source_line>, <parse_location>, <matched_tokens>)"``.
When the parse action completes, the decorator will print
``"<<"`` followed by the returned value, or any exception that the parse action raised.
Example::
wd = Word(alphas)
@traceParseAction
def remove_duplicate_chars(tokens):
return ''.join(sorted(set(''.join(tokens))))
wds = OneOrMore(wd).setParseAction(remove_duplicate_chars)
print(wds.parseString("slkdjs sld sldd sdlf sdljf"))
prints::
>>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {}))
<<leaving remove_duplicate_chars (ret: 'dfjkls')
['dfjkls']
"""
f = _trim_arity(f)
def z(*paArgs):
thisFunc = f.__name__
s,l,t = paArgs[-3:]
if len(paArgs)>3:
thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc
sys.stderr.write( ">>entering %s(line: '%s', %d, %r)\n" % (thisFunc,line(l,s),l,t) )
try:
ret = f(*paArgs)
except Exception as exc:
sys.stderr.write( "<<leaving %s (exception: %s)\n" % (thisFunc,exc) )
raise
sys.stderr.write( "<<leaving %s (ret: %r)\n" % (thisFunc,ret) )
return ret
try:
z.__name__ = f.__name__
except AttributeError:
pass
return z | [
"def",
"traceParseAction",
"(",
"f",
")",
":",
"f",
"=",
"_trim_arity",
"(",
"f",
")",
"def",
"z",
"(",
"*",
"paArgs",
")",
":",
"thisFunc",
"=",
"f",
".",
"__name__",
"s",
",",
"l",
",",
"t",
"=",
"paArgs",
"[",
"-",
"3",
":",
"]",
"if",
"len",
"(",
"paArgs",
")",
">",
"3",
":",
"thisFunc",
"=",
"paArgs",
"[",
"0",
"]",
".",
"__class__",
".",
"__name__",
"+",
"'.'",
"+",
"thisFunc",
"sys",
".",
"stderr",
".",
"write",
"(",
"\">>entering %s(line: '%s', %d, %r)\\n\"",
"%",
"(",
"thisFunc",
",",
"line",
"(",
"l",
",",
"s",
")",
",",
"l",
",",
"t",
")",
")",
"try",
":",
"ret",
"=",
"f",
"(",
"*",
"paArgs",
")",
"except",
"Exception",
"as",
"exc",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"<<leaving %s (exception: %s)\\n\"",
"%",
"(",
"thisFunc",
",",
"exc",
")",
")",
"raise",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"<<leaving %s (ret: %r)\\n\"",
"%",
"(",
"thisFunc",
",",
"ret",
")",
")",
"return",
"ret",
"try",
":",
"z",
".",
"__name__",
"=",
"f",
".",
"__name__",
"except",
"AttributeError",
":",
"pass",
"return",
"z"
] | Decorator for debugging parse actions.
When the parse action is called, this decorator will print
``">> entering method-name(line:<current_source_line>, <parse_location>, <matched_tokens>)"``.
When the parse action completes, the decorator will print
``"<<"`` followed by the returned value, or any exception that the parse action raised.
Example::
wd = Word(alphas)
@traceParseAction
def remove_duplicate_chars(tokens):
return ''.join(sorted(set(''.join(tokens))))
wds = OneOrMore(wd).setParseAction(remove_duplicate_chars)
print(wds.parseString("slkdjs sld sldd sdlf sdljf"))
prints::
>>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {}))
<<leaving remove_duplicate_chars (ret: 'dfjkls')
['dfjkls'] | [
"Decorator",
"for",
"debugging",
"parse",
"actions",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L4846-L4889 |
25,275 | pypa/pipenv | pipenv/vendor/pyparsing.py | delimitedList | def delimitedList( expr, delim=",", combine=False ):
"""Helper to define a delimited list of expressions - the delimiter
defaults to ','. By default, the list elements and delimiters can
have intervening whitespace, and comments, but this can be
overridden by passing ``combine=True`` in the constructor. If
``combine`` is set to ``True``, the matching tokens are
returned as a single token string, with the delimiters included;
otherwise, the matching tokens are returned as a list of tokens,
with the delimiters suppressed.
Example::
delimitedList(Word(alphas)).parseString("aa,bb,cc") # -> ['aa', 'bb', 'cc']
delimitedList(Word(hexnums), delim=':', combine=True).parseString("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE']
"""
dlName = _ustr(expr)+" ["+_ustr(delim)+" "+_ustr(expr)+"]..."
if combine:
return Combine( expr + ZeroOrMore( delim + expr ) ).setName(dlName)
else:
return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName) | python | def delimitedList( expr, delim=",", combine=False ):
"""Helper to define a delimited list of expressions - the delimiter
defaults to ','. By default, the list elements and delimiters can
have intervening whitespace, and comments, but this can be
overridden by passing ``combine=True`` in the constructor. If
``combine`` is set to ``True``, the matching tokens are
returned as a single token string, with the delimiters included;
otherwise, the matching tokens are returned as a list of tokens,
with the delimiters suppressed.
Example::
delimitedList(Word(alphas)).parseString("aa,bb,cc") # -> ['aa', 'bb', 'cc']
delimitedList(Word(hexnums), delim=':', combine=True).parseString("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE']
"""
dlName = _ustr(expr)+" ["+_ustr(delim)+" "+_ustr(expr)+"]..."
if combine:
return Combine( expr + ZeroOrMore( delim + expr ) ).setName(dlName)
else:
return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName) | [
"def",
"delimitedList",
"(",
"expr",
",",
"delim",
"=",
"\",\"",
",",
"combine",
"=",
"False",
")",
":",
"dlName",
"=",
"_ustr",
"(",
"expr",
")",
"+",
"\" [\"",
"+",
"_ustr",
"(",
"delim",
")",
"+",
"\" \"",
"+",
"_ustr",
"(",
"expr",
")",
"+",
"\"]...\"",
"if",
"combine",
":",
"return",
"Combine",
"(",
"expr",
"+",
"ZeroOrMore",
"(",
"delim",
"+",
"expr",
")",
")",
".",
"setName",
"(",
"dlName",
")",
"else",
":",
"return",
"(",
"expr",
"+",
"ZeroOrMore",
"(",
"Suppress",
"(",
"delim",
")",
"+",
"expr",
")",
")",
".",
"setName",
"(",
"dlName",
")"
] | Helper to define a delimited list of expressions - the delimiter
defaults to ','. By default, the list elements and delimiters can
have intervening whitespace, and comments, but this can be
overridden by passing ``combine=True`` in the constructor. If
``combine`` is set to ``True``, the matching tokens are
returned as a single token string, with the delimiters included;
otherwise, the matching tokens are returned as a list of tokens,
with the delimiters suppressed.
Example::
delimitedList(Word(alphas)).parseString("aa,bb,cc") # -> ['aa', 'bb', 'cc']
delimitedList(Word(hexnums), delim=':', combine=True).parseString("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE'] | [
"Helper",
"to",
"define",
"a",
"delimited",
"list",
"of",
"expressions",
"-",
"the",
"delimiter",
"defaults",
"to",
".",
"By",
"default",
"the",
"list",
"elements",
"and",
"delimiters",
"can",
"have",
"intervening",
"whitespace",
"and",
"comments",
"but",
"this",
"can",
"be",
"overridden",
"by",
"passing",
"combine",
"=",
"True",
"in",
"the",
"constructor",
".",
"If",
"combine",
"is",
"set",
"to",
"True",
"the",
"matching",
"tokens",
"are",
"returned",
"as",
"a",
"single",
"token",
"string",
"with",
"the",
"delimiters",
"included",
";",
"otherwise",
"the",
"matching",
"tokens",
"are",
"returned",
"as",
"a",
"list",
"of",
"tokens",
"with",
"the",
"delimiters",
"suppressed",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L4894-L4913 |
25,276 | pypa/pipenv | pipenv/vendor/pyparsing.py | originalTextFor | def originalTextFor(expr, asString=True):
"""Helper to return the original, untokenized text for a given
expression. Useful to restore the parsed fields of an HTML start
tag into the raw tag text itself, or to revert separate tokens with
intervening whitespace back to the original matching input text. By
default, returns astring containing the original parsed text.
If the optional ``asString`` argument is passed as
``False``, then the return value is
a :class:`ParseResults` containing any results names that
were originally matched, and a single token containing the original
matched text from the input string. So if the expression passed to
:class:`originalTextFor` contains expressions with defined
results names, you must set ``asString`` to ``False`` if you
want to preserve those results name values.
Example::
src = "this is test <b> bold <i>text</i> </b> normal text "
for tag in ("b","i"):
opener,closer = makeHTMLTags(tag)
patt = originalTextFor(opener + SkipTo(closer) + closer)
print(patt.searchString(src)[0])
prints::
['<b> bold <i>text</i> </b>']
['<i>text</i>']
"""
locMarker = Empty().setParseAction(lambda s,loc,t: loc)
endlocMarker = locMarker.copy()
endlocMarker.callPreparse = False
matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end")
if asString:
extractText = lambda s,l,t: s[t._original_start:t._original_end]
else:
def extractText(s,l,t):
t[:] = [s[t.pop('_original_start'):t.pop('_original_end')]]
matchExpr.setParseAction(extractText)
matchExpr.ignoreExprs = expr.ignoreExprs
return matchExpr | python | def originalTextFor(expr, asString=True):
"""Helper to return the original, untokenized text for a given
expression. Useful to restore the parsed fields of an HTML start
tag into the raw tag text itself, or to revert separate tokens with
intervening whitespace back to the original matching input text. By
default, returns astring containing the original parsed text.
If the optional ``asString`` argument is passed as
``False``, then the return value is
a :class:`ParseResults` containing any results names that
were originally matched, and a single token containing the original
matched text from the input string. So if the expression passed to
:class:`originalTextFor` contains expressions with defined
results names, you must set ``asString`` to ``False`` if you
want to preserve those results name values.
Example::
src = "this is test <b> bold <i>text</i> </b> normal text "
for tag in ("b","i"):
opener,closer = makeHTMLTags(tag)
patt = originalTextFor(opener + SkipTo(closer) + closer)
print(patt.searchString(src)[0])
prints::
['<b> bold <i>text</i> </b>']
['<i>text</i>']
"""
locMarker = Empty().setParseAction(lambda s,loc,t: loc)
endlocMarker = locMarker.copy()
endlocMarker.callPreparse = False
matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end")
if asString:
extractText = lambda s,l,t: s[t._original_start:t._original_end]
else:
def extractText(s,l,t):
t[:] = [s[t.pop('_original_start'):t.pop('_original_end')]]
matchExpr.setParseAction(extractText)
matchExpr.ignoreExprs = expr.ignoreExprs
return matchExpr | [
"def",
"originalTextFor",
"(",
"expr",
",",
"asString",
"=",
"True",
")",
":",
"locMarker",
"=",
"Empty",
"(",
")",
".",
"setParseAction",
"(",
"lambda",
"s",
",",
"loc",
",",
"t",
":",
"loc",
")",
"endlocMarker",
"=",
"locMarker",
".",
"copy",
"(",
")",
"endlocMarker",
".",
"callPreparse",
"=",
"False",
"matchExpr",
"=",
"locMarker",
"(",
"\"_original_start\"",
")",
"+",
"expr",
"+",
"endlocMarker",
"(",
"\"_original_end\"",
")",
"if",
"asString",
":",
"extractText",
"=",
"lambda",
"s",
",",
"l",
",",
"t",
":",
"s",
"[",
"t",
".",
"_original_start",
":",
"t",
".",
"_original_end",
"]",
"else",
":",
"def",
"extractText",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"t",
"[",
":",
"]",
"=",
"[",
"s",
"[",
"t",
".",
"pop",
"(",
"'_original_start'",
")",
":",
"t",
".",
"pop",
"(",
"'_original_end'",
")",
"]",
"]",
"matchExpr",
".",
"setParseAction",
"(",
"extractText",
")",
"matchExpr",
".",
"ignoreExprs",
"=",
"expr",
".",
"ignoreExprs",
"return",
"matchExpr"
] | Helper to return the original, untokenized text for a given
expression. Useful to restore the parsed fields of an HTML start
tag into the raw tag text itself, or to revert separate tokens with
intervening whitespace back to the original matching input text. By
default, returns astring containing the original parsed text.
If the optional ``asString`` argument is passed as
``False``, then the return value is
a :class:`ParseResults` containing any results names that
were originally matched, and a single token containing the original
matched text from the input string. So if the expression passed to
:class:`originalTextFor` contains expressions with defined
results names, you must set ``asString`` to ``False`` if you
want to preserve those results name values.
Example::
src = "this is test <b> bold <i>text</i> </b> normal text "
for tag in ("b","i"):
opener,closer = makeHTMLTags(tag)
patt = originalTextFor(opener + SkipTo(closer) + closer)
print(patt.searchString(src)[0])
prints::
['<b> bold <i>text</i> </b>']
['<i>text</i>'] | [
"Helper",
"to",
"return",
"the",
"original",
"untokenized",
"text",
"for",
"a",
"given",
"expression",
".",
"Useful",
"to",
"restore",
"the",
"parsed",
"fields",
"of",
"an",
"HTML",
"start",
"tag",
"into",
"the",
"raw",
"tag",
"text",
"itself",
"or",
"to",
"revert",
"separate",
"tokens",
"with",
"intervening",
"whitespace",
"back",
"to",
"the",
"original",
"matching",
"input",
"text",
".",
"By",
"default",
"returns",
"astring",
"containing",
"the",
"original",
"parsed",
"text",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L5146-L5186 |
25,277 | pypa/pipenv | pipenv/vendor/pyparsing.py | locatedExpr | def locatedExpr(expr):
"""Helper to decorate a returned token with its starting and ending
locations in the input string.
This helper adds the following results names:
- locn_start = location where matched expression begins
- locn_end = location where matched expression ends
- value = the actual parsed results
Be careful if the input text contains ``<TAB>`` characters, you
may want to call :class:`ParserElement.parseWithTabs`
Example::
wd = Word(alphas)
for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"):
print(match)
prints::
[[0, 'ljsdf', 5]]
[[8, 'lksdjjf', 15]]
[[18, 'lkkjj', 23]]
"""
locator = Empty().setParseAction(lambda s,l,t: l)
return Group(locator("locn_start") + expr("value") + locator.copy().leaveWhitespace()("locn_end")) | python | def locatedExpr(expr):
"""Helper to decorate a returned token with its starting and ending
locations in the input string.
This helper adds the following results names:
- locn_start = location where matched expression begins
- locn_end = location where matched expression ends
- value = the actual parsed results
Be careful if the input text contains ``<TAB>`` characters, you
may want to call :class:`ParserElement.parseWithTabs`
Example::
wd = Word(alphas)
for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"):
print(match)
prints::
[[0, 'ljsdf', 5]]
[[8, 'lksdjjf', 15]]
[[18, 'lkkjj', 23]]
"""
locator = Empty().setParseAction(lambda s,l,t: l)
return Group(locator("locn_start") + expr("value") + locator.copy().leaveWhitespace()("locn_end")) | [
"def",
"locatedExpr",
"(",
"expr",
")",
":",
"locator",
"=",
"Empty",
"(",
")",
".",
"setParseAction",
"(",
"lambda",
"s",
",",
"l",
",",
"t",
":",
"l",
")",
"return",
"Group",
"(",
"locator",
"(",
"\"locn_start\"",
")",
"+",
"expr",
"(",
"\"value\"",
")",
"+",
"locator",
".",
"copy",
"(",
")",
".",
"leaveWhitespace",
"(",
")",
"(",
"\"locn_end\"",
")",
")"
] | Helper to decorate a returned token with its starting and ending
locations in the input string.
This helper adds the following results names:
- locn_start = location where matched expression begins
- locn_end = location where matched expression ends
- value = the actual parsed results
Be careful if the input text contains ``<TAB>`` characters, you
may want to call :class:`ParserElement.parseWithTabs`
Example::
wd = Word(alphas)
for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"):
print(match)
prints::
[[0, 'ljsdf', 5]]
[[8, 'lksdjjf', 15]]
[[18, 'lkkjj', 23]] | [
"Helper",
"to",
"decorate",
"a",
"returned",
"token",
"with",
"its",
"starting",
"and",
"ending",
"locations",
"in",
"the",
"input",
"string",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L5194-L5220 |
25,278 | pypa/pipenv | pipenv/vendor/pyparsing.py | matchOnlyAtCol | def matchOnlyAtCol(n):
"""Helper method for defining parse actions that require matching at
a specific column in the input text.
"""
def verifyCol(strg,locn,toks):
if col(locn,strg) != n:
raise ParseException(strg,locn,"matched token not at column %d" % n)
return verifyCol | python | def matchOnlyAtCol(n):
"""Helper method for defining parse actions that require matching at
a specific column in the input text.
"""
def verifyCol(strg,locn,toks):
if col(locn,strg) != n:
raise ParseException(strg,locn,"matched token not at column %d" % n)
return verifyCol | [
"def",
"matchOnlyAtCol",
"(",
"n",
")",
":",
"def",
"verifyCol",
"(",
"strg",
",",
"locn",
",",
"toks",
")",
":",
"if",
"col",
"(",
"locn",
",",
"strg",
")",
"!=",
"n",
":",
"raise",
"ParseException",
"(",
"strg",
",",
"locn",
",",
"\"matched token not at column %d\"",
"%",
"n",
")",
"return",
"verifyCol"
] | Helper method for defining parse actions that require matching at
a specific column in the input text. | [
"Helper",
"method",
"for",
"defining",
"parse",
"actions",
"that",
"require",
"matching",
"at",
"a",
"specific",
"column",
"in",
"the",
"input",
"text",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L5269-L5276 |
25,279 | pypa/pipenv | pipenv/vendor/pyparsing.py | ParseBaseException.markInputline | def markInputline( self, markerString = ">!<" ):
"""Extracts the exception line from the input string, and marks
the location of the exception with a special symbol.
"""
line_str = self.line
line_column = self.column - 1
if markerString:
line_str = "".join((line_str[:line_column],
markerString, line_str[line_column:]))
return line_str.strip() | python | def markInputline( self, markerString = ">!<" ):
"""Extracts the exception line from the input string, and marks
the location of the exception with a special symbol.
"""
line_str = self.line
line_column = self.column - 1
if markerString:
line_str = "".join((line_str[:line_column],
markerString, line_str[line_column:]))
return line_str.strip() | [
"def",
"markInputline",
"(",
"self",
",",
"markerString",
"=",
"\">!<\"",
")",
":",
"line_str",
"=",
"self",
".",
"line",
"line_column",
"=",
"self",
".",
"column",
"-",
"1",
"if",
"markerString",
":",
"line_str",
"=",
"\"\"",
".",
"join",
"(",
"(",
"line_str",
"[",
":",
"line_column",
"]",
",",
"markerString",
",",
"line_str",
"[",
"line_column",
":",
"]",
")",
")",
"return",
"line_str",
".",
"strip",
"(",
")"
] | Extracts the exception line from the input string, and marks
the location of the exception with a special symbol. | [
"Extracts",
"the",
"exception",
"line",
"from",
"the",
"input",
"string",
"and",
"marks",
"the",
"location",
"of",
"the",
"exception",
"with",
"a",
"special",
"symbol",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L279-L288 |
25,280 | pypa/pipenv | pipenv/vendor/pyparsing.py | ParseException.explain | def explain(exc, depth=16):
"""
Method to take an exception and translate the Python internal traceback into a list
of the pyparsing expressions that caused the exception to be raised.
Parameters:
- exc - exception raised during parsing (need not be a ParseException, in support
of Python exceptions that might be raised in a parse action)
- depth (default=16) - number of levels back in the stack trace to list expression
and function names; if None, the full stack trace names will be listed; if 0, only
the failing input line, marker, and exception string will be shown
Returns a multi-line string listing the ParserElements and/or function names in the
exception's stack trace.
Note: the diagnostic output will include string representations of the expressions
that failed to parse. These representations will be more helpful if you use `setName` to
give identifiable names to your expressions. Otherwise they will use the default string
forms, which may be cryptic to read.
explain() is only supported under Python 3.
"""
import inspect
if depth is None:
depth = sys.getrecursionlimit()
ret = []
if isinstance(exc, ParseBaseException):
ret.append(exc.line)
ret.append(' ' * (exc.col - 1) + '^')
ret.append("{0}: {1}".format(type(exc).__name__, exc))
if depth > 0:
callers = inspect.getinnerframes(exc.__traceback__, context=depth)
seen = set()
for i, ff in enumerate(callers[-depth:]):
frm = ff.frame
f_self = frm.f_locals.get('self', None)
if isinstance(f_self, ParserElement):
if frm.f_code.co_name not in ('parseImpl', '_parseNoCache'):
continue
if f_self in seen:
continue
seen.add(f_self)
self_type = type(f_self)
ret.append("{0}.{1} - {2}".format(self_type.__module__,
self_type.__name__,
f_self))
elif f_self is not None:
self_type = type(f_self)
ret.append("{0}.{1}".format(self_type.__module__,
self_type.__name__))
else:
code = frm.f_code
if code.co_name in ('wrapper', '<module>'):
continue
ret.append("{0}".format(code.co_name))
depth -= 1
if not depth:
break
return '\n'.join(ret) | python | def explain(exc, depth=16):
"""
Method to take an exception and translate the Python internal traceback into a list
of the pyparsing expressions that caused the exception to be raised.
Parameters:
- exc - exception raised during parsing (need not be a ParseException, in support
of Python exceptions that might be raised in a parse action)
- depth (default=16) - number of levels back in the stack trace to list expression
and function names; if None, the full stack trace names will be listed; if 0, only
the failing input line, marker, and exception string will be shown
Returns a multi-line string listing the ParserElements and/or function names in the
exception's stack trace.
Note: the diagnostic output will include string representations of the expressions
that failed to parse. These representations will be more helpful if you use `setName` to
give identifiable names to your expressions. Otherwise they will use the default string
forms, which may be cryptic to read.
explain() is only supported under Python 3.
"""
import inspect
if depth is None:
depth = sys.getrecursionlimit()
ret = []
if isinstance(exc, ParseBaseException):
ret.append(exc.line)
ret.append(' ' * (exc.col - 1) + '^')
ret.append("{0}: {1}".format(type(exc).__name__, exc))
if depth > 0:
callers = inspect.getinnerframes(exc.__traceback__, context=depth)
seen = set()
for i, ff in enumerate(callers[-depth:]):
frm = ff.frame
f_self = frm.f_locals.get('self', None)
if isinstance(f_self, ParserElement):
if frm.f_code.co_name not in ('parseImpl', '_parseNoCache'):
continue
if f_self in seen:
continue
seen.add(f_self)
self_type = type(f_self)
ret.append("{0}.{1} - {2}".format(self_type.__module__,
self_type.__name__,
f_self))
elif f_self is not None:
self_type = type(f_self)
ret.append("{0}.{1}".format(self_type.__module__,
self_type.__name__))
else:
code = frm.f_code
if code.co_name in ('wrapper', '<module>'):
continue
ret.append("{0}".format(code.co_name))
depth -= 1
if not depth:
break
return '\n'.join(ret) | [
"def",
"explain",
"(",
"exc",
",",
"depth",
"=",
"16",
")",
":",
"import",
"inspect",
"if",
"depth",
"is",
"None",
":",
"depth",
"=",
"sys",
".",
"getrecursionlimit",
"(",
")",
"ret",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"exc",
",",
"ParseBaseException",
")",
":",
"ret",
".",
"append",
"(",
"exc",
".",
"line",
")",
"ret",
".",
"append",
"(",
"' '",
"*",
"(",
"exc",
".",
"col",
"-",
"1",
")",
"+",
"'^'",
")",
"ret",
".",
"append",
"(",
"\"{0}: {1}\"",
".",
"format",
"(",
"type",
"(",
"exc",
")",
".",
"__name__",
",",
"exc",
")",
")",
"if",
"depth",
">",
"0",
":",
"callers",
"=",
"inspect",
".",
"getinnerframes",
"(",
"exc",
".",
"__traceback__",
",",
"context",
"=",
"depth",
")",
"seen",
"=",
"set",
"(",
")",
"for",
"i",
",",
"ff",
"in",
"enumerate",
"(",
"callers",
"[",
"-",
"depth",
":",
"]",
")",
":",
"frm",
"=",
"ff",
".",
"frame",
"f_self",
"=",
"frm",
".",
"f_locals",
".",
"get",
"(",
"'self'",
",",
"None",
")",
"if",
"isinstance",
"(",
"f_self",
",",
"ParserElement",
")",
":",
"if",
"frm",
".",
"f_code",
".",
"co_name",
"not",
"in",
"(",
"'parseImpl'",
",",
"'_parseNoCache'",
")",
":",
"continue",
"if",
"f_self",
"in",
"seen",
":",
"continue",
"seen",
".",
"add",
"(",
"f_self",
")",
"self_type",
"=",
"type",
"(",
"f_self",
")",
"ret",
".",
"append",
"(",
"\"{0}.{1} - {2}\"",
".",
"format",
"(",
"self_type",
".",
"__module__",
",",
"self_type",
".",
"__name__",
",",
"f_self",
")",
")",
"elif",
"f_self",
"is",
"not",
"None",
":",
"self_type",
"=",
"type",
"(",
"f_self",
")",
"ret",
".",
"append",
"(",
"\"{0}.{1}\"",
".",
"format",
"(",
"self_type",
".",
"__module__",
",",
"self_type",
".",
"__name__",
")",
")",
"else",
":",
"code",
"=",
"frm",
".",
"f_code",
"if",
"code",
".",
"co_name",
"in",
"(",
"'wrapper'",
",",
"'<module>'",
")",
":",
"continue",
"ret",
".",
"append",
"(",
"\"{0}\"",
".",
"format",
"(",
"code",
".",
"co_name",
")",
")",
"depth",
"-=",
"1",
"if",
"not",
"depth",
":",
"break",
"return",
"'\\n'",
".",
"join",
"(",
"ret",
")"
] | Method to take an exception and translate the Python internal traceback into a list
of the pyparsing expressions that caused the exception to be raised.
Parameters:
- exc - exception raised during parsing (need not be a ParseException, in support
of Python exceptions that might be raised in a parse action)
- depth (default=16) - number of levels back in the stack trace to list expression
and function names; if None, the full stack trace names will be listed; if 0, only
the failing input line, marker, and exception string will be shown
Returns a multi-line string listing the ParserElements and/or function names in the
exception's stack trace.
Note: the diagnostic output will include string representations of the expressions
that failed to parse. These representations will be more helpful if you use `setName` to
give identifiable names to your expressions. Otherwise they will use the default string
forms, which may be cryptic to read.
explain() is only supported under Python 3. | [
"Method",
"to",
"take",
"an",
"exception",
"and",
"translate",
"the",
"Python",
"internal",
"traceback",
"into",
"a",
"list",
"of",
"the",
"pyparsing",
"expressions",
"that",
"caused",
"the",
"exception",
"to",
"be",
"raised",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L316-L382 |
25,281 | pypa/pipenv | pipenv/vendor/pyparsing.py | ParseResults.extend | def extend( self, itemseq ):
"""
Add sequence of elements to end of ParseResults list of elements.
Example::
patt = OneOrMore(Word(alphas))
# use a parse action to append the reverse of the matched strings, to make a palindrome
def make_palindrome(tokens):
tokens.extend(reversed([t[::-1] for t in tokens]))
return ''.join(tokens)
print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'
"""
if isinstance(itemseq, ParseResults):
self += itemseq
else:
self.__toklist.extend(itemseq) | python | def extend( self, itemseq ):
"""
Add sequence of elements to end of ParseResults list of elements.
Example::
patt = OneOrMore(Word(alphas))
# use a parse action to append the reverse of the matched strings, to make a palindrome
def make_palindrome(tokens):
tokens.extend(reversed([t[::-1] for t in tokens]))
return ''.join(tokens)
print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'
"""
if isinstance(itemseq, ParseResults):
self += itemseq
else:
self.__toklist.extend(itemseq) | [
"def",
"extend",
"(",
"self",
",",
"itemseq",
")",
":",
"if",
"isinstance",
"(",
"itemseq",
",",
"ParseResults",
")",
":",
"self",
"+=",
"itemseq",
"else",
":",
"self",
".",
"__toklist",
".",
"extend",
"(",
"itemseq",
")"
] | Add sequence of elements to end of ParseResults list of elements.
Example::
patt = OneOrMore(Word(alphas))
# use a parse action to append the reverse of the matched strings, to make a palindrome
def make_palindrome(tokens):
tokens.extend(reversed([t[::-1] for t in tokens]))
return ''.join(tokens)
print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl' | [
"Add",
"sequence",
"of",
"elements",
"to",
"end",
"of",
"ParseResults",
"list",
"of",
"elements",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L736-L753 |
25,282 | pypa/pipenv | pipenv/vendor/pyparsing.py | ParseResults.asDict | def asDict( self ):
"""
Returns the named parse results as a nested dictionary.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})
result_dict = result.asDict()
print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}
# even though a ParseResults supports dict-like access, sometime you just need to have a dict
import json
print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable
print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"}
"""
if PY_3:
item_fn = self.items
else:
item_fn = self.iteritems
def toItem(obj):
if isinstance(obj, ParseResults):
if obj.haskeys():
return obj.asDict()
else:
return [toItem(v) for v in obj]
else:
return obj
return dict((k,toItem(v)) for k,v in item_fn()) | python | def asDict( self ):
"""
Returns the named parse results as a nested dictionary.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})
result_dict = result.asDict()
print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}
# even though a ParseResults supports dict-like access, sometime you just need to have a dict
import json
print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable
print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"}
"""
if PY_3:
item_fn = self.items
else:
item_fn = self.iteritems
def toItem(obj):
if isinstance(obj, ParseResults):
if obj.haskeys():
return obj.asDict()
else:
return [toItem(v) for v in obj]
else:
return obj
return dict((k,toItem(v)) for k,v in item_fn()) | [
"def",
"asDict",
"(",
"self",
")",
":",
"if",
"PY_3",
":",
"item_fn",
"=",
"self",
".",
"items",
"else",
":",
"item_fn",
"=",
"self",
".",
"iteritems",
"def",
"toItem",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"ParseResults",
")",
":",
"if",
"obj",
".",
"haskeys",
"(",
")",
":",
"return",
"obj",
".",
"asDict",
"(",
")",
"else",
":",
"return",
"[",
"toItem",
"(",
"v",
")",
"for",
"v",
"in",
"obj",
"]",
"else",
":",
"return",
"obj",
"return",
"dict",
"(",
"(",
"k",
",",
"toItem",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"item_fn",
"(",
")",
")"
] | Returns the named parse results as a nested dictionary.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})
result_dict = result.asDict()
print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}
# even though a ParseResults supports dict-like access, sometime you just need to have a dict
import json
print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable
print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"} | [
"Returns",
"the",
"named",
"parse",
"results",
"as",
"a",
"nested",
"dictionary",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L839-L873 |
25,283 | pypa/pipenv | pipenv/vendor/pyparsing.py | ParseResults.getName | def getName(self):
r"""
Returns the results name for this token expression. Useful when several
different expressions might match at a particular location.
Example::
integer = Word(nums)
ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
house_number_expr = Suppress('#') + Word(nums, alphanums)
user_data = (Group(house_number_expr)("house_number")
| Group(ssn_expr)("ssn")
| Group(integer)("age"))
user_info = OneOrMore(user_data)
result = user_info.parseString("22 111-22-3333 #221B")
for item in result:
print(item.getName(), ':', item[0])
prints::
age : 22
ssn : 111-22-3333
house_number : 221B
"""
if self.__name:
return self.__name
elif self.__parent:
par = self.__parent()
if par:
return par.__lookup(self)
else:
return None
elif (len(self) == 1 and
len(self.__tokdict) == 1 and
next(iter(self.__tokdict.values()))[0][1] in (0,-1)):
return next(iter(self.__tokdict.keys()))
else:
return None | python | def getName(self):
r"""
Returns the results name for this token expression. Useful when several
different expressions might match at a particular location.
Example::
integer = Word(nums)
ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
house_number_expr = Suppress('#') + Word(nums, alphanums)
user_data = (Group(house_number_expr)("house_number")
| Group(ssn_expr)("ssn")
| Group(integer)("age"))
user_info = OneOrMore(user_data)
result = user_info.parseString("22 111-22-3333 #221B")
for item in result:
print(item.getName(), ':', item[0])
prints::
age : 22
ssn : 111-22-3333
house_number : 221B
"""
if self.__name:
return self.__name
elif self.__parent:
par = self.__parent()
if par:
return par.__lookup(self)
else:
return None
elif (len(self) == 1 and
len(self.__tokdict) == 1 and
next(iter(self.__tokdict.values()))[0][1] in (0,-1)):
return next(iter(self.__tokdict.keys()))
else:
return None | [
"def",
"getName",
"(",
"self",
")",
":",
"if",
"self",
".",
"__name",
":",
"return",
"self",
".",
"__name",
"elif",
"self",
".",
"__parent",
":",
"par",
"=",
"self",
".",
"__parent",
"(",
")",
"if",
"par",
":",
"return",
"par",
".",
"__lookup",
"(",
"self",
")",
"else",
":",
"return",
"None",
"elif",
"(",
"len",
"(",
"self",
")",
"==",
"1",
"and",
"len",
"(",
"self",
".",
"__tokdict",
")",
"==",
"1",
"and",
"next",
"(",
"iter",
"(",
"self",
".",
"__tokdict",
".",
"values",
"(",
")",
")",
")",
"[",
"0",
"]",
"[",
"1",
"]",
"in",
"(",
"0",
",",
"-",
"1",
")",
")",
":",
"return",
"next",
"(",
"iter",
"(",
"self",
".",
"__tokdict",
".",
"keys",
"(",
")",
")",
")",
"else",
":",
"return",
"None"
] | r"""
Returns the results name for this token expression. Useful when several
different expressions might match at a particular location.
Example::
integer = Word(nums)
ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
house_number_expr = Suppress('#') + Word(nums, alphanums)
user_data = (Group(house_number_expr)("house_number")
| Group(ssn_expr)("ssn")
| Group(integer)("age"))
user_info = OneOrMore(user_data)
result = user_info.parseString("22 111-22-3333 #221B")
for item in result:
print(item.getName(), ':', item[0])
prints::
age : 22
ssn : 111-22-3333
house_number : 221B | [
"r",
"Returns",
"the",
"results",
"name",
"for",
"this",
"token",
"expression",
".",
"Useful",
"when",
"several",
"different",
"expressions",
"might",
"match",
"at",
"a",
"particular",
"location",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L954-L992 |
25,284 | pypa/pipenv | pipenv/vendor/pyparsing.py | ParserElement.setName | def setName( self, name ):
"""
Define name for this expression, makes debugging and exception messages clearer.
Example::
Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1)
Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1)
"""
self.name = name
self.errmsg = "Expected " + self.name
if hasattr(self,"exception"):
self.exception.msg = self.errmsg
return self | python | def setName( self, name ):
"""
Define name for this expression, makes debugging and exception messages clearer.
Example::
Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1)
Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1)
"""
self.name = name
self.errmsg = "Expected " + self.name
if hasattr(self,"exception"):
self.exception.msg = self.errmsg
return self | [
"def",
"setName",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"name",
"=",
"name",
"self",
".",
"errmsg",
"=",
"\"Expected \"",
"+",
"self",
".",
"name",
"if",
"hasattr",
"(",
"self",
",",
"\"exception\"",
")",
":",
"self",
".",
"exception",
".",
"msg",
"=",
"self",
".",
"errmsg",
"return",
"self"
] | Define name for this expression, makes debugging and exception messages clearer.
Example::
Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1)
Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1) | [
"Define",
"name",
"for",
"this",
"expression",
"makes",
"debugging",
"and",
"exception",
"messages",
"clearer",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L1329-L1342 |
25,285 | pypa/pipenv | pipenv/vendor/pyparsing.py | ParserElement.setWhitespaceChars | def setWhitespaceChars( self, chars ):
"""
Overrides the default whitespace chars
"""
self.skipWhitespace = True
self.whiteChars = chars
self.copyDefaultWhiteChars = False
return self | python | def setWhitespaceChars( self, chars ):
"""
Overrides the default whitespace chars
"""
self.skipWhitespace = True
self.whiteChars = chars
self.copyDefaultWhiteChars = False
return self | [
"def",
"setWhitespaceChars",
"(",
"self",
",",
"chars",
")",
":",
"self",
".",
"skipWhitespace",
"=",
"True",
"self",
".",
"whiteChars",
"=",
"chars",
"self",
".",
"copyDefaultWhiteChars",
"=",
"False",
"return",
"self"
] | Overrides the default whitespace chars | [
"Overrides",
"the",
"default",
"whitespace",
"chars"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L2235-L2242 |
25,286 | pypa/pipenv | pipenv/vendor/pyparsing.py | ParserElement.setDebugActions | def setDebugActions( self, startAction, successAction, exceptionAction ):
"""
Enable display of debugging messages while doing pattern matching.
"""
self.debugActions = (startAction or _defaultStartDebugAction,
successAction or _defaultSuccessDebugAction,
exceptionAction or _defaultExceptionDebugAction)
self.debug = True
return self | python | def setDebugActions( self, startAction, successAction, exceptionAction ):
"""
Enable display of debugging messages while doing pattern matching.
"""
self.debugActions = (startAction or _defaultStartDebugAction,
successAction or _defaultSuccessDebugAction,
exceptionAction or _defaultExceptionDebugAction)
self.debug = True
return self | [
"def",
"setDebugActions",
"(",
"self",
",",
"startAction",
",",
"successAction",
",",
"exceptionAction",
")",
":",
"self",
".",
"debugActions",
"=",
"(",
"startAction",
"or",
"_defaultStartDebugAction",
",",
"successAction",
"or",
"_defaultSuccessDebugAction",
",",
"exceptionAction",
"or",
"_defaultExceptionDebugAction",
")",
"self",
".",
"debug",
"=",
"True",
"return",
"self"
] | Enable display of debugging messages while doing pattern matching. | [
"Enable",
"display",
"of",
"debugging",
"messages",
"while",
"doing",
"pattern",
"matching",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L2277-L2285 |
25,287 | pypa/pipenv | pipenv/vendor/pyparsing.py | ParserElement.setDebug | def setDebug( self, flag=True ):
"""
Enable display of debugging messages while doing pattern matching.
Set ``flag`` to True to enable, False to disable.
Example::
wd = Word(alphas).setName("alphaword")
integer = Word(nums).setName("numword")
term = wd | integer
# turn on debugging for wd
wd.setDebug()
OneOrMore(term).parseString("abc 123 xyz 890")
prints::
Match alphaword at loc 0(1,1)
Matched alphaword -> ['abc']
Match alphaword at loc 3(1,4)
Exception raised:Expected alphaword (at char 4), (line:1, col:5)
Match alphaword at loc 7(1,8)
Matched alphaword -> ['xyz']
Match alphaword at loc 11(1,12)
Exception raised:Expected alphaword (at char 12), (line:1, col:13)
Match alphaword at loc 15(1,16)
Exception raised:Expected alphaword (at char 15), (line:1, col:16)
The output shown is that produced by the default debug actions - custom debug actions can be
specified using :class:`setDebugActions`. Prior to attempting
to match the ``wd`` expression, the debugging message ``"Match <exprname> at loc <n>(<line>,<col>)"``
is shown. Then if the parse succeeds, a ``"Matched"`` message is shown, or an ``"Exception raised"``
message is shown. Also note the use of :class:`setName` to assign a human-readable name to the expression,
which makes debugging and exception messages easier to understand - for instance, the default
name created for the :class:`Word` expression without calling ``setName`` is ``"W:(ABCD...)"``.
"""
if flag:
self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction )
else:
self.debug = False
return self | python | def setDebug( self, flag=True ):
"""
Enable display of debugging messages while doing pattern matching.
Set ``flag`` to True to enable, False to disable.
Example::
wd = Word(alphas).setName("alphaword")
integer = Word(nums).setName("numword")
term = wd | integer
# turn on debugging for wd
wd.setDebug()
OneOrMore(term).parseString("abc 123 xyz 890")
prints::
Match alphaword at loc 0(1,1)
Matched alphaword -> ['abc']
Match alphaword at loc 3(1,4)
Exception raised:Expected alphaword (at char 4), (line:1, col:5)
Match alphaword at loc 7(1,8)
Matched alphaword -> ['xyz']
Match alphaword at loc 11(1,12)
Exception raised:Expected alphaword (at char 12), (line:1, col:13)
Match alphaword at loc 15(1,16)
Exception raised:Expected alphaword (at char 15), (line:1, col:16)
The output shown is that produced by the default debug actions - custom debug actions can be
specified using :class:`setDebugActions`. Prior to attempting
to match the ``wd`` expression, the debugging message ``"Match <exprname> at loc <n>(<line>,<col>)"``
is shown. Then if the parse succeeds, a ``"Matched"`` message is shown, or an ``"Exception raised"``
message is shown. Also note the use of :class:`setName` to assign a human-readable name to the expression,
which makes debugging and exception messages easier to understand - for instance, the default
name created for the :class:`Word` expression without calling ``setName`` is ``"W:(ABCD...)"``.
"""
if flag:
self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction )
else:
self.debug = False
return self | [
"def",
"setDebug",
"(",
"self",
",",
"flag",
"=",
"True",
")",
":",
"if",
"flag",
":",
"self",
".",
"setDebugActions",
"(",
"_defaultStartDebugAction",
",",
"_defaultSuccessDebugAction",
",",
"_defaultExceptionDebugAction",
")",
"else",
":",
"self",
".",
"debug",
"=",
"False",
"return",
"self"
] | Enable display of debugging messages while doing pattern matching.
Set ``flag`` to True to enable, False to disable.
Example::
wd = Word(alphas).setName("alphaword")
integer = Word(nums).setName("numword")
term = wd | integer
# turn on debugging for wd
wd.setDebug()
OneOrMore(term).parseString("abc 123 xyz 890")
prints::
Match alphaword at loc 0(1,1)
Matched alphaword -> ['abc']
Match alphaword at loc 3(1,4)
Exception raised:Expected alphaword (at char 4), (line:1, col:5)
Match alphaword at loc 7(1,8)
Matched alphaword -> ['xyz']
Match alphaword at loc 11(1,12)
Exception raised:Expected alphaword (at char 12), (line:1, col:13)
Match alphaword at loc 15(1,16)
Exception raised:Expected alphaword (at char 15), (line:1, col:16)
The output shown is that produced by the default debug actions - custom debug actions can be
specified using :class:`setDebugActions`. Prior to attempting
to match the ``wd`` expression, the debugging message ``"Match <exprname> at loc <n>(<line>,<col>)"``
is shown. Then if the parse succeeds, a ``"Matched"`` message is shown, or an ``"Exception raised"``
message is shown. Also note the use of :class:`setName` to assign a human-readable name to the expression,
which makes debugging and exception messages easier to understand - for instance, the default
name created for the :class:`Word` expression without calling ``setName`` is ``"W:(ABCD...)"``. | [
"Enable",
"display",
"of",
"debugging",
"messages",
"while",
"doing",
"pattern",
"matching",
".",
"Set",
"flag",
"to",
"True",
"to",
"enable",
"False",
"to",
"disable",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L2287-L2328 |
25,288 | pypa/pipenv | pipenv/vendor/pyparsing.py | ParseExpression.leaveWhitespace | def leaveWhitespace( self ):
"""Extends ``leaveWhitespace`` defined in base class, and also invokes ``leaveWhitespace`` on
all contained expressions."""
self.skipWhitespace = False
self.exprs = [ e.copy() for e in self.exprs ]
for e in self.exprs:
e.leaveWhitespace()
return self | python | def leaveWhitespace( self ):
"""Extends ``leaveWhitespace`` defined in base class, and also invokes ``leaveWhitespace`` on
all contained expressions."""
self.skipWhitespace = False
self.exprs = [ e.copy() for e in self.exprs ]
for e in self.exprs:
e.leaveWhitespace()
return self | [
"def",
"leaveWhitespace",
"(",
"self",
")",
":",
"self",
".",
"skipWhitespace",
"=",
"False",
"self",
".",
"exprs",
"=",
"[",
"e",
".",
"copy",
"(",
")",
"for",
"e",
"in",
"self",
".",
"exprs",
"]",
"for",
"e",
"in",
"self",
".",
"exprs",
":",
"e",
".",
"leaveWhitespace",
"(",
")",
"return",
"self"
] | Extends ``leaveWhitespace`` defined in base class, and also invokes ``leaveWhitespace`` on
all contained expressions. | [
"Extends",
"leaveWhitespace",
"defined",
"in",
"base",
"class",
"and",
"also",
"invokes",
"leaveWhitespace",
"on",
"all",
"contained",
"expressions",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L3586-L3593 |
25,289 | pypa/pipenv | pipenv/vendor/pyparsing.py | pyparsing_common.convertToDate | def convertToDate(fmt="%Y-%m-%d"):
"""
Helper to create a parse action for converting parsed date string to Python datetime.date
Params -
- fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``)
Example::
date_expr = pyparsing_common.iso8601_date.copy()
date_expr.setParseAction(pyparsing_common.convertToDate())
print(date_expr.parseString("1999-12-31"))
prints::
[datetime.date(1999, 12, 31)]
"""
def cvt_fn(s,l,t):
try:
return datetime.strptime(t[0], fmt).date()
except ValueError as ve:
raise ParseException(s, l, str(ve))
return cvt_fn | python | def convertToDate(fmt="%Y-%m-%d"):
"""
Helper to create a parse action for converting parsed date string to Python datetime.date
Params -
- fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``)
Example::
date_expr = pyparsing_common.iso8601_date.copy()
date_expr.setParseAction(pyparsing_common.convertToDate())
print(date_expr.parseString("1999-12-31"))
prints::
[datetime.date(1999, 12, 31)]
"""
def cvt_fn(s,l,t):
try:
return datetime.strptime(t[0], fmt).date()
except ValueError as ve:
raise ParseException(s, l, str(ve))
return cvt_fn | [
"def",
"convertToDate",
"(",
"fmt",
"=",
"\"%Y-%m-%d\"",
")",
":",
"def",
"cvt_fn",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"try",
":",
"return",
"datetime",
".",
"strptime",
"(",
"t",
"[",
"0",
"]",
",",
"fmt",
")",
".",
"date",
"(",
")",
"except",
"ValueError",
"as",
"ve",
":",
"raise",
"ParseException",
"(",
"s",
",",
"l",
",",
"str",
"(",
"ve",
")",
")",
"return",
"cvt_fn"
] | Helper to create a parse action for converting parsed date string to Python datetime.date
Params -
- fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``)
Example::
date_expr = pyparsing_common.iso8601_date.copy()
date_expr.setParseAction(pyparsing_common.convertToDate())
print(date_expr.parseString("1999-12-31"))
prints::
[datetime.date(1999, 12, 31)] | [
"Helper",
"to",
"create",
"a",
"parse",
"action",
"for",
"converting",
"parsed",
"date",
"string",
"to",
"Python",
"datetime",
".",
"date"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L6136-L6158 |
25,290 | pypa/pipenv | pipenv/vendor/pyparsing.py | pyparsing_common.convertToDatetime | def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"):
"""Helper to create a parse action for converting parsed
datetime string to Python datetime.datetime
Params -
- fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%dT%H:%M:%S.%f"``)
Example::
dt_expr = pyparsing_common.iso8601_datetime.copy()
dt_expr.setParseAction(pyparsing_common.convertToDatetime())
print(dt_expr.parseString("1999-12-31T23:59:59.999"))
prints::
[datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
"""
def cvt_fn(s,l,t):
try:
return datetime.strptime(t[0], fmt)
except ValueError as ve:
raise ParseException(s, l, str(ve))
return cvt_fn | python | def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"):
"""Helper to create a parse action for converting parsed
datetime string to Python datetime.datetime
Params -
- fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%dT%H:%M:%S.%f"``)
Example::
dt_expr = pyparsing_common.iso8601_datetime.copy()
dt_expr.setParseAction(pyparsing_common.convertToDatetime())
print(dt_expr.parseString("1999-12-31T23:59:59.999"))
prints::
[datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
"""
def cvt_fn(s,l,t):
try:
return datetime.strptime(t[0], fmt)
except ValueError as ve:
raise ParseException(s, l, str(ve))
return cvt_fn | [
"def",
"convertToDatetime",
"(",
"fmt",
"=",
"\"%Y-%m-%dT%H:%M:%S.%f\"",
")",
":",
"def",
"cvt_fn",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"try",
":",
"return",
"datetime",
".",
"strptime",
"(",
"t",
"[",
"0",
"]",
",",
"fmt",
")",
"except",
"ValueError",
"as",
"ve",
":",
"raise",
"ParseException",
"(",
"s",
",",
"l",
",",
"str",
"(",
"ve",
")",
")",
"return",
"cvt_fn"
] | Helper to create a parse action for converting parsed
datetime string to Python datetime.datetime
Params -
- fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%dT%H:%M:%S.%f"``)
Example::
dt_expr = pyparsing_common.iso8601_datetime.copy()
dt_expr.setParseAction(pyparsing_common.convertToDatetime())
print(dt_expr.parseString("1999-12-31T23:59:59.999"))
prints::
[datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)] | [
"Helper",
"to",
"create",
"a",
"parse",
"action",
"for",
"converting",
"parsed",
"datetime",
"string",
"to",
"Python",
"datetime",
".",
"datetime"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L6161-L6183 |
25,291 | pypa/pipenv | pipenv/patched/notpip/_internal/index.py | _match_vcs_scheme | def _match_vcs_scheme(url):
# type: (str) -> Optional[str]
"""Look for VCS schemes in the URL.
Returns the matched VCS scheme, or None if there's no match.
"""
from pipenv.patched.notpip._internal.vcs import VcsSupport
for scheme in VcsSupport.schemes:
if url.lower().startswith(scheme) and url[len(scheme)] in '+:':
return scheme
return None | python | def _match_vcs_scheme(url):
# type: (str) -> Optional[str]
"""Look for VCS schemes in the URL.
Returns the matched VCS scheme, or None if there's no match.
"""
from pipenv.patched.notpip._internal.vcs import VcsSupport
for scheme in VcsSupport.schemes:
if url.lower().startswith(scheme) and url[len(scheme)] in '+:':
return scheme
return None | [
"def",
"_match_vcs_scheme",
"(",
"url",
")",
":",
"# type: (str) -> Optional[str]",
"from",
"pipenv",
".",
"patched",
".",
"notpip",
".",
"_internal",
".",
"vcs",
"import",
"VcsSupport",
"for",
"scheme",
"in",
"VcsSupport",
".",
"schemes",
":",
"if",
"url",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"scheme",
")",
"and",
"url",
"[",
"len",
"(",
"scheme",
")",
"]",
"in",
"'+:'",
":",
"return",
"scheme",
"return",
"None"
] | Look for VCS schemes in the URL.
Returns the matched VCS scheme, or None if there's no match. | [
"Look",
"for",
"VCS",
"schemes",
"in",
"the",
"URL",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/index.py#L77-L87 |
25,292 | pypa/pipenv | pipenv/patched/notpip/_internal/index.py | _is_url_like_archive | def _is_url_like_archive(url):
# type: (str) -> bool
"""Return whether the URL looks like an archive.
"""
filename = Link(url).filename
for bad_ext in ARCHIVE_EXTENSIONS:
if filename.endswith(bad_ext):
return True
return False | python | def _is_url_like_archive(url):
# type: (str) -> bool
"""Return whether the URL looks like an archive.
"""
filename = Link(url).filename
for bad_ext in ARCHIVE_EXTENSIONS:
if filename.endswith(bad_ext):
return True
return False | [
"def",
"_is_url_like_archive",
"(",
"url",
")",
":",
"# type: (str) -> bool",
"filename",
"=",
"Link",
"(",
"url",
")",
".",
"filename",
"for",
"bad_ext",
"in",
"ARCHIVE_EXTENSIONS",
":",
"if",
"filename",
".",
"endswith",
"(",
"bad_ext",
")",
":",
"return",
"True",
"return",
"False"
] | Return whether the URL looks like an archive. | [
"Return",
"whether",
"the",
"URL",
"looks",
"like",
"an",
"archive",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/index.py#L90-L98 |
25,293 | pypa/pipenv | pipenv/patched/notpip/_internal/index.py | _ensure_html_header | def _ensure_html_header(response):
# type: (Response) -> None
"""Check the Content-Type header to ensure the response contains HTML.
Raises `_NotHTML` if the content type is not text/html.
"""
content_type = response.headers.get("Content-Type", "")
if not content_type.lower().startswith("text/html"):
raise _NotHTML(content_type, response.request.method) | python | def _ensure_html_header(response):
# type: (Response) -> None
"""Check the Content-Type header to ensure the response contains HTML.
Raises `_NotHTML` if the content type is not text/html.
"""
content_type = response.headers.get("Content-Type", "")
if not content_type.lower().startswith("text/html"):
raise _NotHTML(content_type, response.request.method) | [
"def",
"_ensure_html_header",
"(",
"response",
")",
":",
"# type: (Response) -> None",
"content_type",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"\"Content-Type\"",
",",
"\"\"",
")",
"if",
"not",
"content_type",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"\"text/html\"",
")",
":",
"raise",
"_NotHTML",
"(",
"content_type",
",",
"response",
".",
"request",
".",
"method",
")"
] | Check the Content-Type header to ensure the response contains HTML.
Raises `_NotHTML` if the content type is not text/html. | [
"Check",
"the",
"Content",
"-",
"Type",
"header",
"to",
"ensure",
"the",
"response",
"contains",
"HTML",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/index.py#L109-L117 |
25,294 | pypa/pipenv | pipenv/patched/notpip/_internal/index.py | _ensure_html_response | def _ensure_html_response(url, session):
# type: (str, PipSession) -> None
"""Send a HEAD request to the URL, and ensure the response contains HTML.
Raises `_NotHTTP` if the URL is not available for a HEAD request, or
`_NotHTML` if the content type is not text/html.
"""
scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url)
if scheme not in {'http', 'https'}:
raise _NotHTTP()
resp = session.head(url, allow_redirects=True)
resp.raise_for_status()
_ensure_html_header(resp) | python | def _ensure_html_response(url, session):
# type: (str, PipSession) -> None
"""Send a HEAD request to the URL, and ensure the response contains HTML.
Raises `_NotHTTP` if the URL is not available for a HEAD request, or
`_NotHTML` if the content type is not text/html.
"""
scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url)
if scheme not in {'http', 'https'}:
raise _NotHTTP()
resp = session.head(url, allow_redirects=True)
resp.raise_for_status()
_ensure_html_header(resp) | [
"def",
"_ensure_html_response",
"(",
"url",
",",
"session",
")",
":",
"# type: (str, PipSession) -> None",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"fragment",
"=",
"urllib_parse",
".",
"urlsplit",
"(",
"url",
")",
"if",
"scheme",
"not",
"in",
"{",
"'http'",
",",
"'https'",
"}",
":",
"raise",
"_NotHTTP",
"(",
")",
"resp",
"=",
"session",
".",
"head",
"(",
"url",
",",
"allow_redirects",
"=",
"True",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"_ensure_html_header",
"(",
"resp",
")"
] | Send a HEAD request to the URL, and ensure the response contains HTML.
Raises `_NotHTTP` if the URL is not available for a HEAD request, or
`_NotHTML` if the content type is not text/html. | [
"Send",
"a",
"HEAD",
"request",
"to",
"the",
"URL",
"and",
"ensure",
"the",
"response",
"contains",
"HTML",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/index.py#L124-L138 |
25,295 | pypa/pipenv | pipenv/patched/notpip/_internal/index.py | _get_html_response | def _get_html_response(url, session):
# type: (str, PipSession) -> Response
"""Access an HTML page with GET, and return the response.
This consists of three parts:
1. If the URL looks suspiciously like an archive, send a HEAD first to
check the Content-Type is HTML, to avoid downloading a large file.
Raise `_NotHTTP` if the content type cannot be determined, or
`_NotHTML` if it is not HTML.
2. Actually perform the request. Raise HTTP exceptions on network failures.
3. Check the Content-Type header to make sure we got HTML, and raise
`_NotHTML` otherwise.
"""
if _is_url_like_archive(url):
_ensure_html_response(url, session=session)
logger.debug('Getting page %s', url)
resp = session.get(
url,
headers={
"Accept": "text/html",
# We don't want to blindly returned cached data for
# /simple/, because authors generally expecting that
# twine upload && pip install will function, but if
# they've done a pip install in the last ~10 minutes
# it won't. Thus by setting this to zero we will not
# blindly use any cached data, however the benefit of
# using max-age=0 instead of no-cache, is that we will
# still support conditional requests, so we will still
# minimize traffic sent in cases where the page hasn't
# changed at all, we will just always incur the round
# trip for the conditional GET now instead of only
# once per 10 minutes.
# For more information, please see pypa/pip#5670.
"Cache-Control": "max-age=0",
},
)
resp.raise_for_status()
# The check for archives above only works if the url ends with
# something that looks like an archive. However that is not a
# requirement of an url. Unless we issue a HEAD request on every
# url we cannot know ahead of time for sure if something is HTML
# or not. However we can check after we've downloaded it.
_ensure_html_header(resp)
return resp | python | def _get_html_response(url, session):
# type: (str, PipSession) -> Response
"""Access an HTML page with GET, and return the response.
This consists of three parts:
1. If the URL looks suspiciously like an archive, send a HEAD first to
check the Content-Type is HTML, to avoid downloading a large file.
Raise `_NotHTTP` if the content type cannot be determined, or
`_NotHTML` if it is not HTML.
2. Actually perform the request. Raise HTTP exceptions on network failures.
3. Check the Content-Type header to make sure we got HTML, and raise
`_NotHTML` otherwise.
"""
if _is_url_like_archive(url):
_ensure_html_response(url, session=session)
logger.debug('Getting page %s', url)
resp = session.get(
url,
headers={
"Accept": "text/html",
# We don't want to blindly returned cached data for
# /simple/, because authors generally expecting that
# twine upload && pip install will function, but if
# they've done a pip install in the last ~10 minutes
# it won't. Thus by setting this to zero we will not
# blindly use any cached data, however the benefit of
# using max-age=0 instead of no-cache, is that we will
# still support conditional requests, so we will still
# minimize traffic sent in cases where the page hasn't
# changed at all, we will just always incur the round
# trip for the conditional GET now instead of only
# once per 10 minutes.
# For more information, please see pypa/pip#5670.
"Cache-Control": "max-age=0",
},
)
resp.raise_for_status()
# The check for archives above only works if the url ends with
# something that looks like an archive. However that is not a
# requirement of an url. Unless we issue a HEAD request on every
# url we cannot know ahead of time for sure if something is HTML
# or not. However we can check after we've downloaded it.
_ensure_html_header(resp)
return resp | [
"def",
"_get_html_response",
"(",
"url",
",",
"session",
")",
":",
"# type: (str, PipSession) -> Response",
"if",
"_is_url_like_archive",
"(",
"url",
")",
":",
"_ensure_html_response",
"(",
"url",
",",
"session",
"=",
"session",
")",
"logger",
".",
"debug",
"(",
"'Getting page %s'",
",",
"url",
")",
"resp",
"=",
"session",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"{",
"\"Accept\"",
":",
"\"text/html\"",
",",
"# We don't want to blindly returned cached data for",
"# /simple/, because authors generally expecting that",
"# twine upload && pip install will function, but if",
"# they've done a pip install in the last ~10 minutes",
"# it won't. Thus by setting this to zero we will not",
"# blindly use any cached data, however the benefit of",
"# using max-age=0 instead of no-cache, is that we will",
"# still support conditional requests, so we will still",
"# minimize traffic sent in cases where the page hasn't",
"# changed at all, we will just always incur the round",
"# trip for the conditional GET now instead of only",
"# once per 10 minutes.",
"# For more information, please see pypa/pip#5670.",
"\"Cache-Control\"",
":",
"\"max-age=0\"",
",",
"}",
",",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"# The check for archives above only works if the url ends with",
"# something that looks like an archive. However that is not a",
"# requirement of an url. Unless we issue a HEAD request on every",
"# url we cannot know ahead of time for sure if something is HTML",
"# or not. However we can check after we've downloaded it.",
"_ensure_html_header",
"(",
"resp",
")",
"return",
"resp"
] | Access an HTML page with GET, and return the response.
This consists of three parts:
1. If the URL looks suspiciously like an archive, send a HEAD first to
check the Content-Type is HTML, to avoid downloading a large file.
Raise `_NotHTTP` if the content type cannot be determined, or
`_NotHTML` if it is not HTML.
2. Actually perform the request. Raise HTTP exceptions on network failures.
3. Check the Content-Type header to make sure we got HTML, and raise
`_NotHTML` otherwise. | [
"Access",
"an",
"HTML",
"page",
"with",
"GET",
"and",
"return",
"the",
"response",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/index.py#L141-L189 |
25,296 | pypa/pipenv | pipenv/patched/notpip/_internal/index.py | _find_name_version_sep | def _find_name_version_sep(egg_info, canonical_name):
# type: (str, str) -> int
"""Find the separator's index based on the package's canonical name.
`egg_info` must be an egg info string for the given package, and
`canonical_name` must be the package's canonical name.
This function is needed since the canonicalized name does not necessarily
have the same length as the egg info's name part. An example::
>>> egg_info = 'foo__bar-1.0'
>>> canonical_name = 'foo-bar'
>>> _find_name_version_sep(egg_info, canonical_name)
8
"""
# Project name and version must be separated by one single dash. Find all
# occurrences of dashes; if the string in front of it matches the canonical
# name, this is the one separating the name and version parts.
for i, c in enumerate(egg_info):
if c != "-":
continue
if canonicalize_name(egg_info[:i]) == canonical_name:
return i
raise ValueError("{} does not match {}".format(egg_info, canonical_name)) | python | def _find_name_version_sep(egg_info, canonical_name):
# type: (str, str) -> int
"""Find the separator's index based on the package's canonical name.
`egg_info` must be an egg info string for the given package, and
`canonical_name` must be the package's canonical name.
This function is needed since the canonicalized name does not necessarily
have the same length as the egg info's name part. An example::
>>> egg_info = 'foo__bar-1.0'
>>> canonical_name = 'foo-bar'
>>> _find_name_version_sep(egg_info, canonical_name)
8
"""
# Project name and version must be separated by one single dash. Find all
# occurrences of dashes; if the string in front of it matches the canonical
# name, this is the one separating the name and version parts.
for i, c in enumerate(egg_info):
if c != "-":
continue
if canonicalize_name(egg_info[:i]) == canonical_name:
return i
raise ValueError("{} does not match {}".format(egg_info, canonical_name)) | [
"def",
"_find_name_version_sep",
"(",
"egg_info",
",",
"canonical_name",
")",
":",
"# type: (str, str) -> int",
"# Project name and version must be separated by one single dash. Find all",
"# occurrences of dashes; if the string in front of it matches the canonical",
"# name, this is the one separating the name and version parts.",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"egg_info",
")",
":",
"if",
"c",
"!=",
"\"-\"",
":",
"continue",
"if",
"canonicalize_name",
"(",
"egg_info",
"[",
":",
"i",
"]",
")",
"==",
"canonical_name",
":",
"return",
"i",
"raise",
"ValueError",
"(",
"\"{} does not match {}\"",
".",
"format",
"(",
"egg_info",
",",
"canonical_name",
")",
")"
] | Find the separator's index based on the package's canonical name.
`egg_info` must be an egg info string for the given package, and
`canonical_name` must be the package's canonical name.
This function is needed since the canonicalized name does not necessarily
have the same length as the egg info's name part. An example::
>>> egg_info = 'foo__bar-1.0'
>>> canonical_name = 'foo-bar'
>>> _find_name_version_sep(egg_info, canonical_name)
8 | [
"Find",
"the",
"separator",
"s",
"index",
"based",
"on",
"the",
"package",
"s",
"canonical",
"name",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/index.py#L896-L919 |
25,297 | pypa/pipenv | pipenv/patched/notpip/_internal/index.py | _egg_info_matches | def _egg_info_matches(egg_info, canonical_name):
# type: (str, str) -> Optional[str]
"""Pull the version part out of a string.
:param egg_info: The string to parse. E.g. foo-2.1
:param canonical_name: The canonicalized name of the package this
belongs to.
"""
try:
version_start = _find_name_version_sep(egg_info, canonical_name) + 1
except ValueError:
return None
version = egg_info[version_start:]
if not version:
return None
return version | python | def _egg_info_matches(egg_info, canonical_name):
# type: (str, str) -> Optional[str]
"""Pull the version part out of a string.
:param egg_info: The string to parse. E.g. foo-2.1
:param canonical_name: The canonicalized name of the package this
belongs to.
"""
try:
version_start = _find_name_version_sep(egg_info, canonical_name) + 1
except ValueError:
return None
version = egg_info[version_start:]
if not version:
return None
return version | [
"def",
"_egg_info_matches",
"(",
"egg_info",
",",
"canonical_name",
")",
":",
"# type: (str, str) -> Optional[str]",
"try",
":",
"version_start",
"=",
"_find_name_version_sep",
"(",
"egg_info",
",",
"canonical_name",
")",
"+",
"1",
"except",
"ValueError",
":",
"return",
"None",
"version",
"=",
"egg_info",
"[",
"version_start",
":",
"]",
"if",
"not",
"version",
":",
"return",
"None",
"return",
"version"
] | Pull the version part out of a string.
:param egg_info: The string to parse. E.g. foo-2.1
:param canonical_name: The canonicalized name of the package this
belongs to. | [
"Pull",
"the",
"version",
"part",
"out",
"of",
"a",
"string",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/index.py#L922-L937 |
25,298 | pypa/pipenv | pipenv/patched/notpip/_internal/index.py | _determine_base_url | def _determine_base_url(document, page_url):
"""Determine the HTML document's base URL.
This looks for a ``<base>`` tag in the HTML document. If present, its href
attribute denotes the base URL of anchor tags in the document. If there is
no such tag (or if it does not have a valid href attribute), the HTML
file's URL is used as the base URL.
:param document: An HTML document representation. The current
implementation expects the result of ``html5lib.parse()``.
:param page_url: The URL of the HTML document.
"""
for base in document.findall(".//base"):
href = base.get("href")
if href is not None:
return href
return page_url | python | def _determine_base_url(document, page_url):
"""Determine the HTML document's base URL.
This looks for a ``<base>`` tag in the HTML document. If present, its href
attribute denotes the base URL of anchor tags in the document. If there is
no such tag (or if it does not have a valid href attribute), the HTML
file's URL is used as the base URL.
:param document: An HTML document representation. The current
implementation expects the result of ``html5lib.parse()``.
:param page_url: The URL of the HTML document.
"""
for base in document.findall(".//base"):
href = base.get("href")
if href is not None:
return href
return page_url | [
"def",
"_determine_base_url",
"(",
"document",
",",
"page_url",
")",
":",
"for",
"base",
"in",
"document",
".",
"findall",
"(",
"\".//base\"",
")",
":",
"href",
"=",
"base",
".",
"get",
"(",
"\"href\"",
")",
"if",
"href",
"is",
"not",
"None",
":",
"return",
"href",
"return",
"page_url"
] | Determine the HTML document's base URL.
This looks for a ``<base>`` tag in the HTML document. If present, its href
attribute denotes the base URL of anchor tags in the document. If there is
no such tag (or if it does not have a valid href attribute), the HTML
file's URL is used as the base URL.
:param document: An HTML document representation. The current
implementation expects the result of ``html5lib.parse()``.
:param page_url: The URL of the HTML document. | [
"Determine",
"the",
"HTML",
"document",
"s",
"base",
"URL",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/index.py#L940-L956 |
25,299 | pypa/pipenv | pipenv/patched/notpip/_internal/index.py | _get_encoding_from_headers | def _get_encoding_from_headers(headers):
"""Determine if we have any encoding information in our headers.
"""
if headers and "Content-Type" in headers:
content_type, params = cgi.parse_header(headers["Content-Type"])
if "charset" in params:
return params['charset']
return None | python | def _get_encoding_from_headers(headers):
"""Determine if we have any encoding information in our headers.
"""
if headers and "Content-Type" in headers:
content_type, params = cgi.parse_header(headers["Content-Type"])
if "charset" in params:
return params['charset']
return None | [
"def",
"_get_encoding_from_headers",
"(",
"headers",
")",
":",
"if",
"headers",
"and",
"\"Content-Type\"",
"in",
"headers",
":",
"content_type",
",",
"params",
"=",
"cgi",
".",
"parse_header",
"(",
"headers",
"[",
"\"Content-Type\"",
"]",
")",
"if",
"\"charset\"",
"in",
"params",
":",
"return",
"params",
"[",
"'charset'",
"]",
"return",
"None"
] | Determine if we have any encoding information in our headers. | [
"Determine",
"if",
"we",
"have",
"any",
"encoding",
"information",
"in",
"our",
"headers",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/index.py#L959-L966 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.