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,000 | pypa/pipenv | pipenv/vendor/attr/_make.py | _CountingAttr.default | def default(self, meth):
"""
Decorator that allows to set the default for an attribute.
Returns *meth* unchanged.
:raises DefaultAlreadySetError: If default has been set before.
.. versionadded:: 17.1.0
"""
if self._default is not NOTHING:
raise DefaultAlreadySetError()
self._default = Factory(meth, takes_self=True)
return meth | python | def default(self, meth):
"""
Decorator that allows to set the default for an attribute.
Returns *meth* unchanged.
:raises DefaultAlreadySetError: If default has been set before.
.. versionadded:: 17.1.0
"""
if self._default is not NOTHING:
raise DefaultAlreadySetError()
self._default = Factory(meth, takes_self=True)
return meth | [
"def",
"default",
"(",
"self",
",",
"meth",
")",
":",
"if",
"self",
".",
"_default",
"is",
"not",
"NOTHING",
":",
"raise",
"DefaultAlreadySetError",
"(",
")",
"self",
".",
"_default",
"=",
"Factory",
"(",
"meth",
",",
"takes_self",
"=",
"True",
")",
"return",
"meth"
] | Decorator that allows to set the default for an attribute.
Returns *meth* unchanged.
:raises DefaultAlreadySetError: If default has been set before.
.. versionadded:: 17.1.0 | [
"Decorator",
"that",
"allows",
"to",
"set",
"the",
"default",
"for",
"an",
"attribute",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/_make.py#L1948-L1963 |
25,001 | pypa/pipenv | pipenv/vendor/delegator.py | _expand_args | def _expand_args(command):
"""Parses command strings and returns a Popen-ready list."""
# Prepare arguments.
if isinstance(command, STR_TYPES):
if sys.version_info[0] == 2:
splitter = shlex.shlex(command.encode("utf-8"))
elif sys.version_info[0] == 3:
splitter = shlex.shlex(command)
else:
splitter = shlex.shlex(command.encode("utf-8"))
splitter.whitespace = "|"
splitter.whitespace_split = True
command = []
while True:
token = splitter.get_token()
if token:
command.append(token)
else:
break
command = list(map(shlex.split, command))
return command | python | def _expand_args(command):
"""Parses command strings and returns a Popen-ready list."""
# Prepare arguments.
if isinstance(command, STR_TYPES):
if sys.version_info[0] == 2:
splitter = shlex.shlex(command.encode("utf-8"))
elif sys.version_info[0] == 3:
splitter = shlex.shlex(command)
else:
splitter = shlex.shlex(command.encode("utf-8"))
splitter.whitespace = "|"
splitter.whitespace_split = True
command = []
while True:
token = splitter.get_token()
if token:
command.append(token)
else:
break
command = list(map(shlex.split, command))
return command | [
"def",
"_expand_args",
"(",
"command",
")",
":",
"# Prepare arguments.",
"if",
"isinstance",
"(",
"command",
",",
"STR_TYPES",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
":",
"splitter",
"=",
"shlex",
".",
"shlex",
"(",
"command",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"elif",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"3",
":",
"splitter",
"=",
"shlex",
".",
"shlex",
"(",
"command",
")",
"else",
":",
"splitter",
"=",
"shlex",
".",
"shlex",
"(",
"command",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"splitter",
".",
"whitespace",
"=",
"\"|\"",
"splitter",
".",
"whitespace_split",
"=",
"True",
"command",
"=",
"[",
"]",
"while",
"True",
":",
"token",
"=",
"splitter",
".",
"get_token",
"(",
")",
"if",
"token",
":",
"command",
".",
"append",
"(",
"token",
")",
"else",
":",
"break",
"command",
"=",
"list",
"(",
"map",
"(",
"shlex",
".",
"split",
",",
"command",
")",
")",
"return",
"command"
] | Parses command strings and returns a Popen-ready list. | [
"Parses",
"command",
"strings",
"and",
"returns",
"a",
"Popen",
"-",
"ready",
"list",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/delegator.py#L290-L314 |
25,002 | pypa/pipenv | pipenv/vendor/delegator.py | Command.pipe | def pipe(self, command, timeout=None, cwd=None):
"""Runs the current command and passes its output to the next
given process.
"""
if not timeout:
timeout = self.timeout
if not self.was_run:
self.run(block=False, cwd=cwd)
data = self.out
if timeout:
c = Command(command, timeout)
else:
c = Command(command)
c.run(block=False, cwd=cwd)
if data:
c.send(data)
c.block()
return c | python | def pipe(self, command, timeout=None, cwd=None):
"""Runs the current command and passes its output to the next
given process.
"""
if not timeout:
timeout = self.timeout
if not self.was_run:
self.run(block=False, cwd=cwd)
data = self.out
if timeout:
c = Command(command, timeout)
else:
c = Command(command)
c.run(block=False, cwd=cwd)
if data:
c.send(data)
c.block()
return c | [
"def",
"pipe",
"(",
"self",
",",
"command",
",",
"timeout",
"=",
"None",
",",
"cwd",
"=",
"None",
")",
":",
"if",
"not",
"timeout",
":",
"timeout",
"=",
"self",
".",
"timeout",
"if",
"not",
"self",
".",
"was_run",
":",
"self",
".",
"run",
"(",
"block",
"=",
"False",
",",
"cwd",
"=",
"cwd",
")",
"data",
"=",
"self",
".",
"out",
"if",
"timeout",
":",
"c",
"=",
"Command",
"(",
"command",
",",
"timeout",
")",
"else",
":",
"c",
"=",
"Command",
"(",
"command",
")",
"c",
".",
"run",
"(",
"block",
"=",
"False",
",",
"cwd",
"=",
"cwd",
")",
"if",
"data",
":",
"c",
".",
"send",
"(",
"data",
")",
"c",
".",
"block",
"(",
")",
"return",
"c"
] | Runs the current command and passes its output to the next
given process. | [
"Runs",
"the",
"current",
"command",
"and",
"passes",
"its",
"output",
"to",
"the",
"next",
"given",
"process",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/delegator.py#L266-L287 |
25,003 | pypa/pipenv | pipenv/vendor/urllib3/packages/backports/makefile.py | backport_makefile | def backport_makefile(self, mode="r", buffering=None, encoding=None,
errors=None, newline=None):
"""
Backport of ``socket.makefile`` from Python 3.5.
"""
if not set(mode) <= {"r", "w", "b"}:
raise ValueError(
"invalid mode %r (only r, w, b allowed)" % (mode,)
)
writing = "w" in mode
reading = "r" in mode or not writing
assert reading or writing
binary = "b" in mode
rawmode = ""
if reading:
rawmode += "r"
if writing:
rawmode += "w"
raw = SocketIO(self, rawmode)
self._makefile_refs += 1
if buffering is None:
buffering = -1
if buffering < 0:
buffering = io.DEFAULT_BUFFER_SIZE
if buffering == 0:
if not binary:
raise ValueError("unbuffered streams must be binary")
return raw
if reading and writing:
buffer = io.BufferedRWPair(raw, raw, buffering)
elif reading:
buffer = io.BufferedReader(raw, buffering)
else:
assert writing
buffer = io.BufferedWriter(raw, buffering)
if binary:
return buffer
text = io.TextIOWrapper(buffer, encoding, errors, newline)
text.mode = mode
return text | python | def backport_makefile(self, mode="r", buffering=None, encoding=None,
errors=None, newline=None):
"""
Backport of ``socket.makefile`` from Python 3.5.
"""
if not set(mode) <= {"r", "w", "b"}:
raise ValueError(
"invalid mode %r (only r, w, b allowed)" % (mode,)
)
writing = "w" in mode
reading = "r" in mode or not writing
assert reading or writing
binary = "b" in mode
rawmode = ""
if reading:
rawmode += "r"
if writing:
rawmode += "w"
raw = SocketIO(self, rawmode)
self._makefile_refs += 1
if buffering is None:
buffering = -1
if buffering < 0:
buffering = io.DEFAULT_BUFFER_SIZE
if buffering == 0:
if not binary:
raise ValueError("unbuffered streams must be binary")
return raw
if reading and writing:
buffer = io.BufferedRWPair(raw, raw, buffering)
elif reading:
buffer = io.BufferedReader(raw, buffering)
else:
assert writing
buffer = io.BufferedWriter(raw, buffering)
if binary:
return buffer
text = io.TextIOWrapper(buffer, encoding, errors, newline)
text.mode = mode
return text | [
"def",
"backport_makefile",
"(",
"self",
",",
"mode",
"=",
"\"r\"",
",",
"buffering",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
",",
"newline",
"=",
"None",
")",
":",
"if",
"not",
"set",
"(",
"mode",
")",
"<=",
"{",
"\"r\"",
",",
"\"w\"",
",",
"\"b\"",
"}",
":",
"raise",
"ValueError",
"(",
"\"invalid mode %r (only r, w, b allowed)\"",
"%",
"(",
"mode",
",",
")",
")",
"writing",
"=",
"\"w\"",
"in",
"mode",
"reading",
"=",
"\"r\"",
"in",
"mode",
"or",
"not",
"writing",
"assert",
"reading",
"or",
"writing",
"binary",
"=",
"\"b\"",
"in",
"mode",
"rawmode",
"=",
"\"\"",
"if",
"reading",
":",
"rawmode",
"+=",
"\"r\"",
"if",
"writing",
":",
"rawmode",
"+=",
"\"w\"",
"raw",
"=",
"SocketIO",
"(",
"self",
",",
"rawmode",
")",
"self",
".",
"_makefile_refs",
"+=",
"1",
"if",
"buffering",
"is",
"None",
":",
"buffering",
"=",
"-",
"1",
"if",
"buffering",
"<",
"0",
":",
"buffering",
"=",
"io",
".",
"DEFAULT_BUFFER_SIZE",
"if",
"buffering",
"==",
"0",
":",
"if",
"not",
"binary",
":",
"raise",
"ValueError",
"(",
"\"unbuffered streams must be binary\"",
")",
"return",
"raw",
"if",
"reading",
"and",
"writing",
":",
"buffer",
"=",
"io",
".",
"BufferedRWPair",
"(",
"raw",
",",
"raw",
",",
"buffering",
")",
"elif",
"reading",
":",
"buffer",
"=",
"io",
".",
"BufferedReader",
"(",
"raw",
",",
"buffering",
")",
"else",
":",
"assert",
"writing",
"buffer",
"=",
"io",
".",
"BufferedWriter",
"(",
"raw",
",",
"buffering",
")",
"if",
"binary",
":",
"return",
"buffer",
"text",
"=",
"io",
".",
"TextIOWrapper",
"(",
"buffer",
",",
"encoding",
",",
"errors",
",",
"newline",
")",
"text",
".",
"mode",
"=",
"mode",
"return",
"text"
] | Backport of ``socket.makefile`` from Python 3.5. | [
"Backport",
"of",
"socket",
".",
"makefile",
"from",
"Python",
"3",
".",
"5",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/packages/backports/makefile.py#L14-L53 |
25,004 | pypa/pipenv | pipenv/vendor/jinja2/debug.py | make_traceback | def make_traceback(exc_info, source_hint=None):
"""Creates a processed traceback object from the exc_info."""
exc_type, exc_value, tb = exc_info
if isinstance(exc_value, TemplateSyntaxError):
exc_info = translate_syntax_error(exc_value, source_hint)
initial_skip = 0
else:
initial_skip = 1
return translate_exception(exc_info, initial_skip) | python | def make_traceback(exc_info, source_hint=None):
"""Creates a processed traceback object from the exc_info."""
exc_type, exc_value, tb = exc_info
if isinstance(exc_value, TemplateSyntaxError):
exc_info = translate_syntax_error(exc_value, source_hint)
initial_skip = 0
else:
initial_skip = 1
return translate_exception(exc_info, initial_skip) | [
"def",
"make_traceback",
"(",
"exc_info",
",",
"source_hint",
"=",
"None",
")",
":",
"exc_type",
",",
"exc_value",
",",
"tb",
"=",
"exc_info",
"if",
"isinstance",
"(",
"exc_value",
",",
"TemplateSyntaxError",
")",
":",
"exc_info",
"=",
"translate_syntax_error",
"(",
"exc_value",
",",
"source_hint",
")",
"initial_skip",
"=",
"0",
"else",
":",
"initial_skip",
"=",
"1",
"return",
"translate_exception",
"(",
"exc_info",
",",
"initial_skip",
")"
] | Creates a processed traceback object from the exc_info. | [
"Creates",
"a",
"processed",
"traceback",
"object",
"from",
"the",
"exc_info",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/debug.py#L132-L140 |
25,005 | pypa/pipenv | pipenv/vendor/jinja2/debug.py | translate_syntax_error | def translate_syntax_error(error, source=None):
"""Rewrites a syntax error to please traceback systems."""
error.source = source
error.translated = True
exc_info = (error.__class__, error, None)
filename = error.filename
if filename is None:
filename = '<unknown>'
return fake_exc_info(exc_info, filename, error.lineno) | python | def translate_syntax_error(error, source=None):
"""Rewrites a syntax error to please traceback systems."""
error.source = source
error.translated = True
exc_info = (error.__class__, error, None)
filename = error.filename
if filename is None:
filename = '<unknown>'
return fake_exc_info(exc_info, filename, error.lineno) | [
"def",
"translate_syntax_error",
"(",
"error",
",",
"source",
"=",
"None",
")",
":",
"error",
".",
"source",
"=",
"source",
"error",
".",
"translated",
"=",
"True",
"exc_info",
"=",
"(",
"error",
".",
"__class__",
",",
"error",
",",
"None",
")",
"filename",
"=",
"error",
".",
"filename",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"'<unknown>'",
"return",
"fake_exc_info",
"(",
"exc_info",
",",
"filename",
",",
"error",
".",
"lineno",
")"
] | Rewrites a syntax error to please traceback systems. | [
"Rewrites",
"a",
"syntax",
"error",
"to",
"please",
"traceback",
"systems",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/debug.py#L143-L151 |
25,006 | pypa/pipenv | pipenv/vendor/jinja2/debug.py | ProcessedTraceback.render_as_text | def render_as_text(self, limit=None):
"""Return a string with the traceback."""
lines = traceback.format_exception(self.exc_type, self.exc_value,
self.frames[0], limit=limit)
return ''.join(lines).rstrip() | python | def render_as_text(self, limit=None):
"""Return a string with the traceback."""
lines = traceback.format_exception(self.exc_type, self.exc_value,
self.frames[0], limit=limit)
return ''.join(lines).rstrip() | [
"def",
"render_as_text",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"lines",
"=",
"traceback",
".",
"format_exception",
"(",
"self",
".",
"exc_type",
",",
"self",
".",
"exc_value",
",",
"self",
".",
"frames",
"[",
"0",
"]",
",",
"limit",
"=",
"limit",
")",
"return",
"''",
".",
"join",
"(",
"lines",
")",
".",
"rstrip",
"(",
")"
] | Return a string with the traceback. | [
"Return",
"a",
"string",
"with",
"the",
"traceback",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/debug.py#L97-L101 |
25,007 | pypa/pipenv | pipenv/vendor/jinja2/debug.py | ProcessedTraceback.render_as_html | def render_as_html(self, full=False):
"""Return a unicode string with the traceback as rendered HTML."""
from jinja2.debugrenderer import render_traceback
return u'%s\n\n<!--\n%s\n-->' % (
render_traceback(self, full=full),
self.render_as_text().decode('utf-8', 'replace')
) | python | def render_as_html(self, full=False):
"""Return a unicode string with the traceback as rendered HTML."""
from jinja2.debugrenderer import render_traceback
return u'%s\n\n<!--\n%s\n-->' % (
render_traceback(self, full=full),
self.render_as_text().decode('utf-8', 'replace')
) | [
"def",
"render_as_html",
"(",
"self",
",",
"full",
"=",
"False",
")",
":",
"from",
"jinja2",
".",
"debugrenderer",
"import",
"render_traceback",
"return",
"u'%s\\n\\n<!--\\n%s\\n-->'",
"%",
"(",
"render_traceback",
"(",
"self",
",",
"full",
"=",
"full",
")",
",",
"self",
".",
"render_as_text",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
",",
"'replace'",
")",
")"
] | Return a unicode string with the traceback as rendered HTML. | [
"Return",
"a",
"unicode",
"string",
"with",
"the",
"traceback",
"as",
"rendered",
"HTML",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/debug.py#L103-L109 |
25,008 | pypa/pipenv | pipenv/vendor/jinja2/debug.py | ProcessedTraceback.standard_exc_info | def standard_exc_info(self):
"""Standard python exc_info for re-raising"""
tb = self.frames[0]
# the frame will be an actual traceback (or transparent proxy) if
# we are on pypy or a python implementation with support for tproxy
if type(tb) is not TracebackType:
tb = tb.tb
return self.exc_type, self.exc_value, tb | python | def standard_exc_info(self):
"""Standard python exc_info for re-raising"""
tb = self.frames[0]
# the frame will be an actual traceback (or transparent proxy) if
# we are on pypy or a python implementation with support for tproxy
if type(tb) is not TracebackType:
tb = tb.tb
return self.exc_type, self.exc_value, tb | [
"def",
"standard_exc_info",
"(",
"self",
")",
":",
"tb",
"=",
"self",
".",
"frames",
"[",
"0",
"]",
"# the frame will be an actual traceback (or transparent proxy) if",
"# we are on pypy or a python implementation with support for tproxy",
"if",
"type",
"(",
"tb",
")",
"is",
"not",
"TracebackType",
":",
"tb",
"=",
"tb",
".",
"tb",
"return",
"self",
".",
"exc_type",
",",
"self",
".",
"exc_value",
",",
"tb"
] | Standard python exc_info for re-raising | [
"Standard",
"python",
"exc_info",
"for",
"re",
"-",
"raising"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/debug.py#L122-L129 |
25,009 | pypa/pipenv | pipenv/patched/notpip/_internal/operations/prepare.py | make_abstract_dist | def make_abstract_dist(req):
# type: (InstallRequirement) -> DistAbstraction
"""Factory to make an abstract dist object.
Preconditions: Either an editable req with a source_dir, or satisfied_by or
a wheel link, or a non-editable req with a source_dir.
:return: A concrete DistAbstraction.
"""
if req.editable:
return IsSDist(req)
elif req.link and req.link.is_wheel:
return IsWheel(req)
else:
return IsSDist(req) | python | def make_abstract_dist(req):
# type: (InstallRequirement) -> DistAbstraction
"""Factory to make an abstract dist object.
Preconditions: Either an editable req with a source_dir, or satisfied_by or
a wheel link, or a non-editable req with a source_dir.
:return: A concrete DistAbstraction.
"""
if req.editable:
return IsSDist(req)
elif req.link and req.link.is_wheel:
return IsWheel(req)
else:
return IsSDist(req) | [
"def",
"make_abstract_dist",
"(",
"req",
")",
":",
"# type: (InstallRequirement) -> DistAbstraction",
"if",
"req",
".",
"editable",
":",
"return",
"IsSDist",
"(",
"req",
")",
"elif",
"req",
".",
"link",
"and",
"req",
".",
"link",
".",
"is_wheel",
":",
"return",
"IsWheel",
"(",
"req",
")",
"else",
":",
"return",
"IsSDist",
"(",
"req",
")"
] | Factory to make an abstract dist object.
Preconditions: Either an editable req with a source_dir, or satisfied_by or
a wheel link, or a non-editable req with a source_dir.
:return: A concrete DistAbstraction. | [
"Factory",
"to",
"make",
"an",
"abstract",
"dist",
"object",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/operations/prepare.py#L34-L48 |
25,010 | pypa/pipenv | pipenv/patched/notpip/_internal/operations/prepare.py | RequirementPreparer.prepare_linked_requirement | def prepare_linked_requirement(
self,
req, # type: InstallRequirement
session, # type: PipSession
finder, # type: PackageFinder
upgrade_allowed, # type: bool
require_hashes # type: bool
):
# type: (...) -> DistAbstraction
"""Prepare a requirement that would be obtained from req.link
"""
# TODO: Breakup into smaller functions
if req.link and req.link.scheme == 'file':
path = url_to_path(req.link.url)
logger.info('Processing %s', display_path(path))
else:
logger.info('Collecting %s', req)
with indent_log():
# @@ if filesystem packages are not marked
# editable in a req, a non deterministic error
# occurs when the script attempts to unpack the
# build directory
req.ensure_has_source_dir(self.build_dir)
# If a checkout exists, it's unwise to keep going. version
# inconsistencies are logged later, but do not fail the
# installation.
# FIXME: this won't upgrade when there's an existing
# package unpacked in `req.source_dir`
# package unpacked in `req.source_dir`
if os.path.exists(os.path.join(req.source_dir, 'setup.py')):
rmtree(req.source_dir)
req.populate_link(finder, upgrade_allowed, require_hashes)
# We can't hit this spot and have populate_link return None.
# req.satisfied_by is None here (because we're
# guarded) and upgrade has no impact except when satisfied_by
# is not None.
# Then inside find_requirement existing_applicable -> False
# If no new versions are found, DistributionNotFound is raised,
# otherwise a result is guaranteed.
assert req.link
link = req.link
# Now that we have the real link, we can tell what kind of
# requirements we have and raise some more informative errors
# than otherwise. (For example, we can raise VcsHashUnsupported
# for a VCS URL rather than HashMissing.)
if require_hashes:
# We could check these first 2 conditions inside
# unpack_url and save repetition of conditions, but then
# we would report less-useful error messages for
# unhashable requirements, complaining that there's no
# hash provided.
if is_vcs_url(link):
raise VcsHashUnsupported()
elif is_file_url(link) and is_dir_url(link):
raise DirectoryUrlHashUnsupported()
if not req.original_link and not req.is_pinned:
# Unpinned packages are asking for trouble when a new
# version is uploaded. This isn't a security check, but
# it saves users a surprising hash mismatch in the
# future.
#
# file:/// URLs aren't pinnable, so don't complain
# about them not being pinned.
raise HashUnpinned()
hashes = req.hashes(trust_internet=not require_hashes)
if require_hashes and not hashes:
# Known-good hashes are missing for this requirement, so
# shim it with a facade object that will provoke hash
# computation and then raise a HashMissing exception
# showing the user what the hash should be.
hashes = MissingHashes()
try:
download_dir = self.download_dir
# We always delete unpacked sdists after pip ran.
autodelete_unpacked = True
if req.link.is_wheel and self.wheel_download_dir:
# when doing 'pip wheel` we download wheels to a
# dedicated dir.
download_dir = self.wheel_download_dir
if req.link.is_wheel:
if download_dir:
# When downloading, we only unpack wheels to get
# metadata.
autodelete_unpacked = True
else:
# When installing a wheel, we use the unpacked
# wheel.
autodelete_unpacked = False
unpack_url(
req.link, req.source_dir,
download_dir, autodelete_unpacked,
session=session, hashes=hashes,
progress_bar=self.progress_bar
)
except requests.HTTPError as exc:
logger.critical(
'Could not install requirement %s because of error %s',
req,
exc,
)
raise InstallationError(
'Could not install requirement %s because of HTTP '
'error %s for URL %s' %
(req, exc, req.link)
)
abstract_dist = make_abstract_dist(req)
with self.req_tracker.track(req):
abstract_dist.prep_for_dist(finder, self.build_isolation)
if self._download_should_save:
# Make a .zip of the source_dir we already created.
if req.link.scheme in vcs.all_schemes:
req.archive(self.download_dir)
return abstract_dist | python | def prepare_linked_requirement(
self,
req, # type: InstallRequirement
session, # type: PipSession
finder, # type: PackageFinder
upgrade_allowed, # type: bool
require_hashes # type: bool
):
# type: (...) -> DistAbstraction
"""Prepare a requirement that would be obtained from req.link
"""
# TODO: Breakup into smaller functions
if req.link and req.link.scheme == 'file':
path = url_to_path(req.link.url)
logger.info('Processing %s', display_path(path))
else:
logger.info('Collecting %s', req)
with indent_log():
# @@ if filesystem packages are not marked
# editable in a req, a non deterministic error
# occurs when the script attempts to unpack the
# build directory
req.ensure_has_source_dir(self.build_dir)
# If a checkout exists, it's unwise to keep going. version
# inconsistencies are logged later, but do not fail the
# installation.
# FIXME: this won't upgrade when there's an existing
# package unpacked in `req.source_dir`
# package unpacked in `req.source_dir`
if os.path.exists(os.path.join(req.source_dir, 'setup.py')):
rmtree(req.source_dir)
req.populate_link(finder, upgrade_allowed, require_hashes)
# We can't hit this spot and have populate_link return None.
# req.satisfied_by is None here (because we're
# guarded) and upgrade has no impact except when satisfied_by
# is not None.
# Then inside find_requirement existing_applicable -> False
# If no new versions are found, DistributionNotFound is raised,
# otherwise a result is guaranteed.
assert req.link
link = req.link
# Now that we have the real link, we can tell what kind of
# requirements we have and raise some more informative errors
# than otherwise. (For example, we can raise VcsHashUnsupported
# for a VCS URL rather than HashMissing.)
if require_hashes:
# We could check these first 2 conditions inside
# unpack_url and save repetition of conditions, but then
# we would report less-useful error messages for
# unhashable requirements, complaining that there's no
# hash provided.
if is_vcs_url(link):
raise VcsHashUnsupported()
elif is_file_url(link) and is_dir_url(link):
raise DirectoryUrlHashUnsupported()
if not req.original_link and not req.is_pinned:
# Unpinned packages are asking for trouble when a new
# version is uploaded. This isn't a security check, but
# it saves users a surprising hash mismatch in the
# future.
#
# file:/// URLs aren't pinnable, so don't complain
# about them not being pinned.
raise HashUnpinned()
hashes = req.hashes(trust_internet=not require_hashes)
if require_hashes and not hashes:
# Known-good hashes are missing for this requirement, so
# shim it with a facade object that will provoke hash
# computation and then raise a HashMissing exception
# showing the user what the hash should be.
hashes = MissingHashes()
try:
download_dir = self.download_dir
# We always delete unpacked sdists after pip ran.
autodelete_unpacked = True
if req.link.is_wheel and self.wheel_download_dir:
# when doing 'pip wheel` we download wheels to a
# dedicated dir.
download_dir = self.wheel_download_dir
if req.link.is_wheel:
if download_dir:
# When downloading, we only unpack wheels to get
# metadata.
autodelete_unpacked = True
else:
# When installing a wheel, we use the unpacked
# wheel.
autodelete_unpacked = False
unpack_url(
req.link, req.source_dir,
download_dir, autodelete_unpacked,
session=session, hashes=hashes,
progress_bar=self.progress_bar
)
except requests.HTTPError as exc:
logger.critical(
'Could not install requirement %s because of error %s',
req,
exc,
)
raise InstallationError(
'Could not install requirement %s because of HTTP '
'error %s for URL %s' %
(req, exc, req.link)
)
abstract_dist = make_abstract_dist(req)
with self.req_tracker.track(req):
abstract_dist.prep_for_dist(finder, self.build_isolation)
if self._download_should_save:
# Make a .zip of the source_dir we already created.
if req.link.scheme in vcs.all_schemes:
req.archive(self.download_dir)
return abstract_dist | [
"def",
"prepare_linked_requirement",
"(",
"self",
",",
"req",
",",
"# type: InstallRequirement",
"session",
",",
"# type: PipSession",
"finder",
",",
"# type: PackageFinder",
"upgrade_allowed",
",",
"# type: bool",
"require_hashes",
"# type: bool",
")",
":",
"# type: (...) -> DistAbstraction",
"# TODO: Breakup into smaller functions",
"if",
"req",
".",
"link",
"and",
"req",
".",
"link",
".",
"scheme",
"==",
"'file'",
":",
"path",
"=",
"url_to_path",
"(",
"req",
".",
"link",
".",
"url",
")",
"logger",
".",
"info",
"(",
"'Processing %s'",
",",
"display_path",
"(",
"path",
")",
")",
"else",
":",
"logger",
".",
"info",
"(",
"'Collecting %s'",
",",
"req",
")",
"with",
"indent_log",
"(",
")",
":",
"# @@ if filesystem packages are not marked",
"# editable in a req, a non deterministic error",
"# occurs when the script attempts to unpack the",
"# build directory",
"req",
".",
"ensure_has_source_dir",
"(",
"self",
".",
"build_dir",
")",
"# If a checkout exists, it's unwise to keep going. version",
"# inconsistencies are logged later, but do not fail the",
"# installation.",
"# FIXME: this won't upgrade when there's an existing",
"# package unpacked in `req.source_dir`",
"# package unpacked in `req.source_dir`",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"req",
".",
"source_dir",
",",
"'setup.py'",
")",
")",
":",
"rmtree",
"(",
"req",
".",
"source_dir",
")",
"req",
".",
"populate_link",
"(",
"finder",
",",
"upgrade_allowed",
",",
"require_hashes",
")",
"# We can't hit this spot and have populate_link return None.",
"# req.satisfied_by is None here (because we're",
"# guarded) and upgrade has no impact except when satisfied_by",
"# is not None.",
"# Then inside find_requirement existing_applicable -> False",
"# If no new versions are found, DistributionNotFound is raised,",
"# otherwise a result is guaranteed.",
"assert",
"req",
".",
"link",
"link",
"=",
"req",
".",
"link",
"# Now that we have the real link, we can tell what kind of",
"# requirements we have and raise some more informative errors",
"# than otherwise. (For example, we can raise VcsHashUnsupported",
"# for a VCS URL rather than HashMissing.)",
"if",
"require_hashes",
":",
"# We could check these first 2 conditions inside",
"# unpack_url and save repetition of conditions, but then",
"# we would report less-useful error messages for",
"# unhashable requirements, complaining that there's no",
"# hash provided.",
"if",
"is_vcs_url",
"(",
"link",
")",
":",
"raise",
"VcsHashUnsupported",
"(",
")",
"elif",
"is_file_url",
"(",
"link",
")",
"and",
"is_dir_url",
"(",
"link",
")",
":",
"raise",
"DirectoryUrlHashUnsupported",
"(",
")",
"if",
"not",
"req",
".",
"original_link",
"and",
"not",
"req",
".",
"is_pinned",
":",
"# Unpinned packages are asking for trouble when a new",
"# version is uploaded. This isn't a security check, but",
"# it saves users a surprising hash mismatch in the",
"# future.",
"#",
"# file:/// URLs aren't pinnable, so don't complain",
"# about them not being pinned.",
"raise",
"HashUnpinned",
"(",
")",
"hashes",
"=",
"req",
".",
"hashes",
"(",
"trust_internet",
"=",
"not",
"require_hashes",
")",
"if",
"require_hashes",
"and",
"not",
"hashes",
":",
"# Known-good hashes are missing for this requirement, so",
"# shim it with a facade object that will provoke hash",
"# computation and then raise a HashMissing exception",
"# showing the user what the hash should be.",
"hashes",
"=",
"MissingHashes",
"(",
")",
"try",
":",
"download_dir",
"=",
"self",
".",
"download_dir",
"# We always delete unpacked sdists after pip ran.",
"autodelete_unpacked",
"=",
"True",
"if",
"req",
".",
"link",
".",
"is_wheel",
"and",
"self",
".",
"wheel_download_dir",
":",
"# when doing 'pip wheel` we download wheels to a",
"# dedicated dir.",
"download_dir",
"=",
"self",
".",
"wheel_download_dir",
"if",
"req",
".",
"link",
".",
"is_wheel",
":",
"if",
"download_dir",
":",
"# When downloading, we only unpack wheels to get",
"# metadata.",
"autodelete_unpacked",
"=",
"True",
"else",
":",
"# When installing a wheel, we use the unpacked",
"# wheel.",
"autodelete_unpacked",
"=",
"False",
"unpack_url",
"(",
"req",
".",
"link",
",",
"req",
".",
"source_dir",
",",
"download_dir",
",",
"autodelete_unpacked",
",",
"session",
"=",
"session",
",",
"hashes",
"=",
"hashes",
",",
"progress_bar",
"=",
"self",
".",
"progress_bar",
")",
"except",
"requests",
".",
"HTTPError",
"as",
"exc",
":",
"logger",
".",
"critical",
"(",
"'Could not install requirement %s because of error %s'",
",",
"req",
",",
"exc",
",",
")",
"raise",
"InstallationError",
"(",
"'Could not install requirement %s because of HTTP '",
"'error %s for URL %s'",
"%",
"(",
"req",
",",
"exc",
",",
"req",
".",
"link",
")",
")",
"abstract_dist",
"=",
"make_abstract_dist",
"(",
"req",
")",
"with",
"self",
".",
"req_tracker",
".",
"track",
"(",
"req",
")",
":",
"abstract_dist",
".",
"prep_for_dist",
"(",
"finder",
",",
"self",
".",
"build_isolation",
")",
"if",
"self",
".",
"_download_should_save",
":",
"# Make a .zip of the source_dir we already created.",
"if",
"req",
".",
"link",
".",
"scheme",
"in",
"vcs",
".",
"all_schemes",
":",
"req",
".",
"archive",
"(",
"self",
".",
"download_dir",
")",
"return",
"abstract_dist"
] | Prepare a requirement that would be obtained from req.link | [
"Prepare",
"a",
"requirement",
"that",
"would",
"be",
"obtained",
"from",
"req",
".",
"link"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/operations/prepare.py#L230-L347 |
25,011 | pypa/pipenv | pipenv/patched/notpip/_internal/operations/prepare.py | RequirementPreparer.prepare_editable_requirement | def prepare_editable_requirement(
self,
req, # type: InstallRequirement
require_hashes, # type: bool
use_user_site, # type: bool
finder # type: PackageFinder
):
# type: (...) -> DistAbstraction
"""Prepare an editable requirement
"""
assert req.editable, "cannot prepare a non-editable req as editable"
logger.info('Obtaining %s', req)
with indent_log():
if require_hashes:
raise InstallationError(
'The editable requirement %s cannot be installed when '
'requiring hashes, because there is no single file to '
'hash.' % req
)
req.ensure_has_source_dir(self.src_dir)
req.update_editable(not self._download_should_save)
abstract_dist = make_abstract_dist(req)
with self.req_tracker.track(req):
abstract_dist.prep_for_dist(finder, self.build_isolation)
if self._download_should_save:
req.archive(self.download_dir)
req.check_if_exists(use_user_site)
return abstract_dist | python | def prepare_editable_requirement(
self,
req, # type: InstallRequirement
require_hashes, # type: bool
use_user_site, # type: bool
finder # type: PackageFinder
):
# type: (...) -> DistAbstraction
"""Prepare an editable requirement
"""
assert req.editable, "cannot prepare a non-editable req as editable"
logger.info('Obtaining %s', req)
with indent_log():
if require_hashes:
raise InstallationError(
'The editable requirement %s cannot be installed when '
'requiring hashes, because there is no single file to '
'hash.' % req
)
req.ensure_has_source_dir(self.src_dir)
req.update_editable(not self._download_should_save)
abstract_dist = make_abstract_dist(req)
with self.req_tracker.track(req):
abstract_dist.prep_for_dist(finder, self.build_isolation)
if self._download_should_save:
req.archive(self.download_dir)
req.check_if_exists(use_user_site)
return abstract_dist | [
"def",
"prepare_editable_requirement",
"(",
"self",
",",
"req",
",",
"# type: InstallRequirement",
"require_hashes",
",",
"# type: bool",
"use_user_site",
",",
"# type: bool",
"finder",
"# type: PackageFinder",
")",
":",
"# type: (...) -> DistAbstraction",
"assert",
"req",
".",
"editable",
",",
"\"cannot prepare a non-editable req as editable\"",
"logger",
".",
"info",
"(",
"'Obtaining %s'",
",",
"req",
")",
"with",
"indent_log",
"(",
")",
":",
"if",
"require_hashes",
":",
"raise",
"InstallationError",
"(",
"'The editable requirement %s cannot be installed when '",
"'requiring hashes, because there is no single file to '",
"'hash.'",
"%",
"req",
")",
"req",
".",
"ensure_has_source_dir",
"(",
"self",
".",
"src_dir",
")",
"req",
".",
"update_editable",
"(",
"not",
"self",
".",
"_download_should_save",
")",
"abstract_dist",
"=",
"make_abstract_dist",
"(",
"req",
")",
"with",
"self",
".",
"req_tracker",
".",
"track",
"(",
"req",
")",
":",
"abstract_dist",
".",
"prep_for_dist",
"(",
"finder",
",",
"self",
".",
"build_isolation",
")",
"if",
"self",
".",
"_download_should_save",
":",
"req",
".",
"archive",
"(",
"self",
".",
"download_dir",
")",
"req",
".",
"check_if_exists",
"(",
"use_user_site",
")",
"return",
"abstract_dist"
] | Prepare an editable requirement | [
"Prepare",
"an",
"editable",
"requirement"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/operations/prepare.py#L349-L381 |
25,012 | pypa/pipenv | pipenv/patched/notpip/_internal/operations/prepare.py | RequirementPreparer.prepare_installed_requirement | def prepare_installed_requirement(self, req, require_hashes, skip_reason):
# type: (InstallRequirement, bool, Optional[str]) -> DistAbstraction
"""Prepare an already-installed requirement
"""
assert req.satisfied_by, "req should have been satisfied but isn't"
assert skip_reason is not None, (
"did not get skip reason skipped but req.satisfied_by "
"is set to %r" % (req.satisfied_by,)
)
logger.info(
'Requirement %s: %s (%s)',
skip_reason, req, req.satisfied_by.version
)
with indent_log():
if require_hashes:
logger.debug(
'Since it is already installed, we are trusting this '
'package without checking its hash. To ensure a '
'completely repeatable environment, install into an '
'empty virtualenv.'
)
abstract_dist = Installed(req)
return abstract_dist | python | def prepare_installed_requirement(self, req, require_hashes, skip_reason):
# type: (InstallRequirement, bool, Optional[str]) -> DistAbstraction
"""Prepare an already-installed requirement
"""
assert req.satisfied_by, "req should have been satisfied but isn't"
assert skip_reason is not None, (
"did not get skip reason skipped but req.satisfied_by "
"is set to %r" % (req.satisfied_by,)
)
logger.info(
'Requirement %s: %s (%s)',
skip_reason, req, req.satisfied_by.version
)
with indent_log():
if require_hashes:
logger.debug(
'Since it is already installed, we are trusting this '
'package without checking its hash. To ensure a '
'completely repeatable environment, install into an '
'empty virtualenv.'
)
abstract_dist = Installed(req)
return abstract_dist | [
"def",
"prepare_installed_requirement",
"(",
"self",
",",
"req",
",",
"require_hashes",
",",
"skip_reason",
")",
":",
"# type: (InstallRequirement, bool, Optional[str]) -> DistAbstraction",
"assert",
"req",
".",
"satisfied_by",
",",
"\"req should have been satisfied but isn't\"",
"assert",
"skip_reason",
"is",
"not",
"None",
",",
"(",
"\"did not get skip reason skipped but req.satisfied_by \"",
"\"is set to %r\"",
"%",
"(",
"req",
".",
"satisfied_by",
",",
")",
")",
"logger",
".",
"info",
"(",
"'Requirement %s: %s (%s)'",
",",
"skip_reason",
",",
"req",
",",
"req",
".",
"satisfied_by",
".",
"version",
")",
"with",
"indent_log",
"(",
")",
":",
"if",
"require_hashes",
":",
"logger",
".",
"debug",
"(",
"'Since it is already installed, we are trusting this '",
"'package without checking its hash. To ensure a '",
"'completely repeatable environment, install into an '",
"'empty virtualenv.'",
")",
"abstract_dist",
"=",
"Installed",
"(",
"req",
")",
"return",
"abstract_dist"
] | Prepare an already-installed requirement | [
"Prepare",
"an",
"already",
"-",
"installed",
"requirement"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/operations/prepare.py#L383-L406 |
25,013 | pypa/pipenv | pipenv/patched/notpip/_internal/req/__init__.py | install_given_reqs | def install_given_reqs(
to_install, # type: List[InstallRequirement]
install_options, # type: List[str]
global_options=(), # type: Sequence[str]
*args, **kwargs
):
# type: (...) -> List[InstallRequirement]
"""
Install everything in the given list.
(to be called after having downloaded and unpacked the packages)
"""
if to_install:
logger.info(
'Installing collected packages: %s',
', '.join([req.name for req in to_install]),
)
with indent_log():
for requirement in to_install:
if requirement.conflicts_with:
logger.info(
'Found existing installation: %s',
requirement.conflicts_with,
)
with indent_log():
uninstalled_pathset = requirement.uninstall(
auto_confirm=True
)
try:
requirement.install(
install_options,
global_options,
*args,
**kwargs
)
except Exception:
should_rollback = (
requirement.conflicts_with and
not requirement.install_succeeded
)
# if install did not succeed, rollback previous uninstall
if should_rollback:
uninstalled_pathset.rollback()
raise
else:
should_commit = (
requirement.conflicts_with and
requirement.install_succeeded
)
if should_commit:
uninstalled_pathset.commit()
requirement.remove_temporary_source()
return to_install | python | def install_given_reqs(
to_install, # type: List[InstallRequirement]
install_options, # type: List[str]
global_options=(), # type: Sequence[str]
*args, **kwargs
):
# type: (...) -> List[InstallRequirement]
"""
Install everything in the given list.
(to be called after having downloaded and unpacked the packages)
"""
if to_install:
logger.info(
'Installing collected packages: %s',
', '.join([req.name for req in to_install]),
)
with indent_log():
for requirement in to_install:
if requirement.conflicts_with:
logger.info(
'Found existing installation: %s',
requirement.conflicts_with,
)
with indent_log():
uninstalled_pathset = requirement.uninstall(
auto_confirm=True
)
try:
requirement.install(
install_options,
global_options,
*args,
**kwargs
)
except Exception:
should_rollback = (
requirement.conflicts_with and
not requirement.install_succeeded
)
# if install did not succeed, rollback previous uninstall
if should_rollback:
uninstalled_pathset.rollback()
raise
else:
should_commit = (
requirement.conflicts_with and
requirement.install_succeeded
)
if should_commit:
uninstalled_pathset.commit()
requirement.remove_temporary_source()
return to_install | [
"def",
"install_given_reqs",
"(",
"to_install",
",",
"# type: List[InstallRequirement]",
"install_options",
",",
"# type: List[str]",
"global_options",
"=",
"(",
")",
",",
"# type: Sequence[str]",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (...) -> List[InstallRequirement]",
"if",
"to_install",
":",
"logger",
".",
"info",
"(",
"'Installing collected packages: %s'",
",",
"', '",
".",
"join",
"(",
"[",
"req",
".",
"name",
"for",
"req",
"in",
"to_install",
"]",
")",
",",
")",
"with",
"indent_log",
"(",
")",
":",
"for",
"requirement",
"in",
"to_install",
":",
"if",
"requirement",
".",
"conflicts_with",
":",
"logger",
".",
"info",
"(",
"'Found existing installation: %s'",
",",
"requirement",
".",
"conflicts_with",
",",
")",
"with",
"indent_log",
"(",
")",
":",
"uninstalled_pathset",
"=",
"requirement",
".",
"uninstall",
"(",
"auto_confirm",
"=",
"True",
")",
"try",
":",
"requirement",
".",
"install",
"(",
"install_options",
",",
"global_options",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
":",
"should_rollback",
"=",
"(",
"requirement",
".",
"conflicts_with",
"and",
"not",
"requirement",
".",
"install_succeeded",
")",
"# if install did not succeed, rollback previous uninstall",
"if",
"should_rollback",
":",
"uninstalled_pathset",
".",
"rollback",
"(",
")",
"raise",
"else",
":",
"should_commit",
"=",
"(",
"requirement",
".",
"conflicts_with",
"and",
"requirement",
".",
"install_succeeded",
")",
"if",
"should_commit",
":",
"uninstalled_pathset",
".",
"commit",
"(",
")",
"requirement",
".",
"remove_temporary_source",
"(",
")",
"return",
"to_install"
] | Install everything in the given list.
(to be called after having downloaded and unpacked the packages) | [
"Install",
"everything",
"in",
"the",
"given",
"list",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/__init__.py#L22-L77 |
25,014 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | get_provider | def get_provider(moduleOrReq):
"""Return an IResourceProvider for the named module or requirement"""
if isinstance(moduleOrReq, Requirement):
return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
try:
module = sys.modules[moduleOrReq]
except KeyError:
__import__(moduleOrReq)
module = sys.modules[moduleOrReq]
loader = getattr(module, '__loader__', None)
return _find_adapter(_provider_factories, loader)(module) | python | def get_provider(moduleOrReq):
"""Return an IResourceProvider for the named module or requirement"""
if isinstance(moduleOrReq, Requirement):
return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
try:
module = sys.modules[moduleOrReq]
except KeyError:
__import__(moduleOrReq)
module = sys.modules[moduleOrReq]
loader = getattr(module, '__loader__', None)
return _find_adapter(_provider_factories, loader)(module) | [
"def",
"get_provider",
"(",
"moduleOrReq",
")",
":",
"if",
"isinstance",
"(",
"moduleOrReq",
",",
"Requirement",
")",
":",
"return",
"working_set",
".",
"find",
"(",
"moduleOrReq",
")",
"or",
"require",
"(",
"str",
"(",
"moduleOrReq",
")",
")",
"[",
"0",
"]",
"try",
":",
"module",
"=",
"sys",
".",
"modules",
"[",
"moduleOrReq",
"]",
"except",
"KeyError",
":",
"__import__",
"(",
"moduleOrReq",
")",
"module",
"=",
"sys",
".",
"modules",
"[",
"moduleOrReq",
"]",
"loader",
"=",
"getattr",
"(",
"module",
",",
"'__loader__'",
",",
"None",
")",
"return",
"_find_adapter",
"(",
"_provider_factories",
",",
"loader",
")",
"(",
"module",
")"
] | Return an IResourceProvider for the named module or requirement | [
"Return",
"an",
"IResourceProvider",
"for",
"the",
"named",
"module",
"or",
"requirement"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L352-L362 |
25,015 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | get_build_platform | def get_build_platform():
"""Return this platform's string for platform-specific distributions
XXX Currently this is the same as ``distutils.util.get_platform()``, but it
needs some hacks for Linux and Mac OS X.
"""
from sysconfig import get_platform
plat = get_platform()
if sys.platform == "darwin" and not plat.startswith('macosx-'):
try:
version = _macosx_vers()
machine = os.uname()[4].replace(" ", "_")
return "macosx-%d.%d-%s" % (
int(version[0]), int(version[1]),
_macosx_arch(machine),
)
except ValueError:
# if someone is running a non-Mac darwin system, this will fall
# through to the default implementation
pass
return plat | python | def get_build_platform():
"""Return this platform's string for platform-specific distributions
XXX Currently this is the same as ``distutils.util.get_platform()``, but it
needs some hacks for Linux and Mac OS X.
"""
from sysconfig import get_platform
plat = get_platform()
if sys.platform == "darwin" and not plat.startswith('macosx-'):
try:
version = _macosx_vers()
machine = os.uname()[4].replace(" ", "_")
return "macosx-%d.%d-%s" % (
int(version[0]), int(version[1]),
_macosx_arch(machine),
)
except ValueError:
# if someone is running a non-Mac darwin system, this will fall
# through to the default implementation
pass
return plat | [
"def",
"get_build_platform",
"(",
")",
":",
"from",
"sysconfig",
"import",
"get_platform",
"plat",
"=",
"get_platform",
"(",
")",
"if",
"sys",
".",
"platform",
"==",
"\"darwin\"",
"and",
"not",
"plat",
".",
"startswith",
"(",
"'macosx-'",
")",
":",
"try",
":",
"version",
"=",
"_macosx_vers",
"(",
")",
"machine",
"=",
"os",
".",
"uname",
"(",
")",
"[",
"4",
"]",
".",
"replace",
"(",
"\" \"",
",",
"\"_\"",
")",
"return",
"\"macosx-%d.%d-%s\"",
"%",
"(",
"int",
"(",
"version",
"[",
"0",
"]",
")",
",",
"int",
"(",
"version",
"[",
"1",
"]",
")",
",",
"_macosx_arch",
"(",
"machine",
")",
",",
")",
"except",
"ValueError",
":",
"# if someone is running a non-Mac darwin system, this will fall",
"# through to the default implementation",
"pass",
"return",
"plat"
] | Return this platform's string for platform-specific distributions
XXX Currently this is the same as ``distutils.util.get_platform()``, but it
needs some hacks for Linux and Mac OS X. | [
"Return",
"this",
"platform",
"s",
"string",
"for",
"platform",
"-",
"specific",
"distributions"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L385-L406 |
25,016 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | compatible_platforms | def compatible_platforms(provided, required):
"""Can code for the `provided` platform run on the `required` platform?
Returns true if either platform is ``None``, or the platforms are equal.
XXX Needs compatibility checks for Linux and other unixy OSes.
"""
if provided is None or required is None or provided == required:
# easy case
return True
# Mac OS X special cases
reqMac = macosVersionString.match(required)
if reqMac:
provMac = macosVersionString.match(provided)
# is this a Mac package?
if not provMac:
# this is backwards compatibility for packages built before
# setuptools 0.6. All packages built after this point will
# use the new macosx designation.
provDarwin = darwinVersionString.match(provided)
if provDarwin:
dversion = int(provDarwin.group(1))
macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
if dversion == 7 and macosversion >= "10.3" or \
dversion == 8 and macosversion >= "10.4":
return True
# egg isn't macosx or legacy darwin
return False
# are they the same major version and machine type?
if provMac.group(1) != reqMac.group(1) or \
provMac.group(3) != reqMac.group(3):
return False
# is the required OS major update >= the provided one?
if int(provMac.group(2)) > int(reqMac.group(2)):
return False
return True
# XXX Linux and other platforms' special cases should go here
return False | python | def compatible_platforms(provided, required):
"""Can code for the `provided` platform run on the `required` platform?
Returns true if either platform is ``None``, or the platforms are equal.
XXX Needs compatibility checks for Linux and other unixy OSes.
"""
if provided is None or required is None or provided == required:
# easy case
return True
# Mac OS X special cases
reqMac = macosVersionString.match(required)
if reqMac:
provMac = macosVersionString.match(provided)
# is this a Mac package?
if not provMac:
# this is backwards compatibility for packages built before
# setuptools 0.6. All packages built after this point will
# use the new macosx designation.
provDarwin = darwinVersionString.match(provided)
if provDarwin:
dversion = int(provDarwin.group(1))
macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
if dversion == 7 and macosversion >= "10.3" or \
dversion == 8 and macosversion >= "10.4":
return True
# egg isn't macosx or legacy darwin
return False
# are they the same major version and machine type?
if provMac.group(1) != reqMac.group(1) or \
provMac.group(3) != reqMac.group(3):
return False
# is the required OS major update >= the provided one?
if int(provMac.group(2)) > int(reqMac.group(2)):
return False
return True
# XXX Linux and other platforms' special cases should go here
return False | [
"def",
"compatible_platforms",
"(",
"provided",
",",
"required",
")",
":",
"if",
"provided",
"is",
"None",
"or",
"required",
"is",
"None",
"or",
"provided",
"==",
"required",
":",
"# easy case",
"return",
"True",
"# Mac OS X special cases",
"reqMac",
"=",
"macosVersionString",
".",
"match",
"(",
"required",
")",
"if",
"reqMac",
":",
"provMac",
"=",
"macosVersionString",
".",
"match",
"(",
"provided",
")",
"# is this a Mac package?",
"if",
"not",
"provMac",
":",
"# this is backwards compatibility for packages built before",
"# setuptools 0.6. All packages built after this point will",
"# use the new macosx designation.",
"provDarwin",
"=",
"darwinVersionString",
".",
"match",
"(",
"provided",
")",
"if",
"provDarwin",
":",
"dversion",
"=",
"int",
"(",
"provDarwin",
".",
"group",
"(",
"1",
")",
")",
"macosversion",
"=",
"\"%s.%s\"",
"%",
"(",
"reqMac",
".",
"group",
"(",
"1",
")",
",",
"reqMac",
".",
"group",
"(",
"2",
")",
")",
"if",
"dversion",
"==",
"7",
"and",
"macosversion",
">=",
"\"10.3\"",
"or",
"dversion",
"==",
"8",
"and",
"macosversion",
">=",
"\"10.4\"",
":",
"return",
"True",
"# egg isn't macosx or legacy darwin",
"return",
"False",
"# are they the same major version and machine type?",
"if",
"provMac",
".",
"group",
"(",
"1",
")",
"!=",
"reqMac",
".",
"group",
"(",
"1",
")",
"or",
"provMac",
".",
"group",
"(",
"3",
")",
"!=",
"reqMac",
".",
"group",
"(",
"3",
")",
":",
"return",
"False",
"# is the required OS major update >= the provided one?",
"if",
"int",
"(",
"provMac",
".",
"group",
"(",
"2",
")",
")",
">",
"int",
"(",
"reqMac",
".",
"group",
"(",
"2",
")",
")",
":",
"return",
"False",
"return",
"True",
"# XXX Linux and other platforms' special cases should go here",
"return",
"False"
] | Can code for the `provided` platform run on the `required` platform?
Returns true if either platform is ``None``, or the platforms are equal.
XXX Needs compatibility checks for Linux and other unixy OSes. | [
"Can",
"code",
"for",
"the",
"provided",
"platform",
"run",
"on",
"the",
"required",
"platform?"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L415-L458 |
25,017 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | run_script | def run_script(dist_spec, script_name):
"""Locate distribution `dist_spec` and run its `script_name` script"""
ns = sys._getframe(1).f_globals
name = ns['__name__']
ns.clear()
ns['__name__'] = name
require(dist_spec)[0].run_script(script_name, ns) | python | def run_script(dist_spec, script_name):
"""Locate distribution `dist_spec` and run its `script_name` script"""
ns = sys._getframe(1).f_globals
name = ns['__name__']
ns.clear()
ns['__name__'] = name
require(dist_spec)[0].run_script(script_name, ns) | [
"def",
"run_script",
"(",
"dist_spec",
",",
"script_name",
")",
":",
"ns",
"=",
"sys",
".",
"_getframe",
"(",
"1",
")",
".",
"f_globals",
"name",
"=",
"ns",
"[",
"'__name__'",
"]",
"ns",
".",
"clear",
"(",
")",
"ns",
"[",
"'__name__'",
"]",
"=",
"name",
"require",
"(",
"dist_spec",
")",
"[",
"0",
"]",
".",
"run_script",
"(",
"script_name",
",",
"ns",
")"
] | Locate distribution `dist_spec` and run its `script_name` script | [
"Locate",
"distribution",
"dist_spec",
"and",
"run",
"its",
"script_name",
"script"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L461-L467 |
25,018 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | get_distribution | def get_distribution(dist):
"""Return a current distribution object for a Requirement or string"""
if isinstance(dist, six.string_types):
dist = Requirement.parse(dist)
if isinstance(dist, Requirement):
dist = get_provider(dist)
if not isinstance(dist, Distribution):
raise TypeError("Expected string, Requirement, or Distribution", dist)
return dist | python | def get_distribution(dist):
"""Return a current distribution object for a Requirement or string"""
if isinstance(dist, six.string_types):
dist = Requirement.parse(dist)
if isinstance(dist, Requirement):
dist = get_provider(dist)
if not isinstance(dist, Distribution):
raise TypeError("Expected string, Requirement, or Distribution", dist)
return dist | [
"def",
"get_distribution",
"(",
"dist",
")",
":",
"if",
"isinstance",
"(",
"dist",
",",
"six",
".",
"string_types",
")",
":",
"dist",
"=",
"Requirement",
".",
"parse",
"(",
"dist",
")",
"if",
"isinstance",
"(",
"dist",
",",
"Requirement",
")",
":",
"dist",
"=",
"get_provider",
"(",
"dist",
")",
"if",
"not",
"isinstance",
"(",
"dist",
",",
"Distribution",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected string, Requirement, or Distribution\"",
",",
"dist",
")",
"return",
"dist"
] | Return a current distribution object for a Requirement or string | [
"Return",
"a",
"current",
"distribution",
"object",
"for",
"a",
"Requirement",
"or",
"string"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L474-L482 |
25,019 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | safe_version | def safe_version(version):
"""
Convert an arbitrary string to a standard version string
"""
try:
# normalize the version
return str(packaging.version.Version(version))
except packaging.version.InvalidVersion:
version = version.replace(' ', '.')
return re.sub('[^A-Za-z0-9.]+', '-', version) | python | def safe_version(version):
"""
Convert an arbitrary string to a standard version string
"""
try:
# normalize the version
return str(packaging.version.Version(version))
except packaging.version.InvalidVersion:
version = version.replace(' ', '.')
return re.sub('[^A-Za-z0-9.]+', '-', version) | [
"def",
"safe_version",
"(",
"version",
")",
":",
"try",
":",
"# normalize the version",
"return",
"str",
"(",
"packaging",
".",
"version",
".",
"Version",
"(",
"version",
")",
")",
"except",
"packaging",
".",
"version",
".",
"InvalidVersion",
":",
"version",
"=",
"version",
".",
"replace",
"(",
"' '",
",",
"'.'",
")",
"return",
"re",
".",
"sub",
"(",
"'[^A-Za-z0-9.]+'",
",",
"'-'",
",",
"version",
")"
] | Convert an arbitrary string to a standard version string | [
"Convert",
"an",
"arbitrary",
"string",
"to",
"a",
"standard",
"version",
"string"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1323-L1332 |
25,020 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | invalid_marker | def invalid_marker(text):
"""
Validate text as a PEP 508 environment marker; return an exception
if invalid or False otherwise.
"""
try:
evaluate_marker(text)
except SyntaxError as e:
e.filename = None
e.lineno = None
return e
return False | python | def invalid_marker(text):
"""
Validate text as a PEP 508 environment marker; return an exception
if invalid or False otherwise.
"""
try:
evaluate_marker(text)
except SyntaxError as e:
e.filename = None
e.lineno = None
return e
return False | [
"def",
"invalid_marker",
"(",
"text",
")",
":",
"try",
":",
"evaluate_marker",
"(",
"text",
")",
"except",
"SyntaxError",
"as",
"e",
":",
"e",
".",
"filename",
"=",
"None",
"e",
".",
"lineno",
"=",
"None",
"return",
"e",
"return",
"False"
] | Validate text as a PEP 508 environment marker; return an exception
if invalid or False otherwise. | [
"Validate",
"text",
"as",
"a",
"PEP",
"508",
"environment",
"marker",
";",
"return",
"an",
"exception",
"if",
"invalid",
"or",
"False",
"otherwise",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1352-L1363 |
25,021 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | evaluate_marker | def evaluate_marker(text, extra=None):
"""
Evaluate a PEP 508 environment marker.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid.
This implementation uses the 'pyparsing' module.
"""
try:
marker = packaging.markers.Marker(text)
return marker.evaluate()
except packaging.markers.InvalidMarker as e:
raise SyntaxError(e) | python | def evaluate_marker(text, extra=None):
"""
Evaluate a PEP 508 environment marker.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid.
This implementation uses the 'pyparsing' module.
"""
try:
marker = packaging.markers.Marker(text)
return marker.evaluate()
except packaging.markers.InvalidMarker as e:
raise SyntaxError(e) | [
"def",
"evaluate_marker",
"(",
"text",
",",
"extra",
"=",
"None",
")",
":",
"try",
":",
"marker",
"=",
"packaging",
".",
"markers",
".",
"Marker",
"(",
"text",
")",
"return",
"marker",
".",
"evaluate",
"(",
")",
"except",
"packaging",
".",
"markers",
".",
"InvalidMarker",
"as",
"e",
":",
"raise",
"SyntaxError",
"(",
"e",
")"
] | Evaluate a PEP 508 environment marker.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid.
This implementation uses the 'pyparsing' module. | [
"Evaluate",
"a",
"PEP",
"508",
"environment",
"marker",
".",
"Return",
"a",
"boolean",
"indicating",
"the",
"marker",
"result",
"in",
"this",
"environment",
".",
"Raise",
"SyntaxError",
"if",
"marker",
"is",
"invalid",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1366-L1378 |
25,022 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | find_distributions | def find_distributions(path_item, only=False):
"""Yield distributions accessible via `path_item`"""
importer = get_importer(path_item)
finder = _find_adapter(_distribution_finders, importer)
return finder(importer, path_item, only) | python | def find_distributions(path_item, only=False):
"""Yield distributions accessible via `path_item`"""
importer = get_importer(path_item)
finder = _find_adapter(_distribution_finders, importer)
return finder(importer, path_item, only) | [
"def",
"find_distributions",
"(",
"path_item",
",",
"only",
"=",
"False",
")",
":",
"importer",
"=",
"get_importer",
"(",
"path_item",
")",
"finder",
"=",
"_find_adapter",
"(",
"_distribution_finders",
",",
"importer",
")",
"return",
"finder",
"(",
"importer",
",",
"path_item",
",",
"only",
")"
] | Yield distributions accessible via `path_item` | [
"Yield",
"distributions",
"accessible",
"via",
"path_item"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1870-L1874 |
25,023 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | find_eggs_in_zip | def find_eggs_in_zip(importer, path_item, only=False):
"""
Find eggs in zip files; possibly multiple nested eggs.
"""
if importer.archive.endswith('.whl'):
# wheels are not supported with this finder
# they don't have PKG-INFO metadata, and won't ever contain eggs
return
metadata = EggMetadata(importer)
if metadata.has_metadata('PKG-INFO'):
yield Distribution.from_filename(path_item, metadata=metadata)
if only:
# don't yield nested distros
return
for subitem in metadata.resource_listdir('/'):
if _is_egg_path(subitem):
subpath = os.path.join(path_item, subitem)
dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)
for dist in dists:
yield dist
elif subitem.lower().endswith('.dist-info'):
subpath = os.path.join(path_item, subitem)
submeta = EggMetadata(zipimport.zipimporter(subpath))
submeta.egg_info = subpath
yield Distribution.from_location(path_item, subitem, submeta) | python | def find_eggs_in_zip(importer, path_item, only=False):
"""
Find eggs in zip files; possibly multiple nested eggs.
"""
if importer.archive.endswith('.whl'):
# wheels are not supported with this finder
# they don't have PKG-INFO metadata, and won't ever contain eggs
return
metadata = EggMetadata(importer)
if metadata.has_metadata('PKG-INFO'):
yield Distribution.from_filename(path_item, metadata=metadata)
if only:
# don't yield nested distros
return
for subitem in metadata.resource_listdir('/'):
if _is_egg_path(subitem):
subpath = os.path.join(path_item, subitem)
dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)
for dist in dists:
yield dist
elif subitem.lower().endswith('.dist-info'):
subpath = os.path.join(path_item, subitem)
submeta = EggMetadata(zipimport.zipimporter(subpath))
submeta.egg_info = subpath
yield Distribution.from_location(path_item, subitem, submeta) | [
"def",
"find_eggs_in_zip",
"(",
"importer",
",",
"path_item",
",",
"only",
"=",
"False",
")",
":",
"if",
"importer",
".",
"archive",
".",
"endswith",
"(",
"'.whl'",
")",
":",
"# wheels are not supported with this finder",
"# they don't have PKG-INFO metadata, and won't ever contain eggs",
"return",
"metadata",
"=",
"EggMetadata",
"(",
"importer",
")",
"if",
"metadata",
".",
"has_metadata",
"(",
"'PKG-INFO'",
")",
":",
"yield",
"Distribution",
".",
"from_filename",
"(",
"path_item",
",",
"metadata",
"=",
"metadata",
")",
"if",
"only",
":",
"# don't yield nested distros",
"return",
"for",
"subitem",
"in",
"metadata",
".",
"resource_listdir",
"(",
"'/'",
")",
":",
"if",
"_is_egg_path",
"(",
"subitem",
")",
":",
"subpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_item",
",",
"subitem",
")",
"dists",
"=",
"find_eggs_in_zip",
"(",
"zipimport",
".",
"zipimporter",
"(",
"subpath",
")",
",",
"subpath",
")",
"for",
"dist",
"in",
"dists",
":",
"yield",
"dist",
"elif",
"subitem",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.dist-info'",
")",
":",
"subpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_item",
",",
"subitem",
")",
"submeta",
"=",
"EggMetadata",
"(",
"zipimport",
".",
"zipimporter",
"(",
"subpath",
")",
")",
"submeta",
".",
"egg_info",
"=",
"subpath",
"yield",
"Distribution",
".",
"from_location",
"(",
"path_item",
",",
"subitem",
",",
"submeta",
")"
] | Find eggs in zip files; possibly multiple nested eggs. | [
"Find",
"eggs",
"in",
"zip",
"files",
";",
"possibly",
"multiple",
"nested",
"eggs",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1877-L1901 |
25,024 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | _by_version_descending | def _by_version_descending(names):
"""
Given a list of filenames, return them in descending order
by version number.
>>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'
>>> _by_version_descending(names)
['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar']
>>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'
>>> _by_version_descending(names)
['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']
>>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'
>>> _by_version_descending(names)
['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']
"""
def _by_version(name):
"""
Parse each component of the filename
"""
name, ext = os.path.splitext(name)
parts = itertools.chain(name.split('-'), [ext])
return [packaging.version.parse(part) for part in parts]
return sorted(names, key=_by_version, reverse=True) | python | def _by_version_descending(names):
"""
Given a list of filenames, return them in descending order
by version number.
>>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'
>>> _by_version_descending(names)
['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar']
>>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'
>>> _by_version_descending(names)
['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']
>>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'
>>> _by_version_descending(names)
['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']
"""
def _by_version(name):
"""
Parse each component of the filename
"""
name, ext = os.path.splitext(name)
parts = itertools.chain(name.split('-'), [ext])
return [packaging.version.parse(part) for part in parts]
return sorted(names, key=_by_version, reverse=True) | [
"def",
"_by_version_descending",
"(",
"names",
")",
":",
"def",
"_by_version",
"(",
"name",
")",
":",
"\"\"\"\n Parse each component of the filename\n \"\"\"",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"name",
")",
"parts",
"=",
"itertools",
".",
"chain",
"(",
"name",
".",
"split",
"(",
"'-'",
")",
",",
"[",
"ext",
"]",
")",
"return",
"[",
"packaging",
".",
"version",
".",
"parse",
"(",
"part",
")",
"for",
"part",
"in",
"parts",
"]",
"return",
"sorted",
"(",
"names",
",",
"key",
"=",
"_by_version",
",",
"reverse",
"=",
"True",
")"
] | Given a list of filenames, return them in descending order
by version number.
>>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'
>>> _by_version_descending(names)
['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar']
>>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'
>>> _by_version_descending(names)
['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']
>>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'
>>> _by_version_descending(names)
['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg'] | [
"Given",
"a",
"list",
"of",
"filenames",
"return",
"them",
"in",
"descending",
"order",
"by",
"version",
"number",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1914-L1937 |
25,025 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | find_on_path | def find_on_path(importer, path_item, only=False):
"""Yield distributions accessible on a sys.path directory"""
path_item = _normalize_cached(path_item)
if _is_unpacked_egg(path_item):
yield Distribution.from_filename(
path_item, metadata=PathMetadata(
path_item, os.path.join(path_item, 'EGG-INFO')
)
)
return
entries = safe_listdir(path_item)
# for performance, before sorting by version,
# screen entries for only those that will yield
# distributions
filtered = (
entry
for entry in entries
if dist_factory(path_item, entry, only)
)
# scan for .egg and .egg-info in directory
path_item_entries = _by_version_descending(filtered)
for entry in path_item_entries:
fullpath = os.path.join(path_item, entry)
factory = dist_factory(path_item, entry, only)
for dist in factory(fullpath):
yield dist | python | def find_on_path(importer, path_item, only=False):
"""Yield distributions accessible on a sys.path directory"""
path_item = _normalize_cached(path_item)
if _is_unpacked_egg(path_item):
yield Distribution.from_filename(
path_item, metadata=PathMetadata(
path_item, os.path.join(path_item, 'EGG-INFO')
)
)
return
entries = safe_listdir(path_item)
# for performance, before sorting by version,
# screen entries for only those that will yield
# distributions
filtered = (
entry
for entry in entries
if dist_factory(path_item, entry, only)
)
# scan for .egg and .egg-info in directory
path_item_entries = _by_version_descending(filtered)
for entry in path_item_entries:
fullpath = os.path.join(path_item, entry)
factory = dist_factory(path_item, entry, only)
for dist in factory(fullpath):
yield dist | [
"def",
"find_on_path",
"(",
"importer",
",",
"path_item",
",",
"only",
"=",
"False",
")",
":",
"path_item",
"=",
"_normalize_cached",
"(",
"path_item",
")",
"if",
"_is_unpacked_egg",
"(",
"path_item",
")",
":",
"yield",
"Distribution",
".",
"from_filename",
"(",
"path_item",
",",
"metadata",
"=",
"PathMetadata",
"(",
"path_item",
",",
"os",
".",
"path",
".",
"join",
"(",
"path_item",
",",
"'EGG-INFO'",
")",
")",
")",
"return",
"entries",
"=",
"safe_listdir",
"(",
"path_item",
")",
"# for performance, before sorting by version,",
"# screen entries for only those that will yield",
"# distributions",
"filtered",
"=",
"(",
"entry",
"for",
"entry",
"in",
"entries",
"if",
"dist_factory",
"(",
"path_item",
",",
"entry",
",",
"only",
")",
")",
"# scan for .egg and .egg-info in directory",
"path_item_entries",
"=",
"_by_version_descending",
"(",
"filtered",
")",
"for",
"entry",
"in",
"path_item_entries",
":",
"fullpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_item",
",",
"entry",
")",
"factory",
"=",
"dist_factory",
"(",
"path_item",
",",
"entry",
",",
"only",
")",
"for",
"dist",
"in",
"factory",
"(",
"fullpath",
")",
":",
"yield",
"dist"
] | Yield distributions accessible on a sys.path directory | [
"Yield",
"distributions",
"accessible",
"on",
"a",
"sys",
".",
"path",
"directory"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1940-L1969 |
25,026 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | dist_factory | def dist_factory(path_item, entry, only):
"""
Return a dist_factory for a path_item and entry
"""
lower = entry.lower()
is_meta = any(map(lower.endswith, ('.egg-info', '.dist-info')))
return (
distributions_from_metadata
if is_meta else
find_distributions
if not only and _is_egg_path(entry) else
resolve_egg_link
if not only and lower.endswith('.egg-link') else
NoDists()
) | python | def dist_factory(path_item, entry, only):
"""
Return a dist_factory for a path_item and entry
"""
lower = entry.lower()
is_meta = any(map(lower.endswith, ('.egg-info', '.dist-info')))
return (
distributions_from_metadata
if is_meta else
find_distributions
if not only and _is_egg_path(entry) else
resolve_egg_link
if not only and lower.endswith('.egg-link') else
NoDists()
) | [
"def",
"dist_factory",
"(",
"path_item",
",",
"entry",
",",
"only",
")",
":",
"lower",
"=",
"entry",
".",
"lower",
"(",
")",
"is_meta",
"=",
"any",
"(",
"map",
"(",
"lower",
".",
"endswith",
",",
"(",
"'.egg-info'",
",",
"'.dist-info'",
")",
")",
")",
"return",
"(",
"distributions_from_metadata",
"if",
"is_meta",
"else",
"find_distributions",
"if",
"not",
"only",
"and",
"_is_egg_path",
"(",
"entry",
")",
"else",
"resolve_egg_link",
"if",
"not",
"only",
"and",
"lower",
".",
"endswith",
"(",
"'.egg-link'",
")",
"else",
"NoDists",
"(",
")",
")"
] | Return a dist_factory for a path_item and entry | [
"Return",
"a",
"dist_factory",
"for",
"a",
"path_item",
"and",
"entry"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1972-L1986 |
25,027 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | safe_listdir | def safe_listdir(path):
"""
Attempt to list contents of path, but suppress some exceptions.
"""
try:
return os.listdir(path)
except (PermissionError, NotADirectoryError):
pass
except OSError as e:
# Ignore the directory if does not exist, not a directory or
# permission denied
ignorable = (
e.errno in (errno.ENOTDIR, errno.EACCES, errno.ENOENT)
# Python 2 on Windows needs to be handled this way :(
or getattr(e, "winerror", None) == 267
)
if not ignorable:
raise
return () | python | def safe_listdir(path):
"""
Attempt to list contents of path, but suppress some exceptions.
"""
try:
return os.listdir(path)
except (PermissionError, NotADirectoryError):
pass
except OSError as e:
# Ignore the directory if does not exist, not a directory or
# permission denied
ignorable = (
e.errno in (errno.ENOTDIR, errno.EACCES, errno.ENOENT)
# Python 2 on Windows needs to be handled this way :(
or getattr(e, "winerror", None) == 267
)
if not ignorable:
raise
return () | [
"def",
"safe_listdir",
"(",
"path",
")",
":",
"try",
":",
"return",
"os",
".",
"listdir",
"(",
"path",
")",
"except",
"(",
"PermissionError",
",",
"NotADirectoryError",
")",
":",
"pass",
"except",
"OSError",
"as",
"e",
":",
"# Ignore the directory if does not exist, not a directory or",
"# permission denied",
"ignorable",
"=",
"(",
"e",
".",
"errno",
"in",
"(",
"errno",
".",
"ENOTDIR",
",",
"errno",
".",
"EACCES",
",",
"errno",
".",
"ENOENT",
")",
"# Python 2 on Windows needs to be handled this way :(",
"or",
"getattr",
"(",
"e",
",",
"\"winerror\"",
",",
"None",
")",
"==",
"267",
")",
"if",
"not",
"ignorable",
":",
"raise",
"return",
"(",
")"
] | Attempt to list contents of path, but suppress some exceptions. | [
"Attempt",
"to",
"list",
"contents",
"of",
"path",
"but",
"suppress",
"some",
"exceptions",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2006-L2024 |
25,028 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | non_empty_lines | def non_empty_lines(path):
"""
Yield non-empty lines from file at path
"""
with open(path) as f:
for line in f:
line = line.strip()
if line:
yield line | python | def non_empty_lines(path):
"""
Yield non-empty lines from file at path
"""
with open(path) as f:
for line in f:
line = line.strip()
if line:
yield line | [
"def",
"non_empty_lines",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
":",
"yield",
"line"
] | Yield non-empty lines from file at path | [
"Yield",
"non",
"-",
"empty",
"lines",
"from",
"file",
"at",
"path"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2042-L2050 |
25,029 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | resolve_egg_link | def resolve_egg_link(path):
"""
Given a path to an .egg-link, resolve distributions
present in the referenced path.
"""
referenced_paths = non_empty_lines(path)
resolved_paths = (
os.path.join(os.path.dirname(path), ref)
for ref in referenced_paths
)
dist_groups = map(find_distributions, resolved_paths)
return next(dist_groups, ()) | python | def resolve_egg_link(path):
"""
Given a path to an .egg-link, resolve distributions
present in the referenced path.
"""
referenced_paths = non_empty_lines(path)
resolved_paths = (
os.path.join(os.path.dirname(path), ref)
for ref in referenced_paths
)
dist_groups = map(find_distributions, resolved_paths)
return next(dist_groups, ()) | [
"def",
"resolve_egg_link",
"(",
"path",
")",
":",
"referenced_paths",
"=",
"non_empty_lines",
"(",
"path",
")",
"resolved_paths",
"=",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
",",
"ref",
")",
"for",
"ref",
"in",
"referenced_paths",
")",
"dist_groups",
"=",
"map",
"(",
"find_distributions",
",",
"resolved_paths",
")",
"return",
"next",
"(",
"dist_groups",
",",
"(",
")",
")"
] | Given a path to an .egg-link, resolve distributions
present in the referenced path. | [
"Given",
"a",
"path",
"to",
"an",
".",
"egg",
"-",
"link",
"resolve",
"distributions",
"present",
"in",
"the",
"referenced",
"path",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2053-L2064 |
25,030 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | declare_namespace | def declare_namespace(packageName):
"""Declare that package 'packageName' is a namespace package"""
_imp.acquire_lock()
try:
if packageName in _namespace_packages:
return
path = sys.path
parent, _, _ = packageName.rpartition('.')
if parent:
declare_namespace(parent)
if parent not in _namespace_packages:
__import__(parent)
try:
path = sys.modules[parent].__path__
except AttributeError:
raise TypeError("Not a package:", parent)
# Track what packages are namespaces, so when new path items are added,
# they can be updated
_namespace_packages.setdefault(parent or None, []).append(packageName)
_namespace_packages.setdefault(packageName, [])
for path_item in path:
# Ensure all the parent's path items are reflected in the child,
# if they apply
_handle_ns(packageName, path_item)
finally:
_imp.release_lock() | python | def declare_namespace(packageName):
"""Declare that package 'packageName' is a namespace package"""
_imp.acquire_lock()
try:
if packageName in _namespace_packages:
return
path = sys.path
parent, _, _ = packageName.rpartition('.')
if parent:
declare_namespace(parent)
if parent not in _namespace_packages:
__import__(parent)
try:
path = sys.modules[parent].__path__
except AttributeError:
raise TypeError("Not a package:", parent)
# Track what packages are namespaces, so when new path items are added,
# they can be updated
_namespace_packages.setdefault(parent or None, []).append(packageName)
_namespace_packages.setdefault(packageName, [])
for path_item in path:
# Ensure all the parent's path items are reflected in the child,
# if they apply
_handle_ns(packageName, path_item)
finally:
_imp.release_lock() | [
"def",
"declare_namespace",
"(",
"packageName",
")",
":",
"_imp",
".",
"acquire_lock",
"(",
")",
"try",
":",
"if",
"packageName",
"in",
"_namespace_packages",
":",
"return",
"path",
"=",
"sys",
".",
"path",
"parent",
",",
"_",
",",
"_",
"=",
"packageName",
".",
"rpartition",
"(",
"'.'",
")",
"if",
"parent",
":",
"declare_namespace",
"(",
"parent",
")",
"if",
"parent",
"not",
"in",
"_namespace_packages",
":",
"__import__",
"(",
"parent",
")",
"try",
":",
"path",
"=",
"sys",
".",
"modules",
"[",
"parent",
"]",
".",
"__path__",
"except",
"AttributeError",
":",
"raise",
"TypeError",
"(",
"\"Not a package:\"",
",",
"parent",
")",
"# Track what packages are namespaces, so when new path items are added,",
"# they can be updated",
"_namespace_packages",
".",
"setdefault",
"(",
"parent",
"or",
"None",
",",
"[",
"]",
")",
".",
"append",
"(",
"packageName",
")",
"_namespace_packages",
".",
"setdefault",
"(",
"packageName",
",",
"[",
"]",
")",
"for",
"path_item",
"in",
"path",
":",
"# Ensure all the parent's path items are reflected in the child,",
"# if they apply",
"_handle_ns",
"(",
"packageName",
",",
"path_item",
")",
"finally",
":",
"_imp",
".",
"release_lock",
"(",
")"
] | Declare that package 'packageName' is a namespace package | [
"Declare",
"that",
"package",
"packageName",
"is",
"a",
"namespace",
"package"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2159-L2190 |
25,031 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | fixup_namespace_packages | def fixup_namespace_packages(path_item, parent=None):
"""Ensure that previously-declared namespace packages include path_item"""
_imp.acquire_lock()
try:
for package in _namespace_packages.get(parent, ()):
subpath = _handle_ns(package, path_item)
if subpath:
fixup_namespace_packages(subpath, package)
finally:
_imp.release_lock() | python | def fixup_namespace_packages(path_item, parent=None):
"""Ensure that previously-declared namespace packages include path_item"""
_imp.acquire_lock()
try:
for package in _namespace_packages.get(parent, ()):
subpath = _handle_ns(package, path_item)
if subpath:
fixup_namespace_packages(subpath, package)
finally:
_imp.release_lock() | [
"def",
"fixup_namespace_packages",
"(",
"path_item",
",",
"parent",
"=",
"None",
")",
":",
"_imp",
".",
"acquire_lock",
"(",
")",
"try",
":",
"for",
"package",
"in",
"_namespace_packages",
".",
"get",
"(",
"parent",
",",
"(",
")",
")",
":",
"subpath",
"=",
"_handle_ns",
"(",
"package",
",",
"path_item",
")",
"if",
"subpath",
":",
"fixup_namespace_packages",
"(",
"subpath",
",",
"package",
")",
"finally",
":",
"_imp",
".",
"release_lock",
"(",
")"
] | Ensure that previously-declared namespace packages include path_item | [
"Ensure",
"that",
"previously",
"-",
"declared",
"namespace",
"packages",
"include",
"path_item"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2193-L2202 |
25,032 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | file_ns_handler | def file_ns_handler(importer, path_item, packageName, module):
"""Compute an ns-package subpath for a filesystem or zipfile importer"""
subpath = os.path.join(path_item, packageName.split('.')[-1])
normalized = _normalize_cached(subpath)
for item in module.__path__:
if _normalize_cached(item) == normalized:
break
else:
# Only return the path if it's not already there
return subpath | python | def file_ns_handler(importer, path_item, packageName, module):
"""Compute an ns-package subpath for a filesystem or zipfile importer"""
subpath = os.path.join(path_item, packageName.split('.')[-1])
normalized = _normalize_cached(subpath)
for item in module.__path__:
if _normalize_cached(item) == normalized:
break
else:
# Only return the path if it's not already there
return subpath | [
"def",
"file_ns_handler",
"(",
"importer",
",",
"path_item",
",",
"packageName",
",",
"module",
")",
":",
"subpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_item",
",",
"packageName",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
")",
"normalized",
"=",
"_normalize_cached",
"(",
"subpath",
")",
"for",
"item",
"in",
"module",
".",
"__path__",
":",
"if",
"_normalize_cached",
"(",
"item",
")",
"==",
"normalized",
":",
"break",
"else",
":",
"# Only return the path if it's not already there",
"return",
"subpath"
] | Compute an ns-package subpath for a filesystem or zipfile importer | [
"Compute",
"an",
"ns",
"-",
"package",
"subpath",
"for",
"a",
"filesystem",
"or",
"zipfile",
"importer"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2205-L2215 |
25,033 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | _is_unpacked_egg | def _is_unpacked_egg(path):
"""
Determine if given path appears to be an unpacked egg.
"""
return (
_is_egg_path(path) and
os.path.isfile(os.path.join(path, 'EGG-INFO', 'PKG-INFO'))
) | python | def _is_unpacked_egg(path):
"""
Determine if given path appears to be an unpacked egg.
"""
return (
_is_egg_path(path) and
os.path.isfile(os.path.join(path, 'EGG-INFO', 'PKG-INFO'))
) | [
"def",
"_is_unpacked_egg",
"(",
"path",
")",
":",
"return",
"(",
"_is_egg_path",
"(",
"path",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'EGG-INFO'",
",",
"'PKG-INFO'",
")",
")",
")"
] | Determine if given path appears to be an unpacked egg. | [
"Determine",
"if",
"given",
"path",
"appears",
"to",
"be",
"an",
"unpacked",
"egg",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2263-L2270 |
25,034 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | _version_from_file | def _version_from_file(lines):
"""
Given an iterable of lines from a Metadata file, return
the value of the Version field, if present, or None otherwise.
"""
def is_version_line(line):
return line.lower().startswith('version:')
version_lines = filter(is_version_line, lines)
line = next(iter(version_lines), '')
_, _, value = line.partition(':')
return safe_version(value.strip()) or None | python | def _version_from_file(lines):
"""
Given an iterable of lines from a Metadata file, return
the value of the Version field, if present, or None otherwise.
"""
def is_version_line(line):
return line.lower().startswith('version:')
version_lines = filter(is_version_line, lines)
line = next(iter(version_lines), '')
_, _, value = line.partition(':')
return safe_version(value.strip()) or None | [
"def",
"_version_from_file",
"(",
"lines",
")",
":",
"def",
"is_version_line",
"(",
"line",
")",
":",
"return",
"line",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'version:'",
")",
"version_lines",
"=",
"filter",
"(",
"is_version_line",
",",
"lines",
")",
"line",
"=",
"next",
"(",
"iter",
"(",
"version_lines",
")",
",",
"''",
")",
"_",
",",
"_",
",",
"value",
"=",
"line",
".",
"partition",
"(",
"':'",
")",
"return",
"safe_version",
"(",
"value",
".",
"strip",
"(",
")",
")",
"or",
"None"
] | Given an iterable of lines from a Metadata file, return
the value of the Version field, if present, or None otherwise. | [
"Given",
"an",
"iterable",
"of",
"lines",
"from",
"a",
"Metadata",
"file",
"return",
"the",
"value",
"of",
"the",
"Version",
"field",
"if",
"present",
"or",
"None",
"otherwise",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2451-L2461 |
25,035 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | _find_adapter | def _find_adapter(registry, ob):
"""Return an adapter factory for `ob` from `registry`"""
types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))
for t in types:
if t in registry:
return registry[t] | python | def _find_adapter(registry, ob):
"""Return an adapter factory for `ob` from `registry`"""
types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))
for t in types:
if t in registry:
return registry[t] | [
"def",
"_find_adapter",
"(",
"registry",
",",
"ob",
")",
":",
"types",
"=",
"_always_object",
"(",
"inspect",
".",
"getmro",
"(",
"getattr",
"(",
"ob",
",",
"'__class__'",
",",
"type",
"(",
"ob",
")",
")",
")",
")",
"for",
"t",
"in",
"types",
":",
"if",
"t",
"in",
"registry",
":",
"return",
"registry",
"[",
"t",
"]"
] | Return an adapter factory for `ob` from `registry` | [
"Return",
"an",
"adapter",
"factory",
"for",
"ob",
"from",
"registry"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L3037-L3042 |
25,036 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | VersionConflict.with_context | def with_context(self, required_by):
"""
If required_by is non-empty, return a version of self that is a
ContextualVersionConflict.
"""
if not required_by:
return self
args = self.args + (required_by,)
return ContextualVersionConflict(*args) | python | def with_context(self, required_by):
"""
If required_by is non-empty, return a version of self that is a
ContextualVersionConflict.
"""
if not required_by:
return self
args = self.args + (required_by,)
return ContextualVersionConflict(*args) | [
"def",
"with_context",
"(",
"self",
",",
"required_by",
")",
":",
"if",
"not",
"required_by",
":",
"return",
"self",
"args",
"=",
"self",
".",
"args",
"+",
"(",
"required_by",
",",
")",
"return",
"ContextualVersionConflict",
"(",
"*",
"args",
")"
] | If required_by is non-empty, return a version of self that is a
ContextualVersionConflict. | [
"If",
"required_by",
"is",
"non",
"-",
"empty",
"return",
"a",
"version",
"of",
"self",
"that",
"is",
"a",
"ContextualVersionConflict",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L277-L285 |
25,037 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | WorkingSet._build_master | def _build_master(cls):
"""
Prepare the master working set.
"""
ws = cls()
try:
from __main__ import __requires__
except ImportError:
# The main program does not list any requirements
return ws
# ensure the requirements are met
try:
ws.require(__requires__)
except VersionConflict:
return cls._build_from_requirements(__requires__)
return ws | python | def _build_master(cls):
"""
Prepare the master working set.
"""
ws = cls()
try:
from __main__ import __requires__
except ImportError:
# The main program does not list any requirements
return ws
# ensure the requirements are met
try:
ws.require(__requires__)
except VersionConflict:
return cls._build_from_requirements(__requires__)
return ws | [
"def",
"_build_master",
"(",
"cls",
")",
":",
"ws",
"=",
"cls",
"(",
")",
"try",
":",
"from",
"__main__",
"import",
"__requires__",
"except",
"ImportError",
":",
"# The main program does not list any requirements",
"return",
"ws",
"# ensure the requirements are met",
"try",
":",
"ws",
".",
"require",
"(",
"__requires__",
")",
"except",
"VersionConflict",
":",
"return",
"cls",
".",
"_build_from_requirements",
"(",
"__requires__",
")",
"return",
"ws"
] | Prepare the master working set. | [
"Prepare",
"the",
"master",
"working",
"set",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L568-L585 |
25,038 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | WorkingSet._build_from_requirements | def _build_from_requirements(cls, req_spec):
"""
Build a working set from a requirement spec. Rewrites sys.path.
"""
# try it without defaults already on sys.path
# by starting with an empty path
ws = cls([])
reqs = parse_requirements(req_spec)
dists = ws.resolve(reqs, Environment())
for dist in dists:
ws.add(dist)
# add any missing entries from sys.path
for entry in sys.path:
if entry not in ws.entries:
ws.add_entry(entry)
# then copy back to sys.path
sys.path[:] = ws.entries
return ws | python | def _build_from_requirements(cls, req_spec):
"""
Build a working set from a requirement spec. Rewrites sys.path.
"""
# try it without defaults already on sys.path
# by starting with an empty path
ws = cls([])
reqs = parse_requirements(req_spec)
dists = ws.resolve(reqs, Environment())
for dist in dists:
ws.add(dist)
# add any missing entries from sys.path
for entry in sys.path:
if entry not in ws.entries:
ws.add_entry(entry)
# then copy back to sys.path
sys.path[:] = ws.entries
return ws | [
"def",
"_build_from_requirements",
"(",
"cls",
",",
"req_spec",
")",
":",
"# try it without defaults already on sys.path",
"# by starting with an empty path",
"ws",
"=",
"cls",
"(",
"[",
"]",
")",
"reqs",
"=",
"parse_requirements",
"(",
"req_spec",
")",
"dists",
"=",
"ws",
".",
"resolve",
"(",
"reqs",
",",
"Environment",
"(",
")",
")",
"for",
"dist",
"in",
"dists",
":",
"ws",
".",
"add",
"(",
"dist",
")",
"# add any missing entries from sys.path",
"for",
"entry",
"in",
"sys",
".",
"path",
":",
"if",
"entry",
"not",
"in",
"ws",
".",
"entries",
":",
"ws",
".",
"add_entry",
"(",
"entry",
")",
"# then copy back to sys.path",
"sys",
".",
"path",
"[",
":",
"]",
"=",
"ws",
".",
"entries",
"return",
"ws"
] | Build a working set from a requirement spec. Rewrites sys.path. | [
"Build",
"a",
"working",
"set",
"from",
"a",
"requirement",
"spec",
".",
"Rewrites",
"sys",
".",
"path",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L588-L607 |
25,039 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | WorkingSet.add_entry | def add_entry(self, entry):
"""Add a path item to ``.entries``, finding any distributions on it
``find_distributions(entry, True)`` is used to find distributions
corresponding to the path entry, and they are added. `entry` is
always appended to ``.entries``, even if it is already present.
(This is because ``sys.path`` can contain the same value more than
once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
equal ``sys.path``.)
"""
self.entry_keys.setdefault(entry, [])
self.entries.append(entry)
for dist in find_distributions(entry, True):
self.add(dist, entry, False) | python | def add_entry(self, entry):
"""Add a path item to ``.entries``, finding any distributions on it
``find_distributions(entry, True)`` is used to find distributions
corresponding to the path entry, and they are added. `entry` is
always appended to ``.entries``, even if it is already present.
(This is because ``sys.path`` can contain the same value more than
once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
equal ``sys.path``.)
"""
self.entry_keys.setdefault(entry, [])
self.entries.append(entry)
for dist in find_distributions(entry, True):
self.add(dist, entry, False) | [
"def",
"add_entry",
"(",
"self",
",",
"entry",
")",
":",
"self",
".",
"entry_keys",
".",
"setdefault",
"(",
"entry",
",",
"[",
"]",
")",
"self",
".",
"entries",
".",
"append",
"(",
"entry",
")",
"for",
"dist",
"in",
"find_distributions",
"(",
"entry",
",",
"True",
")",
":",
"self",
".",
"add",
"(",
"dist",
",",
"entry",
",",
"False",
")"
] | Add a path item to ``.entries``, finding any distributions on it
``find_distributions(entry, True)`` is used to find distributions
corresponding to the path entry, and they are added. `entry` is
always appended to ``.entries``, even if it is already present.
(This is because ``sys.path`` can contain the same value more than
once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
equal ``sys.path``.) | [
"Add",
"a",
"path",
"item",
"to",
".",
"entries",
"finding",
"any",
"distributions",
"on",
"it"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L609-L622 |
25,040 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | WorkingSet.iter_entry_points | def iter_entry_points(self, group, name=None):
"""Yield entry point objects from `group` matching `name`
If `name` is None, yields all entry points in `group` from all
distributions in the working set, otherwise only ones matching
both `group` and `name` are yielded (in distribution order).
"""
return (
entry
for dist in self
for entry in dist.get_entry_map(group).values()
if name is None or name == entry.name
) | python | def iter_entry_points(self, group, name=None):
"""Yield entry point objects from `group` matching `name`
If `name` is None, yields all entry points in `group` from all
distributions in the working set, otherwise only ones matching
both `group` and `name` are yielded (in distribution order).
"""
return (
entry
for dist in self
for entry in dist.get_entry_map(group).values()
if name is None or name == entry.name
) | [
"def",
"iter_entry_points",
"(",
"self",
",",
"group",
",",
"name",
"=",
"None",
")",
":",
"return",
"(",
"entry",
"for",
"dist",
"in",
"self",
"for",
"entry",
"in",
"dist",
".",
"get_entry_map",
"(",
"group",
")",
".",
"values",
"(",
")",
"if",
"name",
"is",
"None",
"or",
"name",
"==",
"entry",
".",
"name",
")"
] | Yield entry point objects from `group` matching `name`
If `name` is None, yields all entry points in `group` from all
distributions in the working set, otherwise only ones matching
both `group` and `name` are yielded (in distribution order). | [
"Yield",
"entry",
"point",
"objects",
"from",
"group",
"matching",
"name"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L644-L656 |
25,041 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | WorkingSet.run_script | def run_script(self, requires, script_name):
"""Locate distribution for `requires` and run `script_name` script"""
ns = sys._getframe(1).f_globals
name = ns['__name__']
ns.clear()
ns['__name__'] = name
self.require(requires)[0].run_script(script_name, ns) | python | def run_script(self, requires, script_name):
"""Locate distribution for `requires` and run `script_name` script"""
ns = sys._getframe(1).f_globals
name = ns['__name__']
ns.clear()
ns['__name__'] = name
self.require(requires)[0].run_script(script_name, ns) | [
"def",
"run_script",
"(",
"self",
",",
"requires",
",",
"script_name",
")",
":",
"ns",
"=",
"sys",
".",
"_getframe",
"(",
"1",
")",
".",
"f_globals",
"name",
"=",
"ns",
"[",
"'__name__'",
"]",
"ns",
".",
"clear",
"(",
")",
"ns",
"[",
"'__name__'",
"]",
"=",
"name",
"self",
".",
"require",
"(",
"requires",
")",
"[",
"0",
"]",
".",
"run_script",
"(",
"script_name",
",",
"ns",
")"
] | Locate distribution for `requires` and run `script_name` script | [
"Locate",
"distribution",
"for",
"requires",
"and",
"run",
"script_name",
"script"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L658-L664 |
25,042 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | WorkingSet.require | def require(self, *requirements):
"""Ensure that distributions matching `requirements` are activated
`requirements` must be a string or a (possibly-nested) sequence
thereof, specifying the distributions and versions required. The
return value is a sequence of the distributions that needed to be
activated to fulfill the requirements; all relevant distributions are
included, even if they were already activated in this working set.
"""
needed = self.resolve(parse_requirements(requirements))
for dist in needed:
self.add(dist)
return needed | python | def require(self, *requirements):
"""Ensure that distributions matching `requirements` are activated
`requirements` must be a string or a (possibly-nested) sequence
thereof, specifying the distributions and versions required. The
return value is a sequence of the distributions that needed to be
activated to fulfill the requirements; all relevant distributions are
included, even if they were already activated in this working set.
"""
needed = self.resolve(parse_requirements(requirements))
for dist in needed:
self.add(dist)
return needed | [
"def",
"require",
"(",
"self",
",",
"*",
"requirements",
")",
":",
"needed",
"=",
"self",
".",
"resolve",
"(",
"parse_requirements",
"(",
"requirements",
")",
")",
"for",
"dist",
"in",
"needed",
":",
"self",
".",
"add",
"(",
"dist",
")",
"return",
"needed"
] | Ensure that distributions matching `requirements` are activated
`requirements` must be a string or a (possibly-nested) sequence
thereof, specifying the distributions and versions required. The
return value is a sequence of the distributions that needed to be
activated to fulfill the requirements; all relevant distributions are
included, even if they were already activated in this working set. | [
"Ensure",
"that",
"distributions",
"matching",
"requirements",
"are",
"activated"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L889-L903 |
25,043 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | WorkingSet.subscribe | def subscribe(self, callback, existing=True):
"""Invoke `callback` for all distributions
If `existing=True` (default),
call on all existing ones, as well.
"""
if callback in self.callbacks:
return
self.callbacks.append(callback)
if not existing:
return
for dist in self:
callback(dist) | python | def subscribe(self, callback, existing=True):
"""Invoke `callback` for all distributions
If `existing=True` (default),
call on all existing ones, as well.
"""
if callback in self.callbacks:
return
self.callbacks.append(callback)
if not existing:
return
for dist in self:
callback(dist) | [
"def",
"subscribe",
"(",
"self",
",",
"callback",
",",
"existing",
"=",
"True",
")",
":",
"if",
"callback",
"in",
"self",
".",
"callbacks",
":",
"return",
"self",
".",
"callbacks",
".",
"append",
"(",
"callback",
")",
"if",
"not",
"existing",
":",
"return",
"for",
"dist",
"in",
"self",
":",
"callback",
"(",
"dist",
")"
] | Invoke `callback` for all distributions
If `existing=True` (default),
call on all existing ones, as well. | [
"Invoke",
"callback",
"for",
"all",
"distributions"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L905-L917 |
25,044 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | _ReqExtras.markers_pass | def markers_pass(self, req, extras=None):
"""
Evaluate markers for req against each extra that
demanded it.
Return False if the req has a marker and fails
evaluation. Otherwise, return True.
"""
extra_evals = (
req.marker.evaluate({'extra': extra})
for extra in self.get(req, ()) + (extras or (None,))
)
return not req.marker or any(extra_evals) | python | def markers_pass(self, req, extras=None):
"""
Evaluate markers for req against each extra that
demanded it.
Return False if the req has a marker and fails
evaluation. Otherwise, return True.
"""
extra_evals = (
req.marker.evaluate({'extra': extra})
for extra in self.get(req, ()) + (extras or (None,))
)
return not req.marker or any(extra_evals) | [
"def",
"markers_pass",
"(",
"self",
",",
"req",
",",
"extras",
"=",
"None",
")",
":",
"extra_evals",
"=",
"(",
"req",
".",
"marker",
".",
"evaluate",
"(",
"{",
"'extra'",
":",
"extra",
"}",
")",
"for",
"extra",
"in",
"self",
".",
"get",
"(",
"req",
",",
"(",
")",
")",
"+",
"(",
"extras",
"or",
"(",
"None",
",",
")",
")",
")",
"return",
"not",
"req",
".",
"marker",
"or",
"any",
"(",
"extra_evals",
")"
] | Evaluate markers for req against each extra that
demanded it.
Return False if the req has a marker and fails
evaluation. Otherwise, return True. | [
"Evaluate",
"markers",
"for",
"req",
"against",
"each",
"extra",
"that",
"demanded",
"it",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L942-L954 |
25,045 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | Environment.scan | def scan(self, search_path=None):
"""Scan `search_path` for distributions usable in this environment
Any distributions found are added to the environment.
`search_path` should be a sequence of ``sys.path`` items. If not
supplied, ``sys.path`` is used. Only distributions conforming to
the platform/python version defined at initialization are added.
"""
if search_path is None:
search_path = sys.path
for item in search_path:
for dist in find_distributions(item):
self.add(dist) | python | def scan(self, search_path=None):
"""Scan `search_path` for distributions usable in this environment
Any distributions found are added to the environment.
`search_path` should be a sequence of ``sys.path`` items. If not
supplied, ``sys.path`` is used. Only distributions conforming to
the platform/python version defined at initialization are added.
"""
if search_path is None:
search_path = sys.path
for item in search_path:
for dist in find_distributions(item):
self.add(dist) | [
"def",
"scan",
"(",
"self",
",",
"search_path",
"=",
"None",
")",
":",
"if",
"search_path",
"is",
"None",
":",
"search_path",
"=",
"sys",
".",
"path",
"for",
"item",
"in",
"search_path",
":",
"for",
"dist",
"in",
"find_distributions",
"(",
"item",
")",
":",
"self",
".",
"add",
"(",
"dist",
")"
] | Scan `search_path` for distributions usable in this environment
Any distributions found are added to the environment.
`search_path` should be a sequence of ``sys.path`` items. If not
supplied, ``sys.path`` is used. Only distributions conforming to
the platform/python version defined at initialization are added. | [
"Scan",
"search_path",
"for",
"distributions",
"usable",
"in",
"this",
"environment"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1002-L1015 |
25,046 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | Environment.best_match | def best_match(
self, req, working_set, installer=None, replace_conflicting=False):
"""Find distribution best matching `req` and usable on `working_set`
This calls the ``find(req)`` method of the `working_set` to see if a
suitable distribution is already active. (This may raise
``VersionConflict`` if an unsuitable version of the project is already
active in the specified `working_set`.) If a suitable distribution
isn't active, this method returns the newest distribution in the
environment that meets the ``Requirement`` in `req`. If no suitable
distribution is found, and `installer` is supplied, then the result of
calling the environment's ``obtain(req, installer)`` method will be
returned.
"""
try:
dist = working_set.find(req)
except VersionConflict:
if not replace_conflicting:
raise
dist = None
if dist is not None:
return dist
for dist in self[req.key]:
if dist in req:
return dist
# try to download/install
return self.obtain(req, installer) | python | def best_match(
self, req, working_set, installer=None, replace_conflicting=False):
"""Find distribution best matching `req` and usable on `working_set`
This calls the ``find(req)`` method of the `working_set` to see if a
suitable distribution is already active. (This may raise
``VersionConflict`` if an unsuitable version of the project is already
active in the specified `working_set`.) If a suitable distribution
isn't active, this method returns the newest distribution in the
environment that meets the ``Requirement`` in `req`. If no suitable
distribution is found, and `installer` is supplied, then the result of
calling the environment's ``obtain(req, installer)`` method will be
returned.
"""
try:
dist = working_set.find(req)
except VersionConflict:
if not replace_conflicting:
raise
dist = None
if dist is not None:
return dist
for dist in self[req.key]:
if dist in req:
return dist
# try to download/install
return self.obtain(req, installer) | [
"def",
"best_match",
"(",
"self",
",",
"req",
",",
"working_set",
",",
"installer",
"=",
"None",
",",
"replace_conflicting",
"=",
"False",
")",
":",
"try",
":",
"dist",
"=",
"working_set",
".",
"find",
"(",
"req",
")",
"except",
"VersionConflict",
":",
"if",
"not",
"replace_conflicting",
":",
"raise",
"dist",
"=",
"None",
"if",
"dist",
"is",
"not",
"None",
":",
"return",
"dist",
"for",
"dist",
"in",
"self",
"[",
"req",
".",
"key",
"]",
":",
"if",
"dist",
"in",
"req",
":",
"return",
"dist",
"# try to download/install",
"return",
"self",
".",
"obtain",
"(",
"req",
",",
"installer",
")"
] | Find distribution best matching `req` and usable on `working_set`
This calls the ``find(req)`` method of the `working_set` to see if a
suitable distribution is already active. (This may raise
``VersionConflict`` if an unsuitable version of the project is already
active in the specified `working_set`.) If a suitable distribution
isn't active, this method returns the newest distribution in the
environment that meets the ``Requirement`` in `req`. If no suitable
distribution is found, and `installer` is supplied, then the result of
calling the environment's ``obtain(req, installer)`` method will be
returned. | [
"Find",
"distribution",
"best",
"matching",
"req",
"and",
"usable",
"on",
"working_set"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1037-L1063 |
25,047 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | ResourceManager.postprocess | def postprocess(self, tempname, filename):
"""Perform any platform-specific postprocessing of `tempname`
This is where Mac header rewrites should be done; other platforms don't
have anything special they should do.
Resource providers should call this method ONLY after successfully
extracting a compressed resource. They must NOT call it on resources
that are already in the filesystem.
`tempname` is the current (temporary) name of the file, and `filename`
is the name it will be renamed to by the caller after this routine
returns.
"""
if os.name == 'posix':
# Make the resource executable
mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777
os.chmod(tempname, mode) | python | def postprocess(self, tempname, filename):
"""Perform any platform-specific postprocessing of `tempname`
This is where Mac header rewrites should be done; other platforms don't
have anything special they should do.
Resource providers should call this method ONLY after successfully
extracting a compressed resource. They must NOT call it on resources
that are already in the filesystem.
`tempname` is the current (temporary) name of the file, and `filename`
is the name it will be renamed to by the caller after this routine
returns.
"""
if os.name == 'posix':
# Make the resource executable
mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777
os.chmod(tempname, mode) | [
"def",
"postprocess",
"(",
"self",
",",
"tempname",
",",
"filename",
")",
":",
"if",
"os",
".",
"name",
"==",
"'posix'",
":",
"# Make the resource executable",
"mode",
"=",
"(",
"(",
"os",
".",
"stat",
"(",
"tempname",
")",
".",
"st_mode",
")",
"|",
"0o555",
")",
"&",
"0o7777",
"os",
".",
"chmod",
"(",
"tempname",
",",
"mode",
")"
] | Perform any platform-specific postprocessing of `tempname`
This is where Mac header rewrites should be done; other platforms don't
have anything special they should do.
Resource providers should call this method ONLY after successfully
extracting a compressed resource. They must NOT call it on resources
that are already in the filesystem.
`tempname` is the current (temporary) name of the file, and `filename`
is the name it will be renamed to by the caller after this routine
returns. | [
"Perform",
"any",
"platform",
"-",
"specific",
"postprocessing",
"of",
"tempname"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1243-L1261 |
25,048 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | ZipManifests.build | def build(cls, path):
"""
Build a dictionary similar to the zipimport directory
caches, except instead of tuples, store ZipInfo objects.
Use a platform-specific path separator (os.sep) for the path keys
for compatibility with pypy on Windows.
"""
with zipfile.ZipFile(path) as zfile:
items = (
(
name.replace('/', os.sep),
zfile.getinfo(name),
)
for name in zfile.namelist()
)
return dict(items) | python | def build(cls, path):
"""
Build a dictionary similar to the zipimport directory
caches, except instead of tuples, store ZipInfo objects.
Use a platform-specific path separator (os.sep) for the path keys
for compatibility with pypy on Windows.
"""
with zipfile.ZipFile(path) as zfile:
items = (
(
name.replace('/', os.sep),
zfile.getinfo(name),
)
for name in zfile.namelist()
)
return dict(items) | [
"def",
"build",
"(",
"cls",
",",
"path",
")",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"path",
")",
"as",
"zfile",
":",
"items",
"=",
"(",
"(",
"name",
".",
"replace",
"(",
"'/'",
",",
"os",
".",
"sep",
")",
",",
"zfile",
".",
"getinfo",
"(",
"name",
")",
",",
")",
"for",
"name",
"in",
"zfile",
".",
"namelist",
"(",
")",
")",
"return",
"dict",
"(",
"items",
")"
] | Build a dictionary similar to the zipimport directory
caches, except instead of tuples, store ZipInfo objects.
Use a platform-specific path separator (os.sep) for the path keys
for compatibility with pypy on Windows. | [
"Build",
"a",
"dictionary",
"similar",
"to",
"the",
"zipimport",
"directory",
"caches",
"except",
"instead",
"of",
"tuples",
"store",
"ZipInfo",
"objects",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1562-L1578 |
25,049 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | MemoizedZipManifests.load | def load(self, path):
"""
Load a manifest at path or return a suitable manifest already loaded.
"""
path = os.path.normpath(path)
mtime = os.stat(path).st_mtime
if path not in self or self[path].mtime != mtime:
manifest = self.build(path)
self[path] = self.manifest_mod(manifest, mtime)
return self[path].manifest | python | def load(self, path):
"""
Load a manifest at path or return a suitable manifest already loaded.
"""
path = os.path.normpath(path)
mtime = os.stat(path).st_mtime
if path not in self or self[path].mtime != mtime:
manifest = self.build(path)
self[path] = self.manifest_mod(manifest, mtime)
return self[path].manifest | [
"def",
"load",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"path",
")",
"mtime",
"=",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_mtime",
"if",
"path",
"not",
"in",
"self",
"or",
"self",
"[",
"path",
"]",
".",
"mtime",
"!=",
"mtime",
":",
"manifest",
"=",
"self",
".",
"build",
"(",
"path",
")",
"self",
"[",
"path",
"]",
"=",
"self",
".",
"manifest_mod",
"(",
"manifest",
",",
"mtime",
")",
"return",
"self",
"[",
"path",
"]",
".",
"manifest"
] | Load a manifest at path or return a suitable manifest already loaded. | [
"Load",
"a",
"manifest",
"at",
"path",
"or",
"return",
"a",
"suitable",
"manifest",
"already",
"loaded",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1589-L1600 |
25,050 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | ZipProvider._is_current | def _is_current(self, file_path, zip_path):
"""
Return True if the file_path is current for this zip_path
"""
timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
if not os.path.isfile(file_path):
return False
stat = os.stat(file_path)
if stat.st_size != size or stat.st_mtime != timestamp:
return False
# check that the contents match
zip_contents = self.loader.get_data(zip_path)
with open(file_path, 'rb') as f:
file_contents = f.read()
return zip_contents == file_contents | python | def _is_current(self, file_path, zip_path):
"""
Return True if the file_path is current for this zip_path
"""
timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
if not os.path.isfile(file_path):
return False
stat = os.stat(file_path)
if stat.st_size != size or stat.st_mtime != timestamp:
return False
# check that the contents match
zip_contents = self.loader.get_data(zip_path)
with open(file_path, 'rb') as f:
file_contents = f.read()
return zip_contents == file_contents | [
"def",
"_is_current",
"(",
"self",
",",
"file_path",
",",
"zip_path",
")",
":",
"timestamp",
",",
"size",
"=",
"self",
".",
"_get_date_and_size",
"(",
"self",
".",
"zipinfo",
"[",
"zip_path",
"]",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
":",
"return",
"False",
"stat",
"=",
"os",
".",
"stat",
"(",
"file_path",
")",
"if",
"stat",
".",
"st_size",
"!=",
"size",
"or",
"stat",
".",
"st_mtime",
"!=",
"timestamp",
":",
"return",
"False",
"# check that the contents match",
"zip_contents",
"=",
"self",
".",
"loader",
".",
"get_data",
"(",
"zip_path",
")",
"with",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"as",
"f",
":",
"file_contents",
"=",
"f",
".",
"read",
"(",
")",
"return",
"zip_contents",
"==",
"file_contents"
] | Return True if the file_path is current for this zip_path | [
"Return",
"True",
"if",
"the",
"file_path",
"is",
"current",
"for",
"this",
"zip_path"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1716-L1730 |
25,051 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | EntryPoint.load | def load(self, require=True, *args, **kwargs):
"""
Require packages for this EntryPoint, then resolve it.
"""
if not require or args or kwargs:
warnings.warn(
"Parameters to load are deprecated. Call .resolve and "
".require separately.",
PkgResourcesDeprecationWarning,
stacklevel=2,
)
if require:
self.require(*args, **kwargs)
return self.resolve() | python | def load(self, require=True, *args, **kwargs):
"""
Require packages for this EntryPoint, then resolve it.
"""
if not require or args or kwargs:
warnings.warn(
"Parameters to load are deprecated. Call .resolve and "
".require separately.",
PkgResourcesDeprecationWarning,
stacklevel=2,
)
if require:
self.require(*args, **kwargs)
return self.resolve() | [
"def",
"load",
"(",
"self",
",",
"require",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"require",
"or",
"args",
"or",
"kwargs",
":",
"warnings",
".",
"warn",
"(",
"\"Parameters to load are deprecated. Call .resolve and \"",
"\".require separately.\"",
",",
"PkgResourcesDeprecationWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"if",
"require",
":",
"self",
".",
"require",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"resolve",
"(",
")"
] | Require packages for this EntryPoint, then resolve it. | [
"Require",
"packages",
"for",
"this",
"EntryPoint",
"then",
"resolve",
"it",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2333-L2346 |
25,052 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | EntryPoint.resolve | def resolve(self):
"""
Resolve the entry point from its module and attrs.
"""
module = __import__(self.module_name, fromlist=['__name__'], level=0)
try:
return functools.reduce(getattr, self.attrs, module)
except AttributeError as exc:
raise ImportError(str(exc)) | python | def resolve(self):
"""
Resolve the entry point from its module and attrs.
"""
module = __import__(self.module_name, fromlist=['__name__'], level=0)
try:
return functools.reduce(getattr, self.attrs, module)
except AttributeError as exc:
raise ImportError(str(exc)) | [
"def",
"resolve",
"(",
"self",
")",
":",
"module",
"=",
"__import__",
"(",
"self",
".",
"module_name",
",",
"fromlist",
"=",
"[",
"'__name__'",
"]",
",",
"level",
"=",
"0",
")",
"try",
":",
"return",
"functools",
".",
"reduce",
"(",
"getattr",
",",
"self",
".",
"attrs",
",",
"module",
")",
"except",
"AttributeError",
"as",
"exc",
":",
"raise",
"ImportError",
"(",
"str",
"(",
"exc",
")",
")"
] | Resolve the entry point from its module and attrs. | [
"Resolve",
"the",
"entry",
"point",
"from",
"its",
"module",
"and",
"attrs",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2348-L2356 |
25,053 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | EntryPoint.parse | def parse(cls, src, dist=None):
"""Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1, extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional
"""
m = cls.pattern.match(src)
if not m:
msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
raise ValueError(msg, src)
res = m.groupdict()
extras = cls._parse_extras(res['extras'])
attrs = res['attr'].split('.') if res['attr'] else ()
return cls(res['name'], res['module'], attrs, extras, dist) | python | def parse(cls, src, dist=None):
"""Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1, extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional
"""
m = cls.pattern.match(src)
if not m:
msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
raise ValueError(msg, src)
res = m.groupdict()
extras = cls._parse_extras(res['extras'])
attrs = res['attr'].split('.') if res['attr'] else ()
return cls(res['name'], res['module'], attrs, extras, dist) | [
"def",
"parse",
"(",
"cls",
",",
"src",
",",
"dist",
"=",
"None",
")",
":",
"m",
"=",
"cls",
".",
"pattern",
".",
"match",
"(",
"src",
")",
"if",
"not",
"m",
":",
"msg",
"=",
"\"EntryPoint must be in 'name=module:attrs [extras]' format\"",
"raise",
"ValueError",
"(",
"msg",
",",
"src",
")",
"res",
"=",
"m",
".",
"groupdict",
"(",
")",
"extras",
"=",
"cls",
".",
"_parse_extras",
"(",
"res",
"[",
"'extras'",
"]",
")",
"attrs",
"=",
"res",
"[",
"'attr'",
"]",
".",
"split",
"(",
"'.'",
")",
"if",
"res",
"[",
"'attr'",
"]",
"else",
"(",
")",
"return",
"cls",
"(",
"res",
"[",
"'name'",
"]",
",",
"res",
"[",
"'module'",
"]",
",",
"attrs",
",",
"extras",
",",
"dist",
")"
] | Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1, extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional | [
"Parse",
"a",
"single",
"entry",
"point",
"from",
"string",
"src"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2381-L2398 |
25,054 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | EntryPoint.parse_group | def parse_group(cls, group, lines, dist=None):
"""Parse an entry point group"""
if not MODULE(group):
raise ValueError("Invalid group name", group)
this = {}
for line in yield_lines(lines):
ep = cls.parse(line, dist)
if ep.name in this:
raise ValueError("Duplicate entry point", group, ep.name)
this[ep.name] = ep
return this | python | def parse_group(cls, group, lines, dist=None):
"""Parse an entry point group"""
if not MODULE(group):
raise ValueError("Invalid group name", group)
this = {}
for line in yield_lines(lines):
ep = cls.parse(line, dist)
if ep.name in this:
raise ValueError("Duplicate entry point", group, ep.name)
this[ep.name] = ep
return this | [
"def",
"parse_group",
"(",
"cls",
",",
"group",
",",
"lines",
",",
"dist",
"=",
"None",
")",
":",
"if",
"not",
"MODULE",
"(",
"group",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid group name\"",
",",
"group",
")",
"this",
"=",
"{",
"}",
"for",
"line",
"in",
"yield_lines",
"(",
"lines",
")",
":",
"ep",
"=",
"cls",
".",
"parse",
"(",
"line",
",",
"dist",
")",
"if",
"ep",
".",
"name",
"in",
"this",
":",
"raise",
"ValueError",
"(",
"\"Duplicate entry point\"",
",",
"group",
",",
"ep",
".",
"name",
")",
"this",
"[",
"ep",
".",
"name",
"]",
"=",
"ep",
"return",
"this"
] | Parse an entry point group | [
"Parse",
"an",
"entry",
"point",
"group"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2410-L2420 |
25,055 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | EntryPoint.parse_map | def parse_map(cls, data, dist=None):
"""Parse a map of entry point groups"""
if isinstance(data, dict):
data = data.items()
else:
data = split_sections(data)
maps = {}
for group, lines in data:
if group is None:
if not lines:
continue
raise ValueError("Entry points must be listed in groups")
group = group.strip()
if group in maps:
raise ValueError("Duplicate group name", group)
maps[group] = cls.parse_group(group, lines, dist)
return maps | python | def parse_map(cls, data, dist=None):
"""Parse a map of entry point groups"""
if isinstance(data, dict):
data = data.items()
else:
data = split_sections(data)
maps = {}
for group, lines in data:
if group is None:
if not lines:
continue
raise ValueError("Entry points must be listed in groups")
group = group.strip()
if group in maps:
raise ValueError("Duplicate group name", group)
maps[group] = cls.parse_group(group, lines, dist)
return maps | [
"def",
"parse_map",
"(",
"cls",
",",
"data",
",",
"dist",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"data",
"=",
"data",
".",
"items",
"(",
")",
"else",
":",
"data",
"=",
"split_sections",
"(",
"data",
")",
"maps",
"=",
"{",
"}",
"for",
"group",
",",
"lines",
"in",
"data",
":",
"if",
"group",
"is",
"None",
":",
"if",
"not",
"lines",
":",
"continue",
"raise",
"ValueError",
"(",
"\"Entry points must be listed in groups\"",
")",
"group",
"=",
"group",
".",
"strip",
"(",
")",
"if",
"group",
"in",
"maps",
":",
"raise",
"ValueError",
"(",
"\"Duplicate group name\"",
",",
"group",
")",
"maps",
"[",
"group",
"]",
"=",
"cls",
".",
"parse_group",
"(",
"group",
",",
"lines",
",",
"dist",
")",
"return",
"maps"
] | Parse a map of entry point groups | [
"Parse",
"a",
"map",
"of",
"entry",
"point",
"groups"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2423-L2439 |
25,056 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | Distribution._filter_extras | def _filter_extras(dm):
"""
Given a mapping of extras to dependencies, strip off
environment markers and filter out any dependencies
not matching the markers.
"""
for extra in list(filter(None, dm)):
new_extra = extra
reqs = dm.pop(extra)
new_extra, _, marker = extra.partition(':')
fails_marker = marker and (
invalid_marker(marker)
or not evaluate_marker(marker)
)
if fails_marker:
reqs = []
new_extra = safe_extra(new_extra) or None
dm.setdefault(new_extra, []).extend(reqs)
return dm | python | def _filter_extras(dm):
"""
Given a mapping of extras to dependencies, strip off
environment markers and filter out any dependencies
not matching the markers.
"""
for extra in list(filter(None, dm)):
new_extra = extra
reqs = dm.pop(extra)
new_extra, _, marker = extra.partition(':')
fails_marker = marker and (
invalid_marker(marker)
or not evaluate_marker(marker)
)
if fails_marker:
reqs = []
new_extra = safe_extra(new_extra) or None
dm.setdefault(new_extra, []).extend(reqs)
return dm | [
"def",
"_filter_extras",
"(",
"dm",
")",
":",
"for",
"extra",
"in",
"list",
"(",
"filter",
"(",
"None",
",",
"dm",
")",
")",
":",
"new_extra",
"=",
"extra",
"reqs",
"=",
"dm",
".",
"pop",
"(",
"extra",
")",
"new_extra",
",",
"_",
",",
"marker",
"=",
"extra",
".",
"partition",
"(",
"':'",
")",
"fails_marker",
"=",
"marker",
"and",
"(",
"invalid_marker",
"(",
"marker",
")",
"or",
"not",
"evaluate_marker",
"(",
"marker",
")",
")",
"if",
"fails_marker",
":",
"reqs",
"=",
"[",
"]",
"new_extra",
"=",
"safe_extra",
"(",
"new_extra",
")",
"or",
"None",
"dm",
".",
"setdefault",
"(",
"new_extra",
",",
"[",
"]",
")",
".",
"extend",
"(",
"reqs",
")",
"return",
"dm"
] | Given a mapping of extras to dependencies, strip off
environment markers and filter out any dependencies
not matching the markers. | [
"Given",
"a",
"mapping",
"of",
"extras",
"to",
"dependencies",
"strip",
"off",
"environment",
"markers",
"and",
"filter",
"out",
"any",
"dependencies",
"not",
"matching",
"the",
"markers",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2605-L2624 |
25,057 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | Distribution.requires | def requires(self, extras=()):
"""List of Requirements needed for this distro if `extras` are used"""
dm = self._dep_map
deps = []
deps.extend(dm.get(None, ()))
for ext in extras:
try:
deps.extend(dm[safe_extra(ext)])
except KeyError:
raise UnknownExtra(
"%s has no such extra feature %r" % (self, ext)
)
return deps | python | def requires(self, extras=()):
"""List of Requirements needed for this distro if `extras` are used"""
dm = self._dep_map
deps = []
deps.extend(dm.get(None, ()))
for ext in extras:
try:
deps.extend(dm[safe_extra(ext)])
except KeyError:
raise UnknownExtra(
"%s has no such extra feature %r" % (self, ext)
)
return deps | [
"def",
"requires",
"(",
"self",
",",
"extras",
"=",
"(",
")",
")",
":",
"dm",
"=",
"self",
".",
"_dep_map",
"deps",
"=",
"[",
"]",
"deps",
".",
"extend",
"(",
"dm",
".",
"get",
"(",
"None",
",",
"(",
")",
")",
")",
"for",
"ext",
"in",
"extras",
":",
"try",
":",
"deps",
".",
"extend",
"(",
"dm",
"[",
"safe_extra",
"(",
"ext",
")",
"]",
")",
"except",
"KeyError",
":",
"raise",
"UnknownExtra",
"(",
"\"%s has no such extra feature %r\"",
"%",
"(",
"self",
",",
"ext",
")",
")",
"return",
"deps"
] | List of Requirements needed for this distro if `extras` are used | [
"List",
"of",
"Requirements",
"needed",
"for",
"this",
"distro",
"if",
"extras",
"are",
"used"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2633-L2645 |
25,058 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | Distribution.egg_name | def egg_name(self):
"""Return what this distribution's standard .egg filename should be"""
filename = "%s-%s-py%s" % (
to_filename(self.project_name), to_filename(self.version),
self.py_version or PY_MAJOR
)
if self.platform:
filename += '-' + self.platform
return filename | python | def egg_name(self):
"""Return what this distribution's standard .egg filename should be"""
filename = "%s-%s-py%s" % (
to_filename(self.project_name), to_filename(self.version),
self.py_version or PY_MAJOR
)
if self.platform:
filename += '-' + self.platform
return filename | [
"def",
"egg_name",
"(",
"self",
")",
":",
"filename",
"=",
"\"%s-%s-py%s\"",
"%",
"(",
"to_filename",
"(",
"self",
".",
"project_name",
")",
",",
"to_filename",
"(",
"self",
".",
"version",
")",
",",
"self",
".",
"py_version",
"or",
"PY_MAJOR",
")",
"if",
"self",
".",
"platform",
":",
"filename",
"+=",
"'-'",
"+",
"self",
".",
"platform",
"return",
"filename"
] | Return what this distribution's standard .egg filename should be | [
"Return",
"what",
"this",
"distribution",
"s",
"standard",
".",
"egg",
"filename",
"should",
"be"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2663-L2672 |
25,059 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | Distribution.as_requirement | def as_requirement(self):
"""Return a ``Requirement`` that matches this distribution exactly"""
if isinstance(self.parsed_version, packaging.version.Version):
spec = "%s==%s" % (self.project_name, self.parsed_version)
else:
spec = "%s===%s" % (self.project_name, self.parsed_version)
return Requirement.parse(spec) | python | def as_requirement(self):
"""Return a ``Requirement`` that matches this distribution exactly"""
if isinstance(self.parsed_version, packaging.version.Version):
spec = "%s==%s" % (self.project_name, self.parsed_version)
else:
spec = "%s===%s" % (self.project_name, self.parsed_version)
return Requirement.parse(spec) | [
"def",
"as_requirement",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"parsed_version",
",",
"packaging",
".",
"version",
".",
"Version",
")",
":",
"spec",
"=",
"\"%s==%s\"",
"%",
"(",
"self",
".",
"project_name",
",",
"self",
".",
"parsed_version",
")",
"else",
":",
"spec",
"=",
"\"%s===%s\"",
"%",
"(",
"self",
".",
"project_name",
",",
"self",
".",
"parsed_version",
")",
"return",
"Requirement",
".",
"parse",
"(",
"spec",
")"
] | Return a ``Requirement`` that matches this distribution exactly | [
"Return",
"a",
"Requirement",
"that",
"matches",
"this",
"distribution",
"exactly"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2714-L2721 |
25,060 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | Distribution.load_entry_point | def load_entry_point(self, group, name):
"""Return the `name` entry point of `group` or raise ImportError"""
ep = self.get_entry_info(group, name)
if ep is None:
raise ImportError("Entry point %r not found" % ((group, name),))
return ep.load() | python | def load_entry_point(self, group, name):
"""Return the `name` entry point of `group` or raise ImportError"""
ep = self.get_entry_info(group, name)
if ep is None:
raise ImportError("Entry point %r not found" % ((group, name),))
return ep.load() | [
"def",
"load_entry_point",
"(",
"self",
",",
"group",
",",
"name",
")",
":",
"ep",
"=",
"self",
".",
"get_entry_info",
"(",
"group",
",",
"name",
")",
"if",
"ep",
"is",
"None",
":",
"raise",
"ImportError",
"(",
"\"Entry point %r not found\"",
"%",
"(",
"(",
"group",
",",
"name",
")",
",",
")",
")",
"return",
"ep",
".",
"load",
"(",
")"
] | Return the `name` entry point of `group` or raise ImportError | [
"Return",
"the",
"name",
"entry",
"point",
"of",
"group",
"or",
"raise",
"ImportError"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2723-L2728 |
25,061 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | Distribution.get_entry_map | def get_entry_map(self, group=None):
"""Return the entry point map for `group`, or the full entry map"""
try:
ep_map = self._ep_map
except AttributeError:
ep_map = self._ep_map = EntryPoint.parse_map(
self._get_metadata('entry_points.txt'), self
)
if group is not None:
return ep_map.get(group, {})
return ep_map | python | def get_entry_map(self, group=None):
"""Return the entry point map for `group`, or the full entry map"""
try:
ep_map = self._ep_map
except AttributeError:
ep_map = self._ep_map = EntryPoint.parse_map(
self._get_metadata('entry_points.txt'), self
)
if group is not None:
return ep_map.get(group, {})
return ep_map | [
"def",
"get_entry_map",
"(",
"self",
",",
"group",
"=",
"None",
")",
":",
"try",
":",
"ep_map",
"=",
"self",
".",
"_ep_map",
"except",
"AttributeError",
":",
"ep_map",
"=",
"self",
".",
"_ep_map",
"=",
"EntryPoint",
".",
"parse_map",
"(",
"self",
".",
"_get_metadata",
"(",
"'entry_points.txt'",
")",
",",
"self",
")",
"if",
"group",
"is",
"not",
"None",
":",
"return",
"ep_map",
".",
"get",
"(",
"group",
",",
"{",
"}",
")",
"return",
"ep_map"
] | Return the entry point map for `group`, or the full entry map | [
"Return",
"the",
"entry",
"point",
"map",
"for",
"group",
"or",
"the",
"full",
"entry",
"map"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2730-L2740 |
25,062 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | Distribution.clone | def clone(self, **kw):
"""Copy this distribution, substituting in any changed keyword args"""
names = 'project_name version py_version platform location precedence'
for attr in names.split():
kw.setdefault(attr, getattr(self, attr, None))
kw.setdefault('metadata', self._provider)
return self.__class__(**kw) | python | def clone(self, **kw):
"""Copy this distribution, substituting in any changed keyword args"""
names = 'project_name version py_version platform location precedence'
for attr in names.split():
kw.setdefault(attr, getattr(self, attr, None))
kw.setdefault('metadata', self._provider)
return self.__class__(**kw) | [
"def",
"clone",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"names",
"=",
"'project_name version py_version platform location precedence'",
"for",
"attr",
"in",
"names",
".",
"split",
"(",
")",
":",
"kw",
".",
"setdefault",
"(",
"attr",
",",
"getattr",
"(",
"self",
",",
"attr",
",",
"None",
")",
")",
"kw",
".",
"setdefault",
"(",
"'metadata'",
",",
"self",
".",
"_provider",
")",
"return",
"self",
".",
"__class__",
"(",
"*",
"*",
"kw",
")"
] | Copy this distribution, substituting in any changed keyword args | [
"Copy",
"this",
"distribution",
"substituting",
"in",
"any",
"changed",
"keyword",
"args"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2844-L2850 |
25,063 | pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | DistInfoDistribution._compute_dependencies | def _compute_dependencies(self):
"""Recompute this distribution's dependencies."""
dm = self.__dep_map = {None: []}
reqs = []
# Including any condition expressions
for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
reqs.extend(parse_requirements(req))
def reqs_for_extra(extra):
for req in reqs:
if not req.marker or req.marker.evaluate({'extra': extra}):
yield req
common = frozenset(reqs_for_extra(None))
dm[None].extend(common)
for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:
s_extra = safe_extra(extra.strip())
dm[s_extra] = list(frozenset(reqs_for_extra(extra)) - common)
return dm | python | def _compute_dependencies(self):
"""Recompute this distribution's dependencies."""
dm = self.__dep_map = {None: []}
reqs = []
# Including any condition expressions
for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
reqs.extend(parse_requirements(req))
def reqs_for_extra(extra):
for req in reqs:
if not req.marker or req.marker.evaluate({'extra': extra}):
yield req
common = frozenset(reqs_for_extra(None))
dm[None].extend(common)
for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:
s_extra = safe_extra(extra.strip())
dm[s_extra] = list(frozenset(reqs_for_extra(extra)) - common)
return dm | [
"def",
"_compute_dependencies",
"(",
"self",
")",
":",
"dm",
"=",
"self",
".",
"__dep_map",
"=",
"{",
"None",
":",
"[",
"]",
"}",
"reqs",
"=",
"[",
"]",
"# Including any condition expressions",
"for",
"req",
"in",
"self",
".",
"_parsed_pkg_info",
".",
"get_all",
"(",
"'Requires-Dist'",
")",
"or",
"[",
"]",
":",
"reqs",
".",
"extend",
"(",
"parse_requirements",
"(",
"req",
")",
")",
"def",
"reqs_for_extra",
"(",
"extra",
")",
":",
"for",
"req",
"in",
"reqs",
":",
"if",
"not",
"req",
".",
"marker",
"or",
"req",
".",
"marker",
".",
"evaluate",
"(",
"{",
"'extra'",
":",
"extra",
"}",
")",
":",
"yield",
"req",
"common",
"=",
"frozenset",
"(",
"reqs_for_extra",
"(",
"None",
")",
")",
"dm",
"[",
"None",
"]",
".",
"extend",
"(",
"common",
")",
"for",
"extra",
"in",
"self",
".",
"_parsed_pkg_info",
".",
"get_all",
"(",
"'Provides-Extra'",
")",
"or",
"[",
"]",
":",
"s_extra",
"=",
"safe_extra",
"(",
"extra",
".",
"strip",
"(",
")",
")",
"dm",
"[",
"s_extra",
"]",
"=",
"list",
"(",
"frozenset",
"(",
"reqs_for_extra",
"(",
"extra",
")",
")",
"-",
"common",
")",
"return",
"dm"
] | Recompute this distribution's dependencies. | [
"Recompute",
"this",
"distribution",
"s",
"dependencies",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2902-L2923 |
25,064 | pypa/pipenv | pipenv/vendor/cerberus/schema.py | DefinitionSchema._expand_logical_shortcuts | def _expand_logical_shortcuts(cls, schema):
""" Expand agglutinated rules in a definition-schema.
:param schema: The schema-definition to expand.
:return: The expanded schema-definition.
"""
def is_of_rule(x):
return isinstance(x, _str_type) and \
x.startswith(('allof_', 'anyof_', 'noneof_', 'oneof_'))
for field in schema:
for of_rule in (x for x in schema[field] if is_of_rule(x)):
operator, rule = of_rule.split('_')
schema[field].update({operator: []})
for value in schema[field][of_rule]:
schema[field][operator].append({rule: value})
del schema[field][of_rule]
return schema | python | def _expand_logical_shortcuts(cls, schema):
""" Expand agglutinated rules in a definition-schema.
:param schema: The schema-definition to expand.
:return: The expanded schema-definition.
"""
def is_of_rule(x):
return isinstance(x, _str_type) and \
x.startswith(('allof_', 'anyof_', 'noneof_', 'oneof_'))
for field in schema:
for of_rule in (x for x in schema[field] if is_of_rule(x)):
operator, rule = of_rule.split('_')
schema[field].update({operator: []})
for value in schema[field][of_rule]:
schema[field][operator].append({rule: value})
del schema[field][of_rule]
return schema | [
"def",
"_expand_logical_shortcuts",
"(",
"cls",
",",
"schema",
")",
":",
"def",
"is_of_rule",
"(",
"x",
")",
":",
"return",
"isinstance",
"(",
"x",
",",
"_str_type",
")",
"and",
"x",
".",
"startswith",
"(",
"(",
"'allof_'",
",",
"'anyof_'",
",",
"'noneof_'",
",",
"'oneof_'",
")",
")",
"for",
"field",
"in",
"schema",
":",
"for",
"of_rule",
"in",
"(",
"x",
"for",
"x",
"in",
"schema",
"[",
"field",
"]",
"if",
"is_of_rule",
"(",
"x",
")",
")",
":",
"operator",
",",
"rule",
"=",
"of_rule",
".",
"split",
"(",
"'_'",
")",
"schema",
"[",
"field",
"]",
".",
"update",
"(",
"{",
"operator",
":",
"[",
"]",
"}",
")",
"for",
"value",
"in",
"schema",
"[",
"field",
"]",
"[",
"of_rule",
"]",
":",
"schema",
"[",
"field",
"]",
"[",
"operator",
"]",
".",
"append",
"(",
"{",
"rule",
":",
"value",
"}",
")",
"del",
"schema",
"[",
"field",
"]",
"[",
"of_rule",
"]",
"return",
"schema"
] | Expand agglutinated rules in a definition-schema.
:param schema: The schema-definition to expand.
:return: The expanded schema-definition. | [
"Expand",
"agglutinated",
"rules",
"in",
"a",
"definition",
"-",
"schema",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/schema.py#L116-L133 |
25,065 | pypa/pipenv | pipenv/vendor/cerberus/schema.py | DefinitionSchema._validate | def _validate(self, schema):
""" Validates a schema that defines rules against supported rules.
:param schema: The schema to be validated as a legal cerberus schema
according to the rules of this Validator object.
"""
if isinstance(schema, _str_type):
schema = self.validator.schema_registry.get(schema, schema)
if schema is None:
raise SchemaError(errors.SCHEMA_ERROR_MISSING)
schema = copy(schema)
for field in schema:
if isinstance(schema[field], _str_type):
schema[field] = rules_set_registry.get(schema[field],
schema[field])
if not self.schema_validator(schema, normalize=False):
raise SchemaError(self.schema_validator.errors) | python | def _validate(self, schema):
""" Validates a schema that defines rules against supported rules.
:param schema: The schema to be validated as a legal cerberus schema
according to the rules of this Validator object.
"""
if isinstance(schema, _str_type):
schema = self.validator.schema_registry.get(schema, schema)
if schema is None:
raise SchemaError(errors.SCHEMA_ERROR_MISSING)
schema = copy(schema)
for field in schema:
if isinstance(schema[field], _str_type):
schema[field] = rules_set_registry.get(schema[field],
schema[field])
if not self.schema_validator(schema, normalize=False):
raise SchemaError(self.schema_validator.errors) | [
"def",
"_validate",
"(",
"self",
",",
"schema",
")",
":",
"if",
"isinstance",
"(",
"schema",
",",
"_str_type",
")",
":",
"schema",
"=",
"self",
".",
"validator",
".",
"schema_registry",
".",
"get",
"(",
"schema",
",",
"schema",
")",
"if",
"schema",
"is",
"None",
":",
"raise",
"SchemaError",
"(",
"errors",
".",
"SCHEMA_ERROR_MISSING",
")",
"schema",
"=",
"copy",
"(",
"schema",
")",
"for",
"field",
"in",
"schema",
":",
"if",
"isinstance",
"(",
"schema",
"[",
"field",
"]",
",",
"_str_type",
")",
":",
"schema",
"[",
"field",
"]",
"=",
"rules_set_registry",
".",
"get",
"(",
"schema",
"[",
"field",
"]",
",",
"schema",
"[",
"field",
"]",
")",
"if",
"not",
"self",
".",
"schema_validator",
"(",
"schema",
",",
"normalize",
"=",
"False",
")",
":",
"raise",
"SchemaError",
"(",
"self",
".",
"schema_validator",
".",
"errors",
")"
] | Validates a schema that defines rules against supported rules.
:param schema: The schema to be validated as a legal cerberus schema
according to the rules of this Validator object. | [
"Validates",
"a",
"schema",
"that",
"defines",
"rules",
"against",
"supported",
"rules",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/schema.py#L200-L219 |
25,066 | pypa/pipenv | pipenv/vendor/cerberus/schema.py | Registry.add | def add(self, name, definition):
""" Register a definition to the registry. Existing definitions are
replaced silently.
:param name: The name which can be used as reference in a validation
schema.
:type name: :class:`str`
:param definition: The definition.
:type definition: any :term:`mapping` """
self._storage[name] = self._expand_definition(definition) | python | def add(self, name, definition):
""" Register a definition to the registry. Existing definitions are
replaced silently.
:param name: The name which can be used as reference in a validation
schema.
:type name: :class:`str`
:param definition: The definition.
:type definition: any :term:`mapping` """
self._storage[name] = self._expand_definition(definition) | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"definition",
")",
":",
"self",
".",
"_storage",
"[",
"name",
"]",
"=",
"self",
".",
"_expand_definition",
"(",
"definition",
")"
] | Register a definition to the registry. Existing definitions are
replaced silently.
:param name: The name which can be used as reference in a validation
schema.
:type name: :class:`str`
:param definition: The definition.
:type definition: any :term:`mapping` | [
"Register",
"a",
"definition",
"to",
"the",
"registry",
".",
"Existing",
"definitions",
"are",
"replaced",
"silently",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/schema.py#L423-L432 |
25,067 | pypa/pipenv | pipenv/vendor/cerberus/schema.py | Registry.extend | def extend(self, definitions):
""" Add several definitions at once. Existing definitions are
replaced silently.
:param definitions: The names and definitions.
:type definitions: a :term:`mapping` or an :term:`iterable` with
two-value :class:`tuple` s """
for name, definition in dict(definitions).items():
self.add(name, definition) | python | def extend(self, definitions):
""" Add several definitions at once. Existing definitions are
replaced silently.
:param definitions: The names and definitions.
:type definitions: a :term:`mapping` or an :term:`iterable` with
two-value :class:`tuple` s """
for name, definition in dict(definitions).items():
self.add(name, definition) | [
"def",
"extend",
"(",
"self",
",",
"definitions",
")",
":",
"for",
"name",
",",
"definition",
"in",
"dict",
"(",
"definitions",
")",
".",
"items",
"(",
")",
":",
"self",
".",
"add",
"(",
"name",
",",
"definition",
")"
] | Add several definitions at once. Existing definitions are
replaced silently.
:param definitions: The names and definitions.
:type definitions: a :term:`mapping` or an :term:`iterable` with
two-value :class:`tuple` s | [
"Add",
"several",
"definitions",
"at",
"once",
".",
"Existing",
"definitions",
"are",
"replaced",
"silently",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/schema.py#L443-L451 |
25,068 | pypa/pipenv | pipenv/vendor/vistir/contextmanagers.py | cd | def cd(path):
"""Context manager to temporarily change working directories
:param str path: The directory to move into
>>> print(os.path.abspath(os.curdir))
'/home/user/code/myrepo'
>>> with cd("/home/user/code/otherdir/subdir"):
... print("Changed directory: %s" % os.path.abspath(os.curdir))
Changed directory: /home/user/code/otherdir/subdir
>>> print(os.path.abspath(os.curdir))
'/home/user/code/myrepo'
"""
if not path:
return
prev_cwd = Path.cwd().as_posix()
if isinstance(path, Path):
path = path.as_posix()
os.chdir(str(path))
try:
yield
finally:
os.chdir(prev_cwd) | python | def cd(path):
"""Context manager to temporarily change working directories
:param str path: The directory to move into
>>> print(os.path.abspath(os.curdir))
'/home/user/code/myrepo'
>>> with cd("/home/user/code/otherdir/subdir"):
... print("Changed directory: %s" % os.path.abspath(os.curdir))
Changed directory: /home/user/code/otherdir/subdir
>>> print(os.path.abspath(os.curdir))
'/home/user/code/myrepo'
"""
if not path:
return
prev_cwd = Path.cwd().as_posix()
if isinstance(path, Path):
path = path.as_posix()
os.chdir(str(path))
try:
yield
finally:
os.chdir(prev_cwd) | [
"def",
"cd",
"(",
"path",
")",
":",
"if",
"not",
"path",
":",
"return",
"prev_cwd",
"=",
"Path",
".",
"cwd",
"(",
")",
".",
"as_posix",
"(",
")",
"if",
"isinstance",
"(",
"path",
",",
"Path",
")",
":",
"path",
"=",
"path",
".",
"as_posix",
"(",
")",
"os",
".",
"chdir",
"(",
"str",
"(",
"path",
")",
")",
"try",
":",
"yield",
"finally",
":",
"os",
".",
"chdir",
"(",
"prev_cwd",
")"
] | Context manager to temporarily change working directories
:param str path: The directory to move into
>>> print(os.path.abspath(os.curdir))
'/home/user/code/myrepo'
>>> with cd("/home/user/code/otherdir/subdir"):
... print("Changed directory: %s" % os.path.abspath(os.curdir))
Changed directory: /home/user/code/otherdir/subdir
>>> print(os.path.abspath(os.curdir))
'/home/user/code/myrepo' | [
"Context",
"manager",
"to",
"temporarily",
"change",
"working",
"directories"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/contextmanagers.py#L63-L85 |
25,069 | pypa/pipenv | pipenv/vendor/vistir/contextmanagers.py | spinner | def spinner(
spinner_name=None,
start_text=None,
handler_map=None,
nospin=False,
write_to_stdout=True,
):
"""Get a spinner object or a dummy spinner to wrap a context.
:param str spinner_name: A spinner type e.g. "dots" or "bouncingBar" (default: {"bouncingBar"})
:param str start_text: Text to start off the spinner with (default: {None})
:param dict handler_map: Handler map for signals to be handled gracefully (default: {None})
:param bool nospin: If true, use the dummy spinner (default: {False})
:param bool write_to_stdout: Writes to stdout if true, otherwise writes to stderr (default: True)
:return: A spinner object which can be manipulated while alive
:rtype: :class:`~vistir.spin.VistirSpinner`
Raises:
RuntimeError -- Raised if the spinner extra is not installed
"""
from .spin import create_spinner
has_yaspin = None
try:
import yaspin
except ImportError:
has_yaspin = False
if not nospin:
raise RuntimeError(
"Failed to import spinner! Reinstall vistir with command:"
" pip install --upgrade vistir[spinner]"
)
else:
spinner_name = ""
else:
has_yaspin = True
spinner_name = ""
use_yaspin = (has_yaspin is False) or (nospin is True)
if has_yaspin is None or has_yaspin is True and not nospin:
use_yaspin = True
if start_text is None and use_yaspin is True:
start_text = "Running..."
with create_spinner(
spinner_name=spinner_name,
text=start_text,
handler_map=handler_map,
nospin=nospin,
use_yaspin=use_yaspin,
write_to_stdout=write_to_stdout,
) as _spinner:
yield _spinner | python | def spinner(
spinner_name=None,
start_text=None,
handler_map=None,
nospin=False,
write_to_stdout=True,
):
"""Get a spinner object or a dummy spinner to wrap a context.
:param str spinner_name: A spinner type e.g. "dots" or "bouncingBar" (default: {"bouncingBar"})
:param str start_text: Text to start off the spinner with (default: {None})
:param dict handler_map: Handler map for signals to be handled gracefully (default: {None})
:param bool nospin: If true, use the dummy spinner (default: {False})
:param bool write_to_stdout: Writes to stdout if true, otherwise writes to stderr (default: True)
:return: A spinner object which can be manipulated while alive
:rtype: :class:`~vistir.spin.VistirSpinner`
Raises:
RuntimeError -- Raised if the spinner extra is not installed
"""
from .spin import create_spinner
has_yaspin = None
try:
import yaspin
except ImportError:
has_yaspin = False
if not nospin:
raise RuntimeError(
"Failed to import spinner! Reinstall vistir with command:"
" pip install --upgrade vistir[spinner]"
)
else:
spinner_name = ""
else:
has_yaspin = True
spinner_name = ""
use_yaspin = (has_yaspin is False) or (nospin is True)
if has_yaspin is None or has_yaspin is True and not nospin:
use_yaspin = True
if start_text is None and use_yaspin is True:
start_text = "Running..."
with create_spinner(
spinner_name=spinner_name,
text=start_text,
handler_map=handler_map,
nospin=nospin,
use_yaspin=use_yaspin,
write_to_stdout=write_to_stdout,
) as _spinner:
yield _spinner | [
"def",
"spinner",
"(",
"spinner_name",
"=",
"None",
",",
"start_text",
"=",
"None",
",",
"handler_map",
"=",
"None",
",",
"nospin",
"=",
"False",
",",
"write_to_stdout",
"=",
"True",
",",
")",
":",
"from",
".",
"spin",
"import",
"create_spinner",
"has_yaspin",
"=",
"None",
"try",
":",
"import",
"yaspin",
"except",
"ImportError",
":",
"has_yaspin",
"=",
"False",
"if",
"not",
"nospin",
":",
"raise",
"RuntimeError",
"(",
"\"Failed to import spinner! Reinstall vistir with command:\"",
"\" pip install --upgrade vistir[spinner]\"",
")",
"else",
":",
"spinner_name",
"=",
"\"\"",
"else",
":",
"has_yaspin",
"=",
"True",
"spinner_name",
"=",
"\"\"",
"use_yaspin",
"=",
"(",
"has_yaspin",
"is",
"False",
")",
"or",
"(",
"nospin",
"is",
"True",
")",
"if",
"has_yaspin",
"is",
"None",
"or",
"has_yaspin",
"is",
"True",
"and",
"not",
"nospin",
":",
"use_yaspin",
"=",
"True",
"if",
"start_text",
"is",
"None",
"and",
"use_yaspin",
"is",
"True",
":",
"start_text",
"=",
"\"Running...\"",
"with",
"create_spinner",
"(",
"spinner_name",
"=",
"spinner_name",
",",
"text",
"=",
"start_text",
",",
"handler_map",
"=",
"handler_map",
",",
"nospin",
"=",
"nospin",
",",
"use_yaspin",
"=",
"use_yaspin",
",",
"write_to_stdout",
"=",
"write_to_stdout",
",",
")",
"as",
"_spinner",
":",
"yield",
"_spinner"
] | Get a spinner object or a dummy spinner to wrap a context.
:param str spinner_name: A spinner type e.g. "dots" or "bouncingBar" (default: {"bouncingBar"})
:param str start_text: Text to start off the spinner with (default: {None})
:param dict handler_map: Handler map for signals to be handled gracefully (default: {None})
:param bool nospin: If true, use the dummy spinner (default: {False})
:param bool write_to_stdout: Writes to stdout if true, otherwise writes to stderr (default: True)
:return: A spinner object which can be manipulated while alive
:rtype: :class:`~vistir.spin.VistirSpinner`
Raises:
RuntimeError -- Raised if the spinner extra is not installed | [
"Get",
"a",
"spinner",
"object",
"or",
"a",
"dummy",
"spinner",
"to",
"wrap",
"a",
"context",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/contextmanagers.py#L111-L162 |
25,070 | pypa/pipenv | pipenv/vendor/vistir/contextmanagers.py | atomic_open_for_write | def atomic_open_for_write(target, binary=False, newline=None, encoding=None):
"""Atomically open `target` for writing.
This is based on Lektor's `atomic_open()` utility, but simplified a lot
to handle only writing, and skip many multi-process/thread edge cases
handled by Werkzeug.
:param str target: Target filename to write
:param bool binary: Whether to open in binary mode, default False
:param str newline: The newline character to use when writing, determined from system if not supplied
:param str encoding: The encoding to use when writing, defaults to system encoding
How this works:
* Create a temp file (in the same directory of the actual target), and
yield for surrounding code to write to it.
* If some thing goes wrong, try to remove the temp file. The actual target
is not touched whatsoever.
* If everything goes well, close the temp file, and replace the actual
target with this new file.
.. code:: python
>>> fn = "test_file.txt"
>>> def read_test_file(filename=fn):
with open(filename, 'r') as fh:
print(fh.read().strip())
>>> with open(fn, "w") as fh:
fh.write("this is some test text")
>>> read_test_file()
this is some test text
>>> def raise_exception_while_writing(filename):
with open(filename, "w") as fh:
fh.write("writing some new text")
raise RuntimeError("Uh oh, hope your file didn't get overwritten")
>>> raise_exception_while_writing(fn)
Traceback (most recent call last):
...
RuntimeError: Uh oh, hope your file didn't get overwritten
>>> read_test_file()
writing some new text
# Now try with vistir
>>> def raise_exception_while_writing(filename):
with vistir.contextmanagers.atomic_open_for_write(filename) as fh:
fh.write("Overwriting all the text from before with even newer text")
raise RuntimeError("But did it get overwritten now?")
>>> raise_exception_while_writing(fn)
Traceback (most recent call last):
...
RuntimeError: But did it get overwritten now?
>>> read_test_file()
writing some new text
"""
mode = "w+b" if binary else "w"
f = NamedTemporaryFile(
dir=os.path.dirname(target),
prefix=".__atomic-write",
mode=mode,
encoding=encoding,
newline=newline,
delete=False,
)
# set permissions to 0644
os.chmod(f.name, stat.S_IWUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
try:
yield f
except BaseException:
f.close()
try:
os.remove(f.name)
except OSError:
pass
raise
else:
f.close()
try:
os.remove(target) # This is needed on Windows.
except OSError:
pass
os.rename(f.name, target) | python | def atomic_open_for_write(target, binary=False, newline=None, encoding=None):
"""Atomically open `target` for writing.
This is based on Lektor's `atomic_open()` utility, but simplified a lot
to handle only writing, and skip many multi-process/thread edge cases
handled by Werkzeug.
:param str target: Target filename to write
:param bool binary: Whether to open in binary mode, default False
:param str newline: The newline character to use when writing, determined from system if not supplied
:param str encoding: The encoding to use when writing, defaults to system encoding
How this works:
* Create a temp file (in the same directory of the actual target), and
yield for surrounding code to write to it.
* If some thing goes wrong, try to remove the temp file. The actual target
is not touched whatsoever.
* If everything goes well, close the temp file, and replace the actual
target with this new file.
.. code:: python
>>> fn = "test_file.txt"
>>> def read_test_file(filename=fn):
with open(filename, 'r') as fh:
print(fh.read().strip())
>>> with open(fn, "w") as fh:
fh.write("this is some test text")
>>> read_test_file()
this is some test text
>>> def raise_exception_while_writing(filename):
with open(filename, "w") as fh:
fh.write("writing some new text")
raise RuntimeError("Uh oh, hope your file didn't get overwritten")
>>> raise_exception_while_writing(fn)
Traceback (most recent call last):
...
RuntimeError: Uh oh, hope your file didn't get overwritten
>>> read_test_file()
writing some new text
# Now try with vistir
>>> def raise_exception_while_writing(filename):
with vistir.contextmanagers.atomic_open_for_write(filename) as fh:
fh.write("Overwriting all the text from before with even newer text")
raise RuntimeError("But did it get overwritten now?")
>>> raise_exception_while_writing(fn)
Traceback (most recent call last):
...
RuntimeError: But did it get overwritten now?
>>> read_test_file()
writing some new text
"""
mode = "w+b" if binary else "w"
f = NamedTemporaryFile(
dir=os.path.dirname(target),
prefix=".__atomic-write",
mode=mode,
encoding=encoding,
newline=newline,
delete=False,
)
# set permissions to 0644
os.chmod(f.name, stat.S_IWUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
try:
yield f
except BaseException:
f.close()
try:
os.remove(f.name)
except OSError:
pass
raise
else:
f.close()
try:
os.remove(target) # This is needed on Windows.
except OSError:
pass
os.rename(f.name, target) | [
"def",
"atomic_open_for_write",
"(",
"target",
",",
"binary",
"=",
"False",
",",
"newline",
"=",
"None",
",",
"encoding",
"=",
"None",
")",
":",
"mode",
"=",
"\"w+b\"",
"if",
"binary",
"else",
"\"w\"",
"f",
"=",
"NamedTemporaryFile",
"(",
"dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"target",
")",
",",
"prefix",
"=",
"\".__atomic-write\"",
",",
"mode",
"=",
"mode",
",",
"encoding",
"=",
"encoding",
",",
"newline",
"=",
"newline",
",",
"delete",
"=",
"False",
",",
")",
"# set permissions to 0644",
"os",
".",
"chmod",
"(",
"f",
".",
"name",
",",
"stat",
".",
"S_IWUSR",
"|",
"stat",
".",
"S_IRUSR",
"|",
"stat",
".",
"S_IRGRP",
"|",
"stat",
".",
"S_IROTH",
")",
"try",
":",
"yield",
"f",
"except",
"BaseException",
":",
"f",
".",
"close",
"(",
")",
"try",
":",
"os",
".",
"remove",
"(",
"f",
".",
"name",
")",
"except",
"OSError",
":",
"pass",
"raise",
"else",
":",
"f",
".",
"close",
"(",
")",
"try",
":",
"os",
".",
"remove",
"(",
"target",
")",
"# This is needed on Windows.",
"except",
"OSError",
":",
"pass",
"os",
".",
"rename",
"(",
"f",
".",
"name",
",",
"target",
")"
] | Atomically open `target` for writing.
This is based on Lektor's `atomic_open()` utility, but simplified a lot
to handle only writing, and skip many multi-process/thread edge cases
handled by Werkzeug.
:param str target: Target filename to write
:param bool binary: Whether to open in binary mode, default False
:param str newline: The newline character to use when writing, determined from system if not supplied
:param str encoding: The encoding to use when writing, defaults to system encoding
How this works:
* Create a temp file (in the same directory of the actual target), and
yield for surrounding code to write to it.
* If some thing goes wrong, try to remove the temp file. The actual target
is not touched whatsoever.
* If everything goes well, close the temp file, and replace the actual
target with this new file.
.. code:: python
>>> fn = "test_file.txt"
>>> def read_test_file(filename=fn):
with open(filename, 'r') as fh:
print(fh.read().strip())
>>> with open(fn, "w") as fh:
fh.write("this is some test text")
>>> read_test_file()
this is some test text
>>> def raise_exception_while_writing(filename):
with open(filename, "w") as fh:
fh.write("writing some new text")
raise RuntimeError("Uh oh, hope your file didn't get overwritten")
>>> raise_exception_while_writing(fn)
Traceback (most recent call last):
...
RuntimeError: Uh oh, hope your file didn't get overwritten
>>> read_test_file()
writing some new text
# Now try with vistir
>>> def raise_exception_while_writing(filename):
with vistir.contextmanagers.atomic_open_for_write(filename) as fh:
fh.write("Overwriting all the text from before with even newer text")
raise RuntimeError("But did it get overwritten now?")
>>> raise_exception_while_writing(fn)
Traceback (most recent call last):
...
RuntimeError: But did it get overwritten now?
>>> read_test_file()
writing some new text | [
"Atomically",
"open",
"target",
"for",
"writing",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/contextmanagers.py#L166-L252 |
25,071 | pypa/pipenv | pipenv/vendor/vistir/contextmanagers.py | open_file | def open_file(link, session=None, stream=True):
"""
Open local or remote file for reading.
:type link: pip._internal.index.Link or str
:type session: requests.Session
:param bool stream: Try to stream if remote, default True
:raises ValueError: If link points to a local directory.
:return: a context manager to the opened file-like object
"""
if not isinstance(link, six.string_types):
try:
link = link.url_without_fragment
except AttributeError:
raise ValueError("Cannot parse url from unkown type: {0!r}".format(link))
if not is_valid_url(link) and os.path.exists(link):
link = path_to_url(link)
if is_file_url(link):
# Local URL
local_path = url_to_path(link)
if os.path.isdir(local_path):
raise ValueError("Cannot open directory for read: {}".format(link))
else:
with io.open(local_path, "rb") as local_file:
yield local_file
else:
# Remote URL
headers = {"Accept-Encoding": "identity"}
if not session:
from requests import Session
session = Session()
with session.get(link, headers=headers, stream=stream) as resp:
try:
raw = getattr(resp, "raw", None)
result = raw if raw else resp
yield result
finally:
if raw:
conn = getattr(raw, "_connection")
if conn is not None:
conn.close()
result.close() | python | def open_file(link, session=None, stream=True):
"""
Open local or remote file for reading.
:type link: pip._internal.index.Link or str
:type session: requests.Session
:param bool stream: Try to stream if remote, default True
:raises ValueError: If link points to a local directory.
:return: a context manager to the opened file-like object
"""
if not isinstance(link, six.string_types):
try:
link = link.url_without_fragment
except AttributeError:
raise ValueError("Cannot parse url from unkown type: {0!r}".format(link))
if not is_valid_url(link) and os.path.exists(link):
link = path_to_url(link)
if is_file_url(link):
# Local URL
local_path = url_to_path(link)
if os.path.isdir(local_path):
raise ValueError("Cannot open directory for read: {}".format(link))
else:
with io.open(local_path, "rb") as local_file:
yield local_file
else:
# Remote URL
headers = {"Accept-Encoding": "identity"}
if not session:
from requests import Session
session = Session()
with session.get(link, headers=headers, stream=stream) as resp:
try:
raw = getattr(resp, "raw", None)
result = raw if raw else resp
yield result
finally:
if raw:
conn = getattr(raw, "_connection")
if conn is not None:
conn.close()
result.close() | [
"def",
"open_file",
"(",
"link",
",",
"session",
"=",
"None",
",",
"stream",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"link",
",",
"six",
".",
"string_types",
")",
":",
"try",
":",
"link",
"=",
"link",
".",
"url_without_fragment",
"except",
"AttributeError",
":",
"raise",
"ValueError",
"(",
"\"Cannot parse url from unkown type: {0!r}\"",
".",
"format",
"(",
"link",
")",
")",
"if",
"not",
"is_valid_url",
"(",
"link",
")",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"link",
")",
":",
"link",
"=",
"path_to_url",
"(",
"link",
")",
"if",
"is_file_url",
"(",
"link",
")",
":",
"# Local URL",
"local_path",
"=",
"url_to_path",
"(",
"link",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"local_path",
")",
":",
"raise",
"ValueError",
"(",
"\"Cannot open directory for read: {}\"",
".",
"format",
"(",
"link",
")",
")",
"else",
":",
"with",
"io",
".",
"open",
"(",
"local_path",
",",
"\"rb\"",
")",
"as",
"local_file",
":",
"yield",
"local_file",
"else",
":",
"# Remote URL",
"headers",
"=",
"{",
"\"Accept-Encoding\"",
":",
"\"identity\"",
"}",
"if",
"not",
"session",
":",
"from",
"requests",
"import",
"Session",
"session",
"=",
"Session",
"(",
")",
"with",
"session",
".",
"get",
"(",
"link",
",",
"headers",
"=",
"headers",
",",
"stream",
"=",
"stream",
")",
"as",
"resp",
":",
"try",
":",
"raw",
"=",
"getattr",
"(",
"resp",
",",
"\"raw\"",
",",
"None",
")",
"result",
"=",
"raw",
"if",
"raw",
"else",
"resp",
"yield",
"result",
"finally",
":",
"if",
"raw",
":",
"conn",
"=",
"getattr",
"(",
"raw",
",",
"\"_connection\"",
")",
"if",
"conn",
"is",
"not",
"None",
":",
"conn",
".",
"close",
"(",
")",
"result",
".",
"close",
"(",
")"
] | Open local or remote file for reading.
:type link: pip._internal.index.Link or str
:type session: requests.Session
:param bool stream: Try to stream if remote, default True
:raises ValueError: If link points to a local directory.
:return: a context manager to the opened file-like object | [
"Open",
"local",
"or",
"remote",
"file",
"for",
"reading",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/contextmanagers.py#L256-L300 |
25,072 | pypa/pipenv | pipenv/vendor/pexpect/spawnbase.py | SpawnBase.read_nonblocking | def read_nonblocking(self, size=1, timeout=None):
"""This reads data from the file descriptor.
This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it.
The timeout parameter is ignored.
"""
try:
s = os.read(self.child_fd, size)
except OSError as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOF('End Of File (EOF). Exception style platform.')
raise
if s == b'':
# BSD-style EOF
self.flag_eof = True
raise EOF('End Of File (EOF). Empty string style platform.')
s = self._decoder.decode(s, final=False)
self._log(s, 'read')
return s | python | def read_nonblocking(self, size=1, timeout=None):
"""This reads data from the file descriptor.
This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it.
The timeout parameter is ignored.
"""
try:
s = os.read(self.child_fd, size)
except OSError as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOF('End Of File (EOF). Exception style platform.')
raise
if s == b'':
# BSD-style EOF
self.flag_eof = True
raise EOF('End Of File (EOF). Empty string style platform.')
s = self._decoder.decode(s, final=False)
self._log(s, 'read')
return s | [
"def",
"read_nonblocking",
"(",
"self",
",",
"size",
"=",
"1",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"s",
"=",
"os",
".",
"read",
"(",
"self",
".",
"child_fd",
",",
"size",
")",
"except",
"OSError",
"as",
"err",
":",
"if",
"err",
".",
"args",
"[",
"0",
"]",
"==",
"errno",
".",
"EIO",
":",
"# Linux-style EOF",
"self",
".",
"flag_eof",
"=",
"True",
"raise",
"EOF",
"(",
"'End Of File (EOF). Exception style platform.'",
")",
"raise",
"if",
"s",
"==",
"b''",
":",
"# BSD-style EOF",
"self",
".",
"flag_eof",
"=",
"True",
"raise",
"EOF",
"(",
"'End Of File (EOF). Empty string style platform.'",
")",
"s",
"=",
"self",
".",
"_decoder",
".",
"decode",
"(",
"s",
",",
"final",
"=",
"False",
")",
"self",
".",
"_log",
"(",
"s",
",",
"'read'",
")",
"return",
"s"
] | This reads data from the file descriptor.
This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it.
The timeout parameter is ignored. | [
"This",
"reads",
"data",
"from",
"the",
"file",
"descriptor",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/spawnbase.py#L157-L180 |
25,073 | pypa/pipenv | pipenv/vendor/pexpect/spawnbase.py | SpawnBase.expect | def expect(self, pattern, timeout=-1, searchwindowsize=-1, async_=False, **kw):
'''This seeks through the stream until a pattern is matched. The
pattern is overloaded and may take several types. The pattern can be a
StringType, EOF, a compiled re, or a list of any of those types.
Strings will be compiled to re types. This returns the index into the
pattern list. If the pattern was not a list this returns index 0 on a
successful match. This may raise exceptions for EOF or TIMEOUT. To
avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
list. That will cause expect to match an EOF or TIMEOUT condition
instead of raising an exception.
If you pass a list of patterns and more than one matches, the first
match in the stream is chosen. If more than one pattern matches at that
point, the leftmost in the pattern list is chosen. For example::
# the input is 'foobar'
index = p.expect(['bar', 'foo', 'foobar'])
# returns 1('foo') even though 'foobar' is a "better" match
Please note, however, that buffering can affect this behavior, since
input arrives in unpredictable chunks. For example::
# the input is 'foobar'
index = p.expect(['foobar', 'foo'])
# returns 0('foobar') if all input is available at once,
# but returns 1('foo') if parts of the final 'bar' arrive late
When a match is found for the given pattern, the class instance
attribute *match* becomes an re.MatchObject result. Should an EOF
or TIMEOUT pattern match, then the match attribute will be an instance
of that exception class. The pairing before and after class
instance attributes are views of the data preceding and following
the matching pattern. On general exception, class attribute
*before* is all data received up to the exception, while *match* and
*after* attributes are value None.
When the keyword argument timeout is -1 (default), then TIMEOUT will
raise after the default value specified by the class timeout
attribute. When None, TIMEOUT will not be raised and may block
indefinitely until match.
When the keyword argument searchwindowsize is -1 (default), then the
value specified by the class maxread attribute is used.
A list entry may be EOF or TIMEOUT instead of a string. This will
catch these exceptions and return the index of the list entry instead
of raising the exception. The attribute 'after' will be set to the
exception type. The attribute 'match' will be None. This allows you to
write code like this::
index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
if index == 0:
do_something()
elif index == 1:
do_something_else()
elif index == 2:
do_some_other_thing()
elif index == 3:
do_something_completely_different()
instead of code like this::
try:
index = p.expect(['good', 'bad'])
if index == 0:
do_something()
elif index == 1:
do_something_else()
except EOF:
do_some_other_thing()
except TIMEOUT:
do_something_completely_different()
These two forms are equivalent. It all depends on what you want. You
can also just expect the EOF if you are waiting for all output of a
child to finish. For example::
p = pexpect.spawn('/bin/ls')
p.expect(pexpect.EOF)
print p.before
If you are trying to optimize for speed then see expect_list().
On Python 3.4, or Python 3.3 with asyncio installed, passing
``async_=True`` will make this return an :mod:`asyncio` coroutine,
which you can yield from to get the same result that this method would
normally give directly. So, inside a coroutine, you can replace this code::
index = p.expect(patterns)
With this non-blocking form::
index = yield from p.expect(patterns, async_=True)
'''
if 'async' in kw:
async_ = kw.pop('async')
if kw:
raise TypeError("Unknown keyword arguments: {}".format(kw))
compiled_pattern_list = self.compile_pattern_list(pattern)
return self.expect_list(compiled_pattern_list,
timeout, searchwindowsize, async_) | python | def expect(self, pattern, timeout=-1, searchwindowsize=-1, async_=False, **kw):
'''This seeks through the stream until a pattern is matched. The
pattern is overloaded and may take several types. The pattern can be a
StringType, EOF, a compiled re, or a list of any of those types.
Strings will be compiled to re types. This returns the index into the
pattern list. If the pattern was not a list this returns index 0 on a
successful match. This may raise exceptions for EOF or TIMEOUT. To
avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
list. That will cause expect to match an EOF or TIMEOUT condition
instead of raising an exception.
If you pass a list of patterns and more than one matches, the first
match in the stream is chosen. If more than one pattern matches at that
point, the leftmost in the pattern list is chosen. For example::
# the input is 'foobar'
index = p.expect(['bar', 'foo', 'foobar'])
# returns 1('foo') even though 'foobar' is a "better" match
Please note, however, that buffering can affect this behavior, since
input arrives in unpredictable chunks. For example::
# the input is 'foobar'
index = p.expect(['foobar', 'foo'])
# returns 0('foobar') if all input is available at once,
# but returns 1('foo') if parts of the final 'bar' arrive late
When a match is found for the given pattern, the class instance
attribute *match* becomes an re.MatchObject result. Should an EOF
or TIMEOUT pattern match, then the match attribute will be an instance
of that exception class. The pairing before and after class
instance attributes are views of the data preceding and following
the matching pattern. On general exception, class attribute
*before* is all data received up to the exception, while *match* and
*after* attributes are value None.
When the keyword argument timeout is -1 (default), then TIMEOUT will
raise after the default value specified by the class timeout
attribute. When None, TIMEOUT will not be raised and may block
indefinitely until match.
When the keyword argument searchwindowsize is -1 (default), then the
value specified by the class maxread attribute is used.
A list entry may be EOF or TIMEOUT instead of a string. This will
catch these exceptions and return the index of the list entry instead
of raising the exception. The attribute 'after' will be set to the
exception type. The attribute 'match' will be None. This allows you to
write code like this::
index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
if index == 0:
do_something()
elif index == 1:
do_something_else()
elif index == 2:
do_some_other_thing()
elif index == 3:
do_something_completely_different()
instead of code like this::
try:
index = p.expect(['good', 'bad'])
if index == 0:
do_something()
elif index == 1:
do_something_else()
except EOF:
do_some_other_thing()
except TIMEOUT:
do_something_completely_different()
These two forms are equivalent. It all depends on what you want. You
can also just expect the EOF if you are waiting for all output of a
child to finish. For example::
p = pexpect.spawn('/bin/ls')
p.expect(pexpect.EOF)
print p.before
If you are trying to optimize for speed then see expect_list().
On Python 3.4, or Python 3.3 with asyncio installed, passing
``async_=True`` will make this return an :mod:`asyncio` coroutine,
which you can yield from to get the same result that this method would
normally give directly. So, inside a coroutine, you can replace this code::
index = p.expect(patterns)
With this non-blocking form::
index = yield from p.expect(patterns, async_=True)
'''
if 'async' in kw:
async_ = kw.pop('async')
if kw:
raise TypeError("Unknown keyword arguments: {}".format(kw))
compiled_pattern_list = self.compile_pattern_list(pattern)
return self.expect_list(compiled_pattern_list,
timeout, searchwindowsize, async_) | [
"def",
"expect",
"(",
"self",
",",
"pattern",
",",
"timeout",
"=",
"-",
"1",
",",
"searchwindowsize",
"=",
"-",
"1",
",",
"async_",
"=",
"False",
",",
"*",
"*",
"kw",
")",
":",
"if",
"'async'",
"in",
"kw",
":",
"async_",
"=",
"kw",
".",
"pop",
"(",
"'async'",
")",
"if",
"kw",
":",
"raise",
"TypeError",
"(",
"\"Unknown keyword arguments: {}\"",
".",
"format",
"(",
"kw",
")",
")",
"compiled_pattern_list",
"=",
"self",
".",
"compile_pattern_list",
"(",
"pattern",
")",
"return",
"self",
".",
"expect_list",
"(",
"compiled_pattern_list",
",",
"timeout",
",",
"searchwindowsize",
",",
"async_",
")"
] | This seeks through the stream until a pattern is matched. The
pattern is overloaded and may take several types. The pattern can be a
StringType, EOF, a compiled re, or a list of any of those types.
Strings will be compiled to re types. This returns the index into the
pattern list. If the pattern was not a list this returns index 0 on a
successful match. This may raise exceptions for EOF or TIMEOUT. To
avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
list. That will cause expect to match an EOF or TIMEOUT condition
instead of raising an exception.
If you pass a list of patterns and more than one matches, the first
match in the stream is chosen. If more than one pattern matches at that
point, the leftmost in the pattern list is chosen. For example::
# the input is 'foobar'
index = p.expect(['bar', 'foo', 'foobar'])
# returns 1('foo') even though 'foobar' is a "better" match
Please note, however, that buffering can affect this behavior, since
input arrives in unpredictable chunks. For example::
# the input is 'foobar'
index = p.expect(['foobar', 'foo'])
# returns 0('foobar') if all input is available at once,
# but returns 1('foo') if parts of the final 'bar' arrive late
When a match is found for the given pattern, the class instance
attribute *match* becomes an re.MatchObject result. Should an EOF
or TIMEOUT pattern match, then the match attribute will be an instance
of that exception class. The pairing before and after class
instance attributes are views of the data preceding and following
the matching pattern. On general exception, class attribute
*before* is all data received up to the exception, while *match* and
*after* attributes are value None.
When the keyword argument timeout is -1 (default), then TIMEOUT will
raise after the default value specified by the class timeout
attribute. When None, TIMEOUT will not be raised and may block
indefinitely until match.
When the keyword argument searchwindowsize is -1 (default), then the
value specified by the class maxread attribute is used.
A list entry may be EOF or TIMEOUT instead of a string. This will
catch these exceptions and return the index of the list entry instead
of raising the exception. The attribute 'after' will be set to the
exception type. The attribute 'match' will be None. This allows you to
write code like this::
index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
if index == 0:
do_something()
elif index == 1:
do_something_else()
elif index == 2:
do_some_other_thing()
elif index == 3:
do_something_completely_different()
instead of code like this::
try:
index = p.expect(['good', 'bad'])
if index == 0:
do_something()
elif index == 1:
do_something_else()
except EOF:
do_some_other_thing()
except TIMEOUT:
do_something_completely_different()
These two forms are equivalent. It all depends on what you want. You
can also just expect the EOF if you are waiting for all output of a
child to finish. For example::
p = pexpect.spawn('/bin/ls')
p.expect(pexpect.EOF)
print p.before
If you are trying to optimize for speed then see expect_list().
On Python 3.4, or Python 3.3 with asyncio installed, passing
``async_=True`` will make this return an :mod:`asyncio` coroutine,
which you can yield from to get the same result that this method would
normally give directly. So, inside a coroutine, you can replace this code::
index = p.expect(patterns)
With this non-blocking form::
index = yield from p.expect(patterns, async_=True) | [
"This",
"seeks",
"through",
"the",
"stream",
"until",
"a",
"pattern",
"is",
"matched",
".",
"The",
"pattern",
"is",
"overloaded",
"and",
"may",
"take",
"several",
"types",
".",
"The",
"pattern",
"can",
"be",
"a",
"StringType",
"EOF",
"a",
"compiled",
"re",
"or",
"a",
"list",
"of",
"any",
"of",
"those",
"types",
".",
"Strings",
"will",
"be",
"compiled",
"to",
"re",
"types",
".",
"This",
"returns",
"the",
"index",
"into",
"the",
"pattern",
"list",
".",
"If",
"the",
"pattern",
"was",
"not",
"a",
"list",
"this",
"returns",
"index",
"0",
"on",
"a",
"successful",
"match",
".",
"This",
"may",
"raise",
"exceptions",
"for",
"EOF",
"or",
"TIMEOUT",
".",
"To",
"avoid",
"the",
"EOF",
"or",
"TIMEOUT",
"exceptions",
"add",
"EOF",
"or",
"TIMEOUT",
"to",
"the",
"pattern",
"list",
".",
"That",
"will",
"cause",
"expect",
"to",
"match",
"an",
"EOF",
"or",
"TIMEOUT",
"condition",
"instead",
"of",
"raising",
"an",
"exception",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/spawnbase.py#L240-L341 |
25,074 | pypa/pipenv | pipenv/vendor/pexpect/spawnbase.py | SpawnBase.expect_loop | def expect_loop(self, searcher, timeout=-1, searchwindowsize=-1):
'''This is the common loop used inside expect. The 'searcher' should be
an instance of searcher_re or searcher_string, which describes how and
what to search for in the input.
See expect() for other arguments, return value and exceptions. '''
exp = Expecter(self, searcher, searchwindowsize)
return exp.expect_loop(timeout) | python | def expect_loop(self, searcher, timeout=-1, searchwindowsize=-1):
'''This is the common loop used inside expect. The 'searcher' should be
an instance of searcher_re or searcher_string, which describes how and
what to search for in the input.
See expect() for other arguments, return value and exceptions. '''
exp = Expecter(self, searcher, searchwindowsize)
return exp.expect_loop(timeout) | [
"def",
"expect_loop",
"(",
"self",
",",
"searcher",
",",
"timeout",
"=",
"-",
"1",
",",
"searchwindowsize",
"=",
"-",
"1",
")",
":",
"exp",
"=",
"Expecter",
"(",
"self",
",",
"searcher",
",",
"searchwindowsize",
")",
"return",
"exp",
".",
"expect_loop",
"(",
"timeout",
")"
] | This is the common loop used inside expect. The 'searcher' should be
an instance of searcher_re or searcher_string, which describes how and
what to search for in the input.
See expect() for other arguments, return value and exceptions. | [
"This",
"is",
"the",
"common",
"loop",
"used",
"inside",
"expect",
".",
"The",
"searcher",
"should",
"be",
"an",
"instance",
"of",
"searcher_re",
"or",
"searcher_string",
"which",
"describes",
"how",
"and",
"what",
"to",
"search",
"for",
"in",
"the",
"input",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/spawnbase.py#L420-L428 |
25,075 | pypa/pipenv | pipenv/vendor/click/_termui_impl.py | _tempfilepager | def _tempfilepager(generator, cmd, color):
"""Page through text by invoking a program on a temporary file."""
import tempfile
filename = tempfile.mktemp()
# TODO: This never terminates if the passed generator never terminates.
text = "".join(generator)
if not color:
text = strip_ansi(text)
encoding = get_best_encoding(sys.stdout)
with open_stream(filename, 'wb')[0] as f:
f.write(text.encode(encoding))
try:
os.system(cmd + ' "' + filename + '"')
finally:
os.unlink(filename) | python | def _tempfilepager(generator, cmd, color):
"""Page through text by invoking a program on a temporary file."""
import tempfile
filename = tempfile.mktemp()
# TODO: This never terminates if the passed generator never terminates.
text = "".join(generator)
if not color:
text = strip_ansi(text)
encoding = get_best_encoding(sys.stdout)
with open_stream(filename, 'wb')[0] as f:
f.write(text.encode(encoding))
try:
os.system(cmd + ' "' + filename + '"')
finally:
os.unlink(filename) | [
"def",
"_tempfilepager",
"(",
"generator",
",",
"cmd",
",",
"color",
")",
":",
"import",
"tempfile",
"filename",
"=",
"tempfile",
".",
"mktemp",
"(",
")",
"# TODO: This never terminates if the passed generator never terminates.",
"text",
"=",
"\"\"",
".",
"join",
"(",
"generator",
")",
"if",
"not",
"color",
":",
"text",
"=",
"strip_ansi",
"(",
"text",
")",
"encoding",
"=",
"get_best_encoding",
"(",
"sys",
".",
"stdout",
")",
"with",
"open_stream",
"(",
"filename",
",",
"'wb'",
")",
"[",
"0",
"]",
"as",
"f",
":",
"f",
".",
"write",
"(",
"text",
".",
"encode",
"(",
"encoding",
")",
")",
"try",
":",
"os",
".",
"system",
"(",
"cmd",
"+",
"' \"'",
"+",
"filename",
"+",
"'\"'",
")",
"finally",
":",
"os",
".",
"unlink",
"(",
"filename",
")"
] | Page through text by invoking a program on a temporary file. | [
"Page",
"through",
"text",
"by",
"invoking",
"a",
"program",
"on",
"a",
"temporary",
"file",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/_termui_impl.py#L370-L384 |
25,076 | pypa/pipenv | pipenv/vendor/click/_termui_impl.py | _nullpager | def _nullpager(stream, generator, color):
"""Simply print unformatted text. This is the ultimate fallback."""
for text in generator:
if not color:
text = strip_ansi(text)
stream.write(text) | python | def _nullpager(stream, generator, color):
"""Simply print unformatted text. This is the ultimate fallback."""
for text in generator:
if not color:
text = strip_ansi(text)
stream.write(text) | [
"def",
"_nullpager",
"(",
"stream",
",",
"generator",
",",
"color",
")",
":",
"for",
"text",
"in",
"generator",
":",
"if",
"not",
"color",
":",
"text",
"=",
"strip_ansi",
"(",
"text",
")",
"stream",
".",
"write",
"(",
"text",
")"
] | Simply print unformatted text. This is the ultimate fallback. | [
"Simply",
"print",
"unformatted",
"text",
".",
"This",
"is",
"the",
"ultimate",
"fallback",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/_termui_impl.py#L387-L392 |
25,077 | pypa/pipenv | pipenv/progress.py | dots | def dots(it, label="", hide=None, every=1):
"""Progress iterator. Prints a dot for each item being iterated"""
count = 0
if not hide:
STREAM.write(label)
for i, item in enumerate(it):
if not hide:
if i % every == 0: # True every "every" updates
STREAM.write(DOTS_CHAR)
sys.stderr.flush()
count += 1
yield item
STREAM.write("\n")
STREAM.flush() | python | def dots(it, label="", hide=None, every=1):
"""Progress iterator. Prints a dot for each item being iterated"""
count = 0
if not hide:
STREAM.write(label)
for i, item in enumerate(it):
if not hide:
if i % every == 0: # True every "every" updates
STREAM.write(DOTS_CHAR)
sys.stderr.flush()
count += 1
yield item
STREAM.write("\n")
STREAM.flush() | [
"def",
"dots",
"(",
"it",
",",
"label",
"=",
"\"\"",
",",
"hide",
"=",
"None",
",",
"every",
"=",
"1",
")",
":",
"count",
"=",
"0",
"if",
"not",
"hide",
":",
"STREAM",
".",
"write",
"(",
"label",
")",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"it",
")",
":",
"if",
"not",
"hide",
":",
"if",
"i",
"%",
"every",
"==",
"0",
":",
"# True every \"every\" updates",
"STREAM",
".",
"write",
"(",
"DOTS_CHAR",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")",
"count",
"+=",
"1",
"yield",
"item",
"STREAM",
".",
"write",
"(",
"\"\\n\"",
")",
"STREAM",
".",
"flush",
"(",
")"
] | Progress iterator. Prints a dot for each item being iterated | [
"Progress",
"iterator",
".",
"Prints",
"a",
"dot",
"for",
"each",
"item",
"being",
"iterated"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/progress.py#L181-L195 |
25,078 | pypa/pipenv | pipenv/vendor/semver.py | parse | def parse(version):
"""Parse version to major, minor, patch, pre-release, build parts.
:param version: version string
:return: dictionary with the keys 'build', 'major', 'minor', 'patch',
and 'prerelease'. The prerelease or build keys can be None
if not provided
:rtype: dict
>>> import semver
>>> ver = semver.parse('3.4.5-pre.2+build.4')
>>> ver['major']
3
>>> ver['minor']
4
>>> ver['patch']
5
>>> ver['prerelease']
'pre.2'
>>> ver['build']
'build.4'
"""
match = _REGEX.match(version)
if match is None:
raise ValueError('%s is not valid SemVer string' % version)
version_parts = match.groupdict()
version_parts['major'] = int(version_parts['major'])
version_parts['minor'] = int(version_parts['minor'])
version_parts['patch'] = int(version_parts['patch'])
return version_parts | python | def parse(version):
"""Parse version to major, minor, patch, pre-release, build parts.
:param version: version string
:return: dictionary with the keys 'build', 'major', 'minor', 'patch',
and 'prerelease'. The prerelease or build keys can be None
if not provided
:rtype: dict
>>> import semver
>>> ver = semver.parse('3.4.5-pre.2+build.4')
>>> ver['major']
3
>>> ver['minor']
4
>>> ver['patch']
5
>>> ver['prerelease']
'pre.2'
>>> ver['build']
'build.4'
"""
match = _REGEX.match(version)
if match is None:
raise ValueError('%s is not valid SemVer string' % version)
version_parts = match.groupdict()
version_parts['major'] = int(version_parts['major'])
version_parts['minor'] = int(version_parts['minor'])
version_parts['patch'] = int(version_parts['patch'])
return version_parts | [
"def",
"parse",
"(",
"version",
")",
":",
"match",
"=",
"_REGEX",
".",
"match",
"(",
"version",
")",
"if",
"match",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'%s is not valid SemVer string'",
"%",
"version",
")",
"version_parts",
"=",
"match",
".",
"groupdict",
"(",
")",
"version_parts",
"[",
"'major'",
"]",
"=",
"int",
"(",
"version_parts",
"[",
"'major'",
"]",
")",
"version_parts",
"[",
"'minor'",
"]",
"=",
"int",
"(",
"version_parts",
"[",
"'minor'",
"]",
")",
"version_parts",
"[",
"'patch'",
"]",
"=",
"int",
"(",
"version_parts",
"[",
"'patch'",
"]",
")",
"return",
"version_parts"
] | Parse version to major, minor, patch, pre-release, build parts.
:param version: version string
:return: dictionary with the keys 'build', 'major', 'minor', 'patch',
and 'prerelease'. The prerelease or build keys can be None
if not provided
:rtype: dict
>>> import semver
>>> ver = semver.parse('3.4.5-pre.2+build.4')
>>> ver['major']
3
>>> ver['minor']
4
>>> ver['patch']
5
>>> ver['prerelease']
'pre.2'
>>> ver['build']
'build.4' | [
"Parse",
"version",
"to",
"major",
"minor",
"patch",
"pre",
"-",
"release",
"build",
"parts",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/semver.py#L41-L73 |
25,079 | pypa/pipenv | pipenv/vendor/semver.py | parse_version_info | def parse_version_info(version):
"""Parse version string to a VersionInfo instance.
:param version: version string
:return: a :class:`VersionInfo` instance
:rtype: :class:`VersionInfo`
>>> import semver
>>> version_info = semver.parse_version_info("3.4.5-pre.2+build.4")
>>> version_info.major
3
>>> version_info.minor
4
>>> version_info.patch
5
>>> version_info.prerelease
'pre.2'
>>> version_info.build
'build.4'
"""
parts = parse(version)
version_info = VersionInfo(
parts['major'], parts['minor'], parts['patch'],
parts['prerelease'], parts['build'])
return version_info | python | def parse_version_info(version):
"""Parse version string to a VersionInfo instance.
:param version: version string
:return: a :class:`VersionInfo` instance
:rtype: :class:`VersionInfo`
>>> import semver
>>> version_info = semver.parse_version_info("3.4.5-pre.2+build.4")
>>> version_info.major
3
>>> version_info.minor
4
>>> version_info.patch
5
>>> version_info.prerelease
'pre.2'
>>> version_info.build
'build.4'
"""
parts = parse(version)
version_info = VersionInfo(
parts['major'], parts['minor'], parts['patch'],
parts['prerelease'], parts['build'])
return version_info | [
"def",
"parse_version_info",
"(",
"version",
")",
":",
"parts",
"=",
"parse",
"(",
"version",
")",
"version_info",
"=",
"VersionInfo",
"(",
"parts",
"[",
"'major'",
"]",
",",
"parts",
"[",
"'minor'",
"]",
",",
"parts",
"[",
"'patch'",
"]",
",",
"parts",
"[",
"'prerelease'",
"]",
",",
"parts",
"[",
"'build'",
"]",
")",
"return",
"version_info"
] | Parse version string to a VersionInfo instance.
:param version: version string
:return: a :class:`VersionInfo` instance
:rtype: :class:`VersionInfo`
>>> import semver
>>> version_info = semver.parse_version_info("3.4.5-pre.2+build.4")
>>> version_info.major
3
>>> version_info.minor
4
>>> version_info.patch
5
>>> version_info.prerelease
'pre.2'
>>> version_info.build
'build.4' | [
"Parse",
"version",
"string",
"to",
"a",
"VersionInfo",
"instance",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/semver.py#L190-L215 |
25,080 | pypa/pipenv | pipenv/vendor/semver.py | compare | def compare(ver1, ver2):
"""Compare two versions
:param ver1: version string 1
:param ver2: version string 2
:return: The return value is negative if ver1 < ver2,
zero if ver1 == ver2 and strictly positive if ver1 > ver2
:rtype: int
>>> import semver
>>> semver.compare("1.0.0", "2.0.0")
-1
>>> semver.compare("2.0.0", "1.0.0")
1
>>> semver.compare("2.0.0", "2.0.0")
0
"""
v1, v2 = parse(ver1), parse(ver2)
return _compare_by_keys(v1, v2) | python | def compare(ver1, ver2):
"""Compare two versions
:param ver1: version string 1
:param ver2: version string 2
:return: The return value is negative if ver1 < ver2,
zero if ver1 == ver2 and strictly positive if ver1 > ver2
:rtype: int
>>> import semver
>>> semver.compare("1.0.0", "2.0.0")
-1
>>> semver.compare("2.0.0", "1.0.0")
1
>>> semver.compare("2.0.0", "2.0.0")
0
"""
v1, v2 = parse(ver1), parse(ver2)
return _compare_by_keys(v1, v2) | [
"def",
"compare",
"(",
"ver1",
",",
"ver2",
")",
":",
"v1",
",",
"v2",
"=",
"parse",
"(",
"ver1",
")",
",",
"parse",
"(",
"ver2",
")",
"return",
"_compare_by_keys",
"(",
"v1",
",",
"v2",
")"
] | Compare two versions
:param ver1: version string 1
:param ver2: version string 2
:return: The return value is negative if ver1 < ver2,
zero if ver1 == ver2 and strictly positive if ver1 > ver2
:rtype: int
>>> import semver
>>> semver.compare("1.0.0", "2.0.0")
-1
>>> semver.compare("2.0.0", "1.0.0")
1
>>> semver.compare("2.0.0", "2.0.0")
0 | [
"Compare",
"two",
"versions"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/semver.py#L264-L284 |
25,081 | pypa/pipenv | pipenv/vendor/semver.py | match | def match(version, match_expr):
"""Compare two versions through a comparison
:param str version: a version string
:param str match_expr: operator and version; valid operators are
< smaller than
> greater than
>= greator or equal than
<= smaller or equal than
== equal
!= not equal
:return: True if the expression matches the version, otherwise False
:rtype: bool
>>> import semver
>>> semver.match("2.0.0", ">=1.0.0")
True
>>> semver.match("1.0.0", ">1.0.0")
False
"""
prefix = match_expr[:2]
if prefix in ('>=', '<=', '==', '!='):
match_version = match_expr[2:]
elif prefix and prefix[0] in ('>', '<'):
prefix = prefix[0]
match_version = match_expr[1:]
else:
raise ValueError("match_expr parameter should be in format <op><ver>, "
"where <op> is one of "
"['<', '>', '==', '<=', '>=', '!=']. "
"You provided: %r" % match_expr)
possibilities_dict = {
'>': (1,),
'<': (-1,),
'==': (0,),
'!=': (-1, 1),
'>=': (0, 1),
'<=': (-1, 0)
}
possibilities = possibilities_dict[prefix]
cmp_res = compare(version, match_version)
return cmp_res in possibilities | python | def match(version, match_expr):
"""Compare two versions through a comparison
:param str version: a version string
:param str match_expr: operator and version; valid operators are
< smaller than
> greater than
>= greator or equal than
<= smaller or equal than
== equal
!= not equal
:return: True if the expression matches the version, otherwise False
:rtype: bool
>>> import semver
>>> semver.match("2.0.0", ">=1.0.0")
True
>>> semver.match("1.0.0", ">1.0.0")
False
"""
prefix = match_expr[:2]
if prefix in ('>=', '<=', '==', '!='):
match_version = match_expr[2:]
elif prefix and prefix[0] in ('>', '<'):
prefix = prefix[0]
match_version = match_expr[1:]
else:
raise ValueError("match_expr parameter should be in format <op><ver>, "
"where <op> is one of "
"['<', '>', '==', '<=', '>=', '!=']. "
"You provided: %r" % match_expr)
possibilities_dict = {
'>': (1,),
'<': (-1,),
'==': (0,),
'!=': (-1, 1),
'>=': (0, 1),
'<=': (-1, 0)
}
possibilities = possibilities_dict[prefix]
cmp_res = compare(version, match_version)
return cmp_res in possibilities | [
"def",
"match",
"(",
"version",
",",
"match_expr",
")",
":",
"prefix",
"=",
"match_expr",
"[",
":",
"2",
"]",
"if",
"prefix",
"in",
"(",
"'>='",
",",
"'<='",
",",
"'=='",
",",
"'!='",
")",
":",
"match_version",
"=",
"match_expr",
"[",
"2",
":",
"]",
"elif",
"prefix",
"and",
"prefix",
"[",
"0",
"]",
"in",
"(",
"'>'",
",",
"'<'",
")",
":",
"prefix",
"=",
"prefix",
"[",
"0",
"]",
"match_version",
"=",
"match_expr",
"[",
"1",
":",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"\"match_expr parameter should be in format <op><ver>, \"",
"\"where <op> is one of \"",
"\"['<', '>', '==', '<=', '>=', '!=']. \"",
"\"You provided: %r\"",
"%",
"match_expr",
")",
"possibilities_dict",
"=",
"{",
"'>'",
":",
"(",
"1",
",",
")",
",",
"'<'",
":",
"(",
"-",
"1",
",",
")",
",",
"'=='",
":",
"(",
"0",
",",
")",
",",
"'!='",
":",
"(",
"-",
"1",
",",
"1",
")",
",",
"'>='",
":",
"(",
"0",
",",
"1",
")",
",",
"'<='",
":",
"(",
"-",
"1",
",",
"0",
")",
"}",
"possibilities",
"=",
"possibilities_dict",
"[",
"prefix",
"]",
"cmp_res",
"=",
"compare",
"(",
"version",
",",
"match_version",
")",
"return",
"cmp_res",
"in",
"possibilities"
] | Compare two versions through a comparison
:param str version: a version string
:param str match_expr: operator and version; valid operators are
< smaller than
> greater than
>= greator or equal than
<= smaller or equal than
== equal
!= not equal
:return: True if the expression matches the version, otherwise False
:rtype: bool
>>> import semver
>>> semver.match("2.0.0", ">=1.0.0")
True
>>> semver.match("1.0.0", ">1.0.0")
False | [
"Compare",
"two",
"versions",
"through",
"a",
"comparison"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/semver.py#L287-L331 |
25,082 | pypa/pipenv | pipenv/vendor/semver.py | max_ver | def max_ver(ver1, ver2):
"""Returns the greater version of two versions
:param ver1: version string 1
:param ver2: version string 2
:return: the greater version of the two
:rtype: :class:`VersionInfo`
>>> import semver
>>> semver.max_ver("1.0.0", "2.0.0")
'2.0.0'
"""
cmp_res = compare(ver1, ver2)
if cmp_res == 0 or cmp_res == 1:
return ver1
else:
return ver2 | python | def max_ver(ver1, ver2):
"""Returns the greater version of two versions
:param ver1: version string 1
:param ver2: version string 2
:return: the greater version of the two
:rtype: :class:`VersionInfo`
>>> import semver
>>> semver.max_ver("1.0.0", "2.0.0")
'2.0.0'
"""
cmp_res = compare(ver1, ver2)
if cmp_res == 0 or cmp_res == 1:
return ver1
else:
return ver2 | [
"def",
"max_ver",
"(",
"ver1",
",",
"ver2",
")",
":",
"cmp_res",
"=",
"compare",
"(",
"ver1",
",",
"ver2",
")",
"if",
"cmp_res",
"==",
"0",
"or",
"cmp_res",
"==",
"1",
":",
"return",
"ver1",
"else",
":",
"return",
"ver2"
] | Returns the greater version of two versions
:param ver1: version string 1
:param ver2: version string 2
:return: the greater version of the two
:rtype: :class:`VersionInfo`
>>> import semver
>>> semver.max_ver("1.0.0", "2.0.0")
'2.0.0' | [
"Returns",
"the",
"greater",
"version",
"of",
"two",
"versions"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/semver.py#L334-L350 |
25,083 | pypa/pipenv | pipenv/vendor/semver.py | min_ver | def min_ver(ver1, ver2):
"""Returns the smaller version of two versions
:param ver1: version string 1
:param ver2: version string 2
:return: the smaller version of the two
:rtype: :class:`VersionInfo`
>>> import semver
>>> semver.min_ver("1.0.0", "2.0.0")
'1.0.0'
"""
cmp_res = compare(ver1, ver2)
if cmp_res == 0 or cmp_res == -1:
return ver1
else:
return ver2 | python | def min_ver(ver1, ver2):
"""Returns the smaller version of two versions
:param ver1: version string 1
:param ver2: version string 2
:return: the smaller version of the two
:rtype: :class:`VersionInfo`
>>> import semver
>>> semver.min_ver("1.0.0", "2.0.0")
'1.0.0'
"""
cmp_res = compare(ver1, ver2)
if cmp_res == 0 or cmp_res == -1:
return ver1
else:
return ver2 | [
"def",
"min_ver",
"(",
"ver1",
",",
"ver2",
")",
":",
"cmp_res",
"=",
"compare",
"(",
"ver1",
",",
"ver2",
")",
"if",
"cmp_res",
"==",
"0",
"or",
"cmp_res",
"==",
"-",
"1",
":",
"return",
"ver1",
"else",
":",
"return",
"ver2"
] | Returns the smaller version of two versions
:param ver1: version string 1
:param ver2: version string 2
:return: the smaller version of the two
:rtype: :class:`VersionInfo`
>>> import semver
>>> semver.min_ver("1.0.0", "2.0.0")
'1.0.0' | [
"Returns",
"the",
"smaller",
"version",
"of",
"two",
"versions"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/semver.py#L353-L369 |
25,084 | pypa/pipenv | pipenv/vendor/semver.py | format_version | def format_version(major, minor, patch, prerelease=None, build=None):
"""Format a version according to the Semantic Versioning specification
:param str major: the required major part of a version
:param str minor: the required minor part of a version
:param str patch: the required patch part of a version
:param str prerelease: the optional prerelease part of a version
:param str build: the optional build part of a version
:return: the formatted string
:rtype: str
>>> import semver
>>> semver.format_version(3, 4, 5, 'pre.2', 'build.4')
'3.4.5-pre.2+build.4'
"""
version = "%d.%d.%d" % (major, minor, patch)
if prerelease is not None:
version = version + "-%s" % prerelease
if build is not None:
version = version + "+%s" % build
return version | python | def format_version(major, minor, patch, prerelease=None, build=None):
"""Format a version according to the Semantic Versioning specification
:param str major: the required major part of a version
:param str minor: the required minor part of a version
:param str patch: the required patch part of a version
:param str prerelease: the optional prerelease part of a version
:param str build: the optional build part of a version
:return: the formatted string
:rtype: str
>>> import semver
>>> semver.format_version(3, 4, 5, 'pre.2', 'build.4')
'3.4.5-pre.2+build.4'
"""
version = "%d.%d.%d" % (major, minor, patch)
if prerelease is not None:
version = version + "-%s" % prerelease
if build is not None:
version = version + "+%s" % build
return version | [
"def",
"format_version",
"(",
"major",
",",
"minor",
",",
"patch",
",",
"prerelease",
"=",
"None",
",",
"build",
"=",
"None",
")",
":",
"version",
"=",
"\"%d.%d.%d\"",
"%",
"(",
"major",
",",
"minor",
",",
"patch",
")",
"if",
"prerelease",
"is",
"not",
"None",
":",
"version",
"=",
"version",
"+",
"\"-%s\"",
"%",
"prerelease",
"if",
"build",
"is",
"not",
"None",
":",
"version",
"=",
"version",
"+",
"\"+%s\"",
"%",
"build",
"return",
"version"
] | Format a version according to the Semantic Versioning specification
:param str major: the required major part of a version
:param str minor: the required minor part of a version
:param str patch: the required patch part of a version
:param str prerelease: the optional prerelease part of a version
:param str build: the optional build part of a version
:return: the formatted string
:rtype: str
>>> import semver
>>> semver.format_version(3, 4, 5, 'pre.2', 'build.4')
'3.4.5-pre.2+build.4' | [
"Format",
"a",
"version",
"according",
"to",
"the",
"Semantic",
"Versioning",
"specification"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/semver.py#L372-L394 |
25,085 | pypa/pipenv | pipenv/vendor/ptyprocess/ptyprocess.py | _make_eof_intr | def _make_eof_intr():
"""Set constants _EOF and _INTR.
This avoids doing potentially costly operations on module load.
"""
global _EOF, _INTR
if (_EOF is not None) and (_INTR is not None):
return
# inherit EOF and INTR definitions from controlling process.
try:
from termios import VEOF, VINTR
fd = None
for name in 'stdin', 'stdout':
stream = getattr(sys, '__%s__' % name, None)
if stream is None or not hasattr(stream, 'fileno'):
continue
try:
fd = stream.fileno()
except ValueError:
continue
if fd is None:
# no fd, raise ValueError to fallback on CEOF, CINTR
raise ValueError("No stream has a fileno")
intr = ord(termios.tcgetattr(fd)[6][VINTR])
eof = ord(termios.tcgetattr(fd)[6][VEOF])
except (ImportError, OSError, IOError, ValueError, termios.error):
# unless the controlling process is also not a terminal,
# such as cron(1), or when stdin and stdout are both closed.
# Fall-back to using CEOF and CINTR. There
try:
from termios import CEOF, CINTR
(intr, eof) = (CINTR, CEOF)
except ImportError:
# ^C, ^D
(intr, eof) = (3, 4)
_INTR = _byte(intr)
_EOF = _byte(eof) | python | def _make_eof_intr():
"""Set constants _EOF and _INTR.
This avoids doing potentially costly operations on module load.
"""
global _EOF, _INTR
if (_EOF is not None) and (_INTR is not None):
return
# inherit EOF and INTR definitions from controlling process.
try:
from termios import VEOF, VINTR
fd = None
for name in 'stdin', 'stdout':
stream = getattr(sys, '__%s__' % name, None)
if stream is None or not hasattr(stream, 'fileno'):
continue
try:
fd = stream.fileno()
except ValueError:
continue
if fd is None:
# no fd, raise ValueError to fallback on CEOF, CINTR
raise ValueError("No stream has a fileno")
intr = ord(termios.tcgetattr(fd)[6][VINTR])
eof = ord(termios.tcgetattr(fd)[6][VEOF])
except (ImportError, OSError, IOError, ValueError, termios.error):
# unless the controlling process is also not a terminal,
# such as cron(1), or when stdin and stdout are both closed.
# Fall-back to using CEOF and CINTR. There
try:
from termios import CEOF, CINTR
(intr, eof) = (CINTR, CEOF)
except ImportError:
# ^C, ^D
(intr, eof) = (3, 4)
_INTR = _byte(intr)
_EOF = _byte(eof) | [
"def",
"_make_eof_intr",
"(",
")",
":",
"global",
"_EOF",
",",
"_INTR",
"if",
"(",
"_EOF",
"is",
"not",
"None",
")",
"and",
"(",
"_INTR",
"is",
"not",
"None",
")",
":",
"return",
"# inherit EOF and INTR definitions from controlling process.",
"try",
":",
"from",
"termios",
"import",
"VEOF",
",",
"VINTR",
"fd",
"=",
"None",
"for",
"name",
"in",
"'stdin'",
",",
"'stdout'",
":",
"stream",
"=",
"getattr",
"(",
"sys",
",",
"'__%s__'",
"%",
"name",
",",
"None",
")",
"if",
"stream",
"is",
"None",
"or",
"not",
"hasattr",
"(",
"stream",
",",
"'fileno'",
")",
":",
"continue",
"try",
":",
"fd",
"=",
"stream",
".",
"fileno",
"(",
")",
"except",
"ValueError",
":",
"continue",
"if",
"fd",
"is",
"None",
":",
"# no fd, raise ValueError to fallback on CEOF, CINTR",
"raise",
"ValueError",
"(",
"\"No stream has a fileno\"",
")",
"intr",
"=",
"ord",
"(",
"termios",
".",
"tcgetattr",
"(",
"fd",
")",
"[",
"6",
"]",
"[",
"VINTR",
"]",
")",
"eof",
"=",
"ord",
"(",
"termios",
".",
"tcgetattr",
"(",
"fd",
")",
"[",
"6",
"]",
"[",
"VEOF",
"]",
")",
"except",
"(",
"ImportError",
",",
"OSError",
",",
"IOError",
",",
"ValueError",
",",
"termios",
".",
"error",
")",
":",
"# unless the controlling process is also not a terminal,",
"# such as cron(1), or when stdin and stdout are both closed.",
"# Fall-back to using CEOF and CINTR. There",
"try",
":",
"from",
"termios",
"import",
"CEOF",
",",
"CINTR",
"(",
"intr",
",",
"eof",
")",
"=",
"(",
"CINTR",
",",
"CEOF",
")",
"except",
"ImportError",
":",
"# ^C, ^D",
"(",
"intr",
",",
"eof",
")",
"=",
"(",
"3",
",",
"4",
")",
"_INTR",
"=",
"_byte",
"(",
"intr",
")",
"_EOF",
"=",
"_byte",
"(",
"eof",
")"
] | Set constants _EOF and _INTR.
This avoids doing potentially costly operations on module load. | [
"Set",
"constants",
"_EOF",
"and",
"_INTR",
".",
"This",
"avoids",
"doing",
"potentially",
"costly",
"operations",
"on",
"module",
"load",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/ptyprocess/ptyprocess.py#L51-L89 |
25,086 | pypa/pipenv | pipenv/vendor/ptyprocess/ptyprocess.py | PtyProcess.read | def read(self, size=1024):
"""Read and return at most ``size`` bytes from the pty.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to deal
with the vagaries of EOF on platforms that do strange things, like IRIX
or older Solaris systems. It handles the errno=EIO pattern used on
Linux, and the empty-string return used on BSD platforms and (seemingly)
on recent Solaris.
"""
try:
s = self.fileobj.read1(size)
except (OSError, IOError) as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOFError('End Of File (EOF). Exception style platform.')
raise
if s == b'':
# BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
self.flag_eof = True
raise EOFError('End Of File (EOF). Empty string style platform.')
return s | python | def read(self, size=1024):
"""Read and return at most ``size`` bytes from the pty.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to deal
with the vagaries of EOF on platforms that do strange things, like IRIX
or older Solaris systems. It handles the errno=EIO pattern used on
Linux, and the empty-string return used on BSD platforms and (seemingly)
on recent Solaris.
"""
try:
s = self.fileobj.read1(size)
except (OSError, IOError) as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOFError('End Of File (EOF). Exception style platform.')
raise
if s == b'':
# BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
self.flag_eof = True
raise EOFError('End Of File (EOF). Empty string style platform.')
return s | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"1024",
")",
":",
"try",
":",
"s",
"=",
"self",
".",
"fileobj",
".",
"read1",
"(",
"size",
")",
"except",
"(",
"OSError",
",",
"IOError",
")",
"as",
"err",
":",
"if",
"err",
".",
"args",
"[",
"0",
"]",
"==",
"errno",
".",
"EIO",
":",
"# Linux-style EOF",
"self",
".",
"flag_eof",
"=",
"True",
"raise",
"EOFError",
"(",
"'End Of File (EOF). Exception style platform.'",
")",
"raise",
"if",
"s",
"==",
"b''",
":",
"# BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))",
"self",
".",
"flag_eof",
"=",
"True",
"raise",
"EOFError",
"(",
"'End Of File (EOF). Empty string style platform.'",
")",
"return",
"s"
] | Read and return at most ``size`` bytes from the pty.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to deal
with the vagaries of EOF on platforms that do strange things, like IRIX
or older Solaris systems. It handles the errno=EIO pattern used on
Linux, and the empty-string return used on BSD platforms and (seemingly)
on recent Solaris. | [
"Read",
"and",
"return",
"at",
"most",
"size",
"bytes",
"from",
"the",
"pty",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/ptyprocess/ptyprocess.py#L503-L528 |
25,087 | pypa/pipenv | pipenv/vendor/ptyprocess/ptyprocess.py | PtyProcess.write | def write(self, s, flush=True):
"""Write bytes to the pseudoterminal.
Returns the number of bytes written.
"""
return self._writeb(s, flush=flush) | python | def write(self, s, flush=True):
"""Write bytes to the pseudoterminal.
Returns the number of bytes written.
"""
return self._writeb(s, flush=flush) | [
"def",
"write",
"(",
"self",
",",
"s",
",",
"flush",
"=",
"True",
")",
":",
"return",
"self",
".",
"_writeb",
"(",
"s",
",",
"flush",
"=",
"flush",
")"
] | Write bytes to the pseudoterminal.
Returns the number of bytes written. | [
"Write",
"bytes",
"to",
"the",
"pseudoterminal",
".",
"Returns",
"the",
"number",
"of",
"bytes",
"written",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/ptyprocess/ptyprocess.py#L557-L562 |
25,088 | pypa/pipenv | pipenv/vendor/ptyprocess/ptyprocess.py | PtyProcess.terminate | def terminate(self, force=False):
'''This forces a child process to terminate. It starts nicely with
SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
returns True if the child was terminated. This returns False if the
child could not be terminated. '''
if not self.isalive():
return True
try:
self.kill(signal.SIGHUP)
time.sleep(self.delayafterterminate)
if not self.isalive():
return True
self.kill(signal.SIGCONT)
time.sleep(self.delayafterterminate)
if not self.isalive():
return True
self.kill(signal.SIGINT)
time.sleep(self.delayafterterminate)
if not self.isalive():
return True
if force:
self.kill(signal.SIGKILL)
time.sleep(self.delayafterterminate)
if not self.isalive():
return True
else:
return False
return False
except OSError:
# I think there are kernel timing issues that sometimes cause
# this to happen. I think isalive() reports True, but the
# process is dead to the kernel.
# Make one last attempt to see if the kernel is up to date.
time.sleep(self.delayafterterminate)
if not self.isalive():
return True
else:
return False | python | def terminate(self, force=False):
'''This forces a child process to terminate. It starts nicely with
SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
returns True if the child was terminated. This returns False if the
child could not be terminated. '''
if not self.isalive():
return True
try:
self.kill(signal.SIGHUP)
time.sleep(self.delayafterterminate)
if not self.isalive():
return True
self.kill(signal.SIGCONT)
time.sleep(self.delayafterterminate)
if not self.isalive():
return True
self.kill(signal.SIGINT)
time.sleep(self.delayafterterminate)
if not self.isalive():
return True
if force:
self.kill(signal.SIGKILL)
time.sleep(self.delayafterterminate)
if not self.isalive():
return True
else:
return False
return False
except OSError:
# I think there are kernel timing issues that sometimes cause
# this to happen. I think isalive() reports True, but the
# process is dead to the kernel.
# Make one last attempt to see if the kernel is up to date.
time.sleep(self.delayafterterminate)
if not self.isalive():
return True
else:
return False | [
"def",
"terminate",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"isalive",
"(",
")",
":",
"return",
"True",
"try",
":",
"self",
".",
"kill",
"(",
"signal",
".",
"SIGHUP",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"delayafterterminate",
")",
"if",
"not",
"self",
".",
"isalive",
"(",
")",
":",
"return",
"True",
"self",
".",
"kill",
"(",
"signal",
".",
"SIGCONT",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"delayafterterminate",
")",
"if",
"not",
"self",
".",
"isalive",
"(",
")",
":",
"return",
"True",
"self",
".",
"kill",
"(",
"signal",
".",
"SIGINT",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"delayafterterminate",
")",
"if",
"not",
"self",
".",
"isalive",
"(",
")",
":",
"return",
"True",
"if",
"force",
":",
"self",
".",
"kill",
"(",
"signal",
".",
"SIGKILL",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"delayafterterminate",
")",
"if",
"not",
"self",
".",
"isalive",
"(",
")",
":",
"return",
"True",
"else",
":",
"return",
"False",
"return",
"False",
"except",
"OSError",
":",
"# I think there are kernel timing issues that sometimes cause",
"# this to happen. I think isalive() reports True, but the",
"# process is dead to the kernel.",
"# Make one last attempt to see if the kernel is up to date.",
"time",
".",
"sleep",
"(",
"self",
".",
"delayafterterminate",
")",
"if",
"not",
"self",
".",
"isalive",
"(",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | This forces a child process to terminate. It starts nicely with
SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
returns True if the child was terminated. This returns False if the
child could not be terminated. | [
"This",
"forces",
"a",
"child",
"process",
"to",
"terminate",
".",
"It",
"starts",
"nicely",
"with",
"SIGHUP",
"and",
"SIGINT",
".",
"If",
"force",
"is",
"True",
"then",
"moves",
"onto",
"SIGKILL",
".",
"This",
"returns",
"True",
"if",
"the",
"child",
"was",
"terminated",
".",
"This",
"returns",
"False",
"if",
"the",
"child",
"could",
"not",
"be",
"terminated",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/ptyprocess/ptyprocess.py#L616-L654 |
25,089 | pypa/pipenv | pipenv/vendor/ptyprocess/ptyprocess.py | PtyProcess.kill | def kill(self, sig):
"""Send the given signal to the child application.
In keeping with UNIX tradition it has a misleading name. It does not
necessarily kill the child unless you send the right signal. See the
:mod:`signal` module for constants representing signal numbers.
"""
# Same as os.kill, but the pid is given for you.
if self.isalive():
os.kill(self.pid, sig) | python | def kill(self, sig):
"""Send the given signal to the child application.
In keeping with UNIX tradition it has a misleading name. It does not
necessarily kill the child unless you send the right signal. See the
:mod:`signal` module for constants representing signal numbers.
"""
# Same as os.kill, but the pid is given for you.
if self.isalive():
os.kill(self.pid, sig) | [
"def",
"kill",
"(",
"self",
",",
"sig",
")",
":",
"# Same as os.kill, but the pid is given for you.",
"if",
"self",
".",
"isalive",
"(",
")",
":",
"os",
".",
"kill",
"(",
"self",
".",
"pid",
",",
"sig",
")"
] | Send the given signal to the child application.
In keeping with UNIX tradition it has a misleading name. It does not
necessarily kill the child unless you send the right signal. See the
:mod:`signal` module for constants representing signal numbers. | [
"Send",
"the",
"given",
"signal",
"to",
"the",
"child",
"application",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/ptyprocess/ptyprocess.py#L762-L772 |
25,090 | pypa/pipenv | pipenv/vendor/ptyprocess/ptyprocess.py | PtyProcessUnicode.read | def read(self, size=1024):
"""Read at most ``size`` bytes from the pty, return them as unicode.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
The size argument still refers to bytes, not unicode code points.
"""
b = super(PtyProcessUnicode, self).read(size)
return self.decoder.decode(b, final=False) | python | def read(self, size=1024):
"""Read at most ``size`` bytes from the pty, return them as unicode.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
The size argument still refers to bytes, not unicode code points.
"""
b = super(PtyProcessUnicode, self).read(size)
return self.decoder.decode(b, final=False) | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"1024",
")",
":",
"b",
"=",
"super",
"(",
"PtyProcessUnicode",
",",
"self",
")",
".",
"read",
"(",
"size",
")",
"return",
"self",
".",
"decoder",
".",
"decode",
"(",
"b",
",",
"final",
"=",
"False",
")"
] | Read at most ``size`` bytes from the pty, return them as unicode.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
The size argument still refers to bytes, not unicode code points. | [
"Read",
"at",
"most",
"size",
"bytes",
"from",
"the",
"pty",
"return",
"them",
"as",
"unicode",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/ptyprocess/ptyprocess.py#L810-L819 |
25,091 | pypa/pipenv | pipenv/vendor/ptyprocess/ptyprocess.py | PtyProcessUnicode.write | def write(self, s):
"""Write the unicode string ``s`` to the pseudoterminal.
Returns the number of bytes written.
"""
b = s.encode(self.encoding)
return super(PtyProcessUnicode, self).write(b) | python | def write(self, s):
"""Write the unicode string ``s`` to the pseudoterminal.
Returns the number of bytes written.
"""
b = s.encode(self.encoding)
return super(PtyProcessUnicode, self).write(b) | [
"def",
"write",
"(",
"self",
",",
"s",
")",
":",
"b",
"=",
"s",
".",
"encode",
"(",
"self",
".",
"encoding",
")",
"return",
"super",
"(",
"PtyProcessUnicode",
",",
"self",
")",
".",
"write",
"(",
"b",
")"
] | Write the unicode string ``s`` to the pseudoterminal.
Returns the number of bytes written. | [
"Write",
"the",
"unicode",
"string",
"s",
"to",
"the",
"pseudoterminal",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/ptyprocess/ptyprocess.py#L830-L836 |
25,092 | pypa/pipenv | pipenv/vendor/resolvelib/resolvers.py | Criterion.from_requirement | def from_requirement(cls, provider, requirement, parent):
"""Build an instance from a requirement.
"""
candidates = provider.find_matches(requirement)
if not candidates:
raise NoVersionsAvailable(requirement, parent)
return cls(
candidates=candidates,
information=[RequirementInformation(requirement, parent)],
) | python | def from_requirement(cls, provider, requirement, parent):
"""Build an instance from a requirement.
"""
candidates = provider.find_matches(requirement)
if not candidates:
raise NoVersionsAvailable(requirement, parent)
return cls(
candidates=candidates,
information=[RequirementInformation(requirement, parent)],
) | [
"def",
"from_requirement",
"(",
"cls",
",",
"provider",
",",
"requirement",
",",
"parent",
")",
":",
"candidates",
"=",
"provider",
".",
"find_matches",
"(",
"requirement",
")",
"if",
"not",
"candidates",
":",
"raise",
"NoVersionsAvailable",
"(",
"requirement",
",",
"parent",
")",
"return",
"cls",
"(",
"candidates",
"=",
"candidates",
",",
"information",
"=",
"[",
"RequirementInformation",
"(",
"requirement",
",",
"parent",
")",
"]",
",",
")"
] | Build an instance from a requirement. | [
"Build",
"an",
"instance",
"from",
"a",
"requirement",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/resolvelib/resolvers.py#L40-L49 |
25,093 | pypa/pipenv | pipenv/vendor/resolvelib/resolvers.py | Criterion.merged_with | def merged_with(self, provider, requirement, parent):
"""Build a new instance from this and a new requirement.
"""
infos = list(self.information)
infos.append(RequirementInformation(requirement, parent))
candidates = [
c for c in self.candidates
if provider.is_satisfied_by(requirement, c)
]
if not candidates:
raise RequirementsConflicted(self)
return type(self)(candidates, infos) | python | def merged_with(self, provider, requirement, parent):
"""Build a new instance from this and a new requirement.
"""
infos = list(self.information)
infos.append(RequirementInformation(requirement, parent))
candidates = [
c for c in self.candidates
if provider.is_satisfied_by(requirement, c)
]
if not candidates:
raise RequirementsConflicted(self)
return type(self)(candidates, infos) | [
"def",
"merged_with",
"(",
"self",
",",
"provider",
",",
"requirement",
",",
"parent",
")",
":",
"infos",
"=",
"list",
"(",
"self",
".",
"information",
")",
"infos",
".",
"append",
"(",
"RequirementInformation",
"(",
"requirement",
",",
"parent",
")",
")",
"candidates",
"=",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"candidates",
"if",
"provider",
".",
"is_satisfied_by",
"(",
"requirement",
",",
"c",
")",
"]",
"if",
"not",
"candidates",
":",
"raise",
"RequirementsConflicted",
"(",
"self",
")",
"return",
"type",
"(",
"self",
")",
"(",
"candidates",
",",
"infos",
")"
] | Build a new instance from this and a new requirement. | [
"Build",
"a",
"new",
"instance",
"from",
"this",
"and",
"a",
"new",
"requirement",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/resolvelib/resolvers.py#L57-L68 |
25,094 | pypa/pipenv | pipenv/vendor/resolvelib/resolvers.py | Resolution._push_new_state | def _push_new_state(self):
"""Push a new state into history.
This new state will be used to hold resolution results of the next
coming round.
"""
try:
base = self._states[-1]
except IndexError:
graph = DirectedGraph()
graph.add(None) # Sentinel as root dependencies' parent.
state = State(mapping={}, graph=graph)
else:
state = State(
mapping=base.mapping.copy(),
graph=base.graph.copy(),
)
self._states.append(state) | python | def _push_new_state(self):
"""Push a new state into history.
This new state will be used to hold resolution results of the next
coming round.
"""
try:
base = self._states[-1]
except IndexError:
graph = DirectedGraph()
graph.add(None) # Sentinel as root dependencies' parent.
state = State(mapping={}, graph=graph)
else:
state = State(
mapping=base.mapping.copy(),
graph=base.graph.copy(),
)
self._states.append(state) | [
"def",
"_push_new_state",
"(",
"self",
")",
":",
"try",
":",
"base",
"=",
"self",
".",
"_states",
"[",
"-",
"1",
"]",
"except",
"IndexError",
":",
"graph",
"=",
"DirectedGraph",
"(",
")",
"graph",
".",
"add",
"(",
"None",
")",
"# Sentinel as root dependencies' parent.",
"state",
"=",
"State",
"(",
"mapping",
"=",
"{",
"}",
",",
"graph",
"=",
"graph",
")",
"else",
":",
"state",
"=",
"State",
"(",
"mapping",
"=",
"base",
".",
"mapping",
".",
"copy",
"(",
")",
",",
"graph",
"=",
"base",
".",
"graph",
".",
"copy",
"(",
")",
",",
")",
"self",
".",
"_states",
".",
"append",
"(",
"state",
")"
] | Push a new state into history.
This new state will be used to hold resolution results of the next
coming round. | [
"Push",
"a",
"new",
"state",
"into",
"history",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/resolvelib/resolvers.py#L110-L127 |
25,095 | pypa/pipenv | pipenv/vendor/resolvelib/resolvers.py | Resolver.resolve | def resolve(self, requirements, max_rounds=20):
"""Take a collection of constraints, spit out the resolution result.
The return value is a representation to the final resolution result. It
is a tuple subclass with two public members:
* `mapping`: A dict of resolved candidates. Each key is an identifier
of a requirement (as returned by the provider's `identify` method),
and the value is the resolved candidate.
* `graph`: A `DirectedGraph` instance representing the dependency tree.
The vertices are keys of `mapping`, and each edge represents *why*
a particular package is included. A special vertex `None` is
included to represent parents of user-supplied requirements.
The following exceptions may be raised if a resolution cannot be found:
* `NoVersionsAvailable`: A requirement has no available candidates.
* `ResolutionImpossible`: A resolution cannot be found for the given
combination of requirements.
* `ResolutionTooDeep`: The dependency tree is too deeply nested and
the resolver gave up. This is usually caused by a circular
dependency, but you can try to resolve this by increasing the
`max_rounds` argument.
"""
resolution = Resolution(self.provider, self.reporter)
resolution.resolve(requirements, max_rounds=max_rounds)
return resolution.state | python | def resolve(self, requirements, max_rounds=20):
"""Take a collection of constraints, spit out the resolution result.
The return value is a representation to the final resolution result. It
is a tuple subclass with two public members:
* `mapping`: A dict of resolved candidates. Each key is an identifier
of a requirement (as returned by the provider's `identify` method),
and the value is the resolved candidate.
* `graph`: A `DirectedGraph` instance representing the dependency tree.
The vertices are keys of `mapping`, and each edge represents *why*
a particular package is included. A special vertex `None` is
included to represent parents of user-supplied requirements.
The following exceptions may be raised if a resolution cannot be found:
* `NoVersionsAvailable`: A requirement has no available candidates.
* `ResolutionImpossible`: A resolution cannot be found for the given
combination of requirements.
* `ResolutionTooDeep`: The dependency tree is too deeply nested and
the resolver gave up. This is usually caused by a circular
dependency, but you can try to resolve this by increasing the
`max_rounds` argument.
"""
resolution = Resolution(self.provider, self.reporter)
resolution.resolve(requirements, max_rounds=max_rounds)
return resolution.state | [
"def",
"resolve",
"(",
"self",
",",
"requirements",
",",
"max_rounds",
"=",
"20",
")",
":",
"resolution",
"=",
"Resolution",
"(",
"self",
".",
"provider",
",",
"self",
".",
"reporter",
")",
"resolution",
".",
"resolve",
"(",
"requirements",
",",
"max_rounds",
"=",
"max_rounds",
")",
"return",
"resolution",
".",
"state"
] | Take a collection of constraints, spit out the resolution result.
The return value is a representation to the final resolution result. It
is a tuple subclass with two public members:
* `mapping`: A dict of resolved candidates. Each key is an identifier
of a requirement (as returned by the provider's `identify` method),
and the value is the resolved candidate.
* `graph`: A `DirectedGraph` instance representing the dependency tree.
The vertices are keys of `mapping`, and each edge represents *why*
a particular package is included. A special vertex `None` is
included to represent parents of user-supplied requirements.
The following exceptions may be raised if a resolution cannot be found:
* `NoVersionsAvailable`: A requirement has no available candidates.
* `ResolutionImpossible`: A resolution cannot be found for the given
combination of requirements.
* `ResolutionTooDeep`: The dependency tree is too deeply nested and
the resolver gave up. This is usually caused by a circular
dependency, but you can try to resolve this by increasing the
`max_rounds` argument. | [
"Take",
"a",
"collection",
"of",
"constraints",
"spit",
"out",
"the",
"resolution",
"result",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/resolvelib/resolvers.py#L261-L287 |
25,096 | pypa/pipenv | pipenv/vendor/passa/internals/markers.py | _strip_extra | def _strip_extra(elements):
"""Remove the "extra == ..." operands from the list.
This is not a comprehensive implementation, but relies on an important
characteristic of metadata generation: The "extra == ..." operand is always
associated with an "and" operator. This means that we can simply remove the
operand and the "and" operator associated with it.
"""
extra_indexes = []
for i, element in enumerate(elements):
if isinstance(element, list):
cancelled = _strip_extra(element)
if cancelled:
extra_indexes.append(i)
elif isinstance(element, tuple) and element[0].value == "extra":
extra_indexes.append(i)
for i in reversed(extra_indexes):
del elements[i]
if i > 0 and elements[i - 1] == "and":
# Remove the "and" before it.
del elements[i - 1]
elif elements:
# This shouldn't ever happen, but is included for completeness.
# If there is not an "and" before this element, try to remove the
# operator after it.
del elements[0]
return (not elements) | python | def _strip_extra(elements):
"""Remove the "extra == ..." operands from the list.
This is not a comprehensive implementation, but relies on an important
characteristic of metadata generation: The "extra == ..." operand is always
associated with an "and" operator. This means that we can simply remove the
operand and the "and" operator associated with it.
"""
extra_indexes = []
for i, element in enumerate(elements):
if isinstance(element, list):
cancelled = _strip_extra(element)
if cancelled:
extra_indexes.append(i)
elif isinstance(element, tuple) and element[0].value == "extra":
extra_indexes.append(i)
for i in reversed(extra_indexes):
del elements[i]
if i > 0 and elements[i - 1] == "and":
# Remove the "and" before it.
del elements[i - 1]
elif elements:
# This shouldn't ever happen, but is included for completeness.
# If there is not an "and" before this element, try to remove the
# operator after it.
del elements[0]
return (not elements) | [
"def",
"_strip_extra",
"(",
"elements",
")",
":",
"extra_indexes",
"=",
"[",
"]",
"for",
"i",
",",
"element",
"in",
"enumerate",
"(",
"elements",
")",
":",
"if",
"isinstance",
"(",
"element",
",",
"list",
")",
":",
"cancelled",
"=",
"_strip_extra",
"(",
"element",
")",
"if",
"cancelled",
":",
"extra_indexes",
".",
"append",
"(",
"i",
")",
"elif",
"isinstance",
"(",
"element",
",",
"tuple",
")",
"and",
"element",
"[",
"0",
"]",
".",
"value",
"==",
"\"extra\"",
":",
"extra_indexes",
".",
"append",
"(",
"i",
")",
"for",
"i",
"in",
"reversed",
"(",
"extra_indexes",
")",
":",
"del",
"elements",
"[",
"i",
"]",
"if",
"i",
">",
"0",
"and",
"elements",
"[",
"i",
"-",
"1",
"]",
"==",
"\"and\"",
":",
"# Remove the \"and\" before it.",
"del",
"elements",
"[",
"i",
"-",
"1",
"]",
"elif",
"elements",
":",
"# This shouldn't ever happen, but is included for completeness.",
"# If there is not an \"and\" before this element, try to remove the",
"# operator after it.",
"del",
"elements",
"[",
"0",
"]",
"return",
"(",
"not",
"elements",
")"
] | Remove the "extra == ..." operands from the list.
This is not a comprehensive implementation, but relies on an important
characteristic of metadata generation: The "extra == ..." operand is always
associated with an "and" operator. This means that we can simply remove the
operand and the "and" operator associated with it. | [
"Remove",
"the",
"extra",
"==",
"...",
"operands",
"from",
"the",
"list",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/markers.py#L8-L34 |
25,097 | pypa/pipenv | pipenv/vendor/passa/internals/markers.py | get_without_extra | def get_without_extra(marker):
"""Build a new marker without the `extra == ...` part.
The implementation relies very deep into packaging's internals, but I don't
have a better way now (except implementing the whole thing myself).
This could return `None` if the `extra == ...` part is the only one in the
input marker.
"""
# TODO: Why is this very deep in the internals? Why is a better solution
# implementing it yourself when someone is already maintaining a codebase
# for this? It's literally a grammar implementation that is required to
# meet the demands of a pep... -d
if not marker:
return None
marker = Marker(str(marker))
elements = marker._markers
_strip_extra(elements)
if elements:
return marker
return None | python | def get_without_extra(marker):
"""Build a new marker without the `extra == ...` part.
The implementation relies very deep into packaging's internals, but I don't
have a better way now (except implementing the whole thing myself).
This could return `None` if the `extra == ...` part is the only one in the
input marker.
"""
# TODO: Why is this very deep in the internals? Why is a better solution
# implementing it yourself when someone is already maintaining a codebase
# for this? It's literally a grammar implementation that is required to
# meet the demands of a pep... -d
if not marker:
return None
marker = Marker(str(marker))
elements = marker._markers
_strip_extra(elements)
if elements:
return marker
return None | [
"def",
"get_without_extra",
"(",
"marker",
")",
":",
"# TODO: Why is this very deep in the internals? Why is a better solution",
"# implementing it yourself when someone is already maintaining a codebase",
"# for this? It's literally a grammar implementation that is required to",
"# meet the demands of a pep... -d",
"if",
"not",
"marker",
":",
"return",
"None",
"marker",
"=",
"Marker",
"(",
"str",
"(",
"marker",
")",
")",
"elements",
"=",
"marker",
".",
"_markers",
"_strip_extra",
"(",
"elements",
")",
"if",
"elements",
":",
"return",
"marker",
"return",
"None"
] | Build a new marker without the `extra == ...` part.
The implementation relies very deep into packaging's internals, but I don't
have a better way now (except implementing the whole thing myself).
This could return `None` if the `extra == ...` part is the only one in the
input marker. | [
"Build",
"a",
"new",
"marker",
"without",
"the",
"extra",
"==",
"...",
"part",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/markers.py#L37-L57 |
25,098 | pypa/pipenv | pipenv/vendor/distlib/locators.py | Locator.get_errors | def get_errors(self):
"""
Return any errors which have occurred.
"""
result = []
while not self.errors.empty(): # pragma: no cover
try:
e = self.errors.get(False)
result.append(e)
except self.errors.Empty:
continue
self.errors.task_done()
return result | python | def get_errors(self):
"""
Return any errors which have occurred.
"""
result = []
while not self.errors.empty(): # pragma: no cover
try:
e = self.errors.get(False)
result.append(e)
except self.errors.Empty:
continue
self.errors.task_done()
return result | [
"def",
"get_errors",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"while",
"not",
"self",
".",
"errors",
".",
"empty",
"(",
")",
":",
"# pragma: no cover",
"try",
":",
"e",
"=",
"self",
".",
"errors",
".",
"get",
"(",
"False",
")",
"result",
".",
"append",
"(",
"e",
")",
"except",
"self",
".",
"errors",
".",
"Empty",
":",
"continue",
"self",
".",
"errors",
".",
"task_done",
"(",
")",
"return",
"result"
] | Return any errors which have occurred. | [
"Return",
"any",
"errors",
"which",
"have",
"occurred",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/locators.py#L121-L133 |
25,099 | pypa/pipenv | pipenv/vendor/distlib/locators.py | Locator.get_project | def get_project(self, name):
"""
For a given project, get a dictionary mapping available versions to Distribution
instances.
This calls _get_project to do all the work, and just implements a caching layer on top.
"""
if self._cache is None: # pragma: no cover
result = self._get_project(name)
elif name in self._cache:
result = self._cache[name]
else:
self.clear_errors()
result = self._get_project(name)
self._cache[name] = result
return result | python | def get_project(self, name):
"""
For a given project, get a dictionary mapping available versions to Distribution
instances.
This calls _get_project to do all the work, and just implements a caching layer on top.
"""
if self._cache is None: # pragma: no cover
result = self._get_project(name)
elif name in self._cache:
result = self._cache[name]
else:
self.clear_errors()
result = self._get_project(name)
self._cache[name] = result
return result | [
"def",
"get_project",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"_cache",
"is",
"None",
":",
"# pragma: no cover",
"result",
"=",
"self",
".",
"_get_project",
"(",
"name",
")",
"elif",
"name",
"in",
"self",
".",
"_cache",
":",
"result",
"=",
"self",
".",
"_cache",
"[",
"name",
"]",
"else",
":",
"self",
".",
"clear_errors",
"(",
")",
"result",
"=",
"self",
".",
"_get_project",
"(",
"name",
")",
"self",
".",
"_cache",
"[",
"name",
"]",
"=",
"result",
"return",
"result"
] | For a given project, get a dictionary mapping available versions to Distribution
instances.
This calls _get_project to do all the work, and just implements a caching layer on top. | [
"For",
"a",
"given",
"project",
"get",
"a",
"dictionary",
"mapping",
"available",
"versions",
"to",
"Distribution",
"instances",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/locators.py#L171-L186 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.