repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
pypa/pipenv
|
pipenv/vendor/pathlib2/__init__.py
|
Path.rename
|
def rename(self, target):
"""
Rename this path to the given path.
"""
if self._closed:
self._raise_closed()
self._accessor.rename(self, target)
|
python
|
def rename(self, target):
"""
Rename this path to the given path.
"""
if self._closed:
self._raise_closed()
self._accessor.rename(self, target)
|
[
"def",
"rename",
"(",
"self",
",",
"target",
")",
":",
"if",
"self",
".",
"_closed",
":",
"self",
".",
"_raise_closed",
"(",
")",
"self",
".",
"_accessor",
".",
"rename",
"(",
"self",
",",
"target",
")"
] |
Rename this path to the given path.
|
[
"Rename",
"this",
"path",
"to",
"the",
"given",
"path",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1512-L1518
|
train
|
pypa/pipenv
|
pipenv/vendor/pathlib2/__init__.py
|
Path.replace
|
def replace(self, target):
"""
Rename this path to the given path, clobbering the existing
destination if it exists.
"""
if sys.version_info < (3, 3):
raise NotImplementedError("replace() is only available "
"with Python 3.3 and later")
if self._closed:
self._raise_closed()
self._accessor.replace(self, target)
|
python
|
def replace(self, target):
"""
Rename this path to the given path, clobbering the existing
destination if it exists.
"""
if sys.version_info < (3, 3):
raise NotImplementedError("replace() is only available "
"with Python 3.3 and later")
if self._closed:
self._raise_closed()
self._accessor.replace(self, target)
|
[
"def",
"replace",
"(",
"self",
",",
"target",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"3",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"replace() is only available \"",
"\"with Python 3.3 and later\"",
")",
"if",
"self",
".",
"_closed",
":",
"self",
".",
"_raise_closed",
"(",
")",
"self",
".",
"_accessor",
".",
"replace",
"(",
"self",
",",
"target",
")"
] |
Rename this path to the given path, clobbering the existing
destination if it exists.
|
[
"Rename",
"this",
"path",
"to",
"the",
"given",
"path",
"clobbering",
"the",
"existing",
"destination",
"if",
"it",
"exists",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1520-L1530
|
train
|
pypa/pipenv
|
pipenv/vendor/pathlib2/__init__.py
|
Path.symlink_to
|
def symlink_to(self, target, target_is_directory=False):
"""
Make this path a symlink pointing to the given path.
Note the order of arguments (self, target) is the reverse of
os.symlink's.
"""
if self._closed:
self._raise_closed()
self._accessor.symlink(target, self, target_is_directory)
|
python
|
def symlink_to(self, target, target_is_directory=False):
"""
Make this path a symlink pointing to the given path.
Note the order of arguments (self, target) is the reverse of
os.symlink's.
"""
if self._closed:
self._raise_closed()
self._accessor.symlink(target, self, target_is_directory)
|
[
"def",
"symlink_to",
"(",
"self",
",",
"target",
",",
"target_is_directory",
"=",
"False",
")",
":",
"if",
"self",
".",
"_closed",
":",
"self",
".",
"_raise_closed",
"(",
")",
"self",
".",
"_accessor",
".",
"symlink",
"(",
"target",
",",
"self",
",",
"target_is_directory",
")"
] |
Make this path a symlink pointing to the given path.
Note the order of arguments (self, target) is the reverse of
os.symlink's.
|
[
"Make",
"this",
"path",
"a",
"symlink",
"pointing",
"to",
"the",
"given",
"path",
".",
"Note",
"the",
"order",
"of",
"arguments",
"(",
"self",
"target",
")",
"is",
"the",
"reverse",
"of",
"os",
".",
"symlink",
"s",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1532-L1540
|
train
|
pypa/pipenv
|
pipenv/vendor/pathlib2/__init__.py
|
Path.exists
|
def exists(self):
"""
Whether this path exists.
"""
try:
self.stat()
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
return False
return True
|
python
|
def exists(self):
"""
Whether this path exists.
"""
try:
self.stat()
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
return False
return True
|
[
"def",
"exists",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"stat",
"(",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"not",
"in",
"(",
"ENOENT",
",",
"ENOTDIR",
")",
":",
"raise",
"return",
"False",
"return",
"True"
] |
Whether this path exists.
|
[
"Whether",
"this",
"path",
"exists",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1544-L1554
|
train
|
pypa/pipenv
|
pipenv/vendor/pathlib2/__init__.py
|
Path.is_dir
|
def is_dir(self):
"""
Whether this path is a directory.
"""
try:
return S_ISDIR(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False
|
python
|
def is_dir(self):
"""
Whether this path is a directory.
"""
try:
return S_ISDIR(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False
|
[
"def",
"is_dir",
"(",
"self",
")",
":",
"try",
":",
"return",
"S_ISDIR",
"(",
"self",
".",
"stat",
"(",
")",
".",
"st_mode",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"not",
"in",
"(",
"ENOENT",
",",
"ENOTDIR",
")",
":",
"raise",
"# Path doesn't exist or is a broken symlink",
"# (see https://bitbucket.org/pitrou/pathlib/issue/12/)",
"return",
"False"
] |
Whether this path is a directory.
|
[
"Whether",
"this",
"path",
"is",
"a",
"directory",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1556-L1567
|
train
|
pypa/pipenv
|
pipenv/vendor/pathlib2/__init__.py
|
Path.is_file
|
def is_file(self):
"""
Whether this path is a regular file (also True for symlinks pointing
to regular files).
"""
try:
return S_ISREG(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False
|
python
|
def is_file(self):
"""
Whether this path is a regular file (also True for symlinks pointing
to regular files).
"""
try:
return S_ISREG(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False
|
[
"def",
"is_file",
"(",
"self",
")",
":",
"try",
":",
"return",
"S_ISREG",
"(",
"self",
".",
"stat",
"(",
")",
".",
"st_mode",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"not",
"in",
"(",
"ENOENT",
",",
"ENOTDIR",
")",
":",
"raise",
"# Path doesn't exist or is a broken symlink",
"# (see https://bitbucket.org/pitrou/pathlib/issue/12/)",
"return",
"False"
] |
Whether this path is a regular file (also True for symlinks pointing
to regular files).
|
[
"Whether",
"this",
"path",
"is",
"a",
"regular",
"file",
"(",
"also",
"True",
"for",
"symlinks",
"pointing",
"to",
"regular",
"files",
")",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1569-L1581
|
train
|
pypa/pipenv
|
pipenv/vendor/pathlib2/__init__.py
|
Path.is_fifo
|
def is_fifo(self):
"""
Whether this path is a FIFO.
"""
try:
return S_ISFIFO(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False
|
python
|
def is_fifo(self):
"""
Whether this path is a FIFO.
"""
try:
return S_ISFIFO(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False
|
[
"def",
"is_fifo",
"(",
"self",
")",
":",
"try",
":",
"return",
"S_ISFIFO",
"(",
"self",
".",
"stat",
"(",
")",
".",
"st_mode",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"not",
"in",
"(",
"ENOENT",
",",
"ENOTDIR",
")",
":",
"raise",
"# Path doesn't exist or is a broken symlink",
"# (see https://bitbucket.org/pitrou/pathlib/issue/12/)",
"return",
"False"
] |
Whether this path is a FIFO.
|
[
"Whether",
"this",
"path",
"is",
"a",
"FIFO",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1621-L1632
|
train
|
pypa/pipenv
|
pipenv/vendor/pathlib2/__init__.py
|
Path.is_socket
|
def is_socket(self):
"""
Whether this path is a socket.
"""
try:
return S_ISSOCK(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False
|
python
|
def is_socket(self):
"""
Whether this path is a socket.
"""
try:
return S_ISSOCK(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False
|
[
"def",
"is_socket",
"(",
"self",
")",
":",
"try",
":",
"return",
"S_ISSOCK",
"(",
"self",
".",
"stat",
"(",
")",
".",
"st_mode",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"not",
"in",
"(",
"ENOENT",
",",
"ENOTDIR",
")",
":",
"raise",
"# Path doesn't exist or is a broken symlink",
"# (see https://bitbucket.org/pitrou/pathlib/issue/12/)",
"return",
"False"
] |
Whether this path is a socket.
|
[
"Whether",
"this",
"path",
"is",
"a",
"socket",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1634-L1645
|
train
|
pypa/pipenv
|
pipenv/vendor/pathlib2/__init__.py
|
Path.expanduser
|
def expanduser(self):
""" Return a new path with expanded ~ and ~user constructs
(as returned by os.path.expanduser)
"""
if (not (self._drv or self._root)
and self._parts and self._parts[0][:1] == '~'):
homedir = self._flavour.gethomedir(self._parts[0][1:])
return self._from_parts([homedir] + self._parts[1:])
return self
|
python
|
def expanduser(self):
""" Return a new path with expanded ~ and ~user constructs
(as returned by os.path.expanduser)
"""
if (not (self._drv or self._root)
and self._parts and self._parts[0][:1] == '~'):
homedir = self._flavour.gethomedir(self._parts[0][1:])
return self._from_parts([homedir] + self._parts[1:])
return self
|
[
"def",
"expanduser",
"(",
"self",
")",
":",
"if",
"(",
"not",
"(",
"self",
".",
"_drv",
"or",
"self",
".",
"_root",
")",
"and",
"self",
".",
"_parts",
"and",
"self",
".",
"_parts",
"[",
"0",
"]",
"[",
":",
"1",
"]",
"==",
"'~'",
")",
":",
"homedir",
"=",
"self",
".",
"_flavour",
".",
"gethomedir",
"(",
"self",
".",
"_parts",
"[",
"0",
"]",
"[",
"1",
":",
"]",
")",
"return",
"self",
".",
"_from_parts",
"(",
"[",
"homedir",
"]",
"+",
"self",
".",
"_parts",
"[",
"1",
":",
"]",
")",
"return",
"self"
] |
Return a new path with expanded ~ and ~user constructs
(as returned by os.path.expanduser)
|
[
"Return",
"a",
"new",
"path",
"with",
"expanded",
"~",
"and",
"~user",
"constructs",
"(",
"as",
"returned",
"by",
"os",
".",
"path",
".",
"expanduser",
")"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1647-L1656
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/html5lib/_inputstream.py
|
lookupEncoding
|
def lookupEncoding(encoding):
"""Return the python codec name corresponding to an encoding or None if the
string doesn't correspond to a valid encoding."""
if isinstance(encoding, binary_type):
try:
encoding = encoding.decode("ascii")
except UnicodeDecodeError:
return None
if encoding is not None:
try:
return webencodings.lookup(encoding)
except AttributeError:
return None
else:
return None
|
python
|
def lookupEncoding(encoding):
"""Return the python codec name corresponding to an encoding or None if the
string doesn't correspond to a valid encoding."""
if isinstance(encoding, binary_type):
try:
encoding = encoding.decode("ascii")
except UnicodeDecodeError:
return None
if encoding is not None:
try:
return webencodings.lookup(encoding)
except AttributeError:
return None
else:
return None
|
[
"def",
"lookupEncoding",
"(",
"encoding",
")",
":",
"if",
"isinstance",
"(",
"encoding",
",",
"binary_type",
")",
":",
"try",
":",
"encoding",
"=",
"encoding",
".",
"decode",
"(",
"\"ascii\"",
")",
"except",
"UnicodeDecodeError",
":",
"return",
"None",
"if",
"encoding",
"is",
"not",
"None",
":",
"try",
":",
"return",
"webencodings",
".",
"lookup",
"(",
"encoding",
")",
"except",
"AttributeError",
":",
"return",
"None",
"else",
":",
"return",
"None"
] |
Return the python codec name corresponding to an encoding or None if the
string doesn't correspond to a valid encoding.
|
[
"Return",
"the",
"python",
"codec",
"name",
"corresponding",
"to",
"an",
"encoding",
"or",
"None",
"if",
"the",
"string",
"doesn",
"t",
"correspond",
"to",
"a",
"valid",
"encoding",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L908-L923
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/html5lib/_inputstream.py
|
HTMLUnicodeInputStream.openStream
|
def openStream(self, source):
"""Produces a file object from source.
source can be either a file object, local filename or a string.
"""
# Already a file object
if hasattr(source, 'read'):
stream = source
else:
stream = StringIO(source)
return stream
|
python
|
def openStream(self, source):
"""Produces a file object from source.
source can be either a file object, local filename or a string.
"""
# Already a file object
if hasattr(source, 'read'):
stream = source
else:
stream = StringIO(source)
return stream
|
[
"def",
"openStream",
"(",
"self",
",",
"source",
")",
":",
"# Already a file object",
"if",
"hasattr",
"(",
"source",
",",
"'read'",
")",
":",
"stream",
"=",
"source",
"else",
":",
"stream",
"=",
"StringIO",
"(",
"source",
")",
"return",
"stream"
] |
Produces a file object from source.
source can be either a file object, local filename or a string.
|
[
"Produces",
"a",
"file",
"object",
"from",
"source",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L210-L222
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/html5lib/_inputstream.py
|
HTMLUnicodeInputStream.position
|
def position(self):
"""Returns (line, col) of the current position in the stream."""
line, col = self._position(self.chunkOffset)
return (line + 1, col)
|
python
|
def position(self):
"""Returns (line, col) of the current position in the stream."""
line, col = self._position(self.chunkOffset)
return (line + 1, col)
|
[
"def",
"position",
"(",
"self",
")",
":",
"line",
",",
"col",
"=",
"self",
".",
"_position",
"(",
"self",
".",
"chunkOffset",
")",
"return",
"(",
"line",
"+",
"1",
",",
"col",
")"
] |
Returns (line, col) of the current position in the stream.
|
[
"Returns",
"(",
"line",
"col",
")",
"of",
"the",
"current",
"position",
"in",
"the",
"stream",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L235-L238
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/html5lib/_inputstream.py
|
HTMLUnicodeInputStream.char
|
def char(self):
""" Read one character from the stream or queue if available. Return
EOF when EOF is reached.
"""
# Read a new chunk from the input stream if necessary
if self.chunkOffset >= self.chunkSize:
if not self.readChunk():
return EOF
chunkOffset = self.chunkOffset
char = self.chunk[chunkOffset]
self.chunkOffset = chunkOffset + 1
return char
|
python
|
def char(self):
""" Read one character from the stream or queue if available. Return
EOF when EOF is reached.
"""
# Read a new chunk from the input stream if necessary
if self.chunkOffset >= self.chunkSize:
if not self.readChunk():
return EOF
chunkOffset = self.chunkOffset
char = self.chunk[chunkOffset]
self.chunkOffset = chunkOffset + 1
return char
|
[
"def",
"char",
"(",
"self",
")",
":",
"# Read a new chunk from the input stream if necessary",
"if",
"self",
".",
"chunkOffset",
">=",
"self",
".",
"chunkSize",
":",
"if",
"not",
"self",
".",
"readChunk",
"(",
")",
":",
"return",
"EOF",
"chunkOffset",
"=",
"self",
".",
"chunkOffset",
"char",
"=",
"self",
".",
"chunk",
"[",
"chunkOffset",
"]",
"self",
".",
"chunkOffset",
"=",
"chunkOffset",
"+",
"1",
"return",
"char"
] |
Read one character from the stream or queue if available. Return
EOF when EOF is reached.
|
[
"Read",
"one",
"character",
"from",
"the",
"stream",
"or",
"queue",
"if",
"available",
".",
"Return",
"EOF",
"when",
"EOF",
"is",
"reached",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L240-L253
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/html5lib/_inputstream.py
|
HTMLUnicodeInputStream.charsUntil
|
def charsUntil(self, characters, opposite=False):
""" Returns a string of characters from the stream up to but not
including any character in 'characters' or EOF. 'characters' must be
a container that supports the 'in' method and iteration over its
characters.
"""
# Use a cache of regexps to find the required characters
try:
chars = charsUntilRegEx[(characters, opposite)]
except KeyError:
if __debug__:
for c in characters:
assert(ord(c) < 128)
regex = "".join(["\\x%02x" % ord(c) for c in characters])
if not opposite:
regex = "^%s" % regex
chars = charsUntilRegEx[(characters, opposite)] = re.compile("[%s]+" % regex)
rv = []
while True:
# Find the longest matching prefix
m = chars.match(self.chunk, self.chunkOffset)
if m is None:
# If nothing matched, and it wasn't because we ran out of chunk,
# then stop
if self.chunkOffset != self.chunkSize:
break
else:
end = m.end()
# If not the whole chunk matched, return everything
# up to the part that didn't match
if end != self.chunkSize:
rv.append(self.chunk[self.chunkOffset:end])
self.chunkOffset = end
break
# If the whole remainder of the chunk matched,
# use it all and read the next chunk
rv.append(self.chunk[self.chunkOffset:])
if not self.readChunk():
# Reached EOF
break
r = "".join(rv)
return r
|
python
|
def charsUntil(self, characters, opposite=False):
""" Returns a string of characters from the stream up to but not
including any character in 'characters' or EOF. 'characters' must be
a container that supports the 'in' method and iteration over its
characters.
"""
# Use a cache of regexps to find the required characters
try:
chars = charsUntilRegEx[(characters, opposite)]
except KeyError:
if __debug__:
for c in characters:
assert(ord(c) < 128)
regex = "".join(["\\x%02x" % ord(c) for c in characters])
if not opposite:
regex = "^%s" % regex
chars = charsUntilRegEx[(characters, opposite)] = re.compile("[%s]+" % regex)
rv = []
while True:
# Find the longest matching prefix
m = chars.match(self.chunk, self.chunkOffset)
if m is None:
# If nothing matched, and it wasn't because we ran out of chunk,
# then stop
if self.chunkOffset != self.chunkSize:
break
else:
end = m.end()
# If not the whole chunk matched, return everything
# up to the part that didn't match
if end != self.chunkSize:
rv.append(self.chunk[self.chunkOffset:end])
self.chunkOffset = end
break
# If the whole remainder of the chunk matched,
# use it all and read the next chunk
rv.append(self.chunk[self.chunkOffset:])
if not self.readChunk():
# Reached EOF
break
r = "".join(rv)
return r
|
[
"def",
"charsUntil",
"(",
"self",
",",
"characters",
",",
"opposite",
"=",
"False",
")",
":",
"# Use a cache of regexps to find the required characters",
"try",
":",
"chars",
"=",
"charsUntilRegEx",
"[",
"(",
"characters",
",",
"opposite",
")",
"]",
"except",
"KeyError",
":",
"if",
"__debug__",
":",
"for",
"c",
"in",
"characters",
":",
"assert",
"(",
"ord",
"(",
"c",
")",
"<",
"128",
")",
"regex",
"=",
"\"\"",
".",
"join",
"(",
"[",
"\"\\\\x%02x\"",
"%",
"ord",
"(",
"c",
")",
"for",
"c",
"in",
"characters",
"]",
")",
"if",
"not",
"opposite",
":",
"regex",
"=",
"\"^%s\"",
"%",
"regex",
"chars",
"=",
"charsUntilRegEx",
"[",
"(",
"characters",
",",
"opposite",
")",
"]",
"=",
"re",
".",
"compile",
"(",
"\"[%s]+\"",
"%",
"regex",
")",
"rv",
"=",
"[",
"]",
"while",
"True",
":",
"# Find the longest matching prefix",
"m",
"=",
"chars",
".",
"match",
"(",
"self",
".",
"chunk",
",",
"self",
".",
"chunkOffset",
")",
"if",
"m",
"is",
"None",
":",
"# If nothing matched, and it wasn't because we ran out of chunk,",
"# then stop",
"if",
"self",
".",
"chunkOffset",
"!=",
"self",
".",
"chunkSize",
":",
"break",
"else",
":",
"end",
"=",
"m",
".",
"end",
"(",
")",
"# If not the whole chunk matched, return everything",
"# up to the part that didn't match",
"if",
"end",
"!=",
"self",
".",
"chunkSize",
":",
"rv",
".",
"append",
"(",
"self",
".",
"chunk",
"[",
"self",
".",
"chunkOffset",
":",
"end",
"]",
")",
"self",
".",
"chunkOffset",
"=",
"end",
"break",
"# If the whole remainder of the chunk matched,",
"# use it all and read the next chunk",
"rv",
".",
"append",
"(",
"self",
".",
"chunk",
"[",
"self",
".",
"chunkOffset",
":",
"]",
")",
"if",
"not",
"self",
".",
"readChunk",
"(",
")",
":",
"# Reached EOF",
"break",
"r",
"=",
"\"\"",
".",
"join",
"(",
"rv",
")",
"return",
"r"
] |
Returns a string of characters from the stream up to but not
including any character in 'characters' or EOF. 'characters' must be
a container that supports the 'in' method and iteration over its
characters.
|
[
"Returns",
"a",
"string",
"of",
"characters",
"from",
"the",
"stream",
"up",
"to",
"but",
"not",
"including",
"any",
"character",
"in",
"characters",
"or",
"EOF",
".",
"characters",
"must",
"be",
"a",
"container",
"that",
"supports",
"the",
"in",
"method",
"and",
"iteration",
"over",
"its",
"characters",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L320-L365
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/html5lib/_inputstream.py
|
HTMLBinaryInputStream.openStream
|
def openStream(self, source):
"""Produces a file object from source.
source can be either a file object, local filename or a string.
"""
# Already a file object
if hasattr(source, 'read'):
stream = source
else:
stream = BytesIO(source)
try:
stream.seek(stream.tell())
except: # pylint:disable=bare-except
stream = BufferedStream(stream)
return stream
|
python
|
def openStream(self, source):
"""Produces a file object from source.
source can be either a file object, local filename or a string.
"""
# Already a file object
if hasattr(source, 'read'):
stream = source
else:
stream = BytesIO(source)
try:
stream.seek(stream.tell())
except: # pylint:disable=bare-except
stream = BufferedStream(stream)
return stream
|
[
"def",
"openStream",
"(",
"self",
",",
"source",
")",
":",
"# Already a file object",
"if",
"hasattr",
"(",
"source",
",",
"'read'",
")",
":",
"stream",
"=",
"source",
"else",
":",
"stream",
"=",
"BytesIO",
"(",
"source",
")",
"try",
":",
"stream",
".",
"seek",
"(",
"stream",
".",
"tell",
"(",
")",
")",
"except",
":",
"# pylint:disable=bare-except",
"stream",
"=",
"BufferedStream",
"(",
"stream",
")",
"return",
"stream"
] |
Produces a file object from source.
source can be either a file object, local filename or a string.
|
[
"Produces",
"a",
"file",
"object",
"from",
"source",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L438-L455
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/html5lib/_inputstream.py
|
HTMLBinaryInputStream.detectEncodingMeta
|
def detectEncodingMeta(self):
"""Report the encoding declared by the meta element
"""
buffer = self.rawStream.read(self.numBytesMeta)
assert isinstance(buffer, bytes)
parser = EncodingParser(buffer)
self.rawStream.seek(0)
encoding = parser.getEncoding()
if encoding is not None and encoding.name in ("utf-16be", "utf-16le"):
encoding = lookupEncoding("utf-8")
return encoding
|
python
|
def detectEncodingMeta(self):
"""Report the encoding declared by the meta element
"""
buffer = self.rawStream.read(self.numBytesMeta)
assert isinstance(buffer, bytes)
parser = EncodingParser(buffer)
self.rawStream.seek(0)
encoding = parser.getEncoding()
if encoding is not None and encoding.name in ("utf-16be", "utf-16le"):
encoding = lookupEncoding("utf-8")
return encoding
|
[
"def",
"detectEncodingMeta",
"(",
"self",
")",
":",
"buffer",
"=",
"self",
".",
"rawStream",
".",
"read",
"(",
"self",
".",
"numBytesMeta",
")",
"assert",
"isinstance",
"(",
"buffer",
",",
"bytes",
")",
"parser",
"=",
"EncodingParser",
"(",
"buffer",
")",
"self",
".",
"rawStream",
".",
"seek",
"(",
"0",
")",
"encoding",
"=",
"parser",
".",
"getEncoding",
"(",
")",
"if",
"encoding",
"is",
"not",
"None",
"and",
"encoding",
".",
"name",
"in",
"(",
"\"utf-16be\"",
",",
"\"utf-16le\"",
")",
":",
"encoding",
"=",
"lookupEncoding",
"(",
"\"utf-8\"",
")",
"return",
"encoding"
] |
Report the encoding declared by the meta element
|
[
"Report",
"the",
"encoding",
"declared",
"by",
"the",
"meta",
"element"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L569-L581
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/html5lib/_inputstream.py
|
EncodingBytes.skip
|
def skip(self, chars=spaceCharactersBytes):
"""Skip past a list of characters"""
p = self.position # use property for the error-checking
while p < len(self):
c = self[p:p + 1]
if c not in chars:
self._position = p
return c
p += 1
self._position = p
return None
|
python
|
def skip(self, chars=spaceCharactersBytes):
"""Skip past a list of characters"""
p = self.position # use property for the error-checking
while p < len(self):
c = self[p:p + 1]
if c not in chars:
self._position = p
return c
p += 1
self._position = p
return None
|
[
"def",
"skip",
"(",
"self",
",",
"chars",
"=",
"spaceCharactersBytes",
")",
":",
"p",
"=",
"self",
".",
"position",
"# use property for the error-checking",
"while",
"p",
"<",
"len",
"(",
"self",
")",
":",
"c",
"=",
"self",
"[",
"p",
":",
"p",
"+",
"1",
"]",
"if",
"c",
"not",
"in",
"chars",
":",
"self",
".",
"_position",
"=",
"p",
"return",
"c",
"p",
"+=",
"1",
"self",
".",
"_position",
"=",
"p",
"return",
"None"
] |
Skip past a list of characters
|
[
"Skip",
"past",
"a",
"list",
"of",
"characters"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L640-L650
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/html5lib/_inputstream.py
|
EncodingBytes.matchBytes
|
def matchBytes(self, bytes):
"""Look for a sequence of bytes at the start of a string. If the bytes
are found return True and advance the position to the byte after the
match. Otherwise return False and leave the position alone"""
p = self.position
data = self[p:p + len(bytes)]
rv = data.startswith(bytes)
if rv:
self.position += len(bytes)
return rv
|
python
|
def matchBytes(self, bytes):
"""Look for a sequence of bytes at the start of a string. If the bytes
are found return True and advance the position to the byte after the
match. Otherwise return False and leave the position alone"""
p = self.position
data = self[p:p + len(bytes)]
rv = data.startswith(bytes)
if rv:
self.position += len(bytes)
return rv
|
[
"def",
"matchBytes",
"(",
"self",
",",
"bytes",
")",
":",
"p",
"=",
"self",
".",
"position",
"data",
"=",
"self",
"[",
"p",
":",
"p",
"+",
"len",
"(",
"bytes",
")",
"]",
"rv",
"=",
"data",
".",
"startswith",
"(",
"bytes",
")",
"if",
"rv",
":",
"self",
".",
"position",
"+=",
"len",
"(",
"bytes",
")",
"return",
"rv"
] |
Look for a sequence of bytes at the start of a string. If the bytes
are found return True and advance the position to the byte after the
match. Otherwise return False and leave the position alone
|
[
"Look",
"for",
"a",
"sequence",
"of",
"bytes",
"at",
"the",
"start",
"of",
"a",
"string",
".",
"If",
"the",
"bytes",
"are",
"found",
"return",
"True",
"and",
"advance",
"the",
"position",
"to",
"the",
"byte",
"after",
"the",
"match",
".",
"Otherwise",
"return",
"False",
"and",
"leave",
"the",
"position",
"alone"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L663-L672
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/html5lib/_inputstream.py
|
EncodingBytes.jumpTo
|
def jumpTo(self, bytes):
"""Look for the next sequence of bytes matching a given sequence. If
a match is found advance the position to the last byte of the match"""
newPosition = self[self.position:].find(bytes)
if newPosition > -1:
# XXX: This is ugly, but I can't see a nicer way to fix this.
if self._position == -1:
self._position = 0
self._position += (newPosition + len(bytes) - 1)
return True
else:
raise StopIteration
|
python
|
def jumpTo(self, bytes):
"""Look for the next sequence of bytes matching a given sequence. If
a match is found advance the position to the last byte of the match"""
newPosition = self[self.position:].find(bytes)
if newPosition > -1:
# XXX: This is ugly, but I can't see a nicer way to fix this.
if self._position == -1:
self._position = 0
self._position += (newPosition + len(bytes) - 1)
return True
else:
raise StopIteration
|
[
"def",
"jumpTo",
"(",
"self",
",",
"bytes",
")",
":",
"newPosition",
"=",
"self",
"[",
"self",
".",
"position",
":",
"]",
".",
"find",
"(",
"bytes",
")",
"if",
"newPosition",
">",
"-",
"1",
":",
"# XXX: This is ugly, but I can't see a nicer way to fix this.",
"if",
"self",
".",
"_position",
"==",
"-",
"1",
":",
"self",
".",
"_position",
"=",
"0",
"self",
".",
"_position",
"+=",
"(",
"newPosition",
"+",
"len",
"(",
"bytes",
")",
"-",
"1",
")",
"return",
"True",
"else",
":",
"raise",
"StopIteration"
] |
Look for the next sequence of bytes matching a given sequence. If
a match is found advance the position to the last byte of the match
|
[
"Look",
"for",
"the",
"next",
"sequence",
"of",
"bytes",
"matching",
"a",
"given",
"sequence",
".",
"If",
"a",
"match",
"is",
"found",
"advance",
"the",
"position",
"to",
"the",
"last",
"byte",
"of",
"the",
"match"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L674-L685
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/html5lib/_inputstream.py
|
EncodingParser.getAttribute
|
def getAttribute(self):
"""Return a name,value pair for the next attribute in the stream,
if one is found, or None"""
data = self.data
# Step 1 (skip chars)
c = data.skip(spaceCharactersBytes | frozenset([b"/"]))
assert c is None or len(c) == 1
# Step 2
if c in (b">", None):
return None
# Step 3
attrName = []
attrValue = []
# Step 4 attribute name
while True:
if c == b"=" and attrName:
break
elif c in spaceCharactersBytes:
# Step 6!
c = data.skip()
break
elif c in (b"/", b">"):
return b"".join(attrName), b""
elif c in asciiUppercaseBytes:
attrName.append(c.lower())
elif c is None:
return None
else:
attrName.append(c)
# Step 5
c = next(data)
# Step 7
if c != b"=":
data.previous()
return b"".join(attrName), b""
# Step 8
next(data)
# Step 9
c = data.skip()
# Step 10
if c in (b"'", b'"'):
# 10.1
quoteChar = c
while True:
# 10.2
c = next(data)
# 10.3
if c == quoteChar:
next(data)
return b"".join(attrName), b"".join(attrValue)
# 10.4
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
# 10.5
else:
attrValue.append(c)
elif c == b">":
return b"".join(attrName), b""
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
elif c is None:
return None
else:
attrValue.append(c)
# Step 11
while True:
c = next(data)
if c in spacesAngleBrackets:
return b"".join(attrName), b"".join(attrValue)
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
elif c is None:
return None
else:
attrValue.append(c)
|
python
|
def getAttribute(self):
"""Return a name,value pair for the next attribute in the stream,
if one is found, or None"""
data = self.data
# Step 1 (skip chars)
c = data.skip(spaceCharactersBytes | frozenset([b"/"]))
assert c is None or len(c) == 1
# Step 2
if c in (b">", None):
return None
# Step 3
attrName = []
attrValue = []
# Step 4 attribute name
while True:
if c == b"=" and attrName:
break
elif c in spaceCharactersBytes:
# Step 6!
c = data.skip()
break
elif c in (b"/", b">"):
return b"".join(attrName), b""
elif c in asciiUppercaseBytes:
attrName.append(c.lower())
elif c is None:
return None
else:
attrName.append(c)
# Step 5
c = next(data)
# Step 7
if c != b"=":
data.previous()
return b"".join(attrName), b""
# Step 8
next(data)
# Step 9
c = data.skip()
# Step 10
if c in (b"'", b'"'):
# 10.1
quoteChar = c
while True:
# 10.2
c = next(data)
# 10.3
if c == quoteChar:
next(data)
return b"".join(attrName), b"".join(attrValue)
# 10.4
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
# 10.5
else:
attrValue.append(c)
elif c == b">":
return b"".join(attrName), b""
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
elif c is None:
return None
else:
attrValue.append(c)
# Step 11
while True:
c = next(data)
if c in spacesAngleBrackets:
return b"".join(attrName), b"".join(attrValue)
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
elif c is None:
return None
else:
attrValue.append(c)
|
[
"def",
"getAttribute",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"data",
"# Step 1 (skip chars)",
"c",
"=",
"data",
".",
"skip",
"(",
"spaceCharactersBytes",
"|",
"frozenset",
"(",
"[",
"b\"/\"",
"]",
")",
")",
"assert",
"c",
"is",
"None",
"or",
"len",
"(",
"c",
")",
"==",
"1",
"# Step 2",
"if",
"c",
"in",
"(",
"b\">\"",
",",
"None",
")",
":",
"return",
"None",
"# Step 3",
"attrName",
"=",
"[",
"]",
"attrValue",
"=",
"[",
"]",
"# Step 4 attribute name",
"while",
"True",
":",
"if",
"c",
"==",
"b\"=\"",
"and",
"attrName",
":",
"break",
"elif",
"c",
"in",
"spaceCharactersBytes",
":",
"# Step 6!",
"c",
"=",
"data",
".",
"skip",
"(",
")",
"break",
"elif",
"c",
"in",
"(",
"b\"/\"",
",",
"b\">\"",
")",
":",
"return",
"b\"\"",
".",
"join",
"(",
"attrName",
")",
",",
"b\"\"",
"elif",
"c",
"in",
"asciiUppercaseBytes",
":",
"attrName",
".",
"append",
"(",
"c",
".",
"lower",
"(",
")",
")",
"elif",
"c",
"is",
"None",
":",
"return",
"None",
"else",
":",
"attrName",
".",
"append",
"(",
"c",
")",
"# Step 5",
"c",
"=",
"next",
"(",
"data",
")",
"# Step 7",
"if",
"c",
"!=",
"b\"=\"",
":",
"data",
".",
"previous",
"(",
")",
"return",
"b\"\"",
".",
"join",
"(",
"attrName",
")",
",",
"b\"\"",
"# Step 8",
"next",
"(",
"data",
")",
"# Step 9",
"c",
"=",
"data",
".",
"skip",
"(",
")",
"# Step 10",
"if",
"c",
"in",
"(",
"b\"'\"",
",",
"b'\"'",
")",
":",
"# 10.1",
"quoteChar",
"=",
"c",
"while",
"True",
":",
"# 10.2",
"c",
"=",
"next",
"(",
"data",
")",
"# 10.3",
"if",
"c",
"==",
"quoteChar",
":",
"next",
"(",
"data",
")",
"return",
"b\"\"",
".",
"join",
"(",
"attrName",
")",
",",
"b\"\"",
".",
"join",
"(",
"attrValue",
")",
"# 10.4",
"elif",
"c",
"in",
"asciiUppercaseBytes",
":",
"attrValue",
".",
"append",
"(",
"c",
".",
"lower",
"(",
")",
")",
"# 10.5",
"else",
":",
"attrValue",
".",
"append",
"(",
"c",
")",
"elif",
"c",
"==",
"b\">\"",
":",
"return",
"b\"\"",
".",
"join",
"(",
"attrName",
")",
",",
"b\"\"",
"elif",
"c",
"in",
"asciiUppercaseBytes",
":",
"attrValue",
".",
"append",
"(",
"c",
".",
"lower",
"(",
")",
")",
"elif",
"c",
"is",
"None",
":",
"return",
"None",
"else",
":",
"attrValue",
".",
"append",
"(",
"c",
")",
"# Step 11",
"while",
"True",
":",
"c",
"=",
"next",
"(",
"data",
")",
"if",
"c",
"in",
"spacesAngleBrackets",
":",
"return",
"b\"\"",
".",
"join",
"(",
"attrName",
")",
",",
"b\"\"",
".",
"join",
"(",
"attrValue",
")",
"elif",
"c",
"in",
"asciiUppercaseBytes",
":",
"attrValue",
".",
"append",
"(",
"c",
".",
"lower",
"(",
")",
")",
"elif",
"c",
"is",
"None",
":",
"return",
"None",
"else",
":",
"attrValue",
".",
"append",
"(",
"c",
")"
] |
Return a name,value pair for the next attribute in the stream,
if one is found, or None
|
[
"Return",
"a",
"name",
"value",
"pair",
"for",
"the",
"next",
"attribute",
"in",
"the",
"stream",
"if",
"one",
"is",
"found",
"or",
"None"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L792-L866
|
train
|
pypa/pipenv
|
pipenv/vendor/pep517/_in_process.py
|
_build_backend
|
def _build_backend():
"""Find and load the build backend"""
ep = os.environ['PEP517_BUILD_BACKEND']
mod_path, _, obj_path = ep.partition(':')
try:
obj = import_module(mod_path)
except ImportError:
raise BackendUnavailable
if obj_path:
for path_part in obj_path.split('.'):
obj = getattr(obj, path_part)
return obj
|
python
|
def _build_backend():
"""Find and load the build backend"""
ep = os.environ['PEP517_BUILD_BACKEND']
mod_path, _, obj_path = ep.partition(':')
try:
obj = import_module(mod_path)
except ImportError:
raise BackendUnavailable
if obj_path:
for path_part in obj_path.split('.'):
obj = getattr(obj, path_part)
return obj
|
[
"def",
"_build_backend",
"(",
")",
":",
"ep",
"=",
"os",
".",
"environ",
"[",
"'PEP517_BUILD_BACKEND'",
"]",
"mod_path",
",",
"_",
",",
"obj_path",
"=",
"ep",
".",
"partition",
"(",
"':'",
")",
"try",
":",
"obj",
"=",
"import_module",
"(",
"mod_path",
")",
"except",
"ImportError",
":",
"raise",
"BackendUnavailable",
"if",
"obj_path",
":",
"for",
"path_part",
"in",
"obj_path",
".",
"split",
"(",
"'.'",
")",
":",
"obj",
"=",
"getattr",
"(",
"obj",
",",
"path_part",
")",
"return",
"obj"
] |
Find and load the build backend
|
[
"Find",
"and",
"load",
"the",
"build",
"backend"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/_in_process.py#L29-L40
|
train
|
pypa/pipenv
|
pipenv/vendor/pep517/_in_process.py
|
get_requires_for_build_wheel
|
def get_requires_for_build_wheel(config_settings):
"""Invoke the optional get_requires_for_build_wheel hook
Returns [] if the hook is not defined.
"""
backend = _build_backend()
try:
hook = backend.get_requires_for_build_wheel
except AttributeError:
return []
else:
return hook(config_settings)
|
python
|
def get_requires_for_build_wheel(config_settings):
"""Invoke the optional get_requires_for_build_wheel hook
Returns [] if the hook is not defined.
"""
backend = _build_backend()
try:
hook = backend.get_requires_for_build_wheel
except AttributeError:
return []
else:
return hook(config_settings)
|
[
"def",
"get_requires_for_build_wheel",
"(",
"config_settings",
")",
":",
"backend",
"=",
"_build_backend",
"(",
")",
"try",
":",
"hook",
"=",
"backend",
".",
"get_requires_for_build_wheel",
"except",
"AttributeError",
":",
"return",
"[",
"]",
"else",
":",
"return",
"hook",
"(",
"config_settings",
")"
] |
Invoke the optional get_requires_for_build_wheel hook
Returns [] if the hook is not defined.
|
[
"Invoke",
"the",
"optional",
"get_requires_for_build_wheel",
"hook"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/_in_process.py#L43-L54
|
train
|
pypa/pipenv
|
pipenv/vendor/pep517/_in_process.py
|
prepare_metadata_for_build_wheel
|
def prepare_metadata_for_build_wheel(metadata_directory, config_settings):
"""Invoke optional prepare_metadata_for_build_wheel
Implements a fallback by building a wheel if the hook isn't defined.
"""
backend = _build_backend()
try:
hook = backend.prepare_metadata_for_build_wheel
except AttributeError:
return _get_wheel_metadata_from_wheel(backend, metadata_directory,
config_settings)
else:
return hook(metadata_directory, config_settings)
|
python
|
def prepare_metadata_for_build_wheel(metadata_directory, config_settings):
"""Invoke optional prepare_metadata_for_build_wheel
Implements a fallback by building a wheel if the hook isn't defined.
"""
backend = _build_backend()
try:
hook = backend.prepare_metadata_for_build_wheel
except AttributeError:
return _get_wheel_metadata_from_wheel(backend, metadata_directory,
config_settings)
else:
return hook(metadata_directory, config_settings)
|
[
"def",
"prepare_metadata_for_build_wheel",
"(",
"metadata_directory",
",",
"config_settings",
")",
":",
"backend",
"=",
"_build_backend",
"(",
")",
"try",
":",
"hook",
"=",
"backend",
".",
"prepare_metadata_for_build_wheel",
"except",
"AttributeError",
":",
"return",
"_get_wheel_metadata_from_wheel",
"(",
"backend",
",",
"metadata_directory",
",",
"config_settings",
")",
"else",
":",
"return",
"hook",
"(",
"metadata_directory",
",",
"config_settings",
")"
] |
Invoke optional prepare_metadata_for_build_wheel
Implements a fallback by building a wheel if the hook isn't defined.
|
[
"Invoke",
"optional",
"prepare_metadata_for_build_wheel"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/_in_process.py#L57-L69
|
train
|
pypa/pipenv
|
pipenv/vendor/pep517/_in_process.py
|
_dist_info_files
|
def _dist_info_files(whl_zip):
"""Identify the .dist-info folder inside a wheel ZipFile."""
res = []
for path in whl_zip.namelist():
m = re.match(r'[^/\\]+-[^/\\]+\.dist-info/', path)
if m:
res.append(path)
if res:
return res
raise Exception("No .dist-info folder found in wheel")
|
python
|
def _dist_info_files(whl_zip):
"""Identify the .dist-info folder inside a wheel ZipFile."""
res = []
for path in whl_zip.namelist():
m = re.match(r'[^/\\]+-[^/\\]+\.dist-info/', path)
if m:
res.append(path)
if res:
return res
raise Exception("No .dist-info folder found in wheel")
|
[
"def",
"_dist_info_files",
"(",
"whl_zip",
")",
":",
"res",
"=",
"[",
"]",
"for",
"path",
"in",
"whl_zip",
".",
"namelist",
"(",
")",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r'[^/\\\\]+-[^/\\\\]+\\.dist-info/'",
",",
"path",
")",
"if",
"m",
":",
"res",
".",
"append",
"(",
"path",
")",
"if",
"res",
":",
"return",
"res",
"raise",
"Exception",
"(",
"\"No .dist-info folder found in wheel\"",
")"
] |
Identify the .dist-info folder inside a wheel ZipFile.
|
[
"Identify",
"the",
".",
"dist",
"-",
"info",
"folder",
"inside",
"a",
"wheel",
"ZipFile",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/_in_process.py#L75-L84
|
train
|
pypa/pipenv
|
pipenv/vendor/pep517/_in_process.py
|
_get_wheel_metadata_from_wheel
|
def _get_wheel_metadata_from_wheel(
backend, metadata_directory, config_settings):
"""Build a wheel and extract the metadata from it.
Fallback for when the build backend does not
define the 'get_wheel_metadata' hook.
"""
from zipfile import ZipFile
whl_basename = backend.build_wheel(metadata_directory, config_settings)
with open(os.path.join(metadata_directory, WHEEL_BUILT_MARKER), 'wb'):
pass # Touch marker file
whl_file = os.path.join(metadata_directory, whl_basename)
with ZipFile(whl_file) as zipf:
dist_info = _dist_info_files(zipf)
zipf.extractall(path=metadata_directory, members=dist_info)
return dist_info[0].split('/')[0]
|
python
|
def _get_wheel_metadata_from_wheel(
backend, metadata_directory, config_settings):
"""Build a wheel and extract the metadata from it.
Fallback for when the build backend does not
define the 'get_wheel_metadata' hook.
"""
from zipfile import ZipFile
whl_basename = backend.build_wheel(metadata_directory, config_settings)
with open(os.path.join(metadata_directory, WHEEL_BUILT_MARKER), 'wb'):
pass # Touch marker file
whl_file = os.path.join(metadata_directory, whl_basename)
with ZipFile(whl_file) as zipf:
dist_info = _dist_info_files(zipf)
zipf.extractall(path=metadata_directory, members=dist_info)
return dist_info[0].split('/')[0]
|
[
"def",
"_get_wheel_metadata_from_wheel",
"(",
"backend",
",",
"metadata_directory",
",",
"config_settings",
")",
":",
"from",
"zipfile",
"import",
"ZipFile",
"whl_basename",
"=",
"backend",
".",
"build_wheel",
"(",
"metadata_directory",
",",
"config_settings",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"metadata_directory",
",",
"WHEEL_BUILT_MARKER",
")",
",",
"'wb'",
")",
":",
"pass",
"# Touch marker file",
"whl_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"metadata_directory",
",",
"whl_basename",
")",
"with",
"ZipFile",
"(",
"whl_file",
")",
"as",
"zipf",
":",
"dist_info",
"=",
"_dist_info_files",
"(",
"zipf",
")",
"zipf",
".",
"extractall",
"(",
"path",
"=",
"metadata_directory",
",",
"members",
"=",
"dist_info",
")",
"return",
"dist_info",
"[",
"0",
"]",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]"
] |
Build a wheel and extract the metadata from it.
Fallback for when the build backend does not
define the 'get_wheel_metadata' hook.
|
[
"Build",
"a",
"wheel",
"and",
"extract",
"the",
"metadata",
"from",
"it",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/_in_process.py#L87-L103
|
train
|
pypa/pipenv
|
pipenv/vendor/pep517/_in_process.py
|
_find_already_built_wheel
|
def _find_already_built_wheel(metadata_directory):
"""Check for a wheel already built during the get_wheel_metadata hook.
"""
if not metadata_directory:
return None
metadata_parent = os.path.dirname(metadata_directory)
if not os.path.isfile(pjoin(metadata_parent, WHEEL_BUILT_MARKER)):
return None
whl_files = glob(os.path.join(metadata_parent, '*.whl'))
if not whl_files:
print('Found wheel built marker, but no .whl files')
return None
if len(whl_files) > 1:
print('Found multiple .whl files; unspecified behaviour. '
'Will call build_wheel.')
return None
# Exactly one .whl file
return whl_files[0]
|
python
|
def _find_already_built_wheel(metadata_directory):
"""Check for a wheel already built during the get_wheel_metadata hook.
"""
if not metadata_directory:
return None
metadata_parent = os.path.dirname(metadata_directory)
if not os.path.isfile(pjoin(metadata_parent, WHEEL_BUILT_MARKER)):
return None
whl_files = glob(os.path.join(metadata_parent, '*.whl'))
if not whl_files:
print('Found wheel built marker, but no .whl files')
return None
if len(whl_files) > 1:
print('Found multiple .whl files; unspecified behaviour. '
'Will call build_wheel.')
return None
# Exactly one .whl file
return whl_files[0]
|
[
"def",
"_find_already_built_wheel",
"(",
"metadata_directory",
")",
":",
"if",
"not",
"metadata_directory",
":",
"return",
"None",
"metadata_parent",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"metadata_directory",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"pjoin",
"(",
"metadata_parent",
",",
"WHEEL_BUILT_MARKER",
")",
")",
":",
"return",
"None",
"whl_files",
"=",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"metadata_parent",
",",
"'*.whl'",
")",
")",
"if",
"not",
"whl_files",
":",
"print",
"(",
"'Found wheel built marker, but no .whl files'",
")",
"return",
"None",
"if",
"len",
"(",
"whl_files",
")",
">",
"1",
":",
"print",
"(",
"'Found multiple .whl files; unspecified behaviour. '",
"'Will call build_wheel.'",
")",
"return",
"None",
"# Exactly one .whl file",
"return",
"whl_files",
"[",
"0",
"]"
] |
Check for a wheel already built during the get_wheel_metadata hook.
|
[
"Check",
"for",
"a",
"wheel",
"already",
"built",
"during",
"the",
"get_wheel_metadata",
"hook",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/_in_process.py#L106-L125
|
train
|
pypa/pipenv
|
pipenv/vendor/pep517/_in_process.py
|
build_wheel
|
def build_wheel(wheel_directory, config_settings, metadata_directory=None):
"""Invoke the mandatory build_wheel hook.
If a wheel was already built in the
prepare_metadata_for_build_wheel fallback, this
will copy it rather than rebuilding the wheel.
"""
prebuilt_whl = _find_already_built_wheel(metadata_directory)
if prebuilt_whl:
shutil.copy2(prebuilt_whl, wheel_directory)
return os.path.basename(prebuilt_whl)
return _build_backend().build_wheel(wheel_directory, config_settings,
metadata_directory)
|
python
|
def build_wheel(wheel_directory, config_settings, metadata_directory=None):
"""Invoke the mandatory build_wheel hook.
If a wheel was already built in the
prepare_metadata_for_build_wheel fallback, this
will copy it rather than rebuilding the wheel.
"""
prebuilt_whl = _find_already_built_wheel(metadata_directory)
if prebuilt_whl:
shutil.copy2(prebuilt_whl, wheel_directory)
return os.path.basename(prebuilt_whl)
return _build_backend().build_wheel(wheel_directory, config_settings,
metadata_directory)
|
[
"def",
"build_wheel",
"(",
"wheel_directory",
",",
"config_settings",
",",
"metadata_directory",
"=",
"None",
")",
":",
"prebuilt_whl",
"=",
"_find_already_built_wheel",
"(",
"metadata_directory",
")",
"if",
"prebuilt_whl",
":",
"shutil",
".",
"copy2",
"(",
"prebuilt_whl",
",",
"wheel_directory",
")",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"prebuilt_whl",
")",
"return",
"_build_backend",
"(",
")",
".",
"build_wheel",
"(",
"wheel_directory",
",",
"config_settings",
",",
"metadata_directory",
")"
] |
Invoke the mandatory build_wheel hook.
If a wheel was already built in the
prepare_metadata_for_build_wheel fallback, this
will copy it rather than rebuilding the wheel.
|
[
"Invoke",
"the",
"mandatory",
"build_wheel",
"hook",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/_in_process.py#L128-L141
|
train
|
pypa/pipenv
|
pipenv/vendor/pep517/_in_process.py
|
get_requires_for_build_sdist
|
def get_requires_for_build_sdist(config_settings):
"""Invoke the optional get_requires_for_build_wheel hook
Returns [] if the hook is not defined.
"""
backend = _build_backend()
try:
hook = backend.get_requires_for_build_sdist
except AttributeError:
return []
else:
return hook(config_settings)
|
python
|
def get_requires_for_build_sdist(config_settings):
"""Invoke the optional get_requires_for_build_wheel hook
Returns [] if the hook is not defined.
"""
backend = _build_backend()
try:
hook = backend.get_requires_for_build_sdist
except AttributeError:
return []
else:
return hook(config_settings)
|
[
"def",
"get_requires_for_build_sdist",
"(",
"config_settings",
")",
":",
"backend",
"=",
"_build_backend",
"(",
")",
"try",
":",
"hook",
"=",
"backend",
".",
"get_requires_for_build_sdist",
"except",
"AttributeError",
":",
"return",
"[",
"]",
"else",
":",
"return",
"hook",
"(",
"config_settings",
")"
] |
Invoke the optional get_requires_for_build_wheel hook
Returns [] if the hook is not defined.
|
[
"Invoke",
"the",
"optional",
"get_requires_for_build_wheel",
"hook"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/_in_process.py#L144-L155
|
train
|
pypa/pipenv
|
pipenv/vendor/tomlkit/items.py
|
Table.append
|
def append(self, key, _item): # type: (Union[Key, str], Any) -> Table
"""
Appends a (key, item) to the table.
"""
if not isinstance(_item, Item):
_item = item(_item)
self._value.append(key, _item)
if isinstance(key, Key):
key = key.key
if key is not None:
super(Table, self).__setitem__(key, _item)
m = re.match("(?s)^[^ ]*([ ]+).*$", self._trivia.indent)
if not m:
return self
indent = m.group(1)
if not isinstance(_item, Whitespace):
m = re.match("(?s)^([^ ]*)(.*)$", _item.trivia.indent)
if not m:
_item.trivia.indent = indent
else:
_item.trivia.indent = m.group(1) + indent + m.group(2)
return self
|
python
|
def append(self, key, _item): # type: (Union[Key, str], Any) -> Table
"""
Appends a (key, item) to the table.
"""
if not isinstance(_item, Item):
_item = item(_item)
self._value.append(key, _item)
if isinstance(key, Key):
key = key.key
if key is not None:
super(Table, self).__setitem__(key, _item)
m = re.match("(?s)^[^ ]*([ ]+).*$", self._trivia.indent)
if not m:
return self
indent = m.group(1)
if not isinstance(_item, Whitespace):
m = re.match("(?s)^([^ ]*)(.*)$", _item.trivia.indent)
if not m:
_item.trivia.indent = indent
else:
_item.trivia.indent = m.group(1) + indent + m.group(2)
return self
|
[
"def",
"append",
"(",
"self",
",",
"key",
",",
"_item",
")",
":",
"# type: (Union[Key, str], Any) -> Table",
"if",
"not",
"isinstance",
"(",
"_item",
",",
"Item",
")",
":",
"_item",
"=",
"item",
"(",
"_item",
")",
"self",
".",
"_value",
".",
"append",
"(",
"key",
",",
"_item",
")",
"if",
"isinstance",
"(",
"key",
",",
"Key",
")",
":",
"key",
"=",
"key",
".",
"key",
"if",
"key",
"is",
"not",
"None",
":",
"super",
"(",
"Table",
",",
"self",
")",
".",
"__setitem__",
"(",
"key",
",",
"_item",
")",
"m",
"=",
"re",
".",
"match",
"(",
"\"(?s)^[^ ]*([ ]+).*$\"",
",",
"self",
".",
"_trivia",
".",
"indent",
")",
"if",
"not",
"m",
":",
"return",
"self",
"indent",
"=",
"m",
".",
"group",
"(",
"1",
")",
"if",
"not",
"isinstance",
"(",
"_item",
",",
"Whitespace",
")",
":",
"m",
"=",
"re",
".",
"match",
"(",
"\"(?s)^([^ ]*)(.*)$\"",
",",
"_item",
".",
"trivia",
".",
"indent",
")",
"if",
"not",
"m",
":",
"_item",
".",
"trivia",
".",
"indent",
"=",
"indent",
"else",
":",
"_item",
".",
"trivia",
".",
"indent",
"=",
"m",
".",
"group",
"(",
"1",
")",
"+",
"indent",
"+",
"m",
".",
"group",
"(",
"2",
")",
"return",
"self"
] |
Appends a (key, item) to the table.
|
[
"Appends",
"a",
"(",
"key",
"item",
")",
"to",
"the",
"table",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/items.py#L780-L808
|
train
|
pypa/pipenv
|
pipenv/vendor/tomlkit/items.py
|
InlineTable.append
|
def append(self, key, _item): # type: (Union[Key, str], Any) -> InlineTable
"""
Appends a (key, item) to the table.
"""
if not isinstance(_item, Item):
_item = item(_item)
if not isinstance(_item, (Whitespace, Comment)):
if not _item.trivia.indent and len(self._value) > 0:
_item.trivia.indent = " "
if _item.trivia.comment:
_item.trivia.comment = ""
self._value.append(key, _item)
if isinstance(key, Key):
key = key.key
if key is not None:
super(InlineTable, self).__setitem__(key, _item)
return self
|
python
|
def append(self, key, _item): # type: (Union[Key, str], Any) -> InlineTable
"""
Appends a (key, item) to the table.
"""
if not isinstance(_item, Item):
_item = item(_item)
if not isinstance(_item, (Whitespace, Comment)):
if not _item.trivia.indent and len(self._value) > 0:
_item.trivia.indent = " "
if _item.trivia.comment:
_item.trivia.comment = ""
self._value.append(key, _item)
if isinstance(key, Key):
key = key.key
if key is not None:
super(InlineTable, self).__setitem__(key, _item)
return self
|
[
"def",
"append",
"(",
"self",
",",
"key",
",",
"_item",
")",
":",
"# type: (Union[Key, str], Any) -> InlineTable",
"if",
"not",
"isinstance",
"(",
"_item",
",",
"Item",
")",
":",
"_item",
"=",
"item",
"(",
"_item",
")",
"if",
"not",
"isinstance",
"(",
"_item",
",",
"(",
"Whitespace",
",",
"Comment",
")",
")",
":",
"if",
"not",
"_item",
".",
"trivia",
".",
"indent",
"and",
"len",
"(",
"self",
".",
"_value",
")",
">",
"0",
":",
"_item",
".",
"trivia",
".",
"indent",
"=",
"\" \"",
"if",
"_item",
".",
"trivia",
".",
"comment",
":",
"_item",
".",
"trivia",
".",
"comment",
"=",
"\"\"",
"self",
".",
"_value",
".",
"append",
"(",
"key",
",",
"_item",
")",
"if",
"isinstance",
"(",
"key",
",",
"Key",
")",
":",
"key",
"=",
"key",
".",
"key",
"if",
"key",
"is",
"not",
"None",
":",
"super",
"(",
"InlineTable",
",",
"self",
")",
".",
"__setitem__",
"(",
"key",
",",
"_item",
")",
"return",
"self"
] |
Appends a (key, item) to the table.
|
[
"Appends",
"a",
"(",
"key",
"item",
")",
"to",
"the",
"table",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/items.py#L932-L953
|
train
|
pypa/pipenv
|
pipenv/vendor/backports/functools_lru_cache.py
|
update_wrapper
|
def update_wrapper(wrapper,
wrapped,
assigned = functools.WRAPPER_ASSIGNMENTS,
updated = functools.WRAPPER_UPDATES):
"""
Patch two bugs in functools.update_wrapper.
"""
# workaround for http://bugs.python.org/issue3445
assigned = tuple(attr for attr in assigned if hasattr(wrapped, attr))
wrapper = functools.update_wrapper(wrapper, wrapped, assigned, updated)
# workaround for https://bugs.python.org/issue17482
wrapper.__wrapped__ = wrapped
return wrapper
|
python
|
def update_wrapper(wrapper,
wrapped,
assigned = functools.WRAPPER_ASSIGNMENTS,
updated = functools.WRAPPER_UPDATES):
"""
Patch two bugs in functools.update_wrapper.
"""
# workaround for http://bugs.python.org/issue3445
assigned = tuple(attr for attr in assigned if hasattr(wrapped, attr))
wrapper = functools.update_wrapper(wrapper, wrapped, assigned, updated)
# workaround for https://bugs.python.org/issue17482
wrapper.__wrapped__ = wrapped
return wrapper
|
[
"def",
"update_wrapper",
"(",
"wrapper",
",",
"wrapped",
",",
"assigned",
"=",
"functools",
".",
"WRAPPER_ASSIGNMENTS",
",",
"updated",
"=",
"functools",
".",
"WRAPPER_UPDATES",
")",
":",
"# workaround for http://bugs.python.org/issue3445",
"assigned",
"=",
"tuple",
"(",
"attr",
"for",
"attr",
"in",
"assigned",
"if",
"hasattr",
"(",
"wrapped",
",",
"attr",
")",
")",
"wrapper",
"=",
"functools",
".",
"update_wrapper",
"(",
"wrapper",
",",
"wrapped",
",",
"assigned",
",",
"updated",
")",
"# workaround for https://bugs.python.org/issue17482",
"wrapper",
".",
"__wrapped__",
"=",
"wrapped",
"return",
"wrapper"
] |
Patch two bugs in functools.update_wrapper.
|
[
"Patch",
"two",
"bugs",
"in",
"functools",
".",
"update_wrapper",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/backports/functools_lru_cache.py#L11-L23
|
train
|
pypa/pipenv
|
pipenv/vendor/backports/functools_lru_cache.py
|
lru_cache
|
def lru_cache(maxsize=100, typed=False):
"""Least-recently-used cache decorator.
If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.
If *typed* is True, arguments of different types will be cached separately.
For example, f(3.0) and f(3) will be treated as distinct calls with
distinct results.
Arguments to the cached function must be hashable.
View the cache statistics named tuple (hits, misses, maxsize, currsize) with
f.cache_info(). Clear the cache and statistics with f.cache_clear().
Access the underlying function with f.__wrapped__.
See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
"""
# Users should only access the lru_cache through its public API:
# cache_info, cache_clear, and f.__wrapped__
# The internals of the lru_cache are encapsulated for thread safety and
# to allow the implementation to change (including a possible C version).
def decorating_function(user_function):
cache = dict()
stats = [0, 0] # make statistics updateable non-locally
HITS, MISSES = 0, 1 # names for the stats fields
make_key = _make_key
cache_get = cache.get # bound method to lookup key or return None
_len = len # localize the global len() function
lock = RLock() # because linkedlist updates aren't threadsafe
root = [] # root of the circular doubly linked list
root[:] = [root, root, None, None] # initialize by pointing to self
nonlocal_root = [root] # make updateable non-locally
PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields
if maxsize == 0:
def wrapper(*args, **kwds):
# no caching, just do a statistics update after a successful call
result = user_function(*args, **kwds)
stats[MISSES] += 1
return result
elif maxsize is None:
def wrapper(*args, **kwds):
# simple caching without ordering or size limit
key = make_key(args, kwds, typed)
result = cache_get(key, root) # root used here as a unique not-found sentinel
if result is not root:
stats[HITS] += 1
return result
result = user_function(*args, **kwds)
cache[key] = result
stats[MISSES] += 1
return result
else:
def wrapper(*args, **kwds):
# size limited caching that tracks accesses by recency
key = make_key(args, kwds, typed) if kwds or typed else args
with lock:
link = cache_get(key)
if link is not None:
# record recent use of the key by moving it to the front of the list
root, = nonlocal_root
link_prev, link_next, key, result = link
link_prev[NEXT] = link_next
link_next[PREV] = link_prev
last = root[PREV]
last[NEXT] = root[PREV] = link
link[PREV] = last
link[NEXT] = root
stats[HITS] += 1
return result
result = user_function(*args, **kwds)
with lock:
root, = nonlocal_root
if key in cache:
# getting here means that this same key was added to the
# cache while the lock was released. since the link
# update is already done, we need only return the
# computed result and update the count of misses.
pass
elif _len(cache) >= maxsize:
# use the old root to store the new key and result
oldroot = root
oldroot[KEY] = key
oldroot[RESULT] = result
# empty the oldest link and make it the new root
root = nonlocal_root[0] = oldroot[NEXT]
oldkey = root[KEY]
root[KEY] = root[RESULT] = None
# now update the cache dictionary for the new links
del cache[oldkey]
cache[key] = oldroot
else:
# put result in a new link at the front of the list
last = root[PREV]
link = [last, root, key, result]
last[NEXT] = root[PREV] = cache[key] = link
stats[MISSES] += 1
return result
def cache_info():
"""Report cache statistics"""
with lock:
return _CacheInfo(stats[HITS], stats[MISSES], maxsize, len(cache))
def cache_clear():
"""Clear the cache and cache statistics"""
with lock:
cache.clear()
root = nonlocal_root[0]
root[:] = [root, root, None, None]
stats[:] = [0, 0]
wrapper.__wrapped__ = user_function
wrapper.cache_info = cache_info
wrapper.cache_clear = cache_clear
return update_wrapper(wrapper, user_function)
return decorating_function
|
python
|
def lru_cache(maxsize=100, typed=False):
"""Least-recently-used cache decorator.
If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.
If *typed* is True, arguments of different types will be cached separately.
For example, f(3.0) and f(3) will be treated as distinct calls with
distinct results.
Arguments to the cached function must be hashable.
View the cache statistics named tuple (hits, misses, maxsize, currsize) with
f.cache_info(). Clear the cache and statistics with f.cache_clear().
Access the underlying function with f.__wrapped__.
See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
"""
# Users should only access the lru_cache through its public API:
# cache_info, cache_clear, and f.__wrapped__
# The internals of the lru_cache are encapsulated for thread safety and
# to allow the implementation to change (including a possible C version).
def decorating_function(user_function):
cache = dict()
stats = [0, 0] # make statistics updateable non-locally
HITS, MISSES = 0, 1 # names for the stats fields
make_key = _make_key
cache_get = cache.get # bound method to lookup key or return None
_len = len # localize the global len() function
lock = RLock() # because linkedlist updates aren't threadsafe
root = [] # root of the circular doubly linked list
root[:] = [root, root, None, None] # initialize by pointing to self
nonlocal_root = [root] # make updateable non-locally
PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields
if maxsize == 0:
def wrapper(*args, **kwds):
# no caching, just do a statistics update after a successful call
result = user_function(*args, **kwds)
stats[MISSES] += 1
return result
elif maxsize is None:
def wrapper(*args, **kwds):
# simple caching without ordering or size limit
key = make_key(args, kwds, typed)
result = cache_get(key, root) # root used here as a unique not-found sentinel
if result is not root:
stats[HITS] += 1
return result
result = user_function(*args, **kwds)
cache[key] = result
stats[MISSES] += 1
return result
else:
def wrapper(*args, **kwds):
# size limited caching that tracks accesses by recency
key = make_key(args, kwds, typed) if kwds or typed else args
with lock:
link = cache_get(key)
if link is not None:
# record recent use of the key by moving it to the front of the list
root, = nonlocal_root
link_prev, link_next, key, result = link
link_prev[NEXT] = link_next
link_next[PREV] = link_prev
last = root[PREV]
last[NEXT] = root[PREV] = link
link[PREV] = last
link[NEXT] = root
stats[HITS] += 1
return result
result = user_function(*args, **kwds)
with lock:
root, = nonlocal_root
if key in cache:
# getting here means that this same key was added to the
# cache while the lock was released. since the link
# update is already done, we need only return the
# computed result and update the count of misses.
pass
elif _len(cache) >= maxsize:
# use the old root to store the new key and result
oldroot = root
oldroot[KEY] = key
oldroot[RESULT] = result
# empty the oldest link and make it the new root
root = nonlocal_root[0] = oldroot[NEXT]
oldkey = root[KEY]
root[KEY] = root[RESULT] = None
# now update the cache dictionary for the new links
del cache[oldkey]
cache[key] = oldroot
else:
# put result in a new link at the front of the list
last = root[PREV]
link = [last, root, key, result]
last[NEXT] = root[PREV] = cache[key] = link
stats[MISSES] += 1
return result
def cache_info():
"""Report cache statistics"""
with lock:
return _CacheInfo(stats[HITS], stats[MISSES], maxsize, len(cache))
def cache_clear():
"""Clear the cache and cache statistics"""
with lock:
cache.clear()
root = nonlocal_root[0]
root[:] = [root, root, None, None]
stats[:] = [0, 0]
wrapper.__wrapped__ = user_function
wrapper.cache_info = cache_info
wrapper.cache_clear = cache_clear
return update_wrapper(wrapper, user_function)
return decorating_function
|
[
"def",
"lru_cache",
"(",
"maxsize",
"=",
"100",
",",
"typed",
"=",
"False",
")",
":",
"# Users should only access the lru_cache through its public API:",
"# cache_info, cache_clear, and f.__wrapped__",
"# The internals of the lru_cache are encapsulated for thread safety and",
"# to allow the implementation to change (including a possible C version).",
"def",
"decorating_function",
"(",
"user_function",
")",
":",
"cache",
"=",
"dict",
"(",
")",
"stats",
"=",
"[",
"0",
",",
"0",
"]",
"# make statistics updateable non-locally",
"HITS",
",",
"MISSES",
"=",
"0",
",",
"1",
"# names for the stats fields",
"make_key",
"=",
"_make_key",
"cache_get",
"=",
"cache",
".",
"get",
"# bound method to lookup key or return None",
"_len",
"=",
"len",
"# localize the global len() function",
"lock",
"=",
"RLock",
"(",
")",
"# because linkedlist updates aren't threadsafe",
"root",
"=",
"[",
"]",
"# root of the circular doubly linked list",
"root",
"[",
":",
"]",
"=",
"[",
"root",
",",
"root",
",",
"None",
",",
"None",
"]",
"# initialize by pointing to self",
"nonlocal_root",
"=",
"[",
"root",
"]",
"# make updateable non-locally",
"PREV",
",",
"NEXT",
",",
"KEY",
",",
"RESULT",
"=",
"0",
",",
"1",
",",
"2",
",",
"3",
"# names for the link fields",
"if",
"maxsize",
"==",
"0",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"# no caching, just do a statistics update after a successful call",
"result",
"=",
"user_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"stats",
"[",
"MISSES",
"]",
"+=",
"1",
"return",
"result",
"elif",
"maxsize",
"is",
"None",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"# simple caching without ordering or size limit",
"key",
"=",
"make_key",
"(",
"args",
",",
"kwds",
",",
"typed",
")",
"result",
"=",
"cache_get",
"(",
"key",
",",
"root",
")",
"# root used here as a unique not-found sentinel",
"if",
"result",
"is",
"not",
"root",
":",
"stats",
"[",
"HITS",
"]",
"+=",
"1",
"return",
"result",
"result",
"=",
"user_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"cache",
"[",
"key",
"]",
"=",
"result",
"stats",
"[",
"MISSES",
"]",
"+=",
"1",
"return",
"result",
"else",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"# size limited caching that tracks accesses by recency",
"key",
"=",
"make_key",
"(",
"args",
",",
"kwds",
",",
"typed",
")",
"if",
"kwds",
"or",
"typed",
"else",
"args",
"with",
"lock",
":",
"link",
"=",
"cache_get",
"(",
"key",
")",
"if",
"link",
"is",
"not",
"None",
":",
"# record recent use of the key by moving it to the front of the list",
"root",
",",
"=",
"nonlocal_root",
"link_prev",
",",
"link_next",
",",
"key",
",",
"result",
"=",
"link",
"link_prev",
"[",
"NEXT",
"]",
"=",
"link_next",
"link_next",
"[",
"PREV",
"]",
"=",
"link_prev",
"last",
"=",
"root",
"[",
"PREV",
"]",
"last",
"[",
"NEXT",
"]",
"=",
"root",
"[",
"PREV",
"]",
"=",
"link",
"link",
"[",
"PREV",
"]",
"=",
"last",
"link",
"[",
"NEXT",
"]",
"=",
"root",
"stats",
"[",
"HITS",
"]",
"+=",
"1",
"return",
"result",
"result",
"=",
"user_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"with",
"lock",
":",
"root",
",",
"=",
"nonlocal_root",
"if",
"key",
"in",
"cache",
":",
"# getting here means that this same key was added to the",
"# cache while the lock was released. since the link",
"# update is already done, we need only return the",
"# computed result and update the count of misses.",
"pass",
"elif",
"_len",
"(",
"cache",
")",
">=",
"maxsize",
":",
"# use the old root to store the new key and result",
"oldroot",
"=",
"root",
"oldroot",
"[",
"KEY",
"]",
"=",
"key",
"oldroot",
"[",
"RESULT",
"]",
"=",
"result",
"# empty the oldest link and make it the new root",
"root",
"=",
"nonlocal_root",
"[",
"0",
"]",
"=",
"oldroot",
"[",
"NEXT",
"]",
"oldkey",
"=",
"root",
"[",
"KEY",
"]",
"root",
"[",
"KEY",
"]",
"=",
"root",
"[",
"RESULT",
"]",
"=",
"None",
"# now update the cache dictionary for the new links",
"del",
"cache",
"[",
"oldkey",
"]",
"cache",
"[",
"key",
"]",
"=",
"oldroot",
"else",
":",
"# put result in a new link at the front of the list",
"last",
"=",
"root",
"[",
"PREV",
"]",
"link",
"=",
"[",
"last",
",",
"root",
",",
"key",
",",
"result",
"]",
"last",
"[",
"NEXT",
"]",
"=",
"root",
"[",
"PREV",
"]",
"=",
"cache",
"[",
"key",
"]",
"=",
"link",
"stats",
"[",
"MISSES",
"]",
"+=",
"1",
"return",
"result",
"def",
"cache_info",
"(",
")",
":",
"\"\"\"Report cache statistics\"\"\"",
"with",
"lock",
":",
"return",
"_CacheInfo",
"(",
"stats",
"[",
"HITS",
"]",
",",
"stats",
"[",
"MISSES",
"]",
",",
"maxsize",
",",
"len",
"(",
"cache",
")",
")",
"def",
"cache_clear",
"(",
")",
":",
"\"\"\"Clear the cache and cache statistics\"\"\"",
"with",
"lock",
":",
"cache",
".",
"clear",
"(",
")",
"root",
"=",
"nonlocal_root",
"[",
"0",
"]",
"root",
"[",
":",
"]",
"=",
"[",
"root",
",",
"root",
",",
"None",
",",
"None",
"]",
"stats",
"[",
":",
"]",
"=",
"[",
"0",
",",
"0",
"]",
"wrapper",
".",
"__wrapped__",
"=",
"user_function",
"wrapper",
".",
"cache_info",
"=",
"cache_info",
"wrapper",
".",
"cache_clear",
"=",
"cache_clear",
"return",
"update_wrapper",
"(",
"wrapper",
",",
"user_function",
")",
"return",
"decorating_function"
] |
Least-recently-used cache decorator.
If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.
If *typed* is True, arguments of different types will be cached separately.
For example, f(3.0) and f(3) will be treated as distinct calls with
distinct results.
Arguments to the cached function must be hashable.
View the cache statistics named tuple (hits, misses, maxsize, currsize) with
f.cache_info(). Clear the cache and statistics with f.cache_clear().
Access the underlying function with f.__wrapped__.
See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
|
[
"Least",
"-",
"recently",
"-",
"used",
"cache",
"decorator",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/backports/functools_lru_cache.py#L57-L184
|
train
|
pypa/pipenv
|
pipenv/vendor/first.py
|
first
|
def first(iterable, default=None, key=None):
"""
Return first element of `iterable` that evaluates true, else return None
(or an optional default value).
>>> first([0, False, None, [], (), 42])
42
>>> first([0, False, None, [], ()]) is None
True
>>> first([0, False, None, [], ()], default='ohai')
'ohai'
>>> import re
>>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])
>>> m.group(1)
'bc'
The optional `key` argument specifies a one-argument predicate function
like that used for `filter()`. The `key` argument, if supplied, must be
in keyword form. For example:
>>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
4
"""
if key is None:
for el in iterable:
if el:
return el
else:
for el in iterable:
if key(el):
return el
return default
|
python
|
def first(iterable, default=None, key=None):
"""
Return first element of `iterable` that evaluates true, else return None
(or an optional default value).
>>> first([0, False, None, [], (), 42])
42
>>> first([0, False, None, [], ()]) is None
True
>>> first([0, False, None, [], ()], default='ohai')
'ohai'
>>> import re
>>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])
>>> m.group(1)
'bc'
The optional `key` argument specifies a one-argument predicate function
like that used for `filter()`. The `key` argument, if supplied, must be
in keyword form. For example:
>>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
4
"""
if key is None:
for el in iterable:
if el:
return el
else:
for el in iterable:
if key(el):
return el
return default
|
[
"def",
"first",
"(",
"iterable",
",",
"default",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"for",
"el",
"in",
"iterable",
":",
"if",
"el",
":",
"return",
"el",
"else",
":",
"for",
"el",
"in",
"iterable",
":",
"if",
"key",
"(",
"el",
")",
":",
"return",
"el",
"return",
"default"
] |
Return first element of `iterable` that evaluates true, else return None
(or an optional default value).
>>> first([0, False, None, [], (), 42])
42
>>> first([0, False, None, [], ()]) is None
True
>>> first([0, False, None, [], ()], default='ohai')
'ohai'
>>> import re
>>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])
>>> m.group(1)
'bc'
The optional `key` argument specifies a one-argument predicate function
like that used for `filter()`. The `key` argument, if supplied, must be
in keyword form. For example:
>>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
4
|
[
"Return",
"first",
"element",
"of",
"iterable",
"that",
"evaluates",
"true",
"else",
"return",
"None",
"(",
"or",
"an",
"optional",
"default",
"value",
")",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/first.py#L42-L78
|
train
|
pypa/pipenv
|
pipenv/vendor/shellingham/posix/ps.py
|
get_process_mapping
|
def get_process_mapping():
"""Try to look up the process tree via the output of `ps`.
"""
try:
output = subprocess.check_output([
'ps', '-ww', '-o', 'pid=', '-o', 'ppid=', '-o', 'args=',
])
except OSError as e: # Python 2-compatible FileNotFoundError.
if e.errno != errno.ENOENT:
raise
raise PsNotAvailable('ps not found')
except subprocess.CalledProcessError as e:
# `ps` can return 1 if the process list is completely empty.
# (sarugaku/shellingham#15)
if not e.output.strip():
return {}
raise
if not isinstance(output, str):
encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
output = output.decode(encoding)
processes = {}
for line in output.split('\n'):
try:
pid, ppid, args = line.strip().split(None, 2)
# XXX: This is not right, but we are really out of options.
# ps does not offer a sane way to decode the argument display,
# and this is "Good Enough" for obtaining shell names. Hopefully
# people don't name their shell with a space, or have something
# like "/usr/bin/xonsh is uber". (sarugaku/shellingham#14)
args = tuple(a.strip() for a in args.split(' '))
except ValueError:
continue
processes[pid] = Process(args=args, pid=pid, ppid=ppid)
return processes
|
python
|
def get_process_mapping():
"""Try to look up the process tree via the output of `ps`.
"""
try:
output = subprocess.check_output([
'ps', '-ww', '-o', 'pid=', '-o', 'ppid=', '-o', 'args=',
])
except OSError as e: # Python 2-compatible FileNotFoundError.
if e.errno != errno.ENOENT:
raise
raise PsNotAvailable('ps not found')
except subprocess.CalledProcessError as e:
# `ps` can return 1 if the process list is completely empty.
# (sarugaku/shellingham#15)
if not e.output.strip():
return {}
raise
if not isinstance(output, str):
encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
output = output.decode(encoding)
processes = {}
for line in output.split('\n'):
try:
pid, ppid, args = line.strip().split(None, 2)
# XXX: This is not right, but we are really out of options.
# ps does not offer a sane way to decode the argument display,
# and this is "Good Enough" for obtaining shell names. Hopefully
# people don't name their shell with a space, or have something
# like "/usr/bin/xonsh is uber". (sarugaku/shellingham#14)
args = tuple(a.strip() for a in args.split(' '))
except ValueError:
continue
processes[pid] = Process(args=args, pid=pid, ppid=ppid)
return processes
|
[
"def",
"get_process_mapping",
"(",
")",
":",
"try",
":",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'ps'",
",",
"'-ww'",
",",
"'-o'",
",",
"'pid='",
",",
"'-o'",
",",
"'ppid='",
",",
"'-o'",
",",
"'args='",
",",
"]",
")",
"except",
"OSError",
"as",
"e",
":",
"# Python 2-compatible FileNotFoundError.",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise",
"raise",
"PsNotAvailable",
"(",
"'ps not found'",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"# `ps` can return 1 if the process list is completely empty.",
"# (sarugaku/shellingham#15)",
"if",
"not",
"e",
".",
"output",
".",
"strip",
"(",
")",
":",
"return",
"{",
"}",
"raise",
"if",
"not",
"isinstance",
"(",
"output",
",",
"str",
")",
":",
"encoding",
"=",
"sys",
".",
"getfilesystemencoding",
"(",
")",
"or",
"sys",
".",
"getdefaultencoding",
"(",
")",
"output",
"=",
"output",
".",
"decode",
"(",
"encoding",
")",
"processes",
"=",
"{",
"}",
"for",
"line",
"in",
"output",
".",
"split",
"(",
"'\\n'",
")",
":",
"try",
":",
"pid",
",",
"ppid",
",",
"args",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"None",
",",
"2",
")",
"# XXX: This is not right, but we are really out of options.",
"# ps does not offer a sane way to decode the argument display,",
"# and this is \"Good Enough\" for obtaining shell names. Hopefully",
"# people don't name their shell with a space, or have something",
"# like \"/usr/bin/xonsh is uber\". (sarugaku/shellingham#14)",
"args",
"=",
"tuple",
"(",
"a",
".",
"strip",
"(",
")",
"for",
"a",
"in",
"args",
".",
"split",
"(",
"' '",
")",
")",
"except",
"ValueError",
":",
"continue",
"processes",
"[",
"pid",
"]",
"=",
"Process",
"(",
"args",
"=",
"args",
",",
"pid",
"=",
"pid",
",",
"ppid",
"=",
"ppid",
")",
"return",
"processes"
] |
Try to look up the process tree via the output of `ps`.
|
[
"Try",
"to",
"look",
"up",
"the",
"process",
"tree",
"via",
"the",
"output",
"of",
"ps",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/shellingham/posix/ps.py#L12-L45
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/idtracking.py
|
FrameSymbolVisitor.visit_Name
|
def visit_Name(self, node, store_as_param=False, **kwargs):
"""All assignments to names go through this function."""
if store_as_param or node.ctx == 'param':
self.symbols.declare_parameter(node.name)
elif node.ctx == 'store':
self.symbols.store(node.name)
elif node.ctx == 'load':
self.symbols.load(node.name)
|
python
|
def visit_Name(self, node, store_as_param=False, **kwargs):
"""All assignments to names go through this function."""
if store_as_param or node.ctx == 'param':
self.symbols.declare_parameter(node.name)
elif node.ctx == 'store':
self.symbols.store(node.name)
elif node.ctx == 'load':
self.symbols.load(node.name)
|
[
"def",
"visit_Name",
"(",
"self",
",",
"node",
",",
"store_as_param",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"store_as_param",
"or",
"node",
".",
"ctx",
"==",
"'param'",
":",
"self",
".",
"symbols",
".",
"declare_parameter",
"(",
"node",
".",
"name",
")",
"elif",
"node",
".",
"ctx",
"==",
"'store'",
":",
"self",
".",
"symbols",
".",
"store",
"(",
"node",
".",
"name",
")",
"elif",
"node",
".",
"ctx",
"==",
"'load'",
":",
"self",
".",
"symbols",
".",
"load",
"(",
"node",
".",
"name",
")"
] |
All assignments to names go through this function.
|
[
"All",
"assignments",
"to",
"names",
"go",
"through",
"this",
"function",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/idtracking.py#L209-L216
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/idtracking.py
|
FrameSymbolVisitor.visit_Assign
|
def visit_Assign(self, node, **kwargs):
"""Visit assignments in the correct order."""
self.visit(node.node, **kwargs)
self.visit(node.target, **kwargs)
|
python
|
def visit_Assign(self, node, **kwargs):
"""Visit assignments in the correct order."""
self.visit(node.node, **kwargs)
self.visit(node.target, **kwargs)
|
[
"def",
"visit_Assign",
"(",
"self",
",",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"visit",
"(",
"node",
".",
"node",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"visit",
"(",
"node",
".",
"target",
",",
"*",
"*",
"kwargs",
")"
] |
Visit assignments in the correct order.
|
[
"Visit",
"assignments",
"in",
"the",
"correct",
"order",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/idtracking.py#L254-L257
|
train
|
pypa/pipenv
|
pipenv/vendor/attr/_compat.py
|
make_set_closure_cell
|
def make_set_closure_cell():
"""
Moved into a function for testability.
"""
if PYPY: # pragma: no cover
def set_closure_cell(cell, value):
cell.__setstate__((value,))
else:
try:
ctypes = import_ctypes()
set_closure_cell = ctypes.pythonapi.PyCell_Set
set_closure_cell.argtypes = (ctypes.py_object, ctypes.py_object)
set_closure_cell.restype = ctypes.c_int
except Exception:
# We try best effort to set the cell, but sometimes it's not
# possible. For example on Jython or on GAE.
set_closure_cell = just_warn
return set_closure_cell
|
python
|
def make_set_closure_cell():
"""
Moved into a function for testability.
"""
if PYPY: # pragma: no cover
def set_closure_cell(cell, value):
cell.__setstate__((value,))
else:
try:
ctypes = import_ctypes()
set_closure_cell = ctypes.pythonapi.PyCell_Set
set_closure_cell.argtypes = (ctypes.py_object, ctypes.py_object)
set_closure_cell.restype = ctypes.c_int
except Exception:
# We try best effort to set the cell, but sometimes it's not
# possible. For example on Jython or on GAE.
set_closure_cell = just_warn
return set_closure_cell
|
[
"def",
"make_set_closure_cell",
"(",
")",
":",
"if",
"PYPY",
":",
"# pragma: no cover",
"def",
"set_closure_cell",
"(",
"cell",
",",
"value",
")",
":",
"cell",
".",
"__setstate__",
"(",
"(",
"value",
",",
")",
")",
"else",
":",
"try",
":",
"ctypes",
"=",
"import_ctypes",
"(",
")",
"set_closure_cell",
"=",
"ctypes",
".",
"pythonapi",
".",
"PyCell_Set",
"set_closure_cell",
".",
"argtypes",
"=",
"(",
"ctypes",
".",
"py_object",
",",
"ctypes",
".",
"py_object",
")",
"set_closure_cell",
".",
"restype",
"=",
"ctypes",
".",
"c_int",
"except",
"Exception",
":",
"# We try best effort to set the cell, but sometimes it's not",
"# possible. For example on Jython or on GAE.",
"set_closure_cell",
"=",
"just_warn",
"return",
"set_closure_cell"
] |
Moved into a function for testability.
|
[
"Moved",
"into",
"a",
"function",
"for",
"testability",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/_compat.py#L136-L156
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pty_spawn.py
|
spawn._spawn
|
def _spawn(self, command, args=[], preexec_fn=None, dimensions=None):
'''This starts the given command in a child process. This does all the
fork/exec type of stuff for a pty. This is called by __init__. If args
is empty then command will be parsed (split on spaces) and args will be
set to parsed arguments. '''
# The pid and child_fd of this object get set by this method.
# Note that it is difficult for this method to fail.
# You cannot detect if the child process cannot start.
# So the only way you can tell if the child process started
# or not is to try to read from the file descriptor. If you get
# EOF immediately then it means that the child is already dead.
# That may not necessarily be bad because you may have spawned a child
# that performs some task; creates no stdout output; and then dies.
# If command is an int type then it may represent a file descriptor.
if isinstance(command, type(0)):
raise ExceptionPexpect('Command is an int type. ' +
'If this is a file descriptor then maybe you want to ' +
'use fdpexpect.fdspawn which takes an existing ' +
'file descriptor instead of a command string.')
if not isinstance(args, type([])):
raise TypeError('The argument, args, must be a list.')
if args == []:
self.args = split_command_line(command)
self.command = self.args[0]
else:
# Make a shallow copy of the args list.
self.args = args[:]
self.args.insert(0, command)
self.command = command
command_with_path = which(self.command, env=self.env)
if command_with_path is None:
raise ExceptionPexpect('The command was not found or was not ' +
'executable: %s.' % self.command)
self.command = command_with_path
self.args[0] = self.command
self.name = '<' + ' '.join(self.args) + '>'
assert self.pid is None, 'The pid member must be None.'
assert self.command is not None, 'The command member must not be None.'
kwargs = {'echo': self.echo, 'preexec_fn': preexec_fn}
if self.ignore_sighup:
def preexec_wrapper():
"Set SIGHUP to be ignored, then call the real preexec_fn"
signal.signal(signal.SIGHUP, signal.SIG_IGN)
if preexec_fn is not None:
preexec_fn()
kwargs['preexec_fn'] = preexec_wrapper
if dimensions is not None:
kwargs['dimensions'] = dimensions
if self.encoding is not None:
# Encode command line using the specified encoding
self.args = [a if isinstance(a, bytes) else a.encode(self.encoding)
for a in self.args]
self.ptyproc = self._spawnpty(self.args, env=self.env,
cwd=self.cwd, **kwargs)
self.pid = self.ptyproc.pid
self.child_fd = self.ptyproc.fd
self.terminated = False
self.closed = False
|
python
|
def _spawn(self, command, args=[], preexec_fn=None, dimensions=None):
'''This starts the given command in a child process. This does all the
fork/exec type of stuff for a pty. This is called by __init__. If args
is empty then command will be parsed (split on spaces) and args will be
set to parsed arguments. '''
# The pid and child_fd of this object get set by this method.
# Note that it is difficult for this method to fail.
# You cannot detect if the child process cannot start.
# So the only way you can tell if the child process started
# or not is to try to read from the file descriptor. If you get
# EOF immediately then it means that the child is already dead.
# That may not necessarily be bad because you may have spawned a child
# that performs some task; creates no stdout output; and then dies.
# If command is an int type then it may represent a file descriptor.
if isinstance(command, type(0)):
raise ExceptionPexpect('Command is an int type. ' +
'If this is a file descriptor then maybe you want to ' +
'use fdpexpect.fdspawn which takes an existing ' +
'file descriptor instead of a command string.')
if not isinstance(args, type([])):
raise TypeError('The argument, args, must be a list.')
if args == []:
self.args = split_command_line(command)
self.command = self.args[0]
else:
# Make a shallow copy of the args list.
self.args = args[:]
self.args.insert(0, command)
self.command = command
command_with_path = which(self.command, env=self.env)
if command_with_path is None:
raise ExceptionPexpect('The command was not found or was not ' +
'executable: %s.' % self.command)
self.command = command_with_path
self.args[0] = self.command
self.name = '<' + ' '.join(self.args) + '>'
assert self.pid is None, 'The pid member must be None.'
assert self.command is not None, 'The command member must not be None.'
kwargs = {'echo': self.echo, 'preexec_fn': preexec_fn}
if self.ignore_sighup:
def preexec_wrapper():
"Set SIGHUP to be ignored, then call the real preexec_fn"
signal.signal(signal.SIGHUP, signal.SIG_IGN)
if preexec_fn is not None:
preexec_fn()
kwargs['preexec_fn'] = preexec_wrapper
if dimensions is not None:
kwargs['dimensions'] = dimensions
if self.encoding is not None:
# Encode command line using the specified encoding
self.args = [a if isinstance(a, bytes) else a.encode(self.encoding)
for a in self.args]
self.ptyproc = self._spawnpty(self.args, env=self.env,
cwd=self.cwd, **kwargs)
self.pid = self.ptyproc.pid
self.child_fd = self.ptyproc.fd
self.terminated = False
self.closed = False
|
[
"def",
"_spawn",
"(",
"self",
",",
"command",
",",
"args",
"=",
"[",
"]",
",",
"preexec_fn",
"=",
"None",
",",
"dimensions",
"=",
"None",
")",
":",
"# The pid and child_fd of this object get set by this method.",
"# Note that it is difficult for this method to fail.",
"# You cannot detect if the child process cannot start.",
"# So the only way you can tell if the child process started",
"# or not is to try to read from the file descriptor. If you get",
"# EOF immediately then it means that the child is already dead.",
"# That may not necessarily be bad because you may have spawned a child",
"# that performs some task; creates no stdout output; and then dies.",
"# If command is an int type then it may represent a file descriptor.",
"if",
"isinstance",
"(",
"command",
",",
"type",
"(",
"0",
")",
")",
":",
"raise",
"ExceptionPexpect",
"(",
"'Command is an int type. '",
"+",
"'If this is a file descriptor then maybe you want to '",
"+",
"'use fdpexpect.fdspawn which takes an existing '",
"+",
"'file descriptor instead of a command string.'",
")",
"if",
"not",
"isinstance",
"(",
"args",
",",
"type",
"(",
"[",
"]",
")",
")",
":",
"raise",
"TypeError",
"(",
"'The argument, args, must be a list.'",
")",
"if",
"args",
"==",
"[",
"]",
":",
"self",
".",
"args",
"=",
"split_command_line",
"(",
"command",
")",
"self",
".",
"command",
"=",
"self",
".",
"args",
"[",
"0",
"]",
"else",
":",
"# Make a shallow copy of the args list.",
"self",
".",
"args",
"=",
"args",
"[",
":",
"]",
"self",
".",
"args",
".",
"insert",
"(",
"0",
",",
"command",
")",
"self",
".",
"command",
"=",
"command",
"command_with_path",
"=",
"which",
"(",
"self",
".",
"command",
",",
"env",
"=",
"self",
".",
"env",
")",
"if",
"command_with_path",
"is",
"None",
":",
"raise",
"ExceptionPexpect",
"(",
"'The command was not found or was not '",
"+",
"'executable: %s.'",
"%",
"self",
".",
"command",
")",
"self",
".",
"command",
"=",
"command_with_path",
"self",
".",
"args",
"[",
"0",
"]",
"=",
"self",
".",
"command",
"self",
".",
"name",
"=",
"'<'",
"+",
"' '",
".",
"join",
"(",
"self",
".",
"args",
")",
"+",
"'>'",
"assert",
"self",
".",
"pid",
"is",
"None",
",",
"'The pid member must be None.'",
"assert",
"self",
".",
"command",
"is",
"not",
"None",
",",
"'The command member must not be None.'",
"kwargs",
"=",
"{",
"'echo'",
":",
"self",
".",
"echo",
",",
"'preexec_fn'",
":",
"preexec_fn",
"}",
"if",
"self",
".",
"ignore_sighup",
":",
"def",
"preexec_wrapper",
"(",
")",
":",
"\"Set SIGHUP to be ignored, then call the real preexec_fn\"",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGHUP",
",",
"signal",
".",
"SIG_IGN",
")",
"if",
"preexec_fn",
"is",
"not",
"None",
":",
"preexec_fn",
"(",
")",
"kwargs",
"[",
"'preexec_fn'",
"]",
"=",
"preexec_wrapper",
"if",
"dimensions",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'dimensions'",
"]",
"=",
"dimensions",
"if",
"self",
".",
"encoding",
"is",
"not",
"None",
":",
"# Encode command line using the specified encoding",
"self",
".",
"args",
"=",
"[",
"a",
"if",
"isinstance",
"(",
"a",
",",
"bytes",
")",
"else",
"a",
".",
"encode",
"(",
"self",
".",
"encoding",
")",
"for",
"a",
"in",
"self",
".",
"args",
"]",
"self",
".",
"ptyproc",
"=",
"self",
".",
"_spawnpty",
"(",
"self",
".",
"args",
",",
"env",
"=",
"self",
".",
"env",
",",
"cwd",
"=",
"self",
".",
"cwd",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"pid",
"=",
"self",
".",
"ptyproc",
".",
"pid",
"self",
".",
"child_fd",
"=",
"self",
".",
"ptyproc",
".",
"fd",
"self",
".",
"terminated",
"=",
"False",
"self",
".",
"closed",
"=",
"False"
] |
This starts the given command in a child process. This does all the
fork/exec type of stuff for a pty. This is called by __init__. If args
is empty then command will be parsed (split on spaces) and args will be
set to parsed arguments.
|
[
"This",
"starts",
"the",
"given",
"command",
"in",
"a",
"child",
"process",
".",
"This",
"does",
"all",
"the",
"fork",
"/",
"exec",
"type",
"of",
"stuff",
"for",
"a",
"pty",
".",
"This",
"is",
"called",
"by",
"__init__",
".",
"If",
"args",
"is",
"empty",
"then",
"command",
"will",
"be",
"parsed",
"(",
"split",
"on",
"spaces",
")",
"and",
"args",
"will",
"be",
"set",
"to",
"parsed",
"arguments",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L239-L310
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pty_spawn.py
|
spawn.close
|
def close(self, force=True):
'''This closes the connection with the child application. Note that
calling close() more than once is valid. This emulates standard Python
behavior with files. Set force to True if you want to make sure that
the child is terminated (SIGKILL is sent if the child ignores SIGHUP
and SIGINT). '''
self.flush()
with _wrap_ptyprocess_err():
# PtyProcessError may be raised if it is not possible to terminate
# the child.
self.ptyproc.close(force=force)
self.isalive() # Update exit status from ptyproc
self.child_fd = -1
self.closed = True
|
python
|
def close(self, force=True):
'''This closes the connection with the child application. Note that
calling close() more than once is valid. This emulates standard Python
behavior with files. Set force to True if you want to make sure that
the child is terminated (SIGKILL is sent if the child ignores SIGHUP
and SIGINT). '''
self.flush()
with _wrap_ptyprocess_err():
# PtyProcessError may be raised if it is not possible to terminate
# the child.
self.ptyproc.close(force=force)
self.isalive() # Update exit status from ptyproc
self.child_fd = -1
self.closed = True
|
[
"def",
"close",
"(",
"self",
",",
"force",
"=",
"True",
")",
":",
"self",
".",
"flush",
"(",
")",
"with",
"_wrap_ptyprocess_err",
"(",
")",
":",
"# PtyProcessError may be raised if it is not possible to terminate",
"# the child.",
"self",
".",
"ptyproc",
".",
"close",
"(",
"force",
"=",
"force",
")",
"self",
".",
"isalive",
"(",
")",
"# Update exit status from ptyproc",
"self",
".",
"child_fd",
"=",
"-",
"1",
"self",
".",
"closed",
"=",
"True"
] |
This closes the connection with the child application. Note that
calling close() more than once is valid. This emulates standard Python
behavior with files. Set force to True if you want to make sure that
the child is terminated (SIGKILL is sent if the child ignores SIGHUP
and SIGINT).
|
[
"This",
"closes",
"the",
"connection",
"with",
"the",
"child",
"application",
".",
"Note",
"that",
"calling",
"close",
"()",
"more",
"than",
"once",
"is",
"valid",
".",
"This",
"emulates",
"standard",
"Python",
"behavior",
"with",
"files",
".",
"Set",
"force",
"to",
"True",
"if",
"you",
"want",
"to",
"make",
"sure",
"that",
"the",
"child",
"is",
"terminated",
"(",
"SIGKILL",
"is",
"sent",
"if",
"the",
"child",
"ignores",
"SIGHUP",
"and",
"SIGINT",
")",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L316-L330
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pty_spawn.py
|
spawn.waitnoecho
|
def waitnoecho(self, timeout=-1):
'''This waits until the terminal ECHO flag is set False. This returns
True if the echo mode is off. This returns False if the ECHO flag was
not set False before the timeout. This can be used to detect when the
child is waiting for a password. Usually a child application will turn
off echo mode when it is waiting for the user to enter a password. For
example, instead of expecting the "password:" prompt you can wait for
the child to set ECHO off::
p = pexpect.spawn('ssh user@example.com')
p.waitnoecho()
p.sendline(mypassword)
If timeout==-1 then this method will use the value in self.timeout.
If timeout==None then this method to block until ECHO flag is False.
'''
if timeout == -1:
timeout = self.timeout
if timeout is not None:
end_time = time.time() + timeout
while True:
if not self.getecho():
return True
if timeout < 0 and timeout is not None:
return False
if timeout is not None:
timeout = end_time - time.time()
time.sleep(0.1)
|
python
|
def waitnoecho(self, timeout=-1):
'''This waits until the terminal ECHO flag is set False. This returns
True if the echo mode is off. This returns False if the ECHO flag was
not set False before the timeout. This can be used to detect when the
child is waiting for a password. Usually a child application will turn
off echo mode when it is waiting for the user to enter a password. For
example, instead of expecting the "password:" prompt you can wait for
the child to set ECHO off::
p = pexpect.spawn('ssh user@example.com')
p.waitnoecho()
p.sendline(mypassword)
If timeout==-1 then this method will use the value in self.timeout.
If timeout==None then this method to block until ECHO flag is False.
'''
if timeout == -1:
timeout = self.timeout
if timeout is not None:
end_time = time.time() + timeout
while True:
if not self.getecho():
return True
if timeout < 0 and timeout is not None:
return False
if timeout is not None:
timeout = end_time - time.time()
time.sleep(0.1)
|
[
"def",
"waitnoecho",
"(",
"self",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"if",
"timeout",
"==",
"-",
"1",
":",
"timeout",
"=",
"self",
".",
"timeout",
"if",
"timeout",
"is",
"not",
"None",
":",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"while",
"True",
":",
"if",
"not",
"self",
".",
"getecho",
"(",
")",
":",
"return",
"True",
"if",
"timeout",
"<",
"0",
"and",
"timeout",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"end_time",
"-",
"time",
".",
"time",
"(",
")",
"time",
".",
"sleep",
"(",
"0.1",
")"
] |
This waits until the terminal ECHO flag is set False. This returns
True if the echo mode is off. This returns False if the ECHO flag was
not set False before the timeout. This can be used to detect when the
child is waiting for a password. Usually a child application will turn
off echo mode when it is waiting for the user to enter a password. For
example, instead of expecting the "password:" prompt you can wait for
the child to set ECHO off::
p = pexpect.spawn('ssh user@example.com')
p.waitnoecho()
p.sendline(mypassword)
If timeout==-1 then this method will use the value in self.timeout.
If timeout==None then this method to block until ECHO flag is False.
|
[
"This",
"waits",
"until",
"the",
"terminal",
"ECHO",
"flag",
"is",
"set",
"False",
".",
"This",
"returns",
"True",
"if",
"the",
"echo",
"mode",
"is",
"off",
".",
"This",
"returns",
"False",
"if",
"the",
"ECHO",
"flag",
"was",
"not",
"set",
"False",
"before",
"the",
"timeout",
".",
"This",
"can",
"be",
"used",
"to",
"detect",
"when",
"the",
"child",
"is",
"waiting",
"for",
"a",
"password",
".",
"Usually",
"a",
"child",
"application",
"will",
"turn",
"off",
"echo",
"mode",
"when",
"it",
"is",
"waiting",
"for",
"the",
"user",
"to",
"enter",
"a",
"password",
".",
"For",
"example",
"instead",
"of",
"expecting",
"the",
"password",
":",
"prompt",
"you",
"can",
"wait",
"for",
"the",
"child",
"to",
"set",
"ECHO",
"off",
"::"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L343-L371
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pty_spawn.py
|
spawn.read_nonblocking
|
def read_nonblocking(self, size=1, timeout=-1):
'''This reads at most size characters from the child application. It
includes a timeout. If the read does not complete within the timeout
period then a TIMEOUT exception is raised. If the end of file is read
then an EOF exception will be raised. If a logfile is specified, a
copy is written to that log.
If timeout is None then the read may block indefinitely.
If timeout is -1 then the self.timeout value is used. If timeout is 0
then the child is polled and if there is no data immediately ready
then this will raise a TIMEOUT exception.
The timeout refers only to the amount of time to read at least one
character. This is not affected by the 'size' parameter, so if you call
read_nonblocking(size=100, timeout=30) and only one character is
available right away then one character will be returned immediately.
It will not wait for 30 seconds for another 99 characters to come in.
This is a wrapper around os.read(). It uses select.select() to
implement the timeout. '''
if self.closed:
raise ValueError('I/O operation on closed file.')
if timeout == -1:
timeout = self.timeout
# Note that some systems such as Solaris do not give an EOF when
# the child dies. In fact, you can still try to read
# from the child_fd -- it will block forever or until TIMEOUT.
# For this case, I test isalive() before doing any reading.
# If isalive() is false, then I pretend that this is the same as EOF.
if not self.isalive():
# timeout of 0 means "poll"
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd], timeout)
else:
r, w, e = select_ignore_interrupts([self.child_fd], [], [], 0)
if not r:
self.flag_eof = True
raise EOF('End Of File (EOF). Braindead platform.')
elif self.__irix_hack:
# Irix takes a long time before it realizes a child was terminated.
# FIXME So does this mean Irix systems are forced to always have
# FIXME a 2 second delay when calling read_nonblocking? That sucks.
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd], timeout)
else:
r, w, e = select_ignore_interrupts([self.child_fd], [], [], 2)
if not r and not self.isalive():
self.flag_eof = True
raise EOF('End Of File (EOF). Slow platform.')
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd], timeout)
else:
r, w, e = select_ignore_interrupts(
[self.child_fd], [], [], timeout
)
if not r:
if not self.isalive():
# Some platforms, such as Irix, will claim that their
# processes are alive; timeout on the select; and
# then finally admit that they are not alive.
self.flag_eof = True
raise EOF('End of File (EOF). Very slow platform.')
else:
raise TIMEOUT('Timeout exceeded.')
if self.child_fd in r:
return super(spawn, self).read_nonblocking(size)
raise ExceptionPexpect('Reached an unexpected state.')
|
python
|
def read_nonblocking(self, size=1, timeout=-1):
'''This reads at most size characters from the child application. It
includes a timeout. If the read does not complete within the timeout
period then a TIMEOUT exception is raised. If the end of file is read
then an EOF exception will be raised. If a logfile is specified, a
copy is written to that log.
If timeout is None then the read may block indefinitely.
If timeout is -1 then the self.timeout value is used. If timeout is 0
then the child is polled and if there is no data immediately ready
then this will raise a TIMEOUT exception.
The timeout refers only to the amount of time to read at least one
character. This is not affected by the 'size' parameter, so if you call
read_nonblocking(size=100, timeout=30) and only one character is
available right away then one character will be returned immediately.
It will not wait for 30 seconds for another 99 characters to come in.
This is a wrapper around os.read(). It uses select.select() to
implement the timeout. '''
if self.closed:
raise ValueError('I/O operation on closed file.')
if timeout == -1:
timeout = self.timeout
# Note that some systems such as Solaris do not give an EOF when
# the child dies. In fact, you can still try to read
# from the child_fd -- it will block forever or until TIMEOUT.
# For this case, I test isalive() before doing any reading.
# If isalive() is false, then I pretend that this is the same as EOF.
if not self.isalive():
# timeout of 0 means "poll"
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd], timeout)
else:
r, w, e = select_ignore_interrupts([self.child_fd], [], [], 0)
if not r:
self.flag_eof = True
raise EOF('End Of File (EOF). Braindead platform.')
elif self.__irix_hack:
# Irix takes a long time before it realizes a child was terminated.
# FIXME So does this mean Irix systems are forced to always have
# FIXME a 2 second delay when calling read_nonblocking? That sucks.
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd], timeout)
else:
r, w, e = select_ignore_interrupts([self.child_fd], [], [], 2)
if not r and not self.isalive():
self.flag_eof = True
raise EOF('End Of File (EOF). Slow platform.')
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd], timeout)
else:
r, w, e = select_ignore_interrupts(
[self.child_fd], [], [], timeout
)
if not r:
if not self.isalive():
# Some platforms, such as Irix, will claim that their
# processes are alive; timeout on the select; and
# then finally admit that they are not alive.
self.flag_eof = True
raise EOF('End of File (EOF). Very slow platform.')
else:
raise TIMEOUT('Timeout exceeded.')
if self.child_fd in r:
return super(spawn, self).read_nonblocking(size)
raise ExceptionPexpect('Reached an unexpected state.')
|
[
"def",
"read_nonblocking",
"(",
"self",
",",
"size",
"=",
"1",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"ValueError",
"(",
"'I/O operation on closed file.'",
")",
"if",
"timeout",
"==",
"-",
"1",
":",
"timeout",
"=",
"self",
".",
"timeout",
"# Note that some systems such as Solaris do not give an EOF when",
"# the child dies. In fact, you can still try to read",
"# from the child_fd -- it will block forever or until TIMEOUT.",
"# For this case, I test isalive() before doing any reading.",
"# If isalive() is false, then I pretend that this is the same as EOF.",
"if",
"not",
"self",
".",
"isalive",
"(",
")",
":",
"# timeout of 0 means \"poll\"",
"if",
"self",
".",
"use_poll",
":",
"r",
"=",
"poll_ignore_interrupts",
"(",
"[",
"self",
".",
"child_fd",
"]",
",",
"timeout",
")",
"else",
":",
"r",
",",
"w",
",",
"e",
"=",
"select_ignore_interrupts",
"(",
"[",
"self",
".",
"child_fd",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"0",
")",
"if",
"not",
"r",
":",
"self",
".",
"flag_eof",
"=",
"True",
"raise",
"EOF",
"(",
"'End Of File (EOF). Braindead platform.'",
")",
"elif",
"self",
".",
"__irix_hack",
":",
"# Irix takes a long time before it realizes a child was terminated.",
"# FIXME So does this mean Irix systems are forced to always have",
"# FIXME a 2 second delay when calling read_nonblocking? That sucks.",
"if",
"self",
".",
"use_poll",
":",
"r",
"=",
"poll_ignore_interrupts",
"(",
"[",
"self",
".",
"child_fd",
"]",
",",
"timeout",
")",
"else",
":",
"r",
",",
"w",
",",
"e",
"=",
"select_ignore_interrupts",
"(",
"[",
"self",
".",
"child_fd",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"2",
")",
"if",
"not",
"r",
"and",
"not",
"self",
".",
"isalive",
"(",
")",
":",
"self",
".",
"flag_eof",
"=",
"True",
"raise",
"EOF",
"(",
"'End Of File (EOF). Slow platform.'",
")",
"if",
"self",
".",
"use_poll",
":",
"r",
"=",
"poll_ignore_interrupts",
"(",
"[",
"self",
".",
"child_fd",
"]",
",",
"timeout",
")",
"else",
":",
"r",
",",
"w",
",",
"e",
"=",
"select_ignore_interrupts",
"(",
"[",
"self",
".",
"child_fd",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"timeout",
")",
"if",
"not",
"r",
":",
"if",
"not",
"self",
".",
"isalive",
"(",
")",
":",
"# Some platforms, such as Irix, will claim that their",
"# processes are alive; timeout on the select; and",
"# then finally admit that they are not alive.",
"self",
".",
"flag_eof",
"=",
"True",
"raise",
"EOF",
"(",
"'End of File (EOF). Very slow platform.'",
")",
"else",
":",
"raise",
"TIMEOUT",
"(",
"'Timeout exceeded.'",
")",
"if",
"self",
".",
"child_fd",
"in",
"r",
":",
"return",
"super",
"(",
"spawn",
",",
"self",
")",
".",
"read_nonblocking",
"(",
"size",
")",
"raise",
"ExceptionPexpect",
"(",
"'Reached an unexpected state.'",
")"
] |
This reads at most size characters from the child application. It
includes a timeout. If the read does not complete within the timeout
period then a TIMEOUT exception is raised. If the end of file is read
then an EOF exception will be raised. If a logfile is specified, a
copy is written to that log.
If timeout is None then the read may block indefinitely.
If timeout is -1 then the self.timeout value is used. If timeout is 0
then the child is polled and if there is no data immediately ready
then this will raise a TIMEOUT exception.
The timeout refers only to the amount of time to read at least one
character. This is not affected by the 'size' parameter, so if you call
read_nonblocking(size=100, timeout=30) and only one character is
available right away then one character will be returned immediately.
It will not wait for 30 seconds for another 99 characters to come in.
This is a wrapper around os.read(). It uses select.select() to
implement the timeout.
|
[
"This",
"reads",
"at",
"most",
"size",
"characters",
"from",
"the",
"child",
"application",
".",
"It",
"includes",
"a",
"timeout",
".",
"If",
"the",
"read",
"does",
"not",
"complete",
"within",
"the",
"timeout",
"period",
"then",
"a",
"TIMEOUT",
"exception",
"is",
"raised",
".",
"If",
"the",
"end",
"of",
"file",
"is",
"read",
"then",
"an",
"EOF",
"exception",
"will",
"be",
"raised",
".",
"If",
"a",
"logfile",
"is",
"specified",
"a",
"copy",
"is",
"written",
"to",
"that",
"log",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L415-L487
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pty_spawn.py
|
spawn.send
|
def send(self, s):
'''Sends string ``s`` to the child process, returning the number of
bytes written. If a logfile is specified, a copy is written to that
log.
The default terminal input mode is canonical processing unless set
otherwise by the child process. This allows backspace and other line
processing to be performed prior to transmitting to the receiving
program. As this is buffered, there is a limited size of such buffer.
On Linux systems, this is 4096 (defined by N_TTY_BUF_SIZE). All
other systems honor the POSIX.1 definition PC_MAX_CANON -- 1024
on OSX, 256 on OpenSolaris, and 1920 on FreeBSD.
This value may be discovered using fpathconf(3)::
>>> from os import fpathconf
>>> print(fpathconf(0, 'PC_MAX_CANON'))
256
On such a system, only 256 bytes may be received per line. Any
subsequent bytes received will be discarded. BEL (``'\a'``) is then
sent to output if IMAXBEL (termios.h) is set by the tty driver.
This is usually enabled by default. Linux does not honor this as
an option -- it behaves as though it is always set on.
Canonical input processing may be disabled altogether by executing
a shell, then stty(1), before executing the final program::
>>> bash = pexpect.spawn('/bin/bash', echo=False)
>>> bash.sendline('stty -icanon')
>>> bash.sendline('base64')
>>> bash.sendline('x' * 5000)
'''
if self.delaybeforesend is not None:
time.sleep(self.delaybeforesend)
s = self._coerce_send_string(s)
self._log(s, 'send')
b = self._encoder.encode(s, final=False)
return os.write(self.child_fd, b)
|
python
|
def send(self, s):
'''Sends string ``s`` to the child process, returning the number of
bytes written. If a logfile is specified, a copy is written to that
log.
The default terminal input mode is canonical processing unless set
otherwise by the child process. This allows backspace and other line
processing to be performed prior to transmitting to the receiving
program. As this is buffered, there is a limited size of such buffer.
On Linux systems, this is 4096 (defined by N_TTY_BUF_SIZE). All
other systems honor the POSIX.1 definition PC_MAX_CANON -- 1024
on OSX, 256 on OpenSolaris, and 1920 on FreeBSD.
This value may be discovered using fpathconf(3)::
>>> from os import fpathconf
>>> print(fpathconf(0, 'PC_MAX_CANON'))
256
On such a system, only 256 bytes may be received per line. Any
subsequent bytes received will be discarded. BEL (``'\a'``) is then
sent to output if IMAXBEL (termios.h) is set by the tty driver.
This is usually enabled by default. Linux does not honor this as
an option -- it behaves as though it is always set on.
Canonical input processing may be disabled altogether by executing
a shell, then stty(1), before executing the final program::
>>> bash = pexpect.spawn('/bin/bash', echo=False)
>>> bash.sendline('stty -icanon')
>>> bash.sendline('base64')
>>> bash.sendline('x' * 5000)
'''
if self.delaybeforesend is not None:
time.sleep(self.delaybeforesend)
s = self._coerce_send_string(s)
self._log(s, 'send')
b = self._encoder.encode(s, final=False)
return os.write(self.child_fd, b)
|
[
"def",
"send",
"(",
"self",
",",
"s",
")",
":",
"if",
"self",
".",
"delaybeforesend",
"is",
"not",
"None",
":",
"time",
".",
"sleep",
"(",
"self",
".",
"delaybeforesend",
")",
"s",
"=",
"self",
".",
"_coerce_send_string",
"(",
"s",
")",
"self",
".",
"_log",
"(",
"s",
",",
"'send'",
")",
"b",
"=",
"self",
".",
"_encoder",
".",
"encode",
"(",
"s",
",",
"final",
"=",
"False",
")",
"return",
"os",
".",
"write",
"(",
"self",
".",
"child_fd",
",",
"b",
")"
] |
Sends string ``s`` to the child process, returning the number of
bytes written. If a logfile is specified, a copy is written to that
log.
The default terminal input mode is canonical processing unless set
otherwise by the child process. This allows backspace and other line
processing to be performed prior to transmitting to the receiving
program. As this is buffered, there is a limited size of such buffer.
On Linux systems, this is 4096 (defined by N_TTY_BUF_SIZE). All
other systems honor the POSIX.1 definition PC_MAX_CANON -- 1024
on OSX, 256 on OpenSolaris, and 1920 on FreeBSD.
This value may be discovered using fpathconf(3)::
>>> from os import fpathconf
>>> print(fpathconf(0, 'PC_MAX_CANON'))
256
On such a system, only 256 bytes may be received per line. Any
subsequent bytes received will be discarded. BEL (``'\a'``) is then
sent to output if IMAXBEL (termios.h) is set by the tty driver.
This is usually enabled by default. Linux does not honor this as
an option -- it behaves as though it is always set on.
Canonical input processing may be disabled altogether by executing
a shell, then stty(1), before executing the final program::
>>> bash = pexpect.spawn('/bin/bash', echo=False)
>>> bash.sendline('stty -icanon')
>>> bash.sendline('base64')
>>> bash.sendline('x' * 5000)
|
[
"Sends",
"string",
"s",
"to",
"the",
"child",
"process",
"returning",
"the",
"number",
"of",
"bytes",
"written",
".",
"If",
"a",
"logfile",
"is",
"specified",
"a",
"copy",
"is",
"written",
"to",
"that",
"log",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L504-L546
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pty_spawn.py
|
spawn.sendline
|
def sendline(self, s=''):
'''Wraps send(), sending string ``s`` to child process, with
``os.linesep`` automatically appended. Returns number of bytes
written. Only a limited number of bytes may be sent for each
line in the default terminal mode, see docstring of :meth:`send`.
'''
s = self._coerce_send_string(s)
return self.send(s + self.linesep)
|
python
|
def sendline(self, s=''):
'''Wraps send(), sending string ``s`` to child process, with
``os.linesep`` automatically appended. Returns number of bytes
written. Only a limited number of bytes may be sent for each
line in the default terminal mode, see docstring of :meth:`send`.
'''
s = self._coerce_send_string(s)
return self.send(s + self.linesep)
|
[
"def",
"sendline",
"(",
"self",
",",
"s",
"=",
"''",
")",
":",
"s",
"=",
"self",
".",
"_coerce_send_string",
"(",
"s",
")",
"return",
"self",
".",
"send",
"(",
"s",
"+",
"self",
".",
"linesep",
")"
] |
Wraps send(), sending string ``s`` to child process, with
``os.linesep`` automatically appended. Returns number of bytes
written. Only a limited number of bytes may be sent for each
line in the default terminal mode, see docstring of :meth:`send`.
|
[
"Wraps",
"send",
"()",
"sending",
"string",
"s",
"to",
"child",
"process",
"with",
"os",
".",
"linesep",
"automatically",
"appended",
".",
"Returns",
"number",
"of",
"bytes",
"written",
".",
"Only",
"a",
"limited",
"number",
"of",
"bytes",
"may",
"be",
"sent",
"for",
"each",
"line",
"in",
"the",
"default",
"terminal",
"mode",
"see",
"docstring",
"of",
":",
"meth",
":",
"send",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L548-L555
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pty_spawn.py
|
spawn._log_control
|
def _log_control(self, s):
"""Write control characters to the appropriate log files"""
if self.encoding is not None:
s = s.decode(self.encoding, 'replace')
self._log(s, 'send')
|
python
|
def _log_control(self, s):
"""Write control characters to the appropriate log files"""
if self.encoding is not None:
s = s.decode(self.encoding, 'replace')
self._log(s, 'send')
|
[
"def",
"_log_control",
"(",
"self",
",",
"s",
")",
":",
"if",
"self",
".",
"encoding",
"is",
"not",
"None",
":",
"s",
"=",
"s",
".",
"decode",
"(",
"self",
".",
"encoding",
",",
"'replace'",
")",
"self",
".",
"_log",
"(",
"s",
",",
"'send'",
")"
] |
Write control characters to the appropriate log files
|
[
"Write",
"control",
"characters",
"to",
"the",
"appropriate",
"log",
"files"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L557-L561
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pty_spawn.py
|
spawn.sendcontrol
|
def sendcontrol(self, char):
'''Helper method that wraps send() with mnemonic access for sending control
character to the child (such as Ctrl-C or Ctrl-D). For example, to send
Ctrl-G (ASCII 7, bell, '\a')::
child.sendcontrol('g')
See also, sendintr() and sendeof().
'''
n, byte = self.ptyproc.sendcontrol(char)
self._log_control(byte)
return n
|
python
|
def sendcontrol(self, char):
'''Helper method that wraps send() with mnemonic access for sending control
character to the child (such as Ctrl-C or Ctrl-D). For example, to send
Ctrl-G (ASCII 7, bell, '\a')::
child.sendcontrol('g')
See also, sendintr() and sendeof().
'''
n, byte = self.ptyproc.sendcontrol(char)
self._log_control(byte)
return n
|
[
"def",
"sendcontrol",
"(",
"self",
",",
"char",
")",
":",
"n",
",",
"byte",
"=",
"self",
".",
"ptyproc",
".",
"sendcontrol",
"(",
"char",
")",
"self",
".",
"_log_control",
"(",
"byte",
")",
"return",
"n"
] |
Helper method that wraps send() with mnemonic access for sending control
character to the child (such as Ctrl-C or Ctrl-D). For example, to send
Ctrl-G (ASCII 7, bell, '\a')::
child.sendcontrol('g')
See also, sendintr() and sendeof().
|
[
"Helper",
"method",
"that",
"wraps",
"send",
"()",
"with",
"mnemonic",
"access",
"for",
"sending",
"control",
"character",
"to",
"the",
"child",
"(",
"such",
"as",
"Ctrl",
"-",
"C",
"or",
"Ctrl",
"-",
"D",
")",
".",
"For",
"example",
"to",
"send",
"Ctrl",
"-",
"G",
"(",
"ASCII",
"7",
"bell",
"\\",
"a",
")",
"::"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L563-L574
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pty_spawn.py
|
spawn.sendeof
|
def sendeof(self):
'''This sends an EOF to the child. This sends a character which causes
the pending parent output buffer to be sent to the waiting child
program without waiting for end-of-line. If it is the first character
of the line, the read() in the user program returns 0, which signifies
end-of-file. This means to work as expected a sendeof() has to be
called at the beginning of a line. This method does not send a newline.
It is the responsibility of the caller to ensure the eof is sent at the
beginning of a line. '''
n, byte = self.ptyproc.sendeof()
self._log_control(byte)
|
python
|
def sendeof(self):
'''This sends an EOF to the child. This sends a character which causes
the pending parent output buffer to be sent to the waiting child
program without waiting for end-of-line. If it is the first character
of the line, the read() in the user program returns 0, which signifies
end-of-file. This means to work as expected a sendeof() has to be
called at the beginning of a line. This method does not send a newline.
It is the responsibility of the caller to ensure the eof is sent at the
beginning of a line. '''
n, byte = self.ptyproc.sendeof()
self._log_control(byte)
|
[
"def",
"sendeof",
"(",
"self",
")",
":",
"n",
",",
"byte",
"=",
"self",
".",
"ptyproc",
".",
"sendeof",
"(",
")",
"self",
".",
"_log_control",
"(",
"byte",
")"
] |
This sends an EOF to the child. This sends a character which causes
the pending parent output buffer to be sent to the waiting child
program without waiting for end-of-line. If it is the first character
of the line, the read() in the user program returns 0, which signifies
end-of-file. This means to work as expected a sendeof() has to be
called at the beginning of a line. This method does not send a newline.
It is the responsibility of the caller to ensure the eof is sent at the
beginning of a line.
|
[
"This",
"sends",
"an",
"EOF",
"to",
"the",
"child",
".",
"This",
"sends",
"a",
"character",
"which",
"causes",
"the",
"pending",
"parent",
"output",
"buffer",
"to",
"be",
"sent",
"to",
"the",
"waiting",
"child",
"program",
"without",
"waiting",
"for",
"end",
"-",
"of",
"-",
"line",
".",
"If",
"it",
"is",
"the",
"first",
"character",
"of",
"the",
"line",
"the",
"read",
"()",
"in",
"the",
"user",
"program",
"returns",
"0",
"which",
"signifies",
"end",
"-",
"of",
"-",
"file",
".",
"This",
"means",
"to",
"work",
"as",
"expected",
"a",
"sendeof",
"()",
"has",
"to",
"be",
"called",
"at",
"the",
"beginning",
"of",
"a",
"line",
".",
"This",
"method",
"does",
"not",
"send",
"a",
"newline",
".",
"It",
"is",
"the",
"responsibility",
"of",
"the",
"caller",
"to",
"ensure",
"the",
"eof",
"is",
"sent",
"at",
"the",
"beginning",
"of",
"a",
"line",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L576-L587
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pty_spawn.py
|
spawn.sendintr
|
def sendintr(self):
'''This sends a SIGINT to the child. It does not require
the SIGINT to be the first character on a line. '''
n, byte = self.ptyproc.sendintr()
self._log_control(byte)
|
python
|
def sendintr(self):
'''This sends a SIGINT to the child. It does not require
the SIGINT to be the first character on a line. '''
n, byte = self.ptyproc.sendintr()
self._log_control(byte)
|
[
"def",
"sendintr",
"(",
"self",
")",
":",
"n",
",",
"byte",
"=",
"self",
".",
"ptyproc",
".",
"sendintr",
"(",
")",
"self",
".",
"_log_control",
"(",
"byte",
")"
] |
This sends a SIGINT to the child. It does not require
the SIGINT to be the first character on a line.
|
[
"This",
"sends",
"a",
"SIGINT",
"to",
"the",
"child",
".",
"It",
"does",
"not",
"require",
"the",
"SIGINT",
"to",
"be",
"the",
"first",
"character",
"on",
"a",
"line",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L589-L594
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pty_spawn.py
|
spawn.wait
|
def wait(self):
'''This waits until the child exits. This is a blocking call. This will
not read any data from the child, so this will block forever if the
child has unread output and has terminated. In other words, the child
may have printed output then called exit(), but, the child is
technically still alive until its output is read by the parent.
This method is non-blocking if :meth:`wait` has already been called
previously or :meth:`isalive` method returns False. It simply returns
the previously determined exit status.
'''
ptyproc = self.ptyproc
with _wrap_ptyprocess_err():
# exception may occur if "Is some other process attempting
# "job control with our child pid?"
exitstatus = ptyproc.wait()
self.status = ptyproc.status
self.exitstatus = ptyproc.exitstatus
self.signalstatus = ptyproc.signalstatus
self.terminated = True
return exitstatus
|
python
|
def wait(self):
'''This waits until the child exits. This is a blocking call. This will
not read any data from the child, so this will block forever if the
child has unread output and has terminated. In other words, the child
may have printed output then called exit(), but, the child is
technically still alive until its output is read by the parent.
This method is non-blocking if :meth:`wait` has already been called
previously or :meth:`isalive` method returns False. It simply returns
the previously determined exit status.
'''
ptyproc = self.ptyproc
with _wrap_ptyprocess_err():
# exception may occur if "Is some other process attempting
# "job control with our child pid?"
exitstatus = ptyproc.wait()
self.status = ptyproc.status
self.exitstatus = ptyproc.exitstatus
self.signalstatus = ptyproc.signalstatus
self.terminated = True
return exitstatus
|
[
"def",
"wait",
"(",
"self",
")",
":",
"ptyproc",
"=",
"self",
".",
"ptyproc",
"with",
"_wrap_ptyprocess_err",
"(",
")",
":",
"# exception may occur if \"Is some other process attempting",
"# \"job control with our child pid?\"",
"exitstatus",
"=",
"ptyproc",
".",
"wait",
"(",
")",
"self",
".",
"status",
"=",
"ptyproc",
".",
"status",
"self",
".",
"exitstatus",
"=",
"ptyproc",
".",
"exitstatus",
"self",
".",
"signalstatus",
"=",
"ptyproc",
".",
"signalstatus",
"self",
".",
"terminated",
"=",
"True",
"return",
"exitstatus"
] |
This waits until the child exits. This is a blocking call. This will
not read any data from the child, so this will block forever if the
child has unread output and has terminated. In other words, the child
may have printed output then called exit(), but, the child is
technically still alive until its output is read by the parent.
This method is non-blocking if :meth:`wait` has already been called
previously or :meth:`isalive` method returns False. It simply returns
the previously determined exit status.
|
[
"This",
"waits",
"until",
"the",
"child",
"exits",
".",
"This",
"is",
"a",
"blocking",
"call",
".",
"This",
"will",
"not",
"read",
"any",
"data",
"from",
"the",
"child",
"so",
"this",
"will",
"block",
"forever",
"if",
"the",
"child",
"has",
"unread",
"output",
"and",
"has",
"terminated",
".",
"In",
"other",
"words",
"the",
"child",
"may",
"have",
"printed",
"output",
"then",
"called",
"exit",
"()",
"but",
"the",
"child",
"is",
"technically",
"still",
"alive",
"until",
"its",
"output",
"is",
"read",
"by",
"the",
"parent",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L649-L671
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pty_spawn.py
|
spawn.isalive
|
def isalive(self):
'''This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exitstatus or signalstatus of the child. This returns True if the child
process appears to be running or False if not. It can take literally
SECONDS for Solaris to return the right status. '''
ptyproc = self.ptyproc
with _wrap_ptyprocess_err():
alive = ptyproc.isalive()
if not alive:
self.status = ptyproc.status
self.exitstatus = ptyproc.exitstatus
self.signalstatus = ptyproc.signalstatus
self.terminated = True
return alive
|
python
|
def isalive(self):
'''This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exitstatus or signalstatus of the child. This returns True if the child
process appears to be running or False if not. It can take literally
SECONDS for Solaris to return the right status. '''
ptyproc = self.ptyproc
with _wrap_ptyprocess_err():
alive = ptyproc.isalive()
if not alive:
self.status = ptyproc.status
self.exitstatus = ptyproc.exitstatus
self.signalstatus = ptyproc.signalstatus
self.terminated = True
return alive
|
[
"def",
"isalive",
"(",
"self",
")",
":",
"ptyproc",
"=",
"self",
".",
"ptyproc",
"with",
"_wrap_ptyprocess_err",
"(",
")",
":",
"alive",
"=",
"ptyproc",
".",
"isalive",
"(",
")",
"if",
"not",
"alive",
":",
"self",
".",
"status",
"=",
"ptyproc",
".",
"status",
"self",
".",
"exitstatus",
"=",
"ptyproc",
".",
"exitstatus",
"self",
".",
"signalstatus",
"=",
"ptyproc",
".",
"signalstatus",
"self",
".",
"terminated",
"=",
"True",
"return",
"alive"
] |
This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exitstatus or signalstatus of the child. This returns True if the child
process appears to be running or False if not. It can take literally
SECONDS for Solaris to return the right status.
|
[
"This",
"tests",
"if",
"the",
"child",
"process",
"is",
"running",
"or",
"not",
".",
"This",
"is",
"non",
"-",
"blocking",
".",
"If",
"the",
"child",
"was",
"terminated",
"then",
"this",
"will",
"read",
"the",
"exitstatus",
"or",
"signalstatus",
"of",
"the",
"child",
".",
"This",
"returns",
"True",
"if",
"the",
"child",
"process",
"appears",
"to",
"be",
"running",
"or",
"False",
"if",
"not",
".",
"It",
"can",
"take",
"literally",
"SECONDS",
"for",
"Solaris",
"to",
"return",
"the",
"right",
"status",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L673-L690
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pty_spawn.py
|
spawn.interact
|
def interact(self, escape_character=chr(29),
input_filter=None, output_filter=None):
'''This gives control of the child process to the interactive user (the
human at the keyboard). Keystrokes are sent to the child process, and
the stdout and stderr output of the child process is printed. This
simply echos the child stdout and child stderr to the real stdout and
it echos the real stdin to the child stdin. When the user types the
escape_character this method will return None. The escape_character
will not be transmitted. The default for escape_character is
entered as ``Ctrl - ]``, the very same as BSD telnet. To prevent
escaping, escape_character may be set to None.
If a logfile is specified, then the data sent and received from the
child process in interact mode is duplicated to the given log.
You may pass in optional input and output filter functions. These
functions should take a string and return a string. The output_filter
will be passed all the output from the child process. The input_filter
will be passed all the keyboard input from the user. The input_filter
is run BEFORE the check for the escape_character.
Note that if you change the window size of the parent the SIGWINCH
signal will not be passed through to the child. If you want the child
window size to change when the parent's window size changes then do
something like the following example::
import pexpect, struct, fcntl, termios, signal, sys
def sigwinch_passthrough (sig, data):
s = struct.pack("HHHH", 0, 0, 0, 0)
a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(),
termios.TIOCGWINSZ , s))
if not p.closed:
p.setwinsize(a[0],a[1])
# Note this 'p' is global and used in sigwinch_passthrough.
p = pexpect.spawn('/bin/bash')
signal.signal(signal.SIGWINCH, sigwinch_passthrough)
p.interact()
'''
# Flush the buffer.
self.write_to_stdout(self.buffer)
self.stdout.flush()
self._buffer = self.buffer_type()
mode = tty.tcgetattr(self.STDIN_FILENO)
tty.setraw(self.STDIN_FILENO)
if escape_character is not None and PY3:
escape_character = escape_character.encode('latin-1')
try:
self.__interact_copy(escape_character, input_filter, output_filter)
finally:
tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
|
python
|
def interact(self, escape_character=chr(29),
input_filter=None, output_filter=None):
'''This gives control of the child process to the interactive user (the
human at the keyboard). Keystrokes are sent to the child process, and
the stdout and stderr output of the child process is printed. This
simply echos the child stdout and child stderr to the real stdout and
it echos the real stdin to the child stdin. When the user types the
escape_character this method will return None. The escape_character
will not be transmitted. The default for escape_character is
entered as ``Ctrl - ]``, the very same as BSD telnet. To prevent
escaping, escape_character may be set to None.
If a logfile is specified, then the data sent and received from the
child process in interact mode is duplicated to the given log.
You may pass in optional input and output filter functions. These
functions should take a string and return a string. The output_filter
will be passed all the output from the child process. The input_filter
will be passed all the keyboard input from the user. The input_filter
is run BEFORE the check for the escape_character.
Note that if you change the window size of the parent the SIGWINCH
signal will not be passed through to the child. If you want the child
window size to change when the parent's window size changes then do
something like the following example::
import pexpect, struct, fcntl, termios, signal, sys
def sigwinch_passthrough (sig, data):
s = struct.pack("HHHH", 0, 0, 0, 0)
a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(),
termios.TIOCGWINSZ , s))
if not p.closed:
p.setwinsize(a[0],a[1])
# Note this 'p' is global and used in sigwinch_passthrough.
p = pexpect.spawn('/bin/bash')
signal.signal(signal.SIGWINCH, sigwinch_passthrough)
p.interact()
'''
# Flush the buffer.
self.write_to_stdout(self.buffer)
self.stdout.flush()
self._buffer = self.buffer_type()
mode = tty.tcgetattr(self.STDIN_FILENO)
tty.setraw(self.STDIN_FILENO)
if escape_character is not None and PY3:
escape_character = escape_character.encode('latin-1')
try:
self.__interact_copy(escape_character, input_filter, output_filter)
finally:
tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
|
[
"def",
"interact",
"(",
"self",
",",
"escape_character",
"=",
"chr",
"(",
"29",
")",
",",
"input_filter",
"=",
"None",
",",
"output_filter",
"=",
"None",
")",
":",
"# Flush the buffer.",
"self",
".",
"write_to_stdout",
"(",
"self",
".",
"buffer",
")",
"self",
".",
"stdout",
".",
"flush",
"(",
")",
"self",
".",
"_buffer",
"=",
"self",
".",
"buffer_type",
"(",
")",
"mode",
"=",
"tty",
".",
"tcgetattr",
"(",
"self",
".",
"STDIN_FILENO",
")",
"tty",
".",
"setraw",
"(",
"self",
".",
"STDIN_FILENO",
")",
"if",
"escape_character",
"is",
"not",
"None",
"and",
"PY3",
":",
"escape_character",
"=",
"escape_character",
".",
"encode",
"(",
"'latin-1'",
")",
"try",
":",
"self",
".",
"__interact_copy",
"(",
"escape_character",
",",
"input_filter",
",",
"output_filter",
")",
"finally",
":",
"tty",
".",
"tcsetattr",
"(",
"self",
".",
"STDIN_FILENO",
",",
"tty",
".",
"TCSAFLUSH",
",",
"mode",
")"
] |
This gives control of the child process to the interactive user (the
human at the keyboard). Keystrokes are sent to the child process, and
the stdout and stderr output of the child process is printed. This
simply echos the child stdout and child stderr to the real stdout and
it echos the real stdin to the child stdin. When the user types the
escape_character this method will return None. The escape_character
will not be transmitted. The default for escape_character is
entered as ``Ctrl - ]``, the very same as BSD telnet. To prevent
escaping, escape_character may be set to None.
If a logfile is specified, then the data sent and received from the
child process in interact mode is duplicated to the given log.
You may pass in optional input and output filter functions. These
functions should take a string and return a string. The output_filter
will be passed all the output from the child process. The input_filter
will be passed all the keyboard input from the user. The input_filter
is run BEFORE the check for the escape_character.
Note that if you change the window size of the parent the SIGWINCH
signal will not be passed through to the child. If you want the child
window size to change when the parent's window size changes then do
something like the following example::
import pexpect, struct, fcntl, termios, signal, sys
def sigwinch_passthrough (sig, data):
s = struct.pack("HHHH", 0, 0, 0, 0)
a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(),
termios.TIOCGWINSZ , s))
if not p.closed:
p.setwinsize(a[0],a[1])
# Note this 'p' is global and used in sigwinch_passthrough.
p = pexpect.spawn('/bin/bash')
signal.signal(signal.SIGWINCH, sigwinch_passthrough)
p.interact()
|
[
"This",
"gives",
"control",
"of",
"the",
"child",
"process",
"to",
"the",
"interactive",
"user",
"(",
"the",
"human",
"at",
"the",
"keyboard",
")",
".",
"Keystrokes",
"are",
"sent",
"to",
"the",
"child",
"process",
"and",
"the",
"stdout",
"and",
"stderr",
"output",
"of",
"the",
"child",
"process",
"is",
"printed",
".",
"This",
"simply",
"echos",
"the",
"child",
"stdout",
"and",
"child",
"stderr",
"to",
"the",
"real",
"stdout",
"and",
"it",
"echos",
"the",
"real",
"stdin",
"to",
"the",
"child",
"stdin",
".",
"When",
"the",
"user",
"types",
"the",
"escape_character",
"this",
"method",
"will",
"return",
"None",
".",
"The",
"escape_character",
"will",
"not",
"be",
"transmitted",
".",
"The",
"default",
"for",
"escape_character",
"is",
"entered",
"as",
"Ctrl",
"-",
"]",
"the",
"very",
"same",
"as",
"BSD",
"telnet",
".",
"To",
"prevent",
"escaping",
"escape_character",
"may",
"be",
"set",
"to",
"None",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L716-L768
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pty_spawn.py
|
spawn.__interact_writen
|
def __interact_writen(self, fd, data):
'''This is used by the interact() method.
'''
while data != b'' and self.isalive():
n = os.write(fd, data)
data = data[n:]
|
python
|
def __interact_writen(self, fd, data):
'''This is used by the interact() method.
'''
while data != b'' and self.isalive():
n = os.write(fd, data)
data = data[n:]
|
[
"def",
"__interact_writen",
"(",
"self",
",",
"fd",
",",
"data",
")",
":",
"while",
"data",
"!=",
"b''",
"and",
"self",
".",
"isalive",
"(",
")",
":",
"n",
"=",
"os",
".",
"write",
"(",
"fd",
",",
"data",
")",
"data",
"=",
"data",
"[",
"n",
":",
"]"
] |
This is used by the interact() method.
|
[
"This",
"is",
"used",
"by",
"the",
"interact",
"()",
"method",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L770-L776
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pty_spawn.py
|
spawn.__interact_copy
|
def __interact_copy(
self, escape_character=None, input_filter=None, output_filter=None
):
'''This is used by the interact() method.
'''
while self.isalive():
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd, self.STDIN_FILENO])
else:
r, w, e = select_ignore_interrupts(
[self.child_fd, self.STDIN_FILENO], [], []
)
if self.child_fd in r:
try:
data = self.__interact_read(self.child_fd)
except OSError as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
break
raise
if data == b'':
# BSD-style EOF
break
if output_filter:
data = output_filter(data)
self._log(data, 'read')
os.write(self.STDOUT_FILENO, data)
if self.STDIN_FILENO in r:
data = self.__interact_read(self.STDIN_FILENO)
if input_filter:
data = input_filter(data)
i = -1
if escape_character is not None:
i = data.rfind(escape_character)
if i != -1:
data = data[:i]
if data:
self._log(data, 'send')
self.__interact_writen(self.child_fd, data)
break
self._log(data, 'send')
self.__interact_writen(self.child_fd, data)
|
python
|
def __interact_copy(
self, escape_character=None, input_filter=None, output_filter=None
):
'''This is used by the interact() method.
'''
while self.isalive():
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd, self.STDIN_FILENO])
else:
r, w, e = select_ignore_interrupts(
[self.child_fd, self.STDIN_FILENO], [], []
)
if self.child_fd in r:
try:
data = self.__interact_read(self.child_fd)
except OSError as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
break
raise
if data == b'':
# BSD-style EOF
break
if output_filter:
data = output_filter(data)
self._log(data, 'read')
os.write(self.STDOUT_FILENO, data)
if self.STDIN_FILENO in r:
data = self.__interact_read(self.STDIN_FILENO)
if input_filter:
data = input_filter(data)
i = -1
if escape_character is not None:
i = data.rfind(escape_character)
if i != -1:
data = data[:i]
if data:
self._log(data, 'send')
self.__interact_writen(self.child_fd, data)
break
self._log(data, 'send')
self.__interact_writen(self.child_fd, data)
|
[
"def",
"__interact_copy",
"(",
"self",
",",
"escape_character",
"=",
"None",
",",
"input_filter",
"=",
"None",
",",
"output_filter",
"=",
"None",
")",
":",
"while",
"self",
".",
"isalive",
"(",
")",
":",
"if",
"self",
".",
"use_poll",
":",
"r",
"=",
"poll_ignore_interrupts",
"(",
"[",
"self",
".",
"child_fd",
",",
"self",
".",
"STDIN_FILENO",
"]",
")",
"else",
":",
"r",
",",
"w",
",",
"e",
"=",
"select_ignore_interrupts",
"(",
"[",
"self",
".",
"child_fd",
",",
"self",
".",
"STDIN_FILENO",
"]",
",",
"[",
"]",
",",
"[",
"]",
")",
"if",
"self",
".",
"child_fd",
"in",
"r",
":",
"try",
":",
"data",
"=",
"self",
".",
"__interact_read",
"(",
"self",
".",
"child_fd",
")",
"except",
"OSError",
"as",
"err",
":",
"if",
"err",
".",
"args",
"[",
"0",
"]",
"==",
"errno",
".",
"EIO",
":",
"# Linux-style EOF",
"break",
"raise",
"if",
"data",
"==",
"b''",
":",
"# BSD-style EOF",
"break",
"if",
"output_filter",
":",
"data",
"=",
"output_filter",
"(",
"data",
")",
"self",
".",
"_log",
"(",
"data",
",",
"'read'",
")",
"os",
".",
"write",
"(",
"self",
".",
"STDOUT_FILENO",
",",
"data",
")",
"if",
"self",
".",
"STDIN_FILENO",
"in",
"r",
":",
"data",
"=",
"self",
".",
"__interact_read",
"(",
"self",
".",
"STDIN_FILENO",
")",
"if",
"input_filter",
":",
"data",
"=",
"input_filter",
"(",
"data",
")",
"i",
"=",
"-",
"1",
"if",
"escape_character",
"is",
"not",
"None",
":",
"i",
"=",
"data",
".",
"rfind",
"(",
"escape_character",
")",
"if",
"i",
"!=",
"-",
"1",
":",
"data",
"=",
"data",
"[",
":",
"i",
"]",
"if",
"data",
":",
"self",
".",
"_log",
"(",
"data",
",",
"'send'",
")",
"self",
".",
"__interact_writen",
"(",
"self",
".",
"child_fd",
",",
"data",
")",
"break",
"self",
".",
"_log",
"(",
"data",
",",
"'send'",
")",
"self",
".",
"__interact_writen",
"(",
"self",
".",
"child_fd",
",",
"data",
")"
] |
This is used by the interact() method.
|
[
"This",
"is",
"used",
"by",
"the",
"interact",
"()",
"method",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L784-L827
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
extras_to_string
|
def extras_to_string(extras):
# type: (Iterable[S]) -> S
"""Turn a list of extras into a string"""
if isinstance(extras, six.string_types):
if extras.startswith("["):
return extras
else:
extras = [extras]
if not extras:
return ""
return "[{0}]".format(",".join(sorted(set(extras))))
|
python
|
def extras_to_string(extras):
# type: (Iterable[S]) -> S
"""Turn a list of extras into a string"""
if isinstance(extras, six.string_types):
if extras.startswith("["):
return extras
else:
extras = [extras]
if not extras:
return ""
return "[{0}]".format(",".join(sorted(set(extras))))
|
[
"def",
"extras_to_string",
"(",
"extras",
")",
":",
"# type: (Iterable[S]) -> S",
"if",
"isinstance",
"(",
"extras",
",",
"six",
".",
"string_types",
")",
":",
"if",
"extras",
".",
"startswith",
"(",
"\"[\"",
")",
":",
"return",
"extras",
"else",
":",
"extras",
"=",
"[",
"extras",
"]",
"if",
"not",
"extras",
":",
"return",
"\"\"",
"return",
"\"[{0}]\"",
".",
"format",
"(",
"\",\"",
".",
"join",
"(",
"sorted",
"(",
"set",
"(",
"extras",
")",
")",
")",
")"
] |
Turn a list of extras into a string
|
[
"Turn",
"a",
"list",
"of",
"extras",
"into",
"a",
"string"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L143-L153
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
parse_extras
|
def parse_extras(extras_str):
# type: (AnyStr) -> List[AnyStr]
"""
Turn a string of extras into a parsed extras list
"""
from pkg_resources import Requirement
extras = Requirement.parse("fakepkg{0}".format(extras_to_string(extras_str))).extras
return sorted(dedup([extra.lower() for extra in extras]))
|
python
|
def parse_extras(extras_str):
# type: (AnyStr) -> List[AnyStr]
"""
Turn a string of extras into a parsed extras list
"""
from pkg_resources import Requirement
extras = Requirement.parse("fakepkg{0}".format(extras_to_string(extras_str))).extras
return sorted(dedup([extra.lower() for extra in extras]))
|
[
"def",
"parse_extras",
"(",
"extras_str",
")",
":",
"# type: (AnyStr) -> List[AnyStr]",
"from",
"pkg_resources",
"import",
"Requirement",
"extras",
"=",
"Requirement",
".",
"parse",
"(",
"\"fakepkg{0}\"",
".",
"format",
"(",
"extras_to_string",
"(",
"extras_str",
")",
")",
")",
".",
"extras",
"return",
"sorted",
"(",
"dedup",
"(",
"[",
"extra",
".",
"lower",
"(",
")",
"for",
"extra",
"in",
"extras",
"]",
")",
")"
] |
Turn a string of extras into a parsed extras list
|
[
"Turn",
"a",
"string",
"of",
"extras",
"into",
"a",
"parsed",
"extras",
"list"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L156-L165
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
specs_to_string
|
def specs_to_string(specs):
# type: (List[Union[STRING_TYPE, Specifier]]) -> AnyStr
"""
Turn a list of specifier tuples into a string
"""
if specs:
if isinstance(specs, six.string_types):
return specs
try:
extras = ",".join(["".join(spec) for spec in specs])
except TypeError:
extras = ",".join(["".join(spec._spec) for spec in specs]) # type: ignore
return extras
return ""
|
python
|
def specs_to_string(specs):
# type: (List[Union[STRING_TYPE, Specifier]]) -> AnyStr
"""
Turn a list of specifier tuples into a string
"""
if specs:
if isinstance(specs, six.string_types):
return specs
try:
extras = ",".join(["".join(spec) for spec in specs])
except TypeError:
extras = ",".join(["".join(spec._spec) for spec in specs]) # type: ignore
return extras
return ""
|
[
"def",
"specs_to_string",
"(",
"specs",
")",
":",
"# type: (List[Union[STRING_TYPE, Specifier]]) -> AnyStr",
"if",
"specs",
":",
"if",
"isinstance",
"(",
"specs",
",",
"six",
".",
"string_types",
")",
":",
"return",
"specs",
"try",
":",
"extras",
"=",
"\",\"",
".",
"join",
"(",
"[",
"\"\"",
".",
"join",
"(",
"spec",
")",
"for",
"spec",
"in",
"specs",
"]",
")",
"except",
"TypeError",
":",
"extras",
"=",
"\",\"",
".",
"join",
"(",
"[",
"\"\"",
".",
"join",
"(",
"spec",
".",
"_spec",
")",
"for",
"spec",
"in",
"specs",
"]",
")",
"# type: ignore",
"return",
"extras",
"return",
"\"\""
] |
Turn a list of specifier tuples into a string
|
[
"Turn",
"a",
"list",
"of",
"specifier",
"tuples",
"into",
"a",
"string"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L168-L182
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
convert_direct_url_to_url
|
def convert_direct_url_to_url(direct_url):
# type: (AnyStr) -> AnyStr
"""
Given a direct url as defined by *PEP 508*, convert to a :class:`~pip_shims.shims.Link`
compatible URL by moving the name and extras into an **egg_fragment**.
:param str direct_url: A pep-508 compliant direct url.
:return: A reformatted URL for use with Link objects and :class:`~pip_shims.shims.InstallRequirement` objects.
:rtype: AnyStr
"""
direct_match = DIRECT_URL_RE.match(direct_url) # type: Optional[Match]
if direct_match is None:
url_match = URL_RE.match(direct_url)
if url_match or is_valid_url(direct_url):
return direct_url
match_dict = (
{}
) # type: Dict[STRING_TYPE, Union[Tuple[STRING_TYPE, ...], STRING_TYPE]]
if direct_match is not None:
match_dict = direct_match.groupdict() # type: ignore
if not match_dict:
raise ValueError(
"Failed converting value to normal URL, is it a direct URL? {0!r}".format(
direct_url
)
)
url_segments = [match_dict.get(s) for s in ("scheme", "host", "path", "pathsep")]
url = "" # type: STRING_TYPE
url = "".join([s for s in url_segments if s is not None]) # type: ignore
new_url = build_vcs_uri(
None,
url,
ref=match_dict.get("ref"),
name=match_dict.get("name"),
extras=match_dict.get("extras"),
subdirectory=match_dict.get("subdirectory"),
)
return new_url
|
python
|
def convert_direct_url_to_url(direct_url):
# type: (AnyStr) -> AnyStr
"""
Given a direct url as defined by *PEP 508*, convert to a :class:`~pip_shims.shims.Link`
compatible URL by moving the name and extras into an **egg_fragment**.
:param str direct_url: A pep-508 compliant direct url.
:return: A reformatted URL for use with Link objects and :class:`~pip_shims.shims.InstallRequirement` objects.
:rtype: AnyStr
"""
direct_match = DIRECT_URL_RE.match(direct_url) # type: Optional[Match]
if direct_match is None:
url_match = URL_RE.match(direct_url)
if url_match or is_valid_url(direct_url):
return direct_url
match_dict = (
{}
) # type: Dict[STRING_TYPE, Union[Tuple[STRING_TYPE, ...], STRING_TYPE]]
if direct_match is not None:
match_dict = direct_match.groupdict() # type: ignore
if not match_dict:
raise ValueError(
"Failed converting value to normal URL, is it a direct URL? {0!r}".format(
direct_url
)
)
url_segments = [match_dict.get(s) for s in ("scheme", "host", "path", "pathsep")]
url = "" # type: STRING_TYPE
url = "".join([s for s in url_segments if s is not None]) # type: ignore
new_url = build_vcs_uri(
None,
url,
ref=match_dict.get("ref"),
name=match_dict.get("name"),
extras=match_dict.get("extras"),
subdirectory=match_dict.get("subdirectory"),
)
return new_url
|
[
"def",
"convert_direct_url_to_url",
"(",
"direct_url",
")",
":",
"# type: (AnyStr) -> AnyStr",
"direct_match",
"=",
"DIRECT_URL_RE",
".",
"match",
"(",
"direct_url",
")",
"# type: Optional[Match]",
"if",
"direct_match",
"is",
"None",
":",
"url_match",
"=",
"URL_RE",
".",
"match",
"(",
"direct_url",
")",
"if",
"url_match",
"or",
"is_valid_url",
"(",
"direct_url",
")",
":",
"return",
"direct_url",
"match_dict",
"=",
"(",
"{",
"}",
")",
"# type: Dict[STRING_TYPE, Union[Tuple[STRING_TYPE, ...], STRING_TYPE]]",
"if",
"direct_match",
"is",
"not",
"None",
":",
"match_dict",
"=",
"direct_match",
".",
"groupdict",
"(",
")",
"# type: ignore",
"if",
"not",
"match_dict",
":",
"raise",
"ValueError",
"(",
"\"Failed converting value to normal URL, is it a direct URL? {0!r}\"",
".",
"format",
"(",
"direct_url",
")",
")",
"url_segments",
"=",
"[",
"match_dict",
".",
"get",
"(",
"s",
")",
"for",
"s",
"in",
"(",
"\"scheme\"",
",",
"\"host\"",
",",
"\"path\"",
",",
"\"pathsep\"",
")",
"]",
"url",
"=",
"\"\"",
"# type: STRING_TYPE",
"url",
"=",
"\"\"",
".",
"join",
"(",
"[",
"s",
"for",
"s",
"in",
"url_segments",
"if",
"s",
"is",
"not",
"None",
"]",
")",
"# type: ignore",
"new_url",
"=",
"build_vcs_uri",
"(",
"None",
",",
"url",
",",
"ref",
"=",
"match_dict",
".",
"get",
"(",
"\"ref\"",
")",
",",
"name",
"=",
"match_dict",
".",
"get",
"(",
"\"name\"",
")",
",",
"extras",
"=",
"match_dict",
".",
"get",
"(",
"\"extras\"",
")",
",",
"subdirectory",
"=",
"match_dict",
".",
"get",
"(",
"\"subdirectory\"",
")",
",",
")",
"return",
"new_url"
] |
Given a direct url as defined by *PEP 508*, convert to a :class:`~pip_shims.shims.Link`
compatible URL by moving the name and extras into an **egg_fragment**.
:param str direct_url: A pep-508 compliant direct url.
:return: A reformatted URL for use with Link objects and :class:`~pip_shims.shims.InstallRequirement` objects.
:rtype: AnyStr
|
[
"Given",
"a",
"direct",
"url",
"as",
"defined",
"by",
"*",
"PEP",
"508",
"*",
"convert",
"to",
"a",
":",
"class",
":",
"~pip_shims",
".",
"shims",
".",
"Link",
"compatible",
"URL",
"by",
"moving",
"the",
"name",
"and",
"extras",
"into",
"an",
"**",
"egg_fragment",
"**",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L213-L250
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
convert_url_to_direct_url
|
def convert_url_to_direct_url(url, name=None):
# type: (AnyStr, Optional[AnyStr]) -> AnyStr
"""
Given a :class:`~pip_shims.shims.Link` compatible URL, convert to a direct url as
defined by *PEP 508* by extracting the name and extras from the **egg_fragment**.
:param AnyStr url: A :class:`~pip_shims.shims.InstallRequirement` compliant URL.
:param Optiona[AnyStr] name: A name to use in case the supplied URL doesn't provide one.
:return: A pep-508 compliant direct url.
:rtype: AnyStr
:raises ValueError: Raised when the URL can't be parsed or a name can't be found.
:raises TypeError: When a non-string input is provided.
"""
if not isinstance(url, six.string_types):
raise TypeError(
"Expected a string to convert to a direct url, got {0!r}".format(url)
)
direct_match = DIRECT_URL_RE.match(url)
if direct_match:
return url
url_match = URL_RE.match(url)
if url_match is None or not url_match.groupdict():
raise ValueError("Failed parse a valid URL from {0!r}".format(url))
match_dict = url_match.groupdict()
url_segments = [match_dict.get(s) for s in ("scheme", "host", "path", "pathsep")]
name = match_dict.get("name", name)
extras = match_dict.get("extras")
new_url = ""
if extras and not name:
url_segments.append(extras)
elif extras and name:
new_url = "{0}{1}@ ".format(name, extras)
else:
if name is not None:
new_url = "{0}@ ".format(name)
else:
raise ValueError(
"Failed to construct direct url: "
"No name could be parsed from {0!r}".format(url)
)
if match_dict.get("ref"):
url_segments.append("@{0}".format(match_dict.get("ref")))
url = "".join([s for s in url if s is not None])
url = "{0}{1}".format(new_url, url)
return url
|
python
|
def convert_url_to_direct_url(url, name=None):
# type: (AnyStr, Optional[AnyStr]) -> AnyStr
"""
Given a :class:`~pip_shims.shims.Link` compatible URL, convert to a direct url as
defined by *PEP 508* by extracting the name and extras from the **egg_fragment**.
:param AnyStr url: A :class:`~pip_shims.shims.InstallRequirement` compliant URL.
:param Optiona[AnyStr] name: A name to use in case the supplied URL doesn't provide one.
:return: A pep-508 compliant direct url.
:rtype: AnyStr
:raises ValueError: Raised when the URL can't be parsed or a name can't be found.
:raises TypeError: When a non-string input is provided.
"""
if not isinstance(url, six.string_types):
raise TypeError(
"Expected a string to convert to a direct url, got {0!r}".format(url)
)
direct_match = DIRECT_URL_RE.match(url)
if direct_match:
return url
url_match = URL_RE.match(url)
if url_match is None or not url_match.groupdict():
raise ValueError("Failed parse a valid URL from {0!r}".format(url))
match_dict = url_match.groupdict()
url_segments = [match_dict.get(s) for s in ("scheme", "host", "path", "pathsep")]
name = match_dict.get("name", name)
extras = match_dict.get("extras")
new_url = ""
if extras and not name:
url_segments.append(extras)
elif extras and name:
new_url = "{0}{1}@ ".format(name, extras)
else:
if name is not None:
new_url = "{0}@ ".format(name)
else:
raise ValueError(
"Failed to construct direct url: "
"No name could be parsed from {0!r}".format(url)
)
if match_dict.get("ref"):
url_segments.append("@{0}".format(match_dict.get("ref")))
url = "".join([s for s in url if s is not None])
url = "{0}{1}".format(new_url, url)
return url
|
[
"def",
"convert_url_to_direct_url",
"(",
"url",
",",
"name",
"=",
"None",
")",
":",
"# type: (AnyStr, Optional[AnyStr]) -> AnyStr",
"if",
"not",
"isinstance",
"(",
"url",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected a string to convert to a direct url, got {0!r}\"",
".",
"format",
"(",
"url",
")",
")",
"direct_match",
"=",
"DIRECT_URL_RE",
".",
"match",
"(",
"url",
")",
"if",
"direct_match",
":",
"return",
"url",
"url_match",
"=",
"URL_RE",
".",
"match",
"(",
"url",
")",
"if",
"url_match",
"is",
"None",
"or",
"not",
"url_match",
".",
"groupdict",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Failed parse a valid URL from {0!r}\"",
".",
"format",
"(",
"url",
")",
")",
"match_dict",
"=",
"url_match",
".",
"groupdict",
"(",
")",
"url_segments",
"=",
"[",
"match_dict",
".",
"get",
"(",
"s",
")",
"for",
"s",
"in",
"(",
"\"scheme\"",
",",
"\"host\"",
",",
"\"path\"",
",",
"\"pathsep\"",
")",
"]",
"name",
"=",
"match_dict",
".",
"get",
"(",
"\"name\"",
",",
"name",
")",
"extras",
"=",
"match_dict",
".",
"get",
"(",
"\"extras\"",
")",
"new_url",
"=",
"\"\"",
"if",
"extras",
"and",
"not",
"name",
":",
"url_segments",
".",
"append",
"(",
"extras",
")",
"elif",
"extras",
"and",
"name",
":",
"new_url",
"=",
"\"{0}{1}@ \"",
".",
"format",
"(",
"name",
",",
"extras",
")",
"else",
":",
"if",
"name",
"is",
"not",
"None",
":",
"new_url",
"=",
"\"{0}@ \"",
".",
"format",
"(",
"name",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Failed to construct direct url: \"",
"\"No name could be parsed from {0!r}\"",
".",
"format",
"(",
"url",
")",
")",
"if",
"match_dict",
".",
"get",
"(",
"\"ref\"",
")",
":",
"url_segments",
".",
"append",
"(",
"\"@{0}\"",
".",
"format",
"(",
"match_dict",
".",
"get",
"(",
"\"ref\"",
")",
")",
")",
"url",
"=",
"\"\"",
".",
"join",
"(",
"[",
"s",
"for",
"s",
"in",
"url",
"if",
"s",
"is",
"not",
"None",
"]",
")",
"url",
"=",
"\"{0}{1}\"",
".",
"format",
"(",
"new_url",
",",
"url",
")",
"return",
"url"
] |
Given a :class:`~pip_shims.shims.Link` compatible URL, convert to a direct url as
defined by *PEP 508* by extracting the name and extras from the **egg_fragment**.
:param AnyStr url: A :class:`~pip_shims.shims.InstallRequirement` compliant URL.
:param Optiona[AnyStr] name: A name to use in case the supplied URL doesn't provide one.
:return: A pep-508 compliant direct url.
:rtype: AnyStr
:raises ValueError: Raised when the URL can't be parsed or a name can't be found.
:raises TypeError: When a non-string input is provided.
|
[
"Given",
"a",
":",
"class",
":",
"~pip_shims",
".",
"shims",
".",
"Link",
"compatible",
"URL",
"convert",
"to",
"a",
"direct",
"url",
"as",
"defined",
"by",
"*",
"PEP",
"508",
"*",
"by",
"extracting",
"the",
"name",
"and",
"extras",
"from",
"the",
"**",
"egg_fragment",
"**",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L253-L298
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
strip_extras_markers_from_requirement
|
def strip_extras_markers_from_requirement(req):
# type: (TRequirement) -> TRequirement
"""
Given a :class:`~packaging.requirements.Requirement` instance with markers defining
*extra == 'name'*, strip out the extras from the markers and return the cleaned
requirement
:param PackagingRequirement req: A packaging requirement to clean
:return: A cleaned requirement
:rtype: PackagingRequirement
"""
if req is None:
raise TypeError("Must pass in a valid requirement, received {0!r}".format(req))
if getattr(req, "marker", None) is not None:
marker = req.marker # type: TMarker
marker._markers = _strip_extras_markers(marker._markers)
if not marker._markers:
req.marker = None
else:
req.marker = marker
return req
|
python
|
def strip_extras_markers_from_requirement(req):
# type: (TRequirement) -> TRequirement
"""
Given a :class:`~packaging.requirements.Requirement` instance with markers defining
*extra == 'name'*, strip out the extras from the markers and return the cleaned
requirement
:param PackagingRequirement req: A packaging requirement to clean
:return: A cleaned requirement
:rtype: PackagingRequirement
"""
if req is None:
raise TypeError("Must pass in a valid requirement, received {0!r}".format(req))
if getattr(req, "marker", None) is not None:
marker = req.marker # type: TMarker
marker._markers = _strip_extras_markers(marker._markers)
if not marker._markers:
req.marker = None
else:
req.marker = marker
return req
|
[
"def",
"strip_extras_markers_from_requirement",
"(",
"req",
")",
":",
"# type: (TRequirement) -> TRequirement",
"if",
"req",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"Must pass in a valid requirement, received {0!r}\"",
".",
"format",
"(",
"req",
")",
")",
"if",
"getattr",
"(",
"req",
",",
"\"marker\"",
",",
"None",
")",
"is",
"not",
"None",
":",
"marker",
"=",
"req",
".",
"marker",
"# type: TMarker",
"marker",
".",
"_markers",
"=",
"_strip_extras_markers",
"(",
"marker",
".",
"_markers",
")",
"if",
"not",
"marker",
".",
"_markers",
":",
"req",
".",
"marker",
"=",
"None",
"else",
":",
"req",
".",
"marker",
"=",
"marker",
"return",
"req"
] |
Given a :class:`~packaging.requirements.Requirement` instance with markers defining
*extra == 'name'*, strip out the extras from the markers and return the cleaned
requirement
:param PackagingRequirement req: A packaging requirement to clean
:return: A cleaned requirement
:rtype: PackagingRequirement
|
[
"Given",
"a",
":",
"class",
":",
"~packaging",
".",
"requirements",
".",
"Requirement",
"instance",
"with",
"markers",
"defining",
"*",
"extra",
"==",
"name",
"*",
"strip",
"out",
"the",
"extras",
"from",
"the",
"markers",
"and",
"return",
"the",
"cleaned",
"requirement"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L316-L336
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
get_pyproject
|
def get_pyproject(path):
# type: (Union[STRING_TYPE, Path]) -> Optional[Tuple[List[STRING_TYPE], STRING_TYPE]]
"""
Given a base path, look for the corresponding ``pyproject.toml`` file and return its
build_requires and build_backend.
:param AnyStr path: The root path of the project, should be a directory (will be truncated)
:return: A 2 tuple of build requirements and the build backend
:rtype: Optional[Tuple[List[AnyStr], AnyStr]]
"""
if not path:
return
from vistir.compat import Path
if not isinstance(path, Path):
path = Path(path)
if not path.is_dir():
path = path.parent
pp_toml = path.joinpath("pyproject.toml")
setup_py = path.joinpath("setup.py")
if not pp_toml.exists():
if not setup_py.exists():
return None
requires = ["setuptools>=40.8", "wheel"]
backend = get_default_pyproject_backend()
else:
pyproject_data = {}
with io.open(pp_toml.as_posix(), encoding="utf-8") as fh:
pyproject_data = tomlkit.loads(fh.read())
build_system = pyproject_data.get("build-system", None)
if build_system is None:
if setup_py.exists():
requires = ["setuptools>=40.8", "wheel"]
backend = get_default_pyproject_backend()
else:
requires = ["setuptools>=40.8", "wheel"]
backend = get_default_pyproject_backend()
build_system = {"requires": requires, "build-backend": backend}
pyproject_data["build_system"] = build_system
else:
requires = build_system.get("requires", ["setuptools>=40.8", "wheel"])
backend = build_system.get("build-backend", get_default_pyproject_backend())
return requires, backend
|
python
|
def get_pyproject(path):
# type: (Union[STRING_TYPE, Path]) -> Optional[Tuple[List[STRING_TYPE], STRING_TYPE]]
"""
Given a base path, look for the corresponding ``pyproject.toml`` file and return its
build_requires and build_backend.
:param AnyStr path: The root path of the project, should be a directory (will be truncated)
:return: A 2 tuple of build requirements and the build backend
:rtype: Optional[Tuple[List[AnyStr], AnyStr]]
"""
if not path:
return
from vistir.compat import Path
if not isinstance(path, Path):
path = Path(path)
if not path.is_dir():
path = path.parent
pp_toml = path.joinpath("pyproject.toml")
setup_py = path.joinpath("setup.py")
if not pp_toml.exists():
if not setup_py.exists():
return None
requires = ["setuptools>=40.8", "wheel"]
backend = get_default_pyproject_backend()
else:
pyproject_data = {}
with io.open(pp_toml.as_posix(), encoding="utf-8") as fh:
pyproject_data = tomlkit.loads(fh.read())
build_system = pyproject_data.get("build-system", None)
if build_system is None:
if setup_py.exists():
requires = ["setuptools>=40.8", "wheel"]
backend = get_default_pyproject_backend()
else:
requires = ["setuptools>=40.8", "wheel"]
backend = get_default_pyproject_backend()
build_system = {"requires": requires, "build-backend": backend}
pyproject_data["build_system"] = build_system
else:
requires = build_system.get("requires", ["setuptools>=40.8", "wheel"])
backend = build_system.get("build-backend", get_default_pyproject_backend())
return requires, backend
|
[
"def",
"get_pyproject",
"(",
"path",
")",
":",
"# type: (Union[STRING_TYPE, Path]) -> Optional[Tuple[List[STRING_TYPE], STRING_TYPE]]",
"if",
"not",
"path",
":",
"return",
"from",
"vistir",
".",
"compat",
"import",
"Path",
"if",
"not",
"isinstance",
"(",
"path",
",",
"Path",
")",
":",
"path",
"=",
"Path",
"(",
"path",
")",
"if",
"not",
"path",
".",
"is_dir",
"(",
")",
":",
"path",
"=",
"path",
".",
"parent",
"pp_toml",
"=",
"path",
".",
"joinpath",
"(",
"\"pyproject.toml\"",
")",
"setup_py",
"=",
"path",
".",
"joinpath",
"(",
"\"setup.py\"",
")",
"if",
"not",
"pp_toml",
".",
"exists",
"(",
")",
":",
"if",
"not",
"setup_py",
".",
"exists",
"(",
")",
":",
"return",
"None",
"requires",
"=",
"[",
"\"setuptools>=40.8\"",
",",
"\"wheel\"",
"]",
"backend",
"=",
"get_default_pyproject_backend",
"(",
")",
"else",
":",
"pyproject_data",
"=",
"{",
"}",
"with",
"io",
".",
"open",
"(",
"pp_toml",
".",
"as_posix",
"(",
")",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"fh",
":",
"pyproject_data",
"=",
"tomlkit",
".",
"loads",
"(",
"fh",
".",
"read",
"(",
")",
")",
"build_system",
"=",
"pyproject_data",
".",
"get",
"(",
"\"build-system\"",
",",
"None",
")",
"if",
"build_system",
"is",
"None",
":",
"if",
"setup_py",
".",
"exists",
"(",
")",
":",
"requires",
"=",
"[",
"\"setuptools>=40.8\"",
",",
"\"wheel\"",
"]",
"backend",
"=",
"get_default_pyproject_backend",
"(",
")",
"else",
":",
"requires",
"=",
"[",
"\"setuptools>=40.8\"",
",",
"\"wheel\"",
"]",
"backend",
"=",
"get_default_pyproject_backend",
"(",
")",
"build_system",
"=",
"{",
"\"requires\"",
":",
"requires",
",",
"\"build-backend\"",
":",
"backend",
"}",
"pyproject_data",
"[",
"\"build_system\"",
"]",
"=",
"build_system",
"else",
":",
"requires",
"=",
"build_system",
".",
"get",
"(",
"\"requires\"",
",",
"[",
"\"setuptools>=40.8\"",
",",
"\"wheel\"",
"]",
")",
"backend",
"=",
"build_system",
".",
"get",
"(",
"\"build-backend\"",
",",
"get_default_pyproject_backend",
"(",
")",
")",
"return",
"requires",
",",
"backend"
] |
Given a base path, look for the corresponding ``pyproject.toml`` file and return its
build_requires and build_backend.
:param AnyStr path: The root path of the project, should be a directory (will be truncated)
:return: A 2 tuple of build requirements and the build backend
:rtype: Optional[Tuple[List[AnyStr], AnyStr]]
|
[
"Given",
"a",
"base",
"path",
"look",
"for",
"the",
"corresponding",
"pyproject",
".",
"toml",
"file",
"and",
"return",
"its",
"build_requires",
"and",
"build_backend",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L382-L425
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
split_markers_from_line
|
def split_markers_from_line(line):
# type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]
"""Split markers from a dependency"""
if not any(line.startswith(uri_prefix) for uri_prefix in SCHEME_LIST):
marker_sep = ";"
else:
marker_sep = "; "
markers = None
if marker_sep in line:
line, markers = line.split(marker_sep, 1)
markers = markers.strip() if markers else None
return line, markers
|
python
|
def split_markers_from_line(line):
# type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]
"""Split markers from a dependency"""
if not any(line.startswith(uri_prefix) for uri_prefix in SCHEME_LIST):
marker_sep = ";"
else:
marker_sep = "; "
markers = None
if marker_sep in line:
line, markers = line.split(marker_sep, 1)
markers = markers.strip() if markers else None
return line, markers
|
[
"def",
"split_markers_from_line",
"(",
"line",
")",
":",
"# type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]",
"if",
"not",
"any",
"(",
"line",
".",
"startswith",
"(",
"uri_prefix",
")",
"for",
"uri_prefix",
"in",
"SCHEME_LIST",
")",
":",
"marker_sep",
"=",
"\";\"",
"else",
":",
"marker_sep",
"=",
"\"; \"",
"markers",
"=",
"None",
"if",
"marker_sep",
"in",
"line",
":",
"line",
",",
"markers",
"=",
"line",
".",
"split",
"(",
"marker_sep",
",",
"1",
")",
"markers",
"=",
"markers",
".",
"strip",
"(",
")",
"if",
"markers",
"else",
"None",
"return",
"line",
",",
"markers"
] |
Split markers from a dependency
|
[
"Split",
"markers",
"from",
"a",
"dependency"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L428-L439
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
split_vcs_method_from_uri
|
def split_vcs_method_from_uri(uri):
# type: (AnyStr) -> Tuple[Optional[STRING_TYPE], STRING_TYPE]
"""Split a vcs+uri formatted uri into (vcs, uri)"""
vcs_start = "{0}+"
vcs = None # type: Optional[STRING_TYPE]
vcs = first([vcs for vcs in VCS_LIST if uri.startswith(vcs_start.format(vcs))])
if vcs:
vcs, uri = uri.split("+", 1)
return vcs, uri
|
python
|
def split_vcs_method_from_uri(uri):
# type: (AnyStr) -> Tuple[Optional[STRING_TYPE], STRING_TYPE]
"""Split a vcs+uri formatted uri into (vcs, uri)"""
vcs_start = "{0}+"
vcs = None # type: Optional[STRING_TYPE]
vcs = first([vcs for vcs in VCS_LIST if uri.startswith(vcs_start.format(vcs))])
if vcs:
vcs, uri = uri.split("+", 1)
return vcs, uri
|
[
"def",
"split_vcs_method_from_uri",
"(",
"uri",
")",
":",
"# type: (AnyStr) -> Tuple[Optional[STRING_TYPE], STRING_TYPE]",
"vcs_start",
"=",
"\"{0}+\"",
"vcs",
"=",
"None",
"# type: Optional[STRING_TYPE]",
"vcs",
"=",
"first",
"(",
"[",
"vcs",
"for",
"vcs",
"in",
"VCS_LIST",
"if",
"uri",
".",
"startswith",
"(",
"vcs_start",
".",
"format",
"(",
"vcs",
")",
")",
"]",
")",
"if",
"vcs",
":",
"vcs",
",",
"uri",
"=",
"uri",
".",
"split",
"(",
"\"+\"",
",",
"1",
")",
"return",
"vcs",
",",
"uri"
] |
Split a vcs+uri formatted uri into (vcs, uri)
|
[
"Split",
"a",
"vcs",
"+",
"uri",
"formatted",
"uri",
"into",
"(",
"vcs",
"uri",
")"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L442-L450
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
split_ref_from_uri
|
def split_ref_from_uri(uri):
# type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]
"""
Given a path or URI, check for a ref and split it from the path if it is present,
returning a tuple of the original input and the ref or None.
:param AnyStr uri: The path or URI to split
:returns: A 2-tuple of the path or URI and the ref
:rtype: Tuple[AnyStr, Optional[AnyStr]]
"""
if not isinstance(uri, six.string_types):
raise TypeError("Expected a string, received {0!r}".format(uri))
parsed = urllib_parse.urlparse(uri)
path = parsed.path
ref = None
if "@" in path:
path, _, ref = path.rpartition("@")
parsed = parsed._replace(path=path)
return (urllib_parse.urlunparse(parsed), ref)
|
python
|
def split_ref_from_uri(uri):
# type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]
"""
Given a path or URI, check for a ref and split it from the path if it is present,
returning a tuple of the original input and the ref or None.
:param AnyStr uri: The path or URI to split
:returns: A 2-tuple of the path or URI and the ref
:rtype: Tuple[AnyStr, Optional[AnyStr]]
"""
if not isinstance(uri, six.string_types):
raise TypeError("Expected a string, received {0!r}".format(uri))
parsed = urllib_parse.urlparse(uri)
path = parsed.path
ref = None
if "@" in path:
path, _, ref = path.rpartition("@")
parsed = parsed._replace(path=path)
return (urllib_parse.urlunparse(parsed), ref)
|
[
"def",
"split_ref_from_uri",
"(",
"uri",
")",
":",
"# type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]",
"if",
"not",
"isinstance",
"(",
"uri",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected a string, received {0!r}\"",
".",
"format",
"(",
"uri",
")",
")",
"parsed",
"=",
"urllib_parse",
".",
"urlparse",
"(",
"uri",
")",
"path",
"=",
"parsed",
".",
"path",
"ref",
"=",
"None",
"if",
"\"@\"",
"in",
"path",
":",
"path",
",",
"_",
",",
"ref",
"=",
"path",
".",
"rpartition",
"(",
"\"@\"",
")",
"parsed",
"=",
"parsed",
".",
"_replace",
"(",
"path",
"=",
"path",
")",
"return",
"(",
"urllib_parse",
".",
"urlunparse",
"(",
"parsed",
")",
",",
"ref",
")"
] |
Given a path or URI, check for a ref and split it from the path if it is present,
returning a tuple of the original input and the ref or None.
:param AnyStr uri: The path or URI to split
:returns: A 2-tuple of the path or URI and the ref
:rtype: Tuple[AnyStr, Optional[AnyStr]]
|
[
"Given",
"a",
"path",
"or",
"URI",
"check",
"for",
"a",
"ref",
"and",
"split",
"it",
"from",
"the",
"path",
"if",
"it",
"is",
"present",
"returning",
"a",
"tuple",
"of",
"the",
"original",
"input",
"and",
"the",
"ref",
"or",
"None",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L453-L471
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
key_from_ireq
|
def key_from_ireq(ireq):
"""Get a standardized key for an InstallRequirement."""
if ireq.req is None and ireq.link is not None:
return str(ireq.link)
else:
return key_from_req(ireq.req)
|
python
|
def key_from_ireq(ireq):
"""Get a standardized key for an InstallRequirement."""
if ireq.req is None and ireq.link is not None:
return str(ireq.link)
else:
return key_from_req(ireq.req)
|
[
"def",
"key_from_ireq",
"(",
"ireq",
")",
":",
"if",
"ireq",
".",
"req",
"is",
"None",
"and",
"ireq",
".",
"link",
"is",
"not",
"None",
":",
"return",
"str",
"(",
"ireq",
".",
"link",
")",
"else",
":",
"return",
"key_from_req",
"(",
"ireq",
".",
"req",
")"
] |
Get a standardized key for an InstallRequirement.
|
[
"Get",
"a",
"standardized",
"key",
"for",
"an",
"InstallRequirement",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L500-L505
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
key_from_req
|
def key_from_req(req):
"""Get an all-lowercase version of the requirement's name."""
if hasattr(req, "key"):
# from pkg_resources, such as installed dists for pip-sync
key = req.key
else:
# from packaging, such as install requirements from requirements.txt
key = req.name
key = key.replace("_", "-").lower()
return key
|
python
|
def key_from_req(req):
"""Get an all-lowercase version of the requirement's name."""
if hasattr(req, "key"):
# from pkg_resources, such as installed dists for pip-sync
key = req.key
else:
# from packaging, such as install requirements from requirements.txt
key = req.name
key = key.replace("_", "-").lower()
return key
|
[
"def",
"key_from_req",
"(",
"req",
")",
":",
"if",
"hasattr",
"(",
"req",
",",
"\"key\"",
")",
":",
"# from pkg_resources, such as installed dists for pip-sync",
"key",
"=",
"req",
".",
"key",
"else",
":",
"# from packaging, such as install requirements from requirements.txt",
"key",
"=",
"req",
".",
"name",
"key",
"=",
"key",
".",
"replace",
"(",
"\"_\"",
",",
"\"-\"",
")",
".",
"lower",
"(",
")",
"return",
"key"
] |
Get an all-lowercase version of the requirement's name.
|
[
"Get",
"an",
"all",
"-",
"lowercase",
"version",
"of",
"the",
"requirement",
"s",
"name",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L508-L518
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
_requirement_to_str_lowercase_name
|
def _requirement_to_str_lowercase_name(requirement):
"""
Formats a packaging.requirements.Requirement with a lowercase name.
This is simply a copy of
https://github.com/pypa/packaging/blob/16.8/packaging/requirements.py#L109-L124
modified to lowercase the dependency name.
Previously, we were invoking the original Requirement.__str__ method and
lower-casing the entire result, which would lowercase the name, *and* other,
important stuff that should not be lower-cased (such as the marker). See
this issue for more information: https://github.com/pypa/pipenv/issues/2113.
"""
parts = [requirement.name.lower()]
if requirement.extras:
parts.append("[{0}]".format(",".join(sorted(requirement.extras))))
if requirement.specifier:
parts.append(str(requirement.specifier))
if requirement.url:
parts.append("@ {0}".format(requirement.url))
if requirement.marker:
parts.append("; {0}".format(requirement.marker))
return "".join(parts)
|
python
|
def _requirement_to_str_lowercase_name(requirement):
"""
Formats a packaging.requirements.Requirement with a lowercase name.
This is simply a copy of
https://github.com/pypa/packaging/blob/16.8/packaging/requirements.py#L109-L124
modified to lowercase the dependency name.
Previously, we were invoking the original Requirement.__str__ method and
lower-casing the entire result, which would lowercase the name, *and* other,
important stuff that should not be lower-cased (such as the marker). See
this issue for more information: https://github.com/pypa/pipenv/issues/2113.
"""
parts = [requirement.name.lower()]
if requirement.extras:
parts.append("[{0}]".format(",".join(sorted(requirement.extras))))
if requirement.specifier:
parts.append(str(requirement.specifier))
if requirement.url:
parts.append("@ {0}".format(requirement.url))
if requirement.marker:
parts.append("; {0}".format(requirement.marker))
return "".join(parts)
|
[
"def",
"_requirement_to_str_lowercase_name",
"(",
"requirement",
")",
":",
"parts",
"=",
"[",
"requirement",
".",
"name",
".",
"lower",
"(",
")",
"]",
"if",
"requirement",
".",
"extras",
":",
"parts",
".",
"append",
"(",
"\"[{0}]\"",
".",
"format",
"(",
"\",\"",
".",
"join",
"(",
"sorted",
"(",
"requirement",
".",
"extras",
")",
")",
")",
")",
"if",
"requirement",
".",
"specifier",
":",
"parts",
".",
"append",
"(",
"str",
"(",
"requirement",
".",
"specifier",
")",
")",
"if",
"requirement",
".",
"url",
":",
"parts",
".",
"append",
"(",
"\"@ {0}\"",
".",
"format",
"(",
"requirement",
".",
"url",
")",
")",
"if",
"requirement",
".",
"marker",
":",
"parts",
".",
"append",
"(",
"\"; {0}\"",
".",
"format",
"(",
"requirement",
".",
"marker",
")",
")",
"return",
"\"\"",
".",
"join",
"(",
"parts",
")"
] |
Formats a packaging.requirements.Requirement with a lowercase name.
This is simply a copy of
https://github.com/pypa/packaging/blob/16.8/packaging/requirements.py#L109-L124
modified to lowercase the dependency name.
Previously, we were invoking the original Requirement.__str__ method and
lower-casing the entire result, which would lowercase the name, *and* other,
important stuff that should not be lower-cased (such as the marker). See
this issue for more information: https://github.com/pypa/pipenv/issues/2113.
|
[
"Formats",
"a",
"packaging",
".",
"requirements",
".",
"Requirement",
"with",
"a",
"lowercase",
"name",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L521-L549
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
format_requirement
|
def format_requirement(ireq):
"""
Generic formatter for pretty printing InstallRequirements to the terminal
in a less verbose way than using its `__str__` method.
"""
if ireq.editable:
line = "-e {}".format(ireq.link)
else:
line = _requirement_to_str_lowercase_name(ireq.req)
if str(ireq.req.marker) != str(ireq.markers):
if not ireq.req.marker:
line = "{}; {}".format(line, ireq.markers)
else:
name, markers = line.split(";", 1)
markers = markers.strip()
line = "{}; ({}) and ({})".format(name, markers, ireq.markers)
return line
|
python
|
def format_requirement(ireq):
"""
Generic formatter for pretty printing InstallRequirements to the terminal
in a less verbose way than using its `__str__` method.
"""
if ireq.editable:
line = "-e {}".format(ireq.link)
else:
line = _requirement_to_str_lowercase_name(ireq.req)
if str(ireq.req.marker) != str(ireq.markers):
if not ireq.req.marker:
line = "{}; {}".format(line, ireq.markers)
else:
name, markers = line.split(";", 1)
markers = markers.strip()
line = "{}; ({}) and ({})".format(name, markers, ireq.markers)
return line
|
[
"def",
"format_requirement",
"(",
"ireq",
")",
":",
"if",
"ireq",
".",
"editable",
":",
"line",
"=",
"\"-e {}\"",
".",
"format",
"(",
"ireq",
".",
"link",
")",
"else",
":",
"line",
"=",
"_requirement_to_str_lowercase_name",
"(",
"ireq",
".",
"req",
")",
"if",
"str",
"(",
"ireq",
".",
"req",
".",
"marker",
")",
"!=",
"str",
"(",
"ireq",
".",
"markers",
")",
":",
"if",
"not",
"ireq",
".",
"req",
".",
"marker",
":",
"line",
"=",
"\"{}; {}\"",
".",
"format",
"(",
"line",
",",
"ireq",
".",
"markers",
")",
"else",
":",
"name",
",",
"markers",
"=",
"line",
".",
"split",
"(",
"\";\"",
",",
"1",
")",
"markers",
"=",
"markers",
".",
"strip",
"(",
")",
"line",
"=",
"\"{}; ({}) and ({})\"",
".",
"format",
"(",
"name",
",",
"markers",
",",
"ireq",
".",
"markers",
")",
"return",
"line"
] |
Generic formatter for pretty printing InstallRequirements to the terminal
in a less verbose way than using its `__str__` method.
|
[
"Generic",
"formatter",
"for",
"pretty",
"printing",
"InstallRequirements",
"to",
"the",
"terminal",
"in",
"a",
"less",
"verbose",
"way",
"than",
"using",
"its",
"__str__",
"method",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L552-L571
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
format_specifier
|
def format_specifier(ireq):
"""
Generic formatter for pretty printing the specifier part of
InstallRequirements to the terminal.
"""
# TODO: Ideally, this is carried over to the pip library itself
specs = ireq.specifier._specs if ireq.req is not None else []
specs = sorted(specs, key=lambda x: x._spec[1])
return ",".join(str(s) for s in specs) or "<any>"
|
python
|
def format_specifier(ireq):
"""
Generic formatter for pretty printing the specifier part of
InstallRequirements to the terminal.
"""
# TODO: Ideally, this is carried over to the pip library itself
specs = ireq.specifier._specs if ireq.req is not None else []
specs = sorted(specs, key=lambda x: x._spec[1])
return ",".join(str(s) for s in specs) or "<any>"
|
[
"def",
"format_specifier",
"(",
"ireq",
")",
":",
"# TODO: Ideally, this is carried over to the pip library itself",
"specs",
"=",
"ireq",
".",
"specifier",
".",
"_specs",
"if",
"ireq",
".",
"req",
"is",
"not",
"None",
"else",
"[",
"]",
"specs",
"=",
"sorted",
"(",
"specs",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"_spec",
"[",
"1",
"]",
")",
"return",
"\",\"",
".",
"join",
"(",
"str",
"(",
"s",
")",
"for",
"s",
"in",
"specs",
")",
"or",
"\"<any>\""
] |
Generic formatter for pretty printing the specifier part of
InstallRequirements to the terminal.
|
[
"Generic",
"formatter",
"for",
"pretty",
"printing",
"the",
"specifier",
"part",
"of",
"InstallRequirements",
"to",
"the",
"terminal",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L574-L582
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
as_tuple
|
def as_tuple(ireq):
"""
Pulls out the (name: str, version:str, extras:(str)) tuple from the pinned InstallRequirement.
"""
if not is_pinned_requirement(ireq):
raise TypeError("Expected a pinned InstallRequirement, got {}".format(ireq))
name = key_from_req(ireq.req)
version = first(ireq.specifier._specs)._spec[1]
extras = tuple(sorted(ireq.extras))
return name, version, extras
|
python
|
def as_tuple(ireq):
"""
Pulls out the (name: str, version:str, extras:(str)) tuple from the pinned InstallRequirement.
"""
if not is_pinned_requirement(ireq):
raise TypeError("Expected a pinned InstallRequirement, got {}".format(ireq))
name = key_from_req(ireq.req)
version = first(ireq.specifier._specs)._spec[1]
extras = tuple(sorted(ireq.extras))
return name, version, extras
|
[
"def",
"as_tuple",
"(",
"ireq",
")",
":",
"if",
"not",
"is_pinned_requirement",
"(",
"ireq",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected a pinned InstallRequirement, got {}\"",
".",
"format",
"(",
"ireq",
")",
")",
"name",
"=",
"key_from_req",
"(",
"ireq",
".",
"req",
")",
"version",
"=",
"first",
"(",
"ireq",
".",
"specifier",
".",
"_specs",
")",
".",
"_spec",
"[",
"1",
"]",
"extras",
"=",
"tuple",
"(",
"sorted",
"(",
"ireq",
".",
"extras",
")",
")",
"return",
"name",
",",
"version",
",",
"extras"
] |
Pulls out the (name: str, version:str, extras:(str)) tuple from the pinned InstallRequirement.
|
[
"Pulls",
"out",
"the",
"(",
"name",
":",
"str",
"version",
":",
"str",
"extras",
":",
"(",
"str",
"))",
"tuple",
"from",
"the",
"pinned",
"InstallRequirement",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L650-L661
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
full_groupby
|
def full_groupby(iterable, key=None):
"""
Like groupby(), but sorts the input on the group key first.
"""
return groupby(sorted(iterable, key=key), key=key)
|
python
|
def full_groupby(iterable, key=None):
"""
Like groupby(), but sorts the input on the group key first.
"""
return groupby(sorted(iterable, key=key), key=key)
|
[
"def",
"full_groupby",
"(",
"iterable",
",",
"key",
"=",
"None",
")",
":",
"return",
"groupby",
"(",
"sorted",
"(",
"iterable",
",",
"key",
"=",
"key",
")",
",",
"key",
"=",
"key",
")"
] |
Like groupby(), but sorts the input on the group key first.
|
[
"Like",
"groupby",
"()",
"but",
"sorts",
"the",
"input",
"on",
"the",
"group",
"key",
"first",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L664-L669
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
lookup_table
|
def lookup_table(values, key=None, keyval=None, unique=False, use_lists=False):
"""
Builds a dict-based lookup table (index) elegantly.
Supports building normal and unique lookup tables. For example:
>>> assert lookup_table(
... ['foo', 'bar', 'baz', 'qux', 'quux'], lambda s: s[0]) == {
... 'b': {'bar', 'baz'},
... 'f': {'foo'},
... 'q': {'quux', 'qux'}
... }
For key functions that uniquely identify values, set unique=True:
>>> assert lookup_table(
... ['foo', 'bar', 'baz', 'qux', 'quux'], lambda s: s[0], unique=True) == {
... 'b': 'baz',
... 'f': 'foo',
... 'q': 'quux'
... }
The values of the resulting lookup table will be values, not sets.
For extra power, you can even change the values while building up the LUT.
To do so, use the `keyval` function instead of the `key` arg:
>>> assert lookup_table(
... ['foo', 'bar', 'baz', 'qux', 'quux'],
... keyval=lambda s: (s[0], s[1:])) == {
... 'b': {'ar', 'az'},
... 'f': {'oo'},
... 'q': {'uux', 'ux'}
... }
"""
if keyval is None:
if key is None:
keyval = lambda v: v
else:
keyval = lambda v: (key(v), v)
if unique:
return dict(keyval(v) for v in values)
lut = {}
for value in values:
k, v = keyval(value)
try:
s = lut[k]
except KeyError:
if use_lists:
s = lut[k] = list()
else:
s = lut[k] = set()
if use_lists:
s.append(v)
else:
s.add(v)
return dict(lut)
|
python
|
def lookup_table(values, key=None, keyval=None, unique=False, use_lists=False):
"""
Builds a dict-based lookup table (index) elegantly.
Supports building normal and unique lookup tables. For example:
>>> assert lookup_table(
... ['foo', 'bar', 'baz', 'qux', 'quux'], lambda s: s[0]) == {
... 'b': {'bar', 'baz'},
... 'f': {'foo'},
... 'q': {'quux', 'qux'}
... }
For key functions that uniquely identify values, set unique=True:
>>> assert lookup_table(
... ['foo', 'bar', 'baz', 'qux', 'quux'], lambda s: s[0], unique=True) == {
... 'b': 'baz',
... 'f': 'foo',
... 'q': 'quux'
... }
The values of the resulting lookup table will be values, not sets.
For extra power, you can even change the values while building up the LUT.
To do so, use the `keyval` function instead of the `key` arg:
>>> assert lookup_table(
... ['foo', 'bar', 'baz', 'qux', 'quux'],
... keyval=lambda s: (s[0], s[1:])) == {
... 'b': {'ar', 'az'},
... 'f': {'oo'},
... 'q': {'uux', 'ux'}
... }
"""
if keyval is None:
if key is None:
keyval = lambda v: v
else:
keyval = lambda v: (key(v), v)
if unique:
return dict(keyval(v) for v in values)
lut = {}
for value in values:
k, v = keyval(value)
try:
s = lut[k]
except KeyError:
if use_lists:
s = lut[k] = list()
else:
s = lut[k] = set()
if use_lists:
s.append(v)
else:
s.add(v)
return dict(lut)
|
[
"def",
"lookup_table",
"(",
"values",
",",
"key",
"=",
"None",
",",
"keyval",
"=",
"None",
",",
"unique",
"=",
"False",
",",
"use_lists",
"=",
"False",
")",
":",
"if",
"keyval",
"is",
"None",
":",
"if",
"key",
"is",
"None",
":",
"keyval",
"=",
"lambda",
"v",
":",
"v",
"else",
":",
"keyval",
"=",
"lambda",
"v",
":",
"(",
"key",
"(",
"v",
")",
",",
"v",
")",
"if",
"unique",
":",
"return",
"dict",
"(",
"keyval",
"(",
"v",
")",
"for",
"v",
"in",
"values",
")",
"lut",
"=",
"{",
"}",
"for",
"value",
"in",
"values",
":",
"k",
",",
"v",
"=",
"keyval",
"(",
"value",
")",
"try",
":",
"s",
"=",
"lut",
"[",
"k",
"]",
"except",
"KeyError",
":",
"if",
"use_lists",
":",
"s",
"=",
"lut",
"[",
"k",
"]",
"=",
"list",
"(",
")",
"else",
":",
"s",
"=",
"lut",
"[",
"k",
"]",
"=",
"set",
"(",
")",
"if",
"use_lists",
":",
"s",
".",
"append",
"(",
"v",
")",
"else",
":",
"s",
".",
"add",
"(",
"v",
")",
"return",
"dict",
"(",
"lut",
")"
] |
Builds a dict-based lookup table (index) elegantly.
Supports building normal and unique lookup tables. For example:
>>> assert lookup_table(
... ['foo', 'bar', 'baz', 'qux', 'quux'], lambda s: s[0]) == {
... 'b': {'bar', 'baz'},
... 'f': {'foo'},
... 'q': {'quux', 'qux'}
... }
For key functions that uniquely identify values, set unique=True:
>>> assert lookup_table(
... ['foo', 'bar', 'baz', 'qux', 'quux'], lambda s: s[0], unique=True) == {
... 'b': 'baz',
... 'f': 'foo',
... 'q': 'quux'
... }
The values of the resulting lookup table will be values, not sets.
For extra power, you can even change the values while building up the LUT.
To do so, use the `keyval` function instead of the `key` arg:
>>> assert lookup_table(
... ['foo', 'bar', 'baz', 'qux', 'quux'],
... keyval=lambda s: (s[0], s[1:])) == {
... 'b': {'ar', 'az'},
... 'f': {'oo'},
... 'q': {'uux', 'ux'}
... }
|
[
"Builds",
"a",
"dict",
"-",
"based",
"lookup",
"table",
"(",
"index",
")",
"elegantly",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L680-L739
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
make_install_requirement
|
def make_install_requirement(name, version, extras, markers, constraint=False):
"""
Generates an :class:`~pip._internal.req.req_install.InstallRequirement`.
Create an InstallRequirement from the supplied metadata.
:param name: The requirement's name.
:type name: str
:param version: The requirement version (must be pinned).
:type version: str.
:param extras: The desired extras.
:type extras: list[str]
:param markers: The desired markers, without a preceding semicolon.
:type markers: str
:param constraint: Whether to flag the requirement as a constraint, defaults to False.
:param constraint: bool, optional
:return: A generated InstallRequirement
:rtype: :class:`~pip._internal.req.req_install.InstallRequirement`
"""
# If no extras are specified, the extras string is blank
from pip_shims.shims import install_req_from_line
extras_string = ""
if extras:
# Sort extras for stability
extras_string = "[{}]".format(",".join(sorted(extras)))
if not markers:
return install_req_from_line(
str("{}{}=={}".format(name, extras_string, version)), constraint=constraint
)
else:
return install_req_from_line(
str("{}{}=={}; {}".format(name, extras_string, version, str(markers))),
constraint=constraint,
)
|
python
|
def make_install_requirement(name, version, extras, markers, constraint=False):
"""
Generates an :class:`~pip._internal.req.req_install.InstallRequirement`.
Create an InstallRequirement from the supplied metadata.
:param name: The requirement's name.
:type name: str
:param version: The requirement version (must be pinned).
:type version: str.
:param extras: The desired extras.
:type extras: list[str]
:param markers: The desired markers, without a preceding semicolon.
:type markers: str
:param constraint: Whether to flag the requirement as a constraint, defaults to False.
:param constraint: bool, optional
:return: A generated InstallRequirement
:rtype: :class:`~pip._internal.req.req_install.InstallRequirement`
"""
# If no extras are specified, the extras string is blank
from pip_shims.shims import install_req_from_line
extras_string = ""
if extras:
# Sort extras for stability
extras_string = "[{}]".format(",".join(sorted(extras)))
if not markers:
return install_req_from_line(
str("{}{}=={}".format(name, extras_string, version)), constraint=constraint
)
else:
return install_req_from_line(
str("{}{}=={}; {}".format(name, extras_string, version, str(markers))),
constraint=constraint,
)
|
[
"def",
"make_install_requirement",
"(",
"name",
",",
"version",
",",
"extras",
",",
"markers",
",",
"constraint",
"=",
"False",
")",
":",
"# If no extras are specified, the extras string is blank",
"from",
"pip_shims",
".",
"shims",
"import",
"install_req_from_line",
"extras_string",
"=",
"\"\"",
"if",
"extras",
":",
"# Sort extras for stability",
"extras_string",
"=",
"\"[{}]\"",
".",
"format",
"(",
"\",\"",
".",
"join",
"(",
"sorted",
"(",
"extras",
")",
")",
")",
"if",
"not",
"markers",
":",
"return",
"install_req_from_line",
"(",
"str",
"(",
"\"{}{}=={}\"",
".",
"format",
"(",
"name",
",",
"extras_string",
",",
"version",
")",
")",
",",
"constraint",
"=",
"constraint",
")",
"else",
":",
"return",
"install_req_from_line",
"(",
"str",
"(",
"\"{}{}=={}; {}\"",
".",
"format",
"(",
"name",
",",
"extras_string",
",",
"version",
",",
"str",
"(",
"markers",
")",
")",
")",
",",
"constraint",
"=",
"constraint",
",",
")"
] |
Generates an :class:`~pip._internal.req.req_install.InstallRequirement`.
Create an InstallRequirement from the supplied metadata.
:param name: The requirement's name.
:type name: str
:param version: The requirement version (must be pinned).
:type version: str.
:param extras: The desired extras.
:type extras: list[str]
:param markers: The desired markers, without a preceding semicolon.
:type markers: str
:param constraint: Whether to flag the requirement as a constraint, defaults to False.
:param constraint: bool, optional
:return: A generated InstallRequirement
:rtype: :class:`~pip._internal.req.req_install.InstallRequirement`
|
[
"Generates",
"an",
":",
"class",
":",
"~pip",
".",
"_internal",
".",
"req",
".",
"req_install",
".",
"InstallRequirement",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L752-L788
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
clean_requires_python
|
def clean_requires_python(candidates):
"""Get a cleaned list of all the candidates with valid specifiers in the `requires_python` attributes."""
all_candidates = []
sys_version = ".".join(map(str, sys.version_info[:3]))
from packaging.version import parse as parse_version
py_version = parse_version(os.environ.get("PIP_PYTHON_VERSION", sys_version))
for c in candidates:
from_location = attrgetter("location.requires_python")
requires_python = getattr(c, "requires_python", from_location(c))
if requires_python:
# Old specifications had people setting this to single digits
# which is effectively the same as '>=digit,<digit+1'
if requires_python.isdigit():
requires_python = ">={0},<{1}".format(
requires_python, int(requires_python) + 1
)
try:
specifierset = SpecifierSet(requires_python)
except InvalidSpecifier:
continue
else:
if not specifierset.contains(py_version):
continue
all_candidates.append(c)
return all_candidates
|
python
|
def clean_requires_python(candidates):
"""Get a cleaned list of all the candidates with valid specifiers in the `requires_python` attributes."""
all_candidates = []
sys_version = ".".join(map(str, sys.version_info[:3]))
from packaging.version import parse as parse_version
py_version = parse_version(os.environ.get("PIP_PYTHON_VERSION", sys_version))
for c in candidates:
from_location = attrgetter("location.requires_python")
requires_python = getattr(c, "requires_python", from_location(c))
if requires_python:
# Old specifications had people setting this to single digits
# which is effectively the same as '>=digit,<digit+1'
if requires_python.isdigit():
requires_python = ">={0},<{1}".format(
requires_python, int(requires_python) + 1
)
try:
specifierset = SpecifierSet(requires_python)
except InvalidSpecifier:
continue
else:
if not specifierset.contains(py_version):
continue
all_candidates.append(c)
return all_candidates
|
[
"def",
"clean_requires_python",
"(",
"candidates",
")",
":",
"all_candidates",
"=",
"[",
"]",
"sys_version",
"=",
"\".\"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"sys",
".",
"version_info",
"[",
":",
"3",
"]",
")",
")",
"from",
"packaging",
".",
"version",
"import",
"parse",
"as",
"parse_version",
"py_version",
"=",
"parse_version",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"\"PIP_PYTHON_VERSION\"",
",",
"sys_version",
")",
")",
"for",
"c",
"in",
"candidates",
":",
"from_location",
"=",
"attrgetter",
"(",
"\"location.requires_python\"",
")",
"requires_python",
"=",
"getattr",
"(",
"c",
",",
"\"requires_python\"",
",",
"from_location",
"(",
"c",
")",
")",
"if",
"requires_python",
":",
"# Old specifications had people setting this to single digits",
"# which is effectively the same as '>=digit,<digit+1'",
"if",
"requires_python",
".",
"isdigit",
"(",
")",
":",
"requires_python",
"=",
"\">={0},<{1}\"",
".",
"format",
"(",
"requires_python",
",",
"int",
"(",
"requires_python",
")",
"+",
"1",
")",
"try",
":",
"specifierset",
"=",
"SpecifierSet",
"(",
"requires_python",
")",
"except",
"InvalidSpecifier",
":",
"continue",
"else",
":",
"if",
"not",
"specifierset",
".",
"contains",
"(",
"py_version",
")",
":",
"continue",
"all_candidates",
".",
"append",
"(",
"c",
")",
"return",
"all_candidates"
] |
Get a cleaned list of all the candidates with valid specifiers in the `requires_python` attributes.
|
[
"Get",
"a",
"cleaned",
"list",
"of",
"all",
"the",
"candidates",
"with",
"valid",
"specifiers",
"in",
"the",
"requires_python",
"attributes",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L803-L828
|
train
|
pypa/pipenv
|
pipenv/vendor/requirementslib/models/utils.py
|
get_name_variants
|
def get_name_variants(pkg):
# type: (STRING_TYPE) -> Set[STRING_TYPE]
"""
Given a packager name, get the variants of its name for both the canonicalized
and "safe" forms.
:param AnyStr pkg: The package to lookup
:returns: A list of names.
:rtype: Set
"""
if not isinstance(pkg, six.string_types):
raise TypeError("must provide a string to derive package names")
from pkg_resources import safe_name
from packaging.utils import canonicalize_name
pkg = pkg.lower()
names = {safe_name(pkg), canonicalize_name(pkg), pkg.replace("-", "_")}
return names
|
python
|
def get_name_variants(pkg):
# type: (STRING_TYPE) -> Set[STRING_TYPE]
"""
Given a packager name, get the variants of its name for both the canonicalized
and "safe" forms.
:param AnyStr pkg: The package to lookup
:returns: A list of names.
:rtype: Set
"""
if not isinstance(pkg, six.string_types):
raise TypeError("must provide a string to derive package names")
from pkg_resources import safe_name
from packaging.utils import canonicalize_name
pkg = pkg.lower()
names = {safe_name(pkg), canonicalize_name(pkg), pkg.replace("-", "_")}
return names
|
[
"def",
"get_name_variants",
"(",
"pkg",
")",
":",
"# type: (STRING_TYPE) -> Set[STRING_TYPE]",
"if",
"not",
"isinstance",
"(",
"pkg",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"must provide a string to derive package names\"",
")",
"from",
"pkg_resources",
"import",
"safe_name",
"from",
"packaging",
".",
"utils",
"import",
"canonicalize_name",
"pkg",
"=",
"pkg",
".",
"lower",
"(",
")",
"names",
"=",
"{",
"safe_name",
"(",
"pkg",
")",
",",
"canonicalize_name",
"(",
"pkg",
")",
",",
"pkg",
".",
"replace",
"(",
"\"-\"",
",",
"\"_\"",
")",
"}",
"return",
"names"
] |
Given a packager name, get the variants of its name for both the canonicalized
and "safe" forms.
:param AnyStr pkg: The package to lookup
:returns: A list of names.
:rtype: Set
|
[
"Given",
"a",
"packager",
"name",
"get",
"the",
"variants",
"of",
"its",
"name",
"for",
"both",
"the",
"canonicalized",
"and",
"safe",
"forms",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L870-L888
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/metadata.py
|
_best_version
|
def _best_version(fields):
"""Detect the best version depending on the fields used."""
def _has_marker(keys, markers):
for marker in markers:
if marker in keys:
return True
return False
keys = []
for key, value in fields.items():
if value in ([], 'UNKNOWN', None):
continue
keys.append(key)
possible_versions = ['1.0', '1.1', '1.2', '1.3', '2.0', '2.1']
# first let's try to see if a field is not part of one of the version
for key in keys:
if key not in _241_FIELDS and '1.0' in possible_versions:
possible_versions.remove('1.0')
logger.debug('Removed 1.0 due to %s', key)
if key not in _314_FIELDS and '1.1' in possible_versions:
possible_versions.remove('1.1')
logger.debug('Removed 1.1 due to %s', key)
if key not in _345_FIELDS and '1.2' in possible_versions:
possible_versions.remove('1.2')
logger.debug('Removed 1.2 due to %s', key)
if key not in _566_FIELDS and '1.3' in possible_versions:
possible_versions.remove('1.3')
logger.debug('Removed 1.3 due to %s', key)
if key not in _566_FIELDS and '2.1' in possible_versions:
if key != 'Description': # In 2.1, description allowed after headers
possible_versions.remove('2.1')
logger.debug('Removed 2.1 due to %s', key)
if key not in _426_FIELDS and '2.0' in possible_versions:
possible_versions.remove('2.0')
logger.debug('Removed 2.0 due to %s', key)
# possible_version contains qualified versions
if len(possible_versions) == 1:
return possible_versions[0] # found !
elif len(possible_versions) == 0:
logger.debug('Out of options - unknown metadata set: %s', fields)
raise MetadataConflictError('Unknown metadata set')
# let's see if one unique marker is found
is_1_1 = '1.1' in possible_versions and _has_marker(keys, _314_MARKERS)
is_1_2 = '1.2' in possible_versions and _has_marker(keys, _345_MARKERS)
is_2_1 = '2.1' in possible_versions and _has_marker(keys, _566_MARKERS)
is_2_0 = '2.0' in possible_versions and _has_marker(keys, _426_MARKERS)
if int(is_1_1) + int(is_1_2) + int(is_2_1) + int(is_2_0) > 1:
raise MetadataConflictError('You used incompatible 1.1/1.2/2.0/2.1 fields')
# we have the choice, 1.0, or 1.2, or 2.0
# - 1.0 has a broken Summary field but works with all tools
# - 1.1 is to avoid
# - 1.2 fixes Summary but has little adoption
# - 2.0 adds more features and is very new
if not is_1_1 and not is_1_2 and not is_2_1 and not is_2_0:
# we couldn't find any specific marker
if PKG_INFO_PREFERRED_VERSION in possible_versions:
return PKG_INFO_PREFERRED_VERSION
if is_1_1:
return '1.1'
if is_1_2:
return '1.2'
if is_2_1:
return '2.1'
return '2.0'
|
python
|
def _best_version(fields):
"""Detect the best version depending on the fields used."""
def _has_marker(keys, markers):
for marker in markers:
if marker in keys:
return True
return False
keys = []
for key, value in fields.items():
if value in ([], 'UNKNOWN', None):
continue
keys.append(key)
possible_versions = ['1.0', '1.1', '1.2', '1.3', '2.0', '2.1']
# first let's try to see if a field is not part of one of the version
for key in keys:
if key not in _241_FIELDS and '1.0' in possible_versions:
possible_versions.remove('1.0')
logger.debug('Removed 1.0 due to %s', key)
if key not in _314_FIELDS and '1.1' in possible_versions:
possible_versions.remove('1.1')
logger.debug('Removed 1.1 due to %s', key)
if key not in _345_FIELDS and '1.2' in possible_versions:
possible_versions.remove('1.2')
logger.debug('Removed 1.2 due to %s', key)
if key not in _566_FIELDS and '1.3' in possible_versions:
possible_versions.remove('1.3')
logger.debug('Removed 1.3 due to %s', key)
if key not in _566_FIELDS and '2.1' in possible_versions:
if key != 'Description': # In 2.1, description allowed after headers
possible_versions.remove('2.1')
logger.debug('Removed 2.1 due to %s', key)
if key not in _426_FIELDS and '2.0' in possible_versions:
possible_versions.remove('2.0')
logger.debug('Removed 2.0 due to %s', key)
# possible_version contains qualified versions
if len(possible_versions) == 1:
return possible_versions[0] # found !
elif len(possible_versions) == 0:
logger.debug('Out of options - unknown metadata set: %s', fields)
raise MetadataConflictError('Unknown metadata set')
# let's see if one unique marker is found
is_1_1 = '1.1' in possible_versions and _has_marker(keys, _314_MARKERS)
is_1_2 = '1.2' in possible_versions and _has_marker(keys, _345_MARKERS)
is_2_1 = '2.1' in possible_versions and _has_marker(keys, _566_MARKERS)
is_2_0 = '2.0' in possible_versions and _has_marker(keys, _426_MARKERS)
if int(is_1_1) + int(is_1_2) + int(is_2_1) + int(is_2_0) > 1:
raise MetadataConflictError('You used incompatible 1.1/1.2/2.0/2.1 fields')
# we have the choice, 1.0, or 1.2, or 2.0
# - 1.0 has a broken Summary field but works with all tools
# - 1.1 is to avoid
# - 1.2 fixes Summary but has little adoption
# - 2.0 adds more features and is very new
if not is_1_1 and not is_1_2 and not is_2_1 and not is_2_0:
# we couldn't find any specific marker
if PKG_INFO_PREFERRED_VERSION in possible_versions:
return PKG_INFO_PREFERRED_VERSION
if is_1_1:
return '1.1'
if is_1_2:
return '1.2'
if is_2_1:
return '2.1'
return '2.0'
|
[
"def",
"_best_version",
"(",
"fields",
")",
":",
"def",
"_has_marker",
"(",
"keys",
",",
"markers",
")",
":",
"for",
"marker",
"in",
"markers",
":",
"if",
"marker",
"in",
"keys",
":",
"return",
"True",
"return",
"False",
"keys",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"fields",
".",
"items",
"(",
")",
":",
"if",
"value",
"in",
"(",
"[",
"]",
",",
"'UNKNOWN'",
",",
"None",
")",
":",
"continue",
"keys",
".",
"append",
"(",
"key",
")",
"possible_versions",
"=",
"[",
"'1.0'",
",",
"'1.1'",
",",
"'1.2'",
",",
"'1.3'",
",",
"'2.0'",
",",
"'2.1'",
"]",
"# first let's try to see if a field is not part of one of the version",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
"not",
"in",
"_241_FIELDS",
"and",
"'1.0'",
"in",
"possible_versions",
":",
"possible_versions",
".",
"remove",
"(",
"'1.0'",
")",
"logger",
".",
"debug",
"(",
"'Removed 1.0 due to %s'",
",",
"key",
")",
"if",
"key",
"not",
"in",
"_314_FIELDS",
"and",
"'1.1'",
"in",
"possible_versions",
":",
"possible_versions",
".",
"remove",
"(",
"'1.1'",
")",
"logger",
".",
"debug",
"(",
"'Removed 1.1 due to %s'",
",",
"key",
")",
"if",
"key",
"not",
"in",
"_345_FIELDS",
"and",
"'1.2'",
"in",
"possible_versions",
":",
"possible_versions",
".",
"remove",
"(",
"'1.2'",
")",
"logger",
".",
"debug",
"(",
"'Removed 1.2 due to %s'",
",",
"key",
")",
"if",
"key",
"not",
"in",
"_566_FIELDS",
"and",
"'1.3'",
"in",
"possible_versions",
":",
"possible_versions",
".",
"remove",
"(",
"'1.3'",
")",
"logger",
".",
"debug",
"(",
"'Removed 1.3 due to %s'",
",",
"key",
")",
"if",
"key",
"not",
"in",
"_566_FIELDS",
"and",
"'2.1'",
"in",
"possible_versions",
":",
"if",
"key",
"!=",
"'Description'",
":",
"# In 2.1, description allowed after headers",
"possible_versions",
".",
"remove",
"(",
"'2.1'",
")",
"logger",
".",
"debug",
"(",
"'Removed 2.1 due to %s'",
",",
"key",
")",
"if",
"key",
"not",
"in",
"_426_FIELDS",
"and",
"'2.0'",
"in",
"possible_versions",
":",
"possible_versions",
".",
"remove",
"(",
"'2.0'",
")",
"logger",
".",
"debug",
"(",
"'Removed 2.0 due to %s'",
",",
"key",
")",
"# possible_version contains qualified versions",
"if",
"len",
"(",
"possible_versions",
")",
"==",
"1",
":",
"return",
"possible_versions",
"[",
"0",
"]",
"# found !",
"elif",
"len",
"(",
"possible_versions",
")",
"==",
"0",
":",
"logger",
".",
"debug",
"(",
"'Out of options - unknown metadata set: %s'",
",",
"fields",
")",
"raise",
"MetadataConflictError",
"(",
"'Unknown metadata set'",
")",
"# let's see if one unique marker is found",
"is_1_1",
"=",
"'1.1'",
"in",
"possible_versions",
"and",
"_has_marker",
"(",
"keys",
",",
"_314_MARKERS",
")",
"is_1_2",
"=",
"'1.2'",
"in",
"possible_versions",
"and",
"_has_marker",
"(",
"keys",
",",
"_345_MARKERS",
")",
"is_2_1",
"=",
"'2.1'",
"in",
"possible_versions",
"and",
"_has_marker",
"(",
"keys",
",",
"_566_MARKERS",
")",
"is_2_0",
"=",
"'2.0'",
"in",
"possible_versions",
"and",
"_has_marker",
"(",
"keys",
",",
"_426_MARKERS",
")",
"if",
"int",
"(",
"is_1_1",
")",
"+",
"int",
"(",
"is_1_2",
")",
"+",
"int",
"(",
"is_2_1",
")",
"+",
"int",
"(",
"is_2_0",
")",
">",
"1",
":",
"raise",
"MetadataConflictError",
"(",
"'You used incompatible 1.1/1.2/2.0/2.1 fields'",
")",
"# we have the choice, 1.0, or 1.2, or 2.0",
"# - 1.0 has a broken Summary field but works with all tools",
"# - 1.1 is to avoid",
"# - 1.2 fixes Summary but has little adoption",
"# - 2.0 adds more features and is very new",
"if",
"not",
"is_1_1",
"and",
"not",
"is_1_2",
"and",
"not",
"is_2_1",
"and",
"not",
"is_2_0",
":",
"# we couldn't find any specific marker",
"if",
"PKG_INFO_PREFERRED_VERSION",
"in",
"possible_versions",
":",
"return",
"PKG_INFO_PREFERRED_VERSION",
"if",
"is_1_1",
":",
"return",
"'1.1'",
"if",
"is_1_2",
":",
"return",
"'1.2'",
"if",
"is_2_1",
":",
"return",
"'2.1'",
"return",
"'2.0'"
] |
Detect the best version depending on the fields used.
|
[
"Detect",
"the",
"best",
"version",
"depending",
"on",
"the",
"fields",
"used",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L124-L193
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/metadata.py
|
_get_name_and_version
|
def _get_name_and_version(name, version, for_filename=False):
"""Return the distribution name with version.
If for_filename is true, return a filename-escaped form."""
if for_filename:
# For both name and version any runs of non-alphanumeric or '.'
# characters are replaced with a single '-'. Additionally any
# spaces in the version string become '.'
name = _FILESAFE.sub('-', name)
version = _FILESAFE.sub('-', version.replace(' ', '.'))
return '%s-%s' % (name, version)
|
python
|
def _get_name_and_version(name, version, for_filename=False):
"""Return the distribution name with version.
If for_filename is true, return a filename-escaped form."""
if for_filename:
# For both name and version any runs of non-alphanumeric or '.'
# characters are replaced with a single '-'. Additionally any
# spaces in the version string become '.'
name = _FILESAFE.sub('-', name)
version = _FILESAFE.sub('-', version.replace(' ', '.'))
return '%s-%s' % (name, version)
|
[
"def",
"_get_name_and_version",
"(",
"name",
",",
"version",
",",
"for_filename",
"=",
"False",
")",
":",
"if",
"for_filename",
":",
"# For both name and version any runs of non-alphanumeric or '.'",
"# characters are replaced with a single '-'. Additionally any",
"# spaces in the version string become '.'",
"name",
"=",
"_FILESAFE",
".",
"sub",
"(",
"'-'",
",",
"name",
")",
"version",
"=",
"_FILESAFE",
".",
"sub",
"(",
"'-'",
",",
"version",
".",
"replace",
"(",
"' '",
",",
"'.'",
")",
")",
"return",
"'%s-%s'",
"%",
"(",
"name",
",",
"version",
")"
] |
Return the distribution name with version.
If for_filename is true, return a filename-escaped form.
|
[
"Return",
"the",
"distribution",
"name",
"with",
"version",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L247-L257
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/metadata.py
|
LegacyMetadata.read
|
def read(self, filepath):
"""Read the metadata values from a file path."""
fp = codecs.open(filepath, 'r', encoding='utf-8')
try:
self.read_file(fp)
finally:
fp.close()
|
python
|
def read(self, filepath):
"""Read the metadata values from a file path."""
fp = codecs.open(filepath, 'r', encoding='utf-8')
try:
self.read_file(fp)
finally:
fp.close()
|
[
"def",
"read",
"(",
"self",
",",
"filepath",
")",
":",
"fp",
"=",
"codecs",
".",
"open",
"(",
"filepath",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"try",
":",
"self",
".",
"read_file",
"(",
"fp",
")",
"finally",
":",
"fp",
".",
"close",
"(",
")"
] |
Read the metadata values from a file path.
|
[
"Read",
"the",
"metadata",
"values",
"from",
"a",
"file",
"path",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L354-L360
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/metadata.py
|
LegacyMetadata.write
|
def write(self, filepath, skip_unknown=False):
"""Write the metadata fields to filepath."""
fp = codecs.open(filepath, 'w', encoding='utf-8')
try:
self.write_file(fp, skip_unknown)
finally:
fp.close()
|
python
|
def write(self, filepath, skip_unknown=False):
"""Write the metadata fields to filepath."""
fp = codecs.open(filepath, 'w', encoding='utf-8')
try:
self.write_file(fp, skip_unknown)
finally:
fp.close()
|
[
"def",
"write",
"(",
"self",
",",
"filepath",
",",
"skip_unknown",
"=",
"False",
")",
":",
"fp",
"=",
"codecs",
".",
"open",
"(",
"filepath",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"try",
":",
"self",
".",
"write_file",
"(",
"fp",
",",
"skip_unknown",
")",
"finally",
":",
"fp",
".",
"close",
"(",
")"
] |
Write the metadata fields to filepath.
|
[
"Write",
"the",
"metadata",
"fields",
"to",
"filepath",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L385-L391
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/metadata.py
|
LegacyMetadata.write_file
|
def write_file(self, fileobject, skip_unknown=False):
"""Write the PKG-INFO format data to a file object."""
self.set_metadata_version()
for field in _version2fieldlist(self['Metadata-Version']):
values = self.get(field)
if skip_unknown and values in ('UNKNOWN', [], ['UNKNOWN']):
continue
if field in _ELEMENTSFIELD:
self._write_field(fileobject, field, ','.join(values))
continue
if field not in _LISTFIELDS:
if field == 'Description':
if self.metadata_version in ('1.0', '1.1'):
values = values.replace('\n', '\n ')
else:
values = values.replace('\n', '\n |')
values = [values]
if field in _LISTTUPLEFIELDS:
values = [','.join(value) for value in values]
for value in values:
self._write_field(fileobject, field, value)
|
python
|
def write_file(self, fileobject, skip_unknown=False):
"""Write the PKG-INFO format data to a file object."""
self.set_metadata_version()
for field in _version2fieldlist(self['Metadata-Version']):
values = self.get(field)
if skip_unknown and values in ('UNKNOWN', [], ['UNKNOWN']):
continue
if field in _ELEMENTSFIELD:
self._write_field(fileobject, field, ','.join(values))
continue
if field not in _LISTFIELDS:
if field == 'Description':
if self.metadata_version in ('1.0', '1.1'):
values = values.replace('\n', '\n ')
else:
values = values.replace('\n', '\n |')
values = [values]
if field in _LISTTUPLEFIELDS:
values = [','.join(value) for value in values]
for value in values:
self._write_field(fileobject, field, value)
|
[
"def",
"write_file",
"(",
"self",
",",
"fileobject",
",",
"skip_unknown",
"=",
"False",
")",
":",
"self",
".",
"set_metadata_version",
"(",
")",
"for",
"field",
"in",
"_version2fieldlist",
"(",
"self",
"[",
"'Metadata-Version'",
"]",
")",
":",
"values",
"=",
"self",
".",
"get",
"(",
"field",
")",
"if",
"skip_unknown",
"and",
"values",
"in",
"(",
"'UNKNOWN'",
",",
"[",
"]",
",",
"[",
"'UNKNOWN'",
"]",
")",
":",
"continue",
"if",
"field",
"in",
"_ELEMENTSFIELD",
":",
"self",
".",
"_write_field",
"(",
"fileobject",
",",
"field",
",",
"','",
".",
"join",
"(",
"values",
")",
")",
"continue",
"if",
"field",
"not",
"in",
"_LISTFIELDS",
":",
"if",
"field",
"==",
"'Description'",
":",
"if",
"self",
".",
"metadata_version",
"in",
"(",
"'1.0'",
",",
"'1.1'",
")",
":",
"values",
"=",
"values",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n '",
")",
"else",
":",
"values",
"=",
"values",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n |'",
")",
"values",
"=",
"[",
"values",
"]",
"if",
"field",
"in",
"_LISTTUPLEFIELDS",
":",
"values",
"=",
"[",
"','",
".",
"join",
"(",
"value",
")",
"for",
"value",
"in",
"values",
"]",
"for",
"value",
"in",
"values",
":",
"self",
".",
"_write_field",
"(",
"fileobject",
",",
"field",
",",
"value",
")"
] |
Write the PKG-INFO format data to a file object.
|
[
"Write",
"the",
"PKG",
"-",
"INFO",
"format",
"data",
"to",
"a",
"file",
"object",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L393-L416
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/metadata.py
|
LegacyMetadata.update
|
def update(self, other=None, **kwargs):
"""Set metadata values from the given iterable `other` and kwargs.
Behavior is like `dict.update`: If `other` has a ``keys`` method,
they are looped over and ``self[key]`` is assigned ``other[key]``.
Else, ``other`` is an iterable of ``(key, value)`` iterables.
Keys that don't match a metadata field or that have an empty value are
dropped.
"""
def _set(key, value):
if key in _ATTR2FIELD and value:
self.set(self._convert_name(key), value)
if not other:
# other is None or empty container
pass
elif hasattr(other, 'keys'):
for k in other.keys():
_set(k, other[k])
else:
for k, v in other:
_set(k, v)
if kwargs:
for k, v in kwargs.items():
_set(k, v)
|
python
|
def update(self, other=None, **kwargs):
"""Set metadata values from the given iterable `other` and kwargs.
Behavior is like `dict.update`: If `other` has a ``keys`` method,
they are looped over and ``self[key]`` is assigned ``other[key]``.
Else, ``other`` is an iterable of ``(key, value)`` iterables.
Keys that don't match a metadata field or that have an empty value are
dropped.
"""
def _set(key, value):
if key in _ATTR2FIELD and value:
self.set(self._convert_name(key), value)
if not other:
# other is None or empty container
pass
elif hasattr(other, 'keys'):
for k in other.keys():
_set(k, other[k])
else:
for k, v in other:
_set(k, v)
if kwargs:
for k, v in kwargs.items():
_set(k, v)
|
[
"def",
"update",
"(",
"self",
",",
"other",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_set",
"(",
"key",
",",
"value",
")",
":",
"if",
"key",
"in",
"_ATTR2FIELD",
"and",
"value",
":",
"self",
".",
"set",
"(",
"self",
".",
"_convert_name",
"(",
"key",
")",
",",
"value",
")",
"if",
"not",
"other",
":",
"# other is None or empty container",
"pass",
"elif",
"hasattr",
"(",
"other",
",",
"'keys'",
")",
":",
"for",
"k",
"in",
"other",
".",
"keys",
"(",
")",
":",
"_set",
"(",
"k",
",",
"other",
"[",
"k",
"]",
")",
"else",
":",
"for",
"k",
",",
"v",
"in",
"other",
":",
"_set",
"(",
"k",
",",
"v",
")",
"if",
"kwargs",
":",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"_set",
"(",
"k",
",",
"v",
")"
] |
Set metadata values from the given iterable `other` and kwargs.
Behavior is like `dict.update`: If `other` has a ``keys`` method,
they are looped over and ``self[key]`` is assigned ``other[key]``.
Else, ``other`` is an iterable of ``(key, value)`` iterables.
Keys that don't match a metadata field or that have an empty value are
dropped.
|
[
"Set",
"metadata",
"values",
"from",
"the",
"given",
"iterable",
"other",
"and",
"kwargs",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L418-L444
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/metadata.py
|
LegacyMetadata.set
|
def set(self, name, value):
"""Control then set a metadata field."""
name = self._convert_name(name)
if ((name in _ELEMENTSFIELD or name == 'Platform') and
not isinstance(value, (list, tuple))):
if isinstance(value, string_types):
value = [v.strip() for v in value.split(',')]
else:
value = []
elif (name in _LISTFIELDS and
not isinstance(value, (list, tuple))):
if isinstance(value, string_types):
value = [value]
else:
value = []
if logger.isEnabledFor(logging.WARNING):
project_name = self['Name']
scheme = get_scheme(self.scheme)
if name in _PREDICATE_FIELDS and value is not None:
for v in value:
# check that the values are valid
if not scheme.is_valid_matcher(v.split(';')[0]):
logger.warning(
"'%s': '%s' is not valid (field '%s')",
project_name, v, name)
# FIXME this rejects UNKNOWN, is that right?
elif name in _VERSIONS_FIELDS and value is not None:
if not scheme.is_valid_constraint_list(value):
logger.warning("'%s': '%s' is not a valid version (field '%s')",
project_name, value, name)
elif name in _VERSION_FIELDS and value is not None:
if not scheme.is_valid_version(value):
logger.warning("'%s': '%s' is not a valid version (field '%s')",
project_name, value, name)
if name in _UNICODEFIELDS:
if name == 'Description':
value = self._remove_line_prefix(value)
self._fields[name] = value
|
python
|
def set(self, name, value):
"""Control then set a metadata field."""
name = self._convert_name(name)
if ((name in _ELEMENTSFIELD or name == 'Platform') and
not isinstance(value, (list, tuple))):
if isinstance(value, string_types):
value = [v.strip() for v in value.split(',')]
else:
value = []
elif (name in _LISTFIELDS and
not isinstance(value, (list, tuple))):
if isinstance(value, string_types):
value = [value]
else:
value = []
if logger.isEnabledFor(logging.WARNING):
project_name = self['Name']
scheme = get_scheme(self.scheme)
if name in _PREDICATE_FIELDS and value is not None:
for v in value:
# check that the values are valid
if not scheme.is_valid_matcher(v.split(';')[0]):
logger.warning(
"'%s': '%s' is not valid (field '%s')",
project_name, v, name)
# FIXME this rejects UNKNOWN, is that right?
elif name in _VERSIONS_FIELDS and value is not None:
if not scheme.is_valid_constraint_list(value):
logger.warning("'%s': '%s' is not a valid version (field '%s')",
project_name, value, name)
elif name in _VERSION_FIELDS and value is not None:
if not scheme.is_valid_version(value):
logger.warning("'%s': '%s' is not a valid version (field '%s')",
project_name, value, name)
if name in _UNICODEFIELDS:
if name == 'Description':
value = self._remove_line_prefix(value)
self._fields[name] = value
|
[
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"name",
"=",
"self",
".",
"_convert_name",
"(",
"name",
")",
"if",
"(",
"(",
"name",
"in",
"_ELEMENTSFIELD",
"or",
"name",
"==",
"'Platform'",
")",
"and",
"not",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"value",
"=",
"[",
"v",
".",
"strip",
"(",
")",
"for",
"v",
"in",
"value",
".",
"split",
"(",
"','",
")",
"]",
"else",
":",
"value",
"=",
"[",
"]",
"elif",
"(",
"name",
"in",
"_LISTFIELDS",
"and",
"not",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"value",
"=",
"[",
"value",
"]",
"else",
":",
"value",
"=",
"[",
"]",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"WARNING",
")",
":",
"project_name",
"=",
"self",
"[",
"'Name'",
"]",
"scheme",
"=",
"get_scheme",
"(",
"self",
".",
"scheme",
")",
"if",
"name",
"in",
"_PREDICATE_FIELDS",
"and",
"value",
"is",
"not",
"None",
":",
"for",
"v",
"in",
"value",
":",
"# check that the values are valid",
"if",
"not",
"scheme",
".",
"is_valid_matcher",
"(",
"v",
".",
"split",
"(",
"';'",
")",
"[",
"0",
"]",
")",
":",
"logger",
".",
"warning",
"(",
"\"'%s': '%s' is not valid (field '%s')\"",
",",
"project_name",
",",
"v",
",",
"name",
")",
"# FIXME this rejects UNKNOWN, is that right?",
"elif",
"name",
"in",
"_VERSIONS_FIELDS",
"and",
"value",
"is",
"not",
"None",
":",
"if",
"not",
"scheme",
".",
"is_valid_constraint_list",
"(",
"value",
")",
":",
"logger",
".",
"warning",
"(",
"\"'%s': '%s' is not a valid version (field '%s')\"",
",",
"project_name",
",",
"value",
",",
"name",
")",
"elif",
"name",
"in",
"_VERSION_FIELDS",
"and",
"value",
"is",
"not",
"None",
":",
"if",
"not",
"scheme",
".",
"is_valid_version",
"(",
"value",
")",
":",
"logger",
".",
"warning",
"(",
"\"'%s': '%s' is not a valid version (field '%s')\"",
",",
"project_name",
",",
"value",
",",
"name",
")",
"if",
"name",
"in",
"_UNICODEFIELDS",
":",
"if",
"name",
"==",
"'Description'",
":",
"value",
"=",
"self",
".",
"_remove_line_prefix",
"(",
"value",
")",
"self",
".",
"_fields",
"[",
"name",
"]",
"=",
"value"
] |
Control then set a metadata field.
|
[
"Control",
"then",
"set",
"a",
"metadata",
"field",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L446-L488
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/metadata.py
|
LegacyMetadata.get
|
def get(self, name, default=_MISSING):
"""Get a metadata field."""
name = self._convert_name(name)
if name not in self._fields:
if default is _MISSING:
default = self._default_value(name)
return default
if name in _UNICODEFIELDS:
value = self._fields[name]
return value
elif name in _LISTFIELDS:
value = self._fields[name]
if value is None:
return []
res = []
for val in value:
if name not in _LISTTUPLEFIELDS:
res.append(val)
else:
# That's for Project-URL
res.append((val[0], val[1]))
return res
elif name in _ELEMENTSFIELD:
value = self._fields[name]
if isinstance(value, string_types):
return value.split(',')
return self._fields[name]
|
python
|
def get(self, name, default=_MISSING):
"""Get a metadata field."""
name = self._convert_name(name)
if name not in self._fields:
if default is _MISSING:
default = self._default_value(name)
return default
if name in _UNICODEFIELDS:
value = self._fields[name]
return value
elif name in _LISTFIELDS:
value = self._fields[name]
if value is None:
return []
res = []
for val in value:
if name not in _LISTTUPLEFIELDS:
res.append(val)
else:
# That's for Project-URL
res.append((val[0], val[1]))
return res
elif name in _ELEMENTSFIELD:
value = self._fields[name]
if isinstance(value, string_types):
return value.split(',')
return self._fields[name]
|
[
"def",
"get",
"(",
"self",
",",
"name",
",",
"default",
"=",
"_MISSING",
")",
":",
"name",
"=",
"self",
".",
"_convert_name",
"(",
"name",
")",
"if",
"name",
"not",
"in",
"self",
".",
"_fields",
":",
"if",
"default",
"is",
"_MISSING",
":",
"default",
"=",
"self",
".",
"_default_value",
"(",
"name",
")",
"return",
"default",
"if",
"name",
"in",
"_UNICODEFIELDS",
":",
"value",
"=",
"self",
".",
"_fields",
"[",
"name",
"]",
"return",
"value",
"elif",
"name",
"in",
"_LISTFIELDS",
":",
"value",
"=",
"self",
".",
"_fields",
"[",
"name",
"]",
"if",
"value",
"is",
"None",
":",
"return",
"[",
"]",
"res",
"=",
"[",
"]",
"for",
"val",
"in",
"value",
":",
"if",
"name",
"not",
"in",
"_LISTTUPLEFIELDS",
":",
"res",
".",
"append",
"(",
"val",
")",
"else",
":",
"# That's for Project-URL",
"res",
".",
"append",
"(",
"(",
"val",
"[",
"0",
"]",
",",
"val",
"[",
"1",
"]",
")",
")",
"return",
"res",
"elif",
"name",
"in",
"_ELEMENTSFIELD",
":",
"value",
"=",
"self",
".",
"_fields",
"[",
"name",
"]",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"return",
"value",
".",
"split",
"(",
"','",
")",
"return",
"self",
".",
"_fields",
"[",
"name",
"]"
] |
Get a metadata field.
|
[
"Get",
"a",
"metadata",
"field",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L490-L517
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/metadata.py
|
LegacyMetadata.todict
|
def todict(self, skip_missing=False):
"""Return fields as a dict.
Field names will be converted to use the underscore-lowercase style
instead of hyphen-mixed case (i.e. home_page instead of Home-page).
"""
self.set_metadata_version()
mapping_1_0 = (
('metadata_version', 'Metadata-Version'),
('name', 'Name'),
('version', 'Version'),
('summary', 'Summary'),
('home_page', 'Home-page'),
('author', 'Author'),
('author_email', 'Author-email'),
('license', 'License'),
('description', 'Description'),
('keywords', 'Keywords'),
('platform', 'Platform'),
('classifiers', 'Classifier'),
('download_url', 'Download-URL'),
)
data = {}
for key, field_name in mapping_1_0:
if not skip_missing or field_name in self._fields:
data[key] = self[field_name]
if self['Metadata-Version'] == '1.2':
mapping_1_2 = (
('requires_dist', 'Requires-Dist'),
('requires_python', 'Requires-Python'),
('requires_external', 'Requires-External'),
('provides_dist', 'Provides-Dist'),
('obsoletes_dist', 'Obsoletes-Dist'),
('project_url', 'Project-URL'),
('maintainer', 'Maintainer'),
('maintainer_email', 'Maintainer-email'),
)
for key, field_name in mapping_1_2:
if not skip_missing or field_name in self._fields:
if key != 'project_url':
data[key] = self[field_name]
else:
data[key] = [','.join(u) for u in self[field_name]]
elif self['Metadata-Version'] == '1.1':
mapping_1_1 = (
('provides', 'Provides'),
('requires', 'Requires'),
('obsoletes', 'Obsoletes'),
)
for key, field_name in mapping_1_1:
if not skip_missing or field_name in self._fields:
data[key] = self[field_name]
return data
|
python
|
def todict(self, skip_missing=False):
"""Return fields as a dict.
Field names will be converted to use the underscore-lowercase style
instead of hyphen-mixed case (i.e. home_page instead of Home-page).
"""
self.set_metadata_version()
mapping_1_0 = (
('metadata_version', 'Metadata-Version'),
('name', 'Name'),
('version', 'Version'),
('summary', 'Summary'),
('home_page', 'Home-page'),
('author', 'Author'),
('author_email', 'Author-email'),
('license', 'License'),
('description', 'Description'),
('keywords', 'Keywords'),
('platform', 'Platform'),
('classifiers', 'Classifier'),
('download_url', 'Download-URL'),
)
data = {}
for key, field_name in mapping_1_0:
if not skip_missing or field_name in self._fields:
data[key] = self[field_name]
if self['Metadata-Version'] == '1.2':
mapping_1_2 = (
('requires_dist', 'Requires-Dist'),
('requires_python', 'Requires-Python'),
('requires_external', 'Requires-External'),
('provides_dist', 'Provides-Dist'),
('obsoletes_dist', 'Obsoletes-Dist'),
('project_url', 'Project-URL'),
('maintainer', 'Maintainer'),
('maintainer_email', 'Maintainer-email'),
)
for key, field_name in mapping_1_2:
if not skip_missing or field_name in self._fields:
if key != 'project_url':
data[key] = self[field_name]
else:
data[key] = [','.join(u) for u in self[field_name]]
elif self['Metadata-Version'] == '1.1':
mapping_1_1 = (
('provides', 'Provides'),
('requires', 'Requires'),
('obsoletes', 'Obsoletes'),
)
for key, field_name in mapping_1_1:
if not skip_missing or field_name in self._fields:
data[key] = self[field_name]
return data
|
[
"def",
"todict",
"(",
"self",
",",
"skip_missing",
"=",
"False",
")",
":",
"self",
".",
"set_metadata_version",
"(",
")",
"mapping_1_0",
"=",
"(",
"(",
"'metadata_version'",
",",
"'Metadata-Version'",
")",
",",
"(",
"'name'",
",",
"'Name'",
")",
",",
"(",
"'version'",
",",
"'Version'",
")",
",",
"(",
"'summary'",
",",
"'Summary'",
")",
",",
"(",
"'home_page'",
",",
"'Home-page'",
")",
",",
"(",
"'author'",
",",
"'Author'",
")",
",",
"(",
"'author_email'",
",",
"'Author-email'",
")",
",",
"(",
"'license'",
",",
"'License'",
")",
",",
"(",
"'description'",
",",
"'Description'",
")",
",",
"(",
"'keywords'",
",",
"'Keywords'",
")",
",",
"(",
"'platform'",
",",
"'Platform'",
")",
",",
"(",
"'classifiers'",
",",
"'Classifier'",
")",
",",
"(",
"'download_url'",
",",
"'Download-URL'",
")",
",",
")",
"data",
"=",
"{",
"}",
"for",
"key",
",",
"field_name",
"in",
"mapping_1_0",
":",
"if",
"not",
"skip_missing",
"or",
"field_name",
"in",
"self",
".",
"_fields",
":",
"data",
"[",
"key",
"]",
"=",
"self",
"[",
"field_name",
"]",
"if",
"self",
"[",
"'Metadata-Version'",
"]",
"==",
"'1.2'",
":",
"mapping_1_2",
"=",
"(",
"(",
"'requires_dist'",
",",
"'Requires-Dist'",
")",
",",
"(",
"'requires_python'",
",",
"'Requires-Python'",
")",
",",
"(",
"'requires_external'",
",",
"'Requires-External'",
")",
",",
"(",
"'provides_dist'",
",",
"'Provides-Dist'",
")",
",",
"(",
"'obsoletes_dist'",
",",
"'Obsoletes-Dist'",
")",
",",
"(",
"'project_url'",
",",
"'Project-URL'",
")",
",",
"(",
"'maintainer'",
",",
"'Maintainer'",
")",
",",
"(",
"'maintainer_email'",
",",
"'Maintainer-email'",
")",
",",
")",
"for",
"key",
",",
"field_name",
"in",
"mapping_1_2",
":",
"if",
"not",
"skip_missing",
"or",
"field_name",
"in",
"self",
".",
"_fields",
":",
"if",
"key",
"!=",
"'project_url'",
":",
"data",
"[",
"key",
"]",
"=",
"self",
"[",
"field_name",
"]",
"else",
":",
"data",
"[",
"key",
"]",
"=",
"[",
"','",
".",
"join",
"(",
"u",
")",
"for",
"u",
"in",
"self",
"[",
"field_name",
"]",
"]",
"elif",
"self",
"[",
"'Metadata-Version'",
"]",
"==",
"'1.1'",
":",
"mapping_1_1",
"=",
"(",
"(",
"'provides'",
",",
"'Provides'",
")",
",",
"(",
"'requires'",
",",
"'Requires'",
")",
",",
"(",
"'obsoletes'",
",",
"'Obsoletes'",
")",
",",
")",
"for",
"key",
",",
"field_name",
"in",
"mapping_1_1",
":",
"if",
"not",
"skip_missing",
"or",
"field_name",
"in",
"self",
".",
"_fields",
":",
"data",
"[",
"key",
"]",
"=",
"self",
"[",
"field_name",
"]",
"return",
"data"
] |
Return fields as a dict.
Field names will be converted to use the underscore-lowercase style
instead of hyphen-mixed case (i.e. home_page instead of Home-page).
|
[
"Return",
"fields",
"as",
"a",
"dict",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L563-L620
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/metadata.py
|
Metadata.get_requirements
|
def get_requirements(self, reqts, extras=None, env=None):
"""
Base method to get dependencies, given a set of extras
to satisfy and an optional environment context.
:param reqts: A list of sometimes-wanted dependencies,
perhaps dependent on extras and environment.
:param extras: A list of optional components being requested.
:param env: An optional environment for marker evaluation.
"""
if self._legacy:
result = reqts
else:
result = []
extras = get_extras(extras or [], self.extras)
for d in reqts:
if 'extra' not in d and 'environment' not in d:
# unconditional
include = True
else:
if 'extra' not in d:
# Not extra-dependent - only environment-dependent
include = True
else:
include = d.get('extra') in extras
if include:
# Not excluded because of extras, check environment
marker = d.get('environment')
if marker:
include = interpret(marker, env)
if include:
result.extend(d['requires'])
for key in ('build', 'dev', 'test'):
e = ':%s:' % key
if e in extras:
extras.remove(e)
# A recursive call, but it should terminate since 'test'
# has been removed from the extras
reqts = self._data.get('%s_requires' % key, [])
result.extend(self.get_requirements(reqts, extras=extras,
env=env))
return result
|
python
|
def get_requirements(self, reqts, extras=None, env=None):
"""
Base method to get dependencies, given a set of extras
to satisfy and an optional environment context.
:param reqts: A list of sometimes-wanted dependencies,
perhaps dependent on extras and environment.
:param extras: A list of optional components being requested.
:param env: An optional environment for marker evaluation.
"""
if self._legacy:
result = reqts
else:
result = []
extras = get_extras(extras or [], self.extras)
for d in reqts:
if 'extra' not in d and 'environment' not in d:
# unconditional
include = True
else:
if 'extra' not in d:
# Not extra-dependent - only environment-dependent
include = True
else:
include = d.get('extra') in extras
if include:
# Not excluded because of extras, check environment
marker = d.get('environment')
if marker:
include = interpret(marker, env)
if include:
result.extend(d['requires'])
for key in ('build', 'dev', 'test'):
e = ':%s:' % key
if e in extras:
extras.remove(e)
# A recursive call, but it should terminate since 'test'
# has been removed from the extras
reqts = self._data.get('%s_requires' % key, [])
result.extend(self.get_requirements(reqts, extras=extras,
env=env))
return result
|
[
"def",
"get_requirements",
"(",
"self",
",",
"reqts",
",",
"extras",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"if",
"self",
".",
"_legacy",
":",
"result",
"=",
"reqts",
"else",
":",
"result",
"=",
"[",
"]",
"extras",
"=",
"get_extras",
"(",
"extras",
"or",
"[",
"]",
",",
"self",
".",
"extras",
")",
"for",
"d",
"in",
"reqts",
":",
"if",
"'extra'",
"not",
"in",
"d",
"and",
"'environment'",
"not",
"in",
"d",
":",
"# unconditional",
"include",
"=",
"True",
"else",
":",
"if",
"'extra'",
"not",
"in",
"d",
":",
"# Not extra-dependent - only environment-dependent",
"include",
"=",
"True",
"else",
":",
"include",
"=",
"d",
".",
"get",
"(",
"'extra'",
")",
"in",
"extras",
"if",
"include",
":",
"# Not excluded because of extras, check environment",
"marker",
"=",
"d",
".",
"get",
"(",
"'environment'",
")",
"if",
"marker",
":",
"include",
"=",
"interpret",
"(",
"marker",
",",
"env",
")",
"if",
"include",
":",
"result",
".",
"extend",
"(",
"d",
"[",
"'requires'",
"]",
")",
"for",
"key",
"in",
"(",
"'build'",
",",
"'dev'",
",",
"'test'",
")",
":",
"e",
"=",
"':%s:'",
"%",
"key",
"if",
"e",
"in",
"extras",
":",
"extras",
".",
"remove",
"(",
"e",
")",
"# A recursive call, but it should terminate since 'test'",
"# has been removed from the extras",
"reqts",
"=",
"self",
".",
"_data",
".",
"get",
"(",
"'%s_requires'",
"%",
"key",
",",
"[",
"]",
")",
"result",
".",
"extend",
"(",
"self",
".",
"get_requirements",
"(",
"reqts",
",",
"extras",
"=",
"extras",
",",
"env",
"=",
"env",
")",
")",
"return",
"result"
] |
Base method to get dependencies, given a set of extras
to satisfy and an optional environment context.
:param reqts: A list of sometimes-wanted dependencies,
perhaps dependent on extras and environment.
:param extras: A list of optional components being requested.
:param env: An optional environment for marker evaluation.
|
[
"Base",
"method",
"to",
"get",
"dependencies",
"given",
"a",
"set",
"of",
"extras",
"to",
"satisfy",
"and",
"an",
"optional",
"environment",
"context",
".",
":",
"param",
"reqts",
":",
"A",
"list",
"of",
"sometimes",
"-",
"wanted",
"dependencies",
"perhaps",
"dependent",
"on",
"extras",
"and",
"environment",
".",
":",
"param",
"extras",
":",
"A",
"list",
"of",
"optional",
"components",
"being",
"requested",
".",
":",
"param",
"env",
":",
"An",
"optional",
"environment",
"for",
"marker",
"evaluation",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L880-L920
|
train
|
pypa/pipenv
|
pipenv/vendor/six.py
|
remove_move
|
def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,))
|
python
|
def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,))
|
[
"def",
"remove_move",
"(",
"name",
")",
":",
"try",
":",
"delattr",
"(",
"_MovedItems",
",",
"name",
")",
"except",
"AttributeError",
":",
"try",
":",
"del",
"moves",
".",
"__dict__",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"AttributeError",
"(",
"\"no such move, %r\"",
"%",
"(",
"name",
",",
")",
")"
] |
Remove item from six.moves.
|
[
"Remove",
"item",
"from",
"six",
".",
"moves",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/six.py#L497-L505
|
train
|
pypa/pipenv
|
pipenv/vendor/six.py
|
ensure_binary
|
def ensure_binary(s, encoding='utf-8', errors='strict'):
"""Coerce **s** to six.binary_type.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> encoded to `bytes`
- `bytes` -> `bytes`
"""
if isinstance(s, text_type):
return s.encode(encoding, errors)
elif isinstance(s, binary_type):
return s
else:
raise TypeError("not expecting type '%s'" % type(s))
|
python
|
def ensure_binary(s, encoding='utf-8', errors='strict'):
"""Coerce **s** to six.binary_type.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> encoded to `bytes`
- `bytes` -> `bytes`
"""
if isinstance(s, text_type):
return s.encode(encoding, errors)
elif isinstance(s, binary_type):
return s
else:
raise TypeError("not expecting type '%s'" % type(s))
|
[
"def",
"ensure_binary",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"text_type",
")",
":",
"return",
"s",
".",
"encode",
"(",
"encoding",
",",
"errors",
")",
"elif",
"isinstance",
"(",
"s",
",",
"binary_type",
")",
":",
"return",
"s",
"else",
":",
"raise",
"TypeError",
"(",
"\"not expecting type '%s'\"",
"%",
"type",
"(",
"s",
")",
")"
] |
Coerce **s** to six.binary_type.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> encoded to `bytes`
- `bytes` -> `bytes`
|
[
"Coerce",
"**",
"s",
"**",
"to",
"six",
".",
"binary_type",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/six.py#L853-L869
|
train
|
pypa/pipenv
|
pipenv/vendor/six.py
|
ensure_str
|
def ensure_str(s, encoding='utf-8', errors='strict'):
"""Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if not isinstance(s, (text_type, binary_type)):
raise TypeError("not expecting type '%s'" % type(s))
if PY2 and isinstance(s, text_type):
s = s.encode(encoding, errors)
elif PY3 and isinstance(s, binary_type):
s = s.decode(encoding, errors)
return s
|
python
|
def ensure_str(s, encoding='utf-8', errors='strict'):
"""Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if not isinstance(s, (text_type, binary_type)):
raise TypeError("not expecting type '%s'" % type(s))
if PY2 and isinstance(s, text_type):
s = s.encode(encoding, errors)
elif PY3 and isinstance(s, binary_type):
s = s.decode(encoding, errors)
return s
|
[
"def",
"ensure_str",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"(",
"text_type",
",",
"binary_type",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"not expecting type '%s'\"",
"%",
"type",
"(",
"s",
")",
")",
"if",
"PY2",
"and",
"isinstance",
"(",
"s",
",",
"text_type",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"encoding",
",",
"errors",
")",
"elif",
"PY3",
"and",
"isinstance",
"(",
"s",
",",
"binary_type",
")",
":",
"s",
"=",
"s",
".",
"decode",
"(",
"encoding",
",",
"errors",
")",
"return",
"s"
] |
Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
|
[
"Coerce",
"*",
"s",
"*",
"to",
"str",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/six.py#L872-L889
|
train
|
pypa/pipenv
|
pipenv/vendor/six.py
|
ensure_text
|
def ensure_text(s, encoding='utf-8', errors='strict'):
"""Coerce *s* to six.text_type.
For Python 2:
- `unicode` -> `unicode`
- `str` -> `unicode`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if isinstance(s, binary_type):
return s.decode(encoding, errors)
elif isinstance(s, text_type):
return s
else:
raise TypeError("not expecting type '%s'" % type(s))
|
python
|
def ensure_text(s, encoding='utf-8', errors='strict'):
"""Coerce *s* to six.text_type.
For Python 2:
- `unicode` -> `unicode`
- `str` -> `unicode`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if isinstance(s, binary_type):
return s.decode(encoding, errors)
elif isinstance(s, text_type):
return s
else:
raise TypeError("not expecting type '%s'" % type(s))
|
[
"def",
"ensure_text",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"binary_type",
")",
":",
"return",
"s",
".",
"decode",
"(",
"encoding",
",",
"errors",
")",
"elif",
"isinstance",
"(",
"s",
",",
"text_type",
")",
":",
"return",
"s",
"else",
":",
"raise",
"TypeError",
"(",
"\"not expecting type '%s'\"",
"%",
"type",
"(",
"s",
")",
")"
] |
Coerce *s* to six.text_type.
For Python 2:
- `unicode` -> `unicode`
- `str` -> `unicode`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
|
[
"Coerce",
"*",
"s",
"*",
"to",
"six",
".",
"text_type",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/six.py#L892-L908
|
train
|
pypa/pipenv
|
pipenv/vendor/six.py
|
python_2_unicode_compatible
|
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if PY2:
if '__str__' not in klass.__dict__:
raise ValueError("@python_2_unicode_compatible cannot be applied "
"to %s because it doesn't define __str__()." %
klass.__name__)
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
|
python
|
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if PY2:
if '__str__' not in klass.__dict__:
raise ValueError("@python_2_unicode_compatible cannot be applied "
"to %s because it doesn't define __str__()." %
klass.__name__)
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
|
[
"def",
"python_2_unicode_compatible",
"(",
"klass",
")",
":",
"if",
"PY2",
":",
"if",
"'__str__'",
"not",
"in",
"klass",
".",
"__dict__",
":",
"raise",
"ValueError",
"(",
"\"@python_2_unicode_compatible cannot be applied \"",
"\"to %s because it doesn't define __str__().\"",
"%",
"klass",
".",
"__name__",
")",
"klass",
".",
"__unicode__",
"=",
"klass",
".",
"__str__",
"klass",
".",
"__str__",
"=",
"lambda",
"self",
":",
"self",
".",
"__unicode__",
"(",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"klass"
] |
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
|
[
"A",
"decorator",
"that",
"defines",
"__unicode__",
"and",
"__str__",
"methods",
"under",
"Python",
"2",
".",
"Under",
"Python",
"3",
"it",
"does",
"nothing",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/six.py#L912-L927
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/req/req_file.py
|
parse_requirements
|
def parse_requirements(
filename, # type: str
finder=None, # type: Optional[PackageFinder]
comes_from=None, # type: Optional[str]
options=None, # type: Optional[optparse.Values]
session=None, # type: Optional[PipSession]
constraint=False, # type: bool
wheel_cache=None, # type: Optional[WheelCache]
use_pep517=None # type: Optional[bool]
):
# type: (...) -> Iterator[InstallRequirement]
"""Parse a requirements file and yield InstallRequirement instances.
:param filename: Path or url of requirements file.
:param finder: Instance of pip.index.PackageFinder.
:param comes_from: Origin description of requirements.
:param options: cli options.
:param session: Instance of pip.download.PipSession.
:param constraint: If true, parsing a constraint file rather than
requirements file.
:param wheel_cache: Instance of pip.wheel.WheelCache
:param use_pep517: Value of the --use-pep517 option.
"""
if session is None:
raise TypeError(
"parse_requirements() missing 1 required keyword argument: "
"'session'"
)
_, content = get_file_content(
filename, comes_from=comes_from, session=session
)
lines_enum = preprocess(content, options)
for line_number, line in lines_enum:
req_iter = process_line(line, filename, line_number, finder,
comes_from, options, session, wheel_cache,
use_pep517=use_pep517, constraint=constraint)
for req in req_iter:
yield req
|
python
|
def parse_requirements(
filename, # type: str
finder=None, # type: Optional[PackageFinder]
comes_from=None, # type: Optional[str]
options=None, # type: Optional[optparse.Values]
session=None, # type: Optional[PipSession]
constraint=False, # type: bool
wheel_cache=None, # type: Optional[WheelCache]
use_pep517=None # type: Optional[bool]
):
# type: (...) -> Iterator[InstallRequirement]
"""Parse a requirements file and yield InstallRequirement instances.
:param filename: Path or url of requirements file.
:param finder: Instance of pip.index.PackageFinder.
:param comes_from: Origin description of requirements.
:param options: cli options.
:param session: Instance of pip.download.PipSession.
:param constraint: If true, parsing a constraint file rather than
requirements file.
:param wheel_cache: Instance of pip.wheel.WheelCache
:param use_pep517: Value of the --use-pep517 option.
"""
if session is None:
raise TypeError(
"parse_requirements() missing 1 required keyword argument: "
"'session'"
)
_, content = get_file_content(
filename, comes_from=comes_from, session=session
)
lines_enum = preprocess(content, options)
for line_number, line in lines_enum:
req_iter = process_line(line, filename, line_number, finder,
comes_from, options, session, wheel_cache,
use_pep517=use_pep517, constraint=constraint)
for req in req_iter:
yield req
|
[
"def",
"parse_requirements",
"(",
"filename",
",",
"# type: str",
"finder",
"=",
"None",
",",
"# type: Optional[PackageFinder]",
"comes_from",
"=",
"None",
",",
"# type: Optional[str]",
"options",
"=",
"None",
",",
"# type: Optional[optparse.Values]",
"session",
"=",
"None",
",",
"# type: Optional[PipSession]",
"constraint",
"=",
"False",
",",
"# type: bool",
"wheel_cache",
"=",
"None",
",",
"# type: Optional[WheelCache]",
"use_pep517",
"=",
"None",
"# type: Optional[bool]",
")",
":",
"# type: (...) -> Iterator[InstallRequirement]",
"if",
"session",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"parse_requirements() missing 1 required keyword argument: \"",
"\"'session'\"",
")",
"_",
",",
"content",
"=",
"get_file_content",
"(",
"filename",
",",
"comes_from",
"=",
"comes_from",
",",
"session",
"=",
"session",
")",
"lines_enum",
"=",
"preprocess",
"(",
"content",
",",
"options",
")",
"for",
"line_number",
",",
"line",
"in",
"lines_enum",
":",
"req_iter",
"=",
"process_line",
"(",
"line",
",",
"filename",
",",
"line_number",
",",
"finder",
",",
"comes_from",
",",
"options",
",",
"session",
",",
"wheel_cache",
",",
"use_pep517",
"=",
"use_pep517",
",",
"constraint",
"=",
"constraint",
")",
"for",
"req",
"in",
"req_iter",
":",
"yield",
"req"
] |
Parse a requirements file and yield InstallRequirement instances.
:param filename: Path or url of requirements file.
:param finder: Instance of pip.index.PackageFinder.
:param comes_from: Origin description of requirements.
:param options: cli options.
:param session: Instance of pip.download.PipSession.
:param constraint: If true, parsing a constraint file rather than
requirements file.
:param wheel_cache: Instance of pip.wheel.WheelCache
:param use_pep517: Value of the --use-pep517 option.
|
[
"Parse",
"a",
"requirements",
"file",
"and",
"yield",
"InstallRequirement",
"instances",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_file.py#L73-L113
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/req/req_file.py
|
preprocess
|
def preprocess(content, options):
# type: (Text, Optional[optparse.Values]) -> ReqFileLines
"""Split, filter, and join lines, and return a line iterator
:param content: the content of the requirements file
:param options: cli options
"""
lines_enum = enumerate(content.splitlines(), start=1) # type: ReqFileLines
lines_enum = join_lines(lines_enum)
lines_enum = ignore_comments(lines_enum)
lines_enum = skip_regex(lines_enum, options)
lines_enum = expand_env_variables(lines_enum)
return lines_enum
|
python
|
def preprocess(content, options):
# type: (Text, Optional[optparse.Values]) -> ReqFileLines
"""Split, filter, and join lines, and return a line iterator
:param content: the content of the requirements file
:param options: cli options
"""
lines_enum = enumerate(content.splitlines(), start=1) # type: ReqFileLines
lines_enum = join_lines(lines_enum)
lines_enum = ignore_comments(lines_enum)
lines_enum = skip_regex(lines_enum, options)
lines_enum = expand_env_variables(lines_enum)
return lines_enum
|
[
"def",
"preprocess",
"(",
"content",
",",
"options",
")",
":",
"# type: (Text, Optional[optparse.Values]) -> ReqFileLines",
"lines_enum",
"=",
"enumerate",
"(",
"content",
".",
"splitlines",
"(",
")",
",",
"start",
"=",
"1",
")",
"# type: ReqFileLines",
"lines_enum",
"=",
"join_lines",
"(",
"lines_enum",
")",
"lines_enum",
"=",
"ignore_comments",
"(",
"lines_enum",
")",
"lines_enum",
"=",
"skip_regex",
"(",
"lines_enum",
",",
"options",
")",
"lines_enum",
"=",
"expand_env_variables",
"(",
"lines_enum",
")",
"return",
"lines_enum"
] |
Split, filter, and join lines, and return a line iterator
:param content: the content of the requirements file
:param options: cli options
|
[
"Split",
"filter",
"and",
"join",
"lines",
"and",
"return",
"a",
"line",
"iterator"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_file.py#L116-L128
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/req/req_file.py
|
process_line
|
def process_line(
line, # type: Text
filename, # type: str
line_number, # type: int
finder=None, # type: Optional[PackageFinder]
comes_from=None, # type: Optional[str]
options=None, # type: Optional[optparse.Values]
session=None, # type: Optional[PipSession]
wheel_cache=None, # type: Optional[WheelCache]
use_pep517=None, # type: Optional[bool]
constraint=False # type: bool
):
# type: (...) -> Iterator[InstallRequirement]
"""Process a single requirements line; This can result in creating/yielding
requirements, or updating the finder.
For lines that contain requirements, the only options that have an effect
are from SUPPORTED_OPTIONS_REQ, and they are scoped to the
requirement. Other options from SUPPORTED_OPTIONS may be present, but are
ignored.
For lines that do not contain requirements, the only options that have an
effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may
be present, but are ignored. These lines may contain multiple options
(although our docs imply only one is supported), and all our parsed and
affect the finder.
:param constraint: If True, parsing a constraints file.
:param options: OptionParser options that we may update
"""
parser = build_parser(line)
defaults = parser.get_default_values()
defaults.index_url = None
if finder:
defaults.format_control = finder.format_control
args_str, options_str = break_args_options(line)
# Prior to 2.7.3, shlex cannot deal with unicode entries
if sys.version_info < (2, 7, 3):
# https://github.com/python/mypy/issues/1174
options_str = options_str.encode('utf8') # type: ignore
# https://github.com/python/mypy/issues/1174
opts, _ = parser.parse_args(
shlex.split(options_str), defaults) # type: ignore
# preserve for the nested code path
line_comes_from = '%s %s (line %s)' % (
'-c' if constraint else '-r', filename, line_number,
)
# yield a line requirement
if args_str:
isolated = options.isolated_mode if options else False
if options:
cmdoptions.check_install_build_global(options, opts)
# get the options that apply to requirements
req_options = {}
for dest in SUPPORTED_OPTIONS_REQ_DEST:
if dest in opts.__dict__ and opts.__dict__[dest]:
req_options[dest] = opts.__dict__[dest]
yield install_req_from_line(
args_str, line_comes_from, constraint=constraint,
use_pep517=use_pep517,
isolated=isolated, options=req_options, wheel_cache=wheel_cache
)
# yield an editable requirement
elif opts.editables:
isolated = options.isolated_mode if options else False
yield install_req_from_editable(
opts.editables[0], comes_from=line_comes_from,
use_pep517=use_pep517,
constraint=constraint, isolated=isolated, wheel_cache=wheel_cache
)
# parse a nested requirements file
elif opts.requirements or opts.constraints:
if opts.requirements:
req_path = opts.requirements[0]
nested_constraint = False
else:
req_path = opts.constraints[0]
nested_constraint = True
# original file is over http
if SCHEME_RE.search(filename):
# do a url join so relative paths work
req_path = urllib_parse.urljoin(filename, req_path)
# original file and nested file are paths
elif not SCHEME_RE.search(req_path):
# do a join so relative paths work
req_path = os.path.join(os.path.dirname(filename), req_path)
# TODO: Why not use `comes_from='-r {} (line {})'` here as well?
parsed_reqs = parse_requirements(
req_path, finder, comes_from, options, session,
constraint=nested_constraint, wheel_cache=wheel_cache
)
for req in parsed_reqs:
yield req
# percolate hash-checking option upward
elif opts.require_hashes:
options.require_hashes = opts.require_hashes
# set finder options
elif finder:
if opts.index_url:
finder.index_urls = [opts.index_url]
if opts.no_index is True:
finder.index_urls = []
if opts.extra_index_urls:
finder.index_urls.extend(opts.extra_index_urls)
if opts.find_links:
# FIXME: it would be nice to keep track of the source
# of the find_links: support a find-links local path
# relative to a requirements file.
value = opts.find_links[0]
req_dir = os.path.dirname(os.path.abspath(filename))
relative_to_reqs_file = os.path.join(req_dir, value)
if os.path.exists(relative_to_reqs_file):
value = relative_to_reqs_file
finder.find_links.append(value)
if opts.pre:
finder.allow_all_prereleases = True
if opts.trusted_hosts:
finder.secure_origins.extend(
("*", host, "*") for host in opts.trusted_hosts)
|
python
|
def process_line(
line, # type: Text
filename, # type: str
line_number, # type: int
finder=None, # type: Optional[PackageFinder]
comes_from=None, # type: Optional[str]
options=None, # type: Optional[optparse.Values]
session=None, # type: Optional[PipSession]
wheel_cache=None, # type: Optional[WheelCache]
use_pep517=None, # type: Optional[bool]
constraint=False # type: bool
):
# type: (...) -> Iterator[InstallRequirement]
"""Process a single requirements line; This can result in creating/yielding
requirements, or updating the finder.
For lines that contain requirements, the only options that have an effect
are from SUPPORTED_OPTIONS_REQ, and they are scoped to the
requirement. Other options from SUPPORTED_OPTIONS may be present, but are
ignored.
For lines that do not contain requirements, the only options that have an
effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may
be present, but are ignored. These lines may contain multiple options
(although our docs imply only one is supported), and all our parsed and
affect the finder.
:param constraint: If True, parsing a constraints file.
:param options: OptionParser options that we may update
"""
parser = build_parser(line)
defaults = parser.get_default_values()
defaults.index_url = None
if finder:
defaults.format_control = finder.format_control
args_str, options_str = break_args_options(line)
# Prior to 2.7.3, shlex cannot deal with unicode entries
if sys.version_info < (2, 7, 3):
# https://github.com/python/mypy/issues/1174
options_str = options_str.encode('utf8') # type: ignore
# https://github.com/python/mypy/issues/1174
opts, _ = parser.parse_args(
shlex.split(options_str), defaults) # type: ignore
# preserve for the nested code path
line_comes_from = '%s %s (line %s)' % (
'-c' if constraint else '-r', filename, line_number,
)
# yield a line requirement
if args_str:
isolated = options.isolated_mode if options else False
if options:
cmdoptions.check_install_build_global(options, opts)
# get the options that apply to requirements
req_options = {}
for dest in SUPPORTED_OPTIONS_REQ_DEST:
if dest in opts.__dict__ and opts.__dict__[dest]:
req_options[dest] = opts.__dict__[dest]
yield install_req_from_line(
args_str, line_comes_from, constraint=constraint,
use_pep517=use_pep517,
isolated=isolated, options=req_options, wheel_cache=wheel_cache
)
# yield an editable requirement
elif opts.editables:
isolated = options.isolated_mode if options else False
yield install_req_from_editable(
opts.editables[0], comes_from=line_comes_from,
use_pep517=use_pep517,
constraint=constraint, isolated=isolated, wheel_cache=wheel_cache
)
# parse a nested requirements file
elif opts.requirements or opts.constraints:
if opts.requirements:
req_path = opts.requirements[0]
nested_constraint = False
else:
req_path = opts.constraints[0]
nested_constraint = True
# original file is over http
if SCHEME_RE.search(filename):
# do a url join so relative paths work
req_path = urllib_parse.urljoin(filename, req_path)
# original file and nested file are paths
elif not SCHEME_RE.search(req_path):
# do a join so relative paths work
req_path = os.path.join(os.path.dirname(filename), req_path)
# TODO: Why not use `comes_from='-r {} (line {})'` here as well?
parsed_reqs = parse_requirements(
req_path, finder, comes_from, options, session,
constraint=nested_constraint, wheel_cache=wheel_cache
)
for req in parsed_reqs:
yield req
# percolate hash-checking option upward
elif opts.require_hashes:
options.require_hashes = opts.require_hashes
# set finder options
elif finder:
if opts.index_url:
finder.index_urls = [opts.index_url]
if opts.no_index is True:
finder.index_urls = []
if opts.extra_index_urls:
finder.index_urls.extend(opts.extra_index_urls)
if opts.find_links:
# FIXME: it would be nice to keep track of the source
# of the find_links: support a find-links local path
# relative to a requirements file.
value = opts.find_links[0]
req_dir = os.path.dirname(os.path.abspath(filename))
relative_to_reqs_file = os.path.join(req_dir, value)
if os.path.exists(relative_to_reqs_file):
value = relative_to_reqs_file
finder.find_links.append(value)
if opts.pre:
finder.allow_all_prereleases = True
if opts.trusted_hosts:
finder.secure_origins.extend(
("*", host, "*") for host in opts.trusted_hosts)
|
[
"def",
"process_line",
"(",
"line",
",",
"# type: Text",
"filename",
",",
"# type: str",
"line_number",
",",
"# type: int",
"finder",
"=",
"None",
",",
"# type: Optional[PackageFinder]",
"comes_from",
"=",
"None",
",",
"# type: Optional[str]",
"options",
"=",
"None",
",",
"# type: Optional[optparse.Values]",
"session",
"=",
"None",
",",
"# type: Optional[PipSession]",
"wheel_cache",
"=",
"None",
",",
"# type: Optional[WheelCache]",
"use_pep517",
"=",
"None",
",",
"# type: Optional[bool]",
"constraint",
"=",
"False",
"# type: bool",
")",
":",
"# type: (...) -> Iterator[InstallRequirement]",
"parser",
"=",
"build_parser",
"(",
"line",
")",
"defaults",
"=",
"parser",
".",
"get_default_values",
"(",
")",
"defaults",
".",
"index_url",
"=",
"None",
"if",
"finder",
":",
"defaults",
".",
"format_control",
"=",
"finder",
".",
"format_control",
"args_str",
",",
"options_str",
"=",
"break_args_options",
"(",
"line",
")",
"# Prior to 2.7.3, shlex cannot deal with unicode entries",
"if",
"sys",
".",
"version_info",
"<",
"(",
"2",
",",
"7",
",",
"3",
")",
":",
"# https://github.com/python/mypy/issues/1174",
"options_str",
"=",
"options_str",
".",
"encode",
"(",
"'utf8'",
")",
"# type: ignore",
"# https://github.com/python/mypy/issues/1174",
"opts",
",",
"_",
"=",
"parser",
".",
"parse_args",
"(",
"shlex",
".",
"split",
"(",
"options_str",
")",
",",
"defaults",
")",
"# type: ignore",
"# preserve for the nested code path",
"line_comes_from",
"=",
"'%s %s (line %s)'",
"%",
"(",
"'-c'",
"if",
"constraint",
"else",
"'-r'",
",",
"filename",
",",
"line_number",
",",
")",
"# yield a line requirement",
"if",
"args_str",
":",
"isolated",
"=",
"options",
".",
"isolated_mode",
"if",
"options",
"else",
"False",
"if",
"options",
":",
"cmdoptions",
".",
"check_install_build_global",
"(",
"options",
",",
"opts",
")",
"# get the options that apply to requirements",
"req_options",
"=",
"{",
"}",
"for",
"dest",
"in",
"SUPPORTED_OPTIONS_REQ_DEST",
":",
"if",
"dest",
"in",
"opts",
".",
"__dict__",
"and",
"opts",
".",
"__dict__",
"[",
"dest",
"]",
":",
"req_options",
"[",
"dest",
"]",
"=",
"opts",
".",
"__dict__",
"[",
"dest",
"]",
"yield",
"install_req_from_line",
"(",
"args_str",
",",
"line_comes_from",
",",
"constraint",
"=",
"constraint",
",",
"use_pep517",
"=",
"use_pep517",
",",
"isolated",
"=",
"isolated",
",",
"options",
"=",
"req_options",
",",
"wheel_cache",
"=",
"wheel_cache",
")",
"# yield an editable requirement",
"elif",
"opts",
".",
"editables",
":",
"isolated",
"=",
"options",
".",
"isolated_mode",
"if",
"options",
"else",
"False",
"yield",
"install_req_from_editable",
"(",
"opts",
".",
"editables",
"[",
"0",
"]",
",",
"comes_from",
"=",
"line_comes_from",
",",
"use_pep517",
"=",
"use_pep517",
",",
"constraint",
"=",
"constraint",
",",
"isolated",
"=",
"isolated",
",",
"wheel_cache",
"=",
"wheel_cache",
")",
"# parse a nested requirements file",
"elif",
"opts",
".",
"requirements",
"or",
"opts",
".",
"constraints",
":",
"if",
"opts",
".",
"requirements",
":",
"req_path",
"=",
"opts",
".",
"requirements",
"[",
"0",
"]",
"nested_constraint",
"=",
"False",
"else",
":",
"req_path",
"=",
"opts",
".",
"constraints",
"[",
"0",
"]",
"nested_constraint",
"=",
"True",
"# original file is over http",
"if",
"SCHEME_RE",
".",
"search",
"(",
"filename",
")",
":",
"# do a url join so relative paths work",
"req_path",
"=",
"urllib_parse",
".",
"urljoin",
"(",
"filename",
",",
"req_path",
")",
"# original file and nested file are paths",
"elif",
"not",
"SCHEME_RE",
".",
"search",
"(",
"req_path",
")",
":",
"# do a join so relative paths work",
"req_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
",",
"req_path",
")",
"# TODO: Why not use `comes_from='-r {} (line {})'` here as well?",
"parsed_reqs",
"=",
"parse_requirements",
"(",
"req_path",
",",
"finder",
",",
"comes_from",
",",
"options",
",",
"session",
",",
"constraint",
"=",
"nested_constraint",
",",
"wheel_cache",
"=",
"wheel_cache",
")",
"for",
"req",
"in",
"parsed_reqs",
":",
"yield",
"req",
"# percolate hash-checking option upward",
"elif",
"opts",
".",
"require_hashes",
":",
"options",
".",
"require_hashes",
"=",
"opts",
".",
"require_hashes",
"# set finder options",
"elif",
"finder",
":",
"if",
"opts",
".",
"index_url",
":",
"finder",
".",
"index_urls",
"=",
"[",
"opts",
".",
"index_url",
"]",
"if",
"opts",
".",
"no_index",
"is",
"True",
":",
"finder",
".",
"index_urls",
"=",
"[",
"]",
"if",
"opts",
".",
"extra_index_urls",
":",
"finder",
".",
"index_urls",
".",
"extend",
"(",
"opts",
".",
"extra_index_urls",
")",
"if",
"opts",
".",
"find_links",
":",
"# FIXME: it would be nice to keep track of the source",
"# of the find_links: support a find-links local path",
"# relative to a requirements file.",
"value",
"=",
"opts",
".",
"find_links",
"[",
"0",
"]",
"req_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
")",
"relative_to_reqs_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"req_dir",
",",
"value",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"relative_to_reqs_file",
")",
":",
"value",
"=",
"relative_to_reqs_file",
"finder",
".",
"find_links",
".",
"append",
"(",
"value",
")",
"if",
"opts",
".",
"pre",
":",
"finder",
".",
"allow_all_prereleases",
"=",
"True",
"if",
"opts",
".",
"trusted_hosts",
":",
"finder",
".",
"secure_origins",
".",
"extend",
"(",
"(",
"\"*\"",
",",
"host",
",",
"\"*\"",
")",
"for",
"host",
"in",
"opts",
".",
"trusted_hosts",
")"
] |
Process a single requirements line; This can result in creating/yielding
requirements, or updating the finder.
For lines that contain requirements, the only options that have an effect
are from SUPPORTED_OPTIONS_REQ, and they are scoped to the
requirement. Other options from SUPPORTED_OPTIONS may be present, but are
ignored.
For lines that do not contain requirements, the only options that have an
effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may
be present, but are ignored. These lines may contain multiple options
(although our docs imply only one is supported), and all our parsed and
affect the finder.
:param constraint: If True, parsing a constraints file.
:param options: OptionParser options that we may update
|
[
"Process",
"a",
"single",
"requirements",
"line",
";",
"This",
"can",
"result",
"in",
"creating",
"/",
"yielding",
"requirements",
"or",
"updating",
"the",
"finder",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_file.py#L131-L255
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/req/req_file.py
|
break_args_options
|
def break_args_options(line):
# type: (Text) -> Tuple[str, Text]
"""Break up the line into an args and options string. We only want to shlex
(and then optparse) the options, not the args. args can contain markers
which are corrupted by shlex.
"""
tokens = line.split(' ')
args = []
options = tokens[:]
for token in tokens:
if token.startswith('-') or token.startswith('--'):
break
else:
args.append(token)
options.pop(0)
return ' '.join(args), ' '.join(options)
|
python
|
def break_args_options(line):
# type: (Text) -> Tuple[str, Text]
"""Break up the line into an args and options string. We only want to shlex
(and then optparse) the options, not the args. args can contain markers
which are corrupted by shlex.
"""
tokens = line.split(' ')
args = []
options = tokens[:]
for token in tokens:
if token.startswith('-') or token.startswith('--'):
break
else:
args.append(token)
options.pop(0)
return ' '.join(args), ' '.join(options)
|
[
"def",
"break_args_options",
"(",
"line",
")",
":",
"# type: (Text) -> Tuple[str, Text]",
"tokens",
"=",
"line",
".",
"split",
"(",
"' '",
")",
"args",
"=",
"[",
"]",
"options",
"=",
"tokens",
"[",
":",
"]",
"for",
"token",
"in",
"tokens",
":",
"if",
"token",
".",
"startswith",
"(",
"'-'",
")",
"or",
"token",
".",
"startswith",
"(",
"'--'",
")",
":",
"break",
"else",
":",
"args",
".",
"append",
"(",
"token",
")",
"options",
".",
"pop",
"(",
"0",
")",
"return",
"' '",
".",
"join",
"(",
"args",
")",
",",
"' '",
".",
"join",
"(",
"options",
")"
] |
Break up the line into an args and options string. We only want to shlex
(and then optparse) the options, not the args. args can contain markers
which are corrupted by shlex.
|
[
"Break",
"up",
"the",
"line",
"into",
"an",
"args",
"and",
"options",
"string",
".",
"We",
"only",
"want",
"to",
"shlex",
"(",
"and",
"then",
"optparse",
")",
"the",
"options",
"not",
"the",
"args",
".",
"args",
"can",
"contain",
"markers",
"which",
"are",
"corrupted",
"by",
"shlex",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_file.py#L258-L273
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/req/req_file.py
|
build_parser
|
def build_parser(line):
# type: (Text) -> optparse.OptionParser
"""
Return a parser for parsing requirement lines
"""
parser = optparse.OptionParser(add_help_option=False)
option_factories = SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ
for option_factory in option_factories:
option = option_factory()
parser.add_option(option)
# By default optparse sys.exits on parsing errors. We want to wrap
# that in our own exception.
def parser_exit(self, msg):
# add offending line
msg = 'Invalid requirement: %s\n%s' % (line, msg)
raise RequirementsFileParseError(msg)
# NOTE: mypy disallows assigning to a method
# https://github.com/python/mypy/issues/2427
parser.exit = parser_exit # type: ignore
return parser
|
python
|
def build_parser(line):
# type: (Text) -> optparse.OptionParser
"""
Return a parser for parsing requirement lines
"""
parser = optparse.OptionParser(add_help_option=False)
option_factories = SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ
for option_factory in option_factories:
option = option_factory()
parser.add_option(option)
# By default optparse sys.exits on parsing errors. We want to wrap
# that in our own exception.
def parser_exit(self, msg):
# add offending line
msg = 'Invalid requirement: %s\n%s' % (line, msg)
raise RequirementsFileParseError(msg)
# NOTE: mypy disallows assigning to a method
# https://github.com/python/mypy/issues/2427
parser.exit = parser_exit # type: ignore
return parser
|
[
"def",
"build_parser",
"(",
"line",
")",
":",
"# type: (Text) -> optparse.OptionParser",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"add_help_option",
"=",
"False",
")",
"option_factories",
"=",
"SUPPORTED_OPTIONS",
"+",
"SUPPORTED_OPTIONS_REQ",
"for",
"option_factory",
"in",
"option_factories",
":",
"option",
"=",
"option_factory",
"(",
")",
"parser",
".",
"add_option",
"(",
"option",
")",
"# By default optparse sys.exits on parsing errors. We want to wrap",
"# that in our own exception.",
"def",
"parser_exit",
"(",
"self",
",",
"msg",
")",
":",
"# add offending line",
"msg",
"=",
"'Invalid requirement: %s\\n%s'",
"%",
"(",
"line",
",",
"msg",
")",
"raise",
"RequirementsFileParseError",
"(",
"msg",
")",
"# NOTE: mypy disallows assigning to a method",
"# https://github.com/python/mypy/issues/2427",
"parser",
".",
"exit",
"=",
"parser_exit",
"# type: ignore",
"return",
"parser"
] |
Return a parser for parsing requirement lines
|
[
"Return",
"a",
"parser",
"for",
"parsing",
"requirement",
"lines"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_file.py#L276-L298
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/req/req_file.py
|
join_lines
|
def join_lines(lines_enum):
# type: (ReqFileLines) -> ReqFileLines
"""Joins a line ending in '\' with the previous line (except when following
comments). The joined line takes on the index of the first line.
"""
primary_line_number = None
new_line = [] # type: List[Text]
for line_number, line in lines_enum:
if not line.endswith('\\') or COMMENT_RE.match(line):
if COMMENT_RE.match(line):
# this ensures comments are always matched later
line = ' ' + line
if new_line:
new_line.append(line)
yield primary_line_number, ''.join(new_line)
new_line = []
else:
yield line_number, line
else:
if not new_line:
primary_line_number = line_number
new_line.append(line.strip('\\'))
# last line contains \
if new_line:
yield primary_line_number, ''.join(new_line)
|
python
|
def join_lines(lines_enum):
# type: (ReqFileLines) -> ReqFileLines
"""Joins a line ending in '\' with the previous line (except when following
comments). The joined line takes on the index of the first line.
"""
primary_line_number = None
new_line = [] # type: List[Text]
for line_number, line in lines_enum:
if not line.endswith('\\') or COMMENT_RE.match(line):
if COMMENT_RE.match(line):
# this ensures comments are always matched later
line = ' ' + line
if new_line:
new_line.append(line)
yield primary_line_number, ''.join(new_line)
new_line = []
else:
yield line_number, line
else:
if not new_line:
primary_line_number = line_number
new_line.append(line.strip('\\'))
# last line contains \
if new_line:
yield primary_line_number, ''.join(new_line)
|
[
"def",
"join_lines",
"(",
"lines_enum",
")",
":",
"# type: (ReqFileLines) -> ReqFileLines",
"primary_line_number",
"=",
"None",
"new_line",
"=",
"[",
"]",
"# type: List[Text]",
"for",
"line_number",
",",
"line",
"in",
"lines_enum",
":",
"if",
"not",
"line",
".",
"endswith",
"(",
"'\\\\'",
")",
"or",
"COMMENT_RE",
".",
"match",
"(",
"line",
")",
":",
"if",
"COMMENT_RE",
".",
"match",
"(",
"line",
")",
":",
"# this ensures comments are always matched later",
"line",
"=",
"' '",
"+",
"line",
"if",
"new_line",
":",
"new_line",
".",
"append",
"(",
"line",
")",
"yield",
"primary_line_number",
",",
"''",
".",
"join",
"(",
"new_line",
")",
"new_line",
"=",
"[",
"]",
"else",
":",
"yield",
"line_number",
",",
"line",
"else",
":",
"if",
"not",
"new_line",
":",
"primary_line_number",
"=",
"line_number",
"new_line",
".",
"append",
"(",
"line",
".",
"strip",
"(",
"'\\\\'",
")",
")",
"# last line contains \\",
"if",
"new_line",
":",
"yield",
"primary_line_number",
",",
"''",
".",
"join",
"(",
"new_line",
")"
] |
Joins a line ending in '\' with the previous line (except when following
comments). The joined line takes on the index of the first line.
|
[
"Joins",
"a",
"line",
"ending",
"in",
"\\",
"with",
"the",
"previous",
"line",
"(",
"except",
"when",
"following",
"comments",
")",
".",
"The",
"joined",
"line",
"takes",
"on",
"the",
"index",
"of",
"the",
"first",
"line",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_file.py#L301-L326
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/req/req_file.py
|
ignore_comments
|
def ignore_comments(lines_enum):
# type: (ReqFileLines) -> ReqFileLines
"""
Strips comments and filter empty lines.
"""
for line_number, line in lines_enum:
line = COMMENT_RE.sub('', line)
line = line.strip()
if line:
yield line_number, line
|
python
|
def ignore_comments(lines_enum):
# type: (ReqFileLines) -> ReqFileLines
"""
Strips comments and filter empty lines.
"""
for line_number, line in lines_enum:
line = COMMENT_RE.sub('', line)
line = line.strip()
if line:
yield line_number, line
|
[
"def",
"ignore_comments",
"(",
"lines_enum",
")",
":",
"# type: (ReqFileLines) -> ReqFileLines",
"for",
"line_number",
",",
"line",
"in",
"lines_enum",
":",
"line",
"=",
"COMMENT_RE",
".",
"sub",
"(",
"''",
",",
"line",
")",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
":",
"yield",
"line_number",
",",
"line"
] |
Strips comments and filter empty lines.
|
[
"Strips",
"comments",
"and",
"filter",
"empty",
"lines",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_file.py#L331-L340
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/req/req_file.py
|
skip_regex
|
def skip_regex(lines_enum, options):
# type: (ReqFileLines, Optional[optparse.Values]) -> ReqFileLines
"""
Skip lines that match '--skip-requirements-regex' pattern
Note: the regex pattern is only built once
"""
skip_regex = options.skip_requirements_regex if options else None
if skip_regex:
pattern = re.compile(skip_regex)
lines_enum = filterfalse(lambda e: pattern.search(e[1]), lines_enum)
return lines_enum
|
python
|
def skip_regex(lines_enum, options):
# type: (ReqFileLines, Optional[optparse.Values]) -> ReqFileLines
"""
Skip lines that match '--skip-requirements-regex' pattern
Note: the regex pattern is only built once
"""
skip_regex = options.skip_requirements_regex if options else None
if skip_regex:
pattern = re.compile(skip_regex)
lines_enum = filterfalse(lambda e: pattern.search(e[1]), lines_enum)
return lines_enum
|
[
"def",
"skip_regex",
"(",
"lines_enum",
",",
"options",
")",
":",
"# type: (ReqFileLines, Optional[optparse.Values]) -> ReqFileLines",
"skip_regex",
"=",
"options",
".",
"skip_requirements_regex",
"if",
"options",
"else",
"None",
"if",
"skip_regex",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"skip_regex",
")",
"lines_enum",
"=",
"filterfalse",
"(",
"lambda",
"e",
":",
"pattern",
".",
"search",
"(",
"e",
"[",
"1",
"]",
")",
",",
"lines_enum",
")",
"return",
"lines_enum"
] |
Skip lines that match '--skip-requirements-regex' pattern
Note: the regex pattern is only built once
|
[
"Skip",
"lines",
"that",
"match",
"--",
"skip",
"-",
"requirements",
"-",
"regex",
"pattern"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_file.py#L343-L354
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/req/req_file.py
|
expand_env_variables
|
def expand_env_variables(lines_enum):
# type: (ReqFileLines) -> ReqFileLines
"""Replace all environment variables that can be retrieved via `os.getenv`.
The only allowed format for environment variables defined in the
requirement file is `${MY_VARIABLE_1}` to ensure two things:
1. Strings that contain a `$` aren't accidentally (partially) expanded.
2. Ensure consistency across platforms for requirement files.
These points are the result of a discusssion on the `github pull
request #3514 <https://github.com/pypa/pip/pull/3514>`_.
Valid characters in variable names follow the `POSIX standard
<http://pubs.opengroup.org/onlinepubs/9699919799/>`_ and are limited
to uppercase letter, digits and the `_` (underscore).
"""
for line_number, line in lines_enum:
for env_var, var_name in ENV_VAR_RE.findall(line):
value = os.getenv(var_name)
if not value:
continue
line = line.replace(env_var, value)
yield line_number, line
|
python
|
def expand_env_variables(lines_enum):
# type: (ReqFileLines) -> ReqFileLines
"""Replace all environment variables that can be retrieved via `os.getenv`.
The only allowed format for environment variables defined in the
requirement file is `${MY_VARIABLE_1}` to ensure two things:
1. Strings that contain a `$` aren't accidentally (partially) expanded.
2. Ensure consistency across platforms for requirement files.
These points are the result of a discusssion on the `github pull
request #3514 <https://github.com/pypa/pip/pull/3514>`_.
Valid characters in variable names follow the `POSIX standard
<http://pubs.opengroup.org/onlinepubs/9699919799/>`_ and are limited
to uppercase letter, digits and the `_` (underscore).
"""
for line_number, line in lines_enum:
for env_var, var_name in ENV_VAR_RE.findall(line):
value = os.getenv(var_name)
if not value:
continue
line = line.replace(env_var, value)
yield line_number, line
|
[
"def",
"expand_env_variables",
"(",
"lines_enum",
")",
":",
"# type: (ReqFileLines) -> ReqFileLines",
"for",
"line_number",
",",
"line",
"in",
"lines_enum",
":",
"for",
"env_var",
",",
"var_name",
"in",
"ENV_VAR_RE",
".",
"findall",
"(",
"line",
")",
":",
"value",
"=",
"os",
".",
"getenv",
"(",
"var_name",
")",
"if",
"not",
"value",
":",
"continue",
"line",
"=",
"line",
".",
"replace",
"(",
"env_var",
",",
"value",
")",
"yield",
"line_number",
",",
"line"
] |
Replace all environment variables that can be retrieved via `os.getenv`.
The only allowed format for environment variables defined in the
requirement file is `${MY_VARIABLE_1}` to ensure two things:
1. Strings that contain a `$` aren't accidentally (partially) expanded.
2. Ensure consistency across platforms for requirement files.
These points are the result of a discusssion on the `github pull
request #3514 <https://github.com/pypa/pip/pull/3514>`_.
Valid characters in variable names follow the `POSIX standard
<http://pubs.opengroup.org/onlinepubs/9699919799/>`_ and are limited
to uppercase letter, digits and the `_` (underscore).
|
[
"Replace",
"all",
"environment",
"variables",
"that",
"can",
"be",
"retrieved",
"via",
"os",
".",
"getenv",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_file.py#L357-L382
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/utils/ui.py
|
InterruptibleMixin.finish
|
def finish(self):
"""
Restore the original SIGINT handler after finishing.
This should happen regardless of whether the progress display finishes
normally, or gets interrupted.
"""
super(InterruptibleMixin, self).finish()
signal(SIGINT, self.original_handler)
|
python
|
def finish(self):
"""
Restore the original SIGINT handler after finishing.
This should happen regardless of whether the progress display finishes
normally, or gets interrupted.
"""
super(InterruptibleMixin, self).finish()
signal(SIGINT, self.original_handler)
|
[
"def",
"finish",
"(",
"self",
")",
":",
"super",
"(",
"InterruptibleMixin",
",",
"self",
")",
".",
"finish",
"(",
")",
"signal",
"(",
"SIGINT",
",",
"self",
".",
"original_handler",
")"
] |
Restore the original SIGINT handler after finishing.
This should happen regardless of whether the progress display finishes
normally, or gets interrupted.
|
[
"Restore",
"the",
"original",
"SIGINT",
"handler",
"after",
"finishing",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/ui.py#L100-L108
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/utils/ui.py
|
InterruptibleMixin.handle_sigint
|
def handle_sigint(self, signum, frame):
"""
Call self.finish() before delegating to the original SIGINT handler.
This handler should only be in place while the progress display is
active.
"""
self.finish()
self.original_handler(signum, frame)
|
python
|
def handle_sigint(self, signum, frame):
"""
Call self.finish() before delegating to the original SIGINT handler.
This handler should only be in place while the progress display is
active.
"""
self.finish()
self.original_handler(signum, frame)
|
[
"def",
"handle_sigint",
"(",
"self",
",",
"signum",
",",
"frame",
")",
":",
"self",
".",
"finish",
"(",
")",
"self",
".",
"original_handler",
"(",
"signum",
",",
"frame",
")"
] |
Call self.finish() before delegating to the original SIGINT handler.
This handler should only be in place while the progress display is
active.
|
[
"Call",
"self",
".",
"finish",
"()",
"before",
"delegating",
"to",
"the",
"original",
"SIGINT",
"handler",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/ui.py#L110-L118
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/nodes.py
|
Node.iter_fields
|
def iter_fields(self, exclude=None, only=None):
"""This method iterates over all fields that are defined and yields
``(key, value)`` tuples. Per default all fields are returned, but
it's possible to limit that to some fields by providing the `only`
parameter or to exclude some using the `exclude` parameter. Both
should be sets or tuples of field names.
"""
for name in self.fields:
if (exclude is only is None) or \
(exclude is not None and name not in exclude) or \
(only is not None and name in only):
try:
yield name, getattr(self, name)
except AttributeError:
pass
|
python
|
def iter_fields(self, exclude=None, only=None):
"""This method iterates over all fields that are defined and yields
``(key, value)`` tuples. Per default all fields are returned, but
it's possible to limit that to some fields by providing the `only`
parameter or to exclude some using the `exclude` parameter. Both
should be sets or tuples of field names.
"""
for name in self.fields:
if (exclude is only is None) or \
(exclude is not None and name not in exclude) or \
(only is not None and name in only):
try:
yield name, getattr(self, name)
except AttributeError:
pass
|
[
"def",
"iter_fields",
"(",
"self",
",",
"exclude",
"=",
"None",
",",
"only",
"=",
"None",
")",
":",
"for",
"name",
"in",
"self",
".",
"fields",
":",
"if",
"(",
"exclude",
"is",
"only",
"is",
"None",
")",
"or",
"(",
"exclude",
"is",
"not",
"None",
"and",
"name",
"not",
"in",
"exclude",
")",
"or",
"(",
"only",
"is",
"not",
"None",
"and",
"name",
"in",
"only",
")",
":",
"try",
":",
"yield",
"name",
",",
"getattr",
"(",
"self",
",",
"name",
")",
"except",
"AttributeError",
":",
"pass"
] |
This method iterates over all fields that are defined and yields
``(key, value)`` tuples. Per default all fields are returned, but
it's possible to limit that to some fields by providing the `only`
parameter or to exclude some using the `exclude` parameter. Both
should be sets or tuples of field names.
|
[
"This",
"method",
"iterates",
"over",
"all",
"fields",
"that",
"are",
"defined",
"and",
"yields",
"(",
"key",
"value",
")",
"tuples",
".",
"Per",
"default",
"all",
"fields",
"are",
"returned",
"but",
"it",
"s",
"possible",
"to",
"limit",
"that",
"to",
"some",
"fields",
"by",
"providing",
"the",
"only",
"parameter",
"or",
"to",
"exclude",
"some",
"using",
"the",
"exclude",
"parameter",
".",
"Both",
"should",
"be",
"sets",
"or",
"tuples",
"of",
"field",
"names",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/nodes.py#L148-L162
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.