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/distlib/_backport/tarfile.py
|
TarFile.list
|
def list(self, verbose=True):
"""Print a table of contents to sys.stdout. If `verbose' is False, only
the names of the members are printed. If it is True, an `ls -l'-like
output is produced.
"""
self._check()
for tarinfo in self:
if verbose:
print(filemode(tarinfo.mode), end=' ')
print("%s/%s" % (tarinfo.uname or tarinfo.uid,
tarinfo.gname or tarinfo.gid), end=' ')
if tarinfo.ischr() or tarinfo.isblk():
print("%10s" % ("%d,%d" \
% (tarinfo.devmajor, tarinfo.devminor)), end=' ')
else:
print("%10d" % tarinfo.size, end=' ')
print("%d-%02d-%02d %02d:%02d:%02d" \
% time.localtime(tarinfo.mtime)[:6], end=' ')
print(tarinfo.name + ("/" if tarinfo.isdir() else ""), end=' ')
if verbose:
if tarinfo.issym():
print("->", tarinfo.linkname, end=' ')
if tarinfo.islnk():
print("link to", tarinfo.linkname, end=' ')
print()
|
python
|
def list(self, verbose=True):
"""Print a table of contents to sys.stdout. If `verbose' is False, only
the names of the members are printed. If it is True, an `ls -l'-like
output is produced.
"""
self._check()
for tarinfo in self:
if verbose:
print(filemode(tarinfo.mode), end=' ')
print("%s/%s" % (tarinfo.uname or tarinfo.uid,
tarinfo.gname or tarinfo.gid), end=' ')
if tarinfo.ischr() or tarinfo.isblk():
print("%10s" % ("%d,%d" \
% (tarinfo.devmajor, tarinfo.devminor)), end=' ')
else:
print("%10d" % tarinfo.size, end=' ')
print("%d-%02d-%02d %02d:%02d:%02d" \
% time.localtime(tarinfo.mtime)[:6], end=' ')
print(tarinfo.name + ("/" if tarinfo.isdir() else ""), end=' ')
if verbose:
if tarinfo.issym():
print("->", tarinfo.linkname, end=' ')
if tarinfo.islnk():
print("link to", tarinfo.linkname, end=' ')
print()
|
[
"def",
"list",
"(",
"self",
",",
"verbose",
"=",
"True",
")",
":",
"self",
".",
"_check",
"(",
")",
"for",
"tarinfo",
"in",
"self",
":",
"if",
"verbose",
":",
"print",
"(",
"filemode",
"(",
"tarinfo",
".",
"mode",
")",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"%s/%s\"",
"%",
"(",
"tarinfo",
".",
"uname",
"or",
"tarinfo",
".",
"uid",
",",
"tarinfo",
".",
"gname",
"or",
"tarinfo",
".",
"gid",
")",
",",
"end",
"=",
"' '",
")",
"if",
"tarinfo",
".",
"ischr",
"(",
")",
"or",
"tarinfo",
".",
"isblk",
"(",
")",
":",
"print",
"(",
"\"%10s\"",
"%",
"(",
"\"%d,%d\"",
"%",
"(",
"tarinfo",
".",
"devmajor",
",",
"tarinfo",
".",
"devminor",
")",
")",
",",
"end",
"=",
"' '",
")",
"else",
":",
"print",
"(",
"\"%10d\"",
"%",
"tarinfo",
".",
"size",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"%d-%02d-%02d %02d:%02d:%02d\"",
"%",
"time",
".",
"localtime",
"(",
"tarinfo",
".",
"mtime",
")",
"[",
":",
"6",
"]",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"tarinfo",
".",
"name",
"+",
"(",
"\"/\"",
"if",
"tarinfo",
".",
"isdir",
"(",
")",
"else",
"\"\"",
")",
",",
"end",
"=",
"' '",
")",
"if",
"verbose",
":",
"if",
"tarinfo",
".",
"issym",
"(",
")",
":",
"print",
"(",
"\"->\"",
",",
"tarinfo",
".",
"linkname",
",",
"end",
"=",
"' '",
")",
"if",
"tarinfo",
".",
"islnk",
"(",
")",
":",
"print",
"(",
"\"link to\"",
",",
"tarinfo",
".",
"linkname",
",",
"end",
"=",
"' '",
")",
"print",
"(",
")"
] |
Print a table of contents to sys.stdout. If `verbose' is False, only
the names of the members are printed. If it is True, an `ls -l'-like
output is produced.
|
[
"Print",
"a",
"table",
"of",
"contents",
"to",
"sys",
".",
"stdout",
".",
"If",
"verbose",
"is",
"False",
"only",
"the",
"names",
"of",
"the",
"members",
"are",
"printed",
".",
"If",
"it",
"is",
"True",
"an",
"ls",
"-",
"l",
"-",
"like",
"output",
"is",
"produced",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2009-L2036
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile.addfile
|
def addfile(self, tarinfo, fileobj=None):
"""Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
given, tarinfo.size bytes are read from it and added to the archive.
You can create TarInfo objects using gettarinfo().
On Windows platforms, `fileobj' should always be opened with mode
'rb' to avoid irritation about the file size.
"""
self._check("aw")
tarinfo = copy.copy(tarinfo)
buf = tarinfo.tobuf(self.format, self.encoding, self.errors)
self.fileobj.write(buf)
self.offset += len(buf)
# If there's data to follow, append it.
if fileobj is not None:
copyfileobj(fileobj, self.fileobj, tarinfo.size)
blocks, remainder = divmod(tarinfo.size, BLOCKSIZE)
if remainder > 0:
self.fileobj.write(NUL * (BLOCKSIZE - remainder))
blocks += 1
self.offset += blocks * BLOCKSIZE
self.members.append(tarinfo)
|
python
|
def addfile(self, tarinfo, fileobj=None):
"""Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
given, tarinfo.size bytes are read from it and added to the archive.
You can create TarInfo objects using gettarinfo().
On Windows platforms, `fileobj' should always be opened with mode
'rb' to avoid irritation about the file size.
"""
self._check("aw")
tarinfo = copy.copy(tarinfo)
buf = tarinfo.tobuf(self.format, self.encoding, self.errors)
self.fileobj.write(buf)
self.offset += len(buf)
# If there's data to follow, append it.
if fileobj is not None:
copyfileobj(fileobj, self.fileobj, tarinfo.size)
blocks, remainder = divmod(tarinfo.size, BLOCKSIZE)
if remainder > 0:
self.fileobj.write(NUL * (BLOCKSIZE - remainder))
blocks += 1
self.offset += blocks * BLOCKSIZE
self.members.append(tarinfo)
|
[
"def",
"addfile",
"(",
"self",
",",
"tarinfo",
",",
"fileobj",
"=",
"None",
")",
":",
"self",
".",
"_check",
"(",
"\"aw\"",
")",
"tarinfo",
"=",
"copy",
".",
"copy",
"(",
"tarinfo",
")",
"buf",
"=",
"tarinfo",
".",
"tobuf",
"(",
"self",
".",
"format",
",",
"self",
".",
"encoding",
",",
"self",
".",
"errors",
")",
"self",
".",
"fileobj",
".",
"write",
"(",
"buf",
")",
"self",
".",
"offset",
"+=",
"len",
"(",
"buf",
")",
"# If there's data to follow, append it.",
"if",
"fileobj",
"is",
"not",
"None",
":",
"copyfileobj",
"(",
"fileobj",
",",
"self",
".",
"fileobj",
",",
"tarinfo",
".",
"size",
")",
"blocks",
",",
"remainder",
"=",
"divmod",
"(",
"tarinfo",
".",
"size",
",",
"BLOCKSIZE",
")",
"if",
"remainder",
">",
"0",
":",
"self",
".",
"fileobj",
".",
"write",
"(",
"NUL",
"*",
"(",
"BLOCKSIZE",
"-",
"remainder",
")",
")",
"blocks",
"+=",
"1",
"self",
".",
"offset",
"+=",
"blocks",
"*",
"BLOCKSIZE",
"self",
".",
"members",
".",
"append",
"(",
"tarinfo",
")"
] |
Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
given, tarinfo.size bytes are read from it and added to the archive.
You can create TarInfo objects using gettarinfo().
On Windows platforms, `fileobj' should always be opened with mode
'rb' to avoid irritation about the file size.
|
[
"Add",
"the",
"TarInfo",
"object",
"tarinfo",
"to",
"the",
"archive",
".",
"If",
"fileobj",
"is",
"given",
"tarinfo",
".",
"size",
"bytes",
"are",
"read",
"from",
"it",
"and",
"added",
"to",
"the",
"archive",
".",
"You",
"can",
"create",
"TarInfo",
"objects",
"using",
"gettarinfo",
"()",
".",
"On",
"Windows",
"platforms",
"fileobj",
"should",
"always",
"be",
"opened",
"with",
"mode",
"rb",
"to",
"avoid",
"irritation",
"about",
"the",
"file",
"size",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2100-L2124
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile.extractall
|
def extractall(self, path=".", members=None):
"""Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must be a subset of the
list returned by getmembers().
"""
directories = []
if members is None:
members = self
for tarinfo in members:
if tarinfo.isdir():
# Extract directories with a safe mode.
directories.append(tarinfo)
tarinfo = copy.copy(tarinfo)
tarinfo.mode = 0o700
# Do not set_attrs directories, as we will do that further down
self.extract(tarinfo, path, set_attrs=not tarinfo.isdir())
# Reverse sort directories.
directories.sort(key=lambda a: a.name)
directories.reverse()
# Set correct owner, mtime and filemode on directories.
for tarinfo in directories:
dirpath = os.path.join(path, tarinfo.name)
try:
self.chown(tarinfo, dirpath)
self.utime(tarinfo, dirpath)
self.chmod(tarinfo, dirpath)
except ExtractError as e:
if self.errorlevel > 1:
raise
else:
self._dbg(1, "tarfile: %s" % e)
|
python
|
def extractall(self, path=".", members=None):
"""Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must be a subset of the
list returned by getmembers().
"""
directories = []
if members is None:
members = self
for tarinfo in members:
if tarinfo.isdir():
# Extract directories with a safe mode.
directories.append(tarinfo)
tarinfo = copy.copy(tarinfo)
tarinfo.mode = 0o700
# Do not set_attrs directories, as we will do that further down
self.extract(tarinfo, path, set_attrs=not tarinfo.isdir())
# Reverse sort directories.
directories.sort(key=lambda a: a.name)
directories.reverse()
# Set correct owner, mtime and filemode on directories.
for tarinfo in directories:
dirpath = os.path.join(path, tarinfo.name)
try:
self.chown(tarinfo, dirpath)
self.utime(tarinfo, dirpath)
self.chmod(tarinfo, dirpath)
except ExtractError as e:
if self.errorlevel > 1:
raise
else:
self._dbg(1, "tarfile: %s" % e)
|
[
"def",
"extractall",
"(",
"self",
",",
"path",
"=",
"\".\"",
",",
"members",
"=",
"None",
")",
":",
"directories",
"=",
"[",
"]",
"if",
"members",
"is",
"None",
":",
"members",
"=",
"self",
"for",
"tarinfo",
"in",
"members",
":",
"if",
"tarinfo",
".",
"isdir",
"(",
")",
":",
"# Extract directories with a safe mode.",
"directories",
".",
"append",
"(",
"tarinfo",
")",
"tarinfo",
"=",
"copy",
".",
"copy",
"(",
"tarinfo",
")",
"tarinfo",
".",
"mode",
"=",
"0o700",
"# Do not set_attrs directories, as we will do that further down",
"self",
".",
"extract",
"(",
"tarinfo",
",",
"path",
",",
"set_attrs",
"=",
"not",
"tarinfo",
".",
"isdir",
"(",
")",
")",
"# Reverse sort directories.",
"directories",
".",
"sort",
"(",
"key",
"=",
"lambda",
"a",
":",
"a",
".",
"name",
")",
"directories",
".",
"reverse",
"(",
")",
"# Set correct owner, mtime and filemode on directories.",
"for",
"tarinfo",
"in",
"directories",
":",
"dirpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"tarinfo",
".",
"name",
")",
"try",
":",
"self",
".",
"chown",
"(",
"tarinfo",
",",
"dirpath",
")",
"self",
".",
"utime",
"(",
"tarinfo",
",",
"dirpath",
")",
"self",
".",
"chmod",
"(",
"tarinfo",
",",
"dirpath",
")",
"except",
"ExtractError",
"as",
"e",
":",
"if",
"self",
".",
"errorlevel",
">",
"1",
":",
"raise",
"else",
":",
"self",
".",
"_dbg",
"(",
"1",
",",
"\"tarfile: %s\"",
"%",
"e",
")"
] |
Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must be a subset of the
list returned by getmembers().
|
[
"Extract",
"all",
"members",
"from",
"the",
"archive",
"to",
"the",
"current",
"working",
"directory",
"and",
"set",
"owner",
"modification",
"time",
"and",
"permissions",
"on",
"directories",
"afterwards",
".",
"path",
"specifies",
"a",
"different",
"directory",
"to",
"extract",
"to",
".",
"members",
"is",
"optional",
"and",
"must",
"be",
"a",
"subset",
"of",
"the",
"list",
"returned",
"by",
"getmembers",
"()",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2126-L2162
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile.extract
|
def extract(self, member, path="", set_attrs=True):
"""Extract a member from the archive to the current working directory,
using its full name. Its file information is extracted as accurately
as possible. `member' may be a filename or a TarInfo object. You can
specify a different directory using `path'. File attributes (owner,
mtime, mode) are set unless `set_attrs' is False.
"""
self._check("r")
if isinstance(member, str):
tarinfo = self.getmember(member)
else:
tarinfo = member
# Prepare the link target for makelink().
if tarinfo.islnk():
tarinfo._link_target = os.path.join(path, tarinfo.linkname)
try:
self._extract_member(tarinfo, os.path.join(path, tarinfo.name),
set_attrs=set_attrs)
except EnvironmentError as e:
if self.errorlevel > 0:
raise
else:
if e.filename is None:
self._dbg(1, "tarfile: %s" % e.strerror)
else:
self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename))
except ExtractError as e:
if self.errorlevel > 1:
raise
else:
self._dbg(1, "tarfile: %s" % e)
|
python
|
def extract(self, member, path="", set_attrs=True):
"""Extract a member from the archive to the current working directory,
using its full name. Its file information is extracted as accurately
as possible. `member' may be a filename or a TarInfo object. You can
specify a different directory using `path'. File attributes (owner,
mtime, mode) are set unless `set_attrs' is False.
"""
self._check("r")
if isinstance(member, str):
tarinfo = self.getmember(member)
else:
tarinfo = member
# Prepare the link target for makelink().
if tarinfo.islnk():
tarinfo._link_target = os.path.join(path, tarinfo.linkname)
try:
self._extract_member(tarinfo, os.path.join(path, tarinfo.name),
set_attrs=set_attrs)
except EnvironmentError as e:
if self.errorlevel > 0:
raise
else:
if e.filename is None:
self._dbg(1, "tarfile: %s" % e.strerror)
else:
self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename))
except ExtractError as e:
if self.errorlevel > 1:
raise
else:
self._dbg(1, "tarfile: %s" % e)
|
[
"def",
"extract",
"(",
"self",
",",
"member",
",",
"path",
"=",
"\"\"",
",",
"set_attrs",
"=",
"True",
")",
":",
"self",
".",
"_check",
"(",
"\"r\"",
")",
"if",
"isinstance",
"(",
"member",
",",
"str",
")",
":",
"tarinfo",
"=",
"self",
".",
"getmember",
"(",
"member",
")",
"else",
":",
"tarinfo",
"=",
"member",
"# Prepare the link target for makelink().",
"if",
"tarinfo",
".",
"islnk",
"(",
")",
":",
"tarinfo",
".",
"_link_target",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"tarinfo",
".",
"linkname",
")",
"try",
":",
"self",
".",
"_extract_member",
"(",
"tarinfo",
",",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"tarinfo",
".",
"name",
")",
",",
"set_attrs",
"=",
"set_attrs",
")",
"except",
"EnvironmentError",
"as",
"e",
":",
"if",
"self",
".",
"errorlevel",
">",
"0",
":",
"raise",
"else",
":",
"if",
"e",
".",
"filename",
"is",
"None",
":",
"self",
".",
"_dbg",
"(",
"1",
",",
"\"tarfile: %s\"",
"%",
"e",
".",
"strerror",
")",
"else",
":",
"self",
".",
"_dbg",
"(",
"1",
",",
"\"tarfile: %s %r\"",
"%",
"(",
"e",
".",
"strerror",
",",
"e",
".",
"filename",
")",
")",
"except",
"ExtractError",
"as",
"e",
":",
"if",
"self",
".",
"errorlevel",
">",
"1",
":",
"raise",
"else",
":",
"self",
".",
"_dbg",
"(",
"1",
",",
"\"tarfile: %s\"",
"%",
"e",
")"
] |
Extract a member from the archive to the current working directory,
using its full name. Its file information is extracted as accurately
as possible. `member' may be a filename or a TarInfo object. You can
specify a different directory using `path'. File attributes (owner,
mtime, mode) are set unless `set_attrs' is False.
|
[
"Extract",
"a",
"member",
"from",
"the",
"archive",
"to",
"the",
"current",
"working",
"directory",
"using",
"its",
"full",
"name",
".",
"Its",
"file",
"information",
"is",
"extracted",
"as",
"accurately",
"as",
"possible",
".",
"member",
"may",
"be",
"a",
"filename",
"or",
"a",
"TarInfo",
"object",
".",
"You",
"can",
"specify",
"a",
"different",
"directory",
"using",
"path",
".",
"File",
"attributes",
"(",
"owner",
"mtime",
"mode",
")",
"are",
"set",
"unless",
"set_attrs",
"is",
"False",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2164-L2197
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile.extractfile
|
def extractfile(self, member):
"""Extract a member from the archive as a file object. `member' may be
a filename or a TarInfo object. If `member' is a regular file, a
file-like object is returned. If `member' is a link, a file-like
object is constructed from the link's target. If `member' is none of
the above, None is returned.
The file-like object is read-only and provides the following
methods: read(), readline(), readlines(), seek() and tell()
"""
self._check("r")
if isinstance(member, str):
tarinfo = self.getmember(member)
else:
tarinfo = member
if tarinfo.isreg():
return self.fileobject(self, tarinfo)
elif tarinfo.type not in SUPPORTED_TYPES:
# If a member's type is unknown, it is treated as a
# regular file.
return self.fileobject(self, tarinfo)
elif tarinfo.islnk() or tarinfo.issym():
if isinstance(self.fileobj, _Stream):
# A small but ugly workaround for the case that someone tries
# to extract a (sym)link as a file-object from a non-seekable
# stream of tar blocks.
raise StreamError("cannot extract (sym)link as file object")
else:
# A (sym)link's file object is its target's file object.
return self.extractfile(self._find_link_target(tarinfo))
else:
# If there's no data associated with the member (directory, chrdev,
# blkdev, etc.), return None instead of a file object.
return None
|
python
|
def extractfile(self, member):
"""Extract a member from the archive as a file object. `member' may be
a filename or a TarInfo object. If `member' is a regular file, a
file-like object is returned. If `member' is a link, a file-like
object is constructed from the link's target. If `member' is none of
the above, None is returned.
The file-like object is read-only and provides the following
methods: read(), readline(), readlines(), seek() and tell()
"""
self._check("r")
if isinstance(member, str):
tarinfo = self.getmember(member)
else:
tarinfo = member
if tarinfo.isreg():
return self.fileobject(self, tarinfo)
elif tarinfo.type not in SUPPORTED_TYPES:
# If a member's type is unknown, it is treated as a
# regular file.
return self.fileobject(self, tarinfo)
elif tarinfo.islnk() or tarinfo.issym():
if isinstance(self.fileobj, _Stream):
# A small but ugly workaround for the case that someone tries
# to extract a (sym)link as a file-object from a non-seekable
# stream of tar blocks.
raise StreamError("cannot extract (sym)link as file object")
else:
# A (sym)link's file object is its target's file object.
return self.extractfile(self._find_link_target(tarinfo))
else:
# If there's no data associated with the member (directory, chrdev,
# blkdev, etc.), return None instead of a file object.
return None
|
[
"def",
"extractfile",
"(",
"self",
",",
"member",
")",
":",
"self",
".",
"_check",
"(",
"\"r\"",
")",
"if",
"isinstance",
"(",
"member",
",",
"str",
")",
":",
"tarinfo",
"=",
"self",
".",
"getmember",
"(",
"member",
")",
"else",
":",
"tarinfo",
"=",
"member",
"if",
"tarinfo",
".",
"isreg",
"(",
")",
":",
"return",
"self",
".",
"fileobject",
"(",
"self",
",",
"tarinfo",
")",
"elif",
"tarinfo",
".",
"type",
"not",
"in",
"SUPPORTED_TYPES",
":",
"# If a member's type is unknown, it is treated as a",
"# regular file.",
"return",
"self",
".",
"fileobject",
"(",
"self",
",",
"tarinfo",
")",
"elif",
"tarinfo",
".",
"islnk",
"(",
")",
"or",
"tarinfo",
".",
"issym",
"(",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"fileobj",
",",
"_Stream",
")",
":",
"# A small but ugly workaround for the case that someone tries",
"# to extract a (sym)link as a file-object from a non-seekable",
"# stream of tar blocks.",
"raise",
"StreamError",
"(",
"\"cannot extract (sym)link as file object\"",
")",
"else",
":",
"# A (sym)link's file object is its target's file object.",
"return",
"self",
".",
"extractfile",
"(",
"self",
".",
"_find_link_target",
"(",
"tarinfo",
")",
")",
"else",
":",
"# If there's no data associated with the member (directory, chrdev,",
"# blkdev, etc.), return None instead of a file object.",
"return",
"None"
] |
Extract a member from the archive as a file object. `member' may be
a filename or a TarInfo object. If `member' is a regular file, a
file-like object is returned. If `member' is a link, a file-like
object is constructed from the link's target. If `member' is none of
the above, None is returned.
The file-like object is read-only and provides the following
methods: read(), readline(), readlines(), seek() and tell()
|
[
"Extract",
"a",
"member",
"from",
"the",
"archive",
"as",
"a",
"file",
"object",
".",
"member",
"may",
"be",
"a",
"filename",
"or",
"a",
"TarInfo",
"object",
".",
"If",
"member",
"is",
"a",
"regular",
"file",
"a",
"file",
"-",
"like",
"object",
"is",
"returned",
".",
"If",
"member",
"is",
"a",
"link",
"a",
"file",
"-",
"like",
"object",
"is",
"constructed",
"from",
"the",
"link",
"s",
"target",
".",
"If",
"member",
"is",
"none",
"of",
"the",
"above",
"None",
"is",
"returned",
".",
"The",
"file",
"-",
"like",
"object",
"is",
"read",
"-",
"only",
"and",
"provides",
"the",
"following",
"methods",
":",
"read",
"()",
"readline",
"()",
"readlines",
"()",
"seek",
"()",
"and",
"tell",
"()"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2199-L2235
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile._extract_member
|
def _extract_member(self, tarinfo, targetpath, set_attrs=True):
"""Extract the TarInfo object tarinfo to a physical
file called targetpath.
"""
# Fetch the TarInfo object for the given name
# and build the destination pathname, replacing
# forward slashes to platform specific separators.
targetpath = targetpath.rstrip("/")
targetpath = targetpath.replace("/", os.sep)
# Create all upper directories.
upperdirs = os.path.dirname(targetpath)
if upperdirs and not os.path.exists(upperdirs):
# Create directories that are not part of the archive with
# default permissions.
os.makedirs(upperdirs)
if tarinfo.islnk() or tarinfo.issym():
self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname))
else:
self._dbg(1, tarinfo.name)
if tarinfo.isreg():
self.makefile(tarinfo, targetpath)
elif tarinfo.isdir():
self.makedir(tarinfo, targetpath)
elif tarinfo.isfifo():
self.makefifo(tarinfo, targetpath)
elif tarinfo.ischr() or tarinfo.isblk():
self.makedev(tarinfo, targetpath)
elif tarinfo.islnk() or tarinfo.issym():
self.makelink(tarinfo, targetpath)
elif tarinfo.type not in SUPPORTED_TYPES:
self.makeunknown(tarinfo, targetpath)
else:
self.makefile(tarinfo, targetpath)
if set_attrs:
self.chown(tarinfo, targetpath)
if not tarinfo.issym():
self.chmod(tarinfo, targetpath)
self.utime(tarinfo, targetpath)
|
python
|
def _extract_member(self, tarinfo, targetpath, set_attrs=True):
"""Extract the TarInfo object tarinfo to a physical
file called targetpath.
"""
# Fetch the TarInfo object for the given name
# and build the destination pathname, replacing
# forward slashes to platform specific separators.
targetpath = targetpath.rstrip("/")
targetpath = targetpath.replace("/", os.sep)
# Create all upper directories.
upperdirs = os.path.dirname(targetpath)
if upperdirs and not os.path.exists(upperdirs):
# Create directories that are not part of the archive with
# default permissions.
os.makedirs(upperdirs)
if tarinfo.islnk() or tarinfo.issym():
self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname))
else:
self._dbg(1, tarinfo.name)
if tarinfo.isreg():
self.makefile(tarinfo, targetpath)
elif tarinfo.isdir():
self.makedir(tarinfo, targetpath)
elif tarinfo.isfifo():
self.makefifo(tarinfo, targetpath)
elif tarinfo.ischr() or tarinfo.isblk():
self.makedev(tarinfo, targetpath)
elif tarinfo.islnk() or tarinfo.issym():
self.makelink(tarinfo, targetpath)
elif tarinfo.type not in SUPPORTED_TYPES:
self.makeunknown(tarinfo, targetpath)
else:
self.makefile(tarinfo, targetpath)
if set_attrs:
self.chown(tarinfo, targetpath)
if not tarinfo.issym():
self.chmod(tarinfo, targetpath)
self.utime(tarinfo, targetpath)
|
[
"def",
"_extract_member",
"(",
"self",
",",
"tarinfo",
",",
"targetpath",
",",
"set_attrs",
"=",
"True",
")",
":",
"# Fetch the TarInfo object for the given name",
"# and build the destination pathname, replacing",
"# forward slashes to platform specific separators.",
"targetpath",
"=",
"targetpath",
".",
"rstrip",
"(",
"\"/\"",
")",
"targetpath",
"=",
"targetpath",
".",
"replace",
"(",
"\"/\"",
",",
"os",
".",
"sep",
")",
"# Create all upper directories.",
"upperdirs",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"targetpath",
")",
"if",
"upperdirs",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"upperdirs",
")",
":",
"# Create directories that are not part of the archive with",
"# default permissions.",
"os",
".",
"makedirs",
"(",
"upperdirs",
")",
"if",
"tarinfo",
".",
"islnk",
"(",
")",
"or",
"tarinfo",
".",
"issym",
"(",
")",
":",
"self",
".",
"_dbg",
"(",
"1",
",",
"\"%s -> %s\"",
"%",
"(",
"tarinfo",
".",
"name",
",",
"tarinfo",
".",
"linkname",
")",
")",
"else",
":",
"self",
".",
"_dbg",
"(",
"1",
",",
"tarinfo",
".",
"name",
")",
"if",
"tarinfo",
".",
"isreg",
"(",
")",
":",
"self",
".",
"makefile",
"(",
"tarinfo",
",",
"targetpath",
")",
"elif",
"tarinfo",
".",
"isdir",
"(",
")",
":",
"self",
".",
"makedir",
"(",
"tarinfo",
",",
"targetpath",
")",
"elif",
"tarinfo",
".",
"isfifo",
"(",
")",
":",
"self",
".",
"makefifo",
"(",
"tarinfo",
",",
"targetpath",
")",
"elif",
"tarinfo",
".",
"ischr",
"(",
")",
"or",
"tarinfo",
".",
"isblk",
"(",
")",
":",
"self",
".",
"makedev",
"(",
"tarinfo",
",",
"targetpath",
")",
"elif",
"tarinfo",
".",
"islnk",
"(",
")",
"or",
"tarinfo",
".",
"issym",
"(",
")",
":",
"self",
".",
"makelink",
"(",
"tarinfo",
",",
"targetpath",
")",
"elif",
"tarinfo",
".",
"type",
"not",
"in",
"SUPPORTED_TYPES",
":",
"self",
".",
"makeunknown",
"(",
"tarinfo",
",",
"targetpath",
")",
"else",
":",
"self",
".",
"makefile",
"(",
"tarinfo",
",",
"targetpath",
")",
"if",
"set_attrs",
":",
"self",
".",
"chown",
"(",
"tarinfo",
",",
"targetpath",
")",
"if",
"not",
"tarinfo",
".",
"issym",
"(",
")",
":",
"self",
".",
"chmod",
"(",
"tarinfo",
",",
"targetpath",
")",
"self",
".",
"utime",
"(",
"tarinfo",
",",
"targetpath",
")"
] |
Extract the TarInfo object tarinfo to a physical
file called targetpath.
|
[
"Extract",
"the",
"TarInfo",
"object",
"tarinfo",
"to",
"a",
"physical",
"file",
"called",
"targetpath",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2237-L2278
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile.makedir
|
def makedir(self, tarinfo, targetpath):
"""Make a directory called targetpath.
"""
try:
# Use a safe mode for the directory, the real mode is set
# later in _extract_member().
os.mkdir(targetpath, 0o700)
except EnvironmentError as e:
if e.errno != errno.EEXIST:
raise
|
python
|
def makedir(self, tarinfo, targetpath):
"""Make a directory called targetpath.
"""
try:
# Use a safe mode for the directory, the real mode is set
# later in _extract_member().
os.mkdir(targetpath, 0o700)
except EnvironmentError as e:
if e.errno != errno.EEXIST:
raise
|
[
"def",
"makedir",
"(",
"self",
",",
"tarinfo",
",",
"targetpath",
")",
":",
"try",
":",
"# Use a safe mode for the directory, the real mode is set",
"# later in _extract_member().",
"os",
".",
"mkdir",
"(",
"targetpath",
",",
"0o700",
")",
"except",
"EnvironmentError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise"
] |
Make a directory called targetpath.
|
[
"Make",
"a",
"directory",
"called",
"targetpath",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2285-L2294
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile.makefile
|
def makefile(self, tarinfo, targetpath):
"""Make a file called targetpath.
"""
source = self.fileobj
source.seek(tarinfo.offset_data)
target = bltn_open(targetpath, "wb")
if tarinfo.sparse is not None:
for offset, size in tarinfo.sparse:
target.seek(offset)
copyfileobj(source, target, size)
else:
copyfileobj(source, target, tarinfo.size)
target.seek(tarinfo.size)
target.truncate()
target.close()
|
python
|
def makefile(self, tarinfo, targetpath):
"""Make a file called targetpath.
"""
source = self.fileobj
source.seek(tarinfo.offset_data)
target = bltn_open(targetpath, "wb")
if tarinfo.sparse is not None:
for offset, size in tarinfo.sparse:
target.seek(offset)
copyfileobj(source, target, size)
else:
copyfileobj(source, target, tarinfo.size)
target.seek(tarinfo.size)
target.truncate()
target.close()
|
[
"def",
"makefile",
"(",
"self",
",",
"tarinfo",
",",
"targetpath",
")",
":",
"source",
"=",
"self",
".",
"fileobj",
"source",
".",
"seek",
"(",
"tarinfo",
".",
"offset_data",
")",
"target",
"=",
"bltn_open",
"(",
"targetpath",
",",
"\"wb\"",
")",
"if",
"tarinfo",
".",
"sparse",
"is",
"not",
"None",
":",
"for",
"offset",
",",
"size",
"in",
"tarinfo",
".",
"sparse",
":",
"target",
".",
"seek",
"(",
"offset",
")",
"copyfileobj",
"(",
"source",
",",
"target",
",",
"size",
")",
"else",
":",
"copyfileobj",
"(",
"source",
",",
"target",
",",
"tarinfo",
".",
"size",
")",
"target",
".",
"seek",
"(",
"tarinfo",
".",
"size",
")",
"target",
".",
"truncate",
"(",
")",
"target",
".",
"close",
"(",
")"
] |
Make a file called targetpath.
|
[
"Make",
"a",
"file",
"called",
"targetpath",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2296-L2310
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile.makeunknown
|
def makeunknown(self, tarinfo, targetpath):
"""Make a file from a TarInfo object with an unknown type
at targetpath.
"""
self.makefile(tarinfo, targetpath)
self._dbg(1, "tarfile: Unknown file type %r, " \
"extracted as regular file." % tarinfo.type)
|
python
|
def makeunknown(self, tarinfo, targetpath):
"""Make a file from a TarInfo object with an unknown type
at targetpath.
"""
self.makefile(tarinfo, targetpath)
self._dbg(1, "tarfile: Unknown file type %r, " \
"extracted as regular file." % tarinfo.type)
|
[
"def",
"makeunknown",
"(",
"self",
",",
"tarinfo",
",",
"targetpath",
")",
":",
"self",
".",
"makefile",
"(",
"tarinfo",
",",
"targetpath",
")",
"self",
".",
"_dbg",
"(",
"1",
",",
"\"tarfile: Unknown file type %r, \"",
"\"extracted as regular file.\"",
"%",
"tarinfo",
".",
"type",
")"
] |
Make a file from a TarInfo object with an unknown type
at targetpath.
|
[
"Make",
"a",
"file",
"from",
"a",
"TarInfo",
"object",
"with",
"an",
"unknown",
"type",
"at",
"targetpath",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2312-L2318
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile.makefifo
|
def makefifo(self, tarinfo, targetpath):
"""Make a fifo called targetpath.
"""
if hasattr(os, "mkfifo"):
os.mkfifo(targetpath)
else:
raise ExtractError("fifo not supported by system")
|
python
|
def makefifo(self, tarinfo, targetpath):
"""Make a fifo called targetpath.
"""
if hasattr(os, "mkfifo"):
os.mkfifo(targetpath)
else:
raise ExtractError("fifo not supported by system")
|
[
"def",
"makefifo",
"(",
"self",
",",
"tarinfo",
",",
"targetpath",
")",
":",
"if",
"hasattr",
"(",
"os",
",",
"\"mkfifo\"",
")",
":",
"os",
".",
"mkfifo",
"(",
"targetpath",
")",
"else",
":",
"raise",
"ExtractError",
"(",
"\"fifo not supported by system\"",
")"
] |
Make a fifo called targetpath.
|
[
"Make",
"a",
"fifo",
"called",
"targetpath",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2320-L2326
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile.makedev
|
def makedev(self, tarinfo, targetpath):
"""Make a character or block device called targetpath.
"""
if not hasattr(os, "mknod") or not hasattr(os, "makedev"):
raise ExtractError("special devices not supported by system")
mode = tarinfo.mode
if tarinfo.isblk():
mode |= stat.S_IFBLK
else:
mode |= stat.S_IFCHR
os.mknod(targetpath, mode,
os.makedev(tarinfo.devmajor, tarinfo.devminor))
|
python
|
def makedev(self, tarinfo, targetpath):
"""Make a character or block device called targetpath.
"""
if not hasattr(os, "mknod") or not hasattr(os, "makedev"):
raise ExtractError("special devices not supported by system")
mode = tarinfo.mode
if tarinfo.isblk():
mode |= stat.S_IFBLK
else:
mode |= stat.S_IFCHR
os.mknod(targetpath, mode,
os.makedev(tarinfo.devmajor, tarinfo.devminor))
|
[
"def",
"makedev",
"(",
"self",
",",
"tarinfo",
",",
"targetpath",
")",
":",
"if",
"not",
"hasattr",
"(",
"os",
",",
"\"mknod\"",
")",
"or",
"not",
"hasattr",
"(",
"os",
",",
"\"makedev\"",
")",
":",
"raise",
"ExtractError",
"(",
"\"special devices not supported by system\"",
")",
"mode",
"=",
"tarinfo",
".",
"mode",
"if",
"tarinfo",
".",
"isblk",
"(",
")",
":",
"mode",
"|=",
"stat",
".",
"S_IFBLK",
"else",
":",
"mode",
"|=",
"stat",
".",
"S_IFCHR",
"os",
".",
"mknod",
"(",
"targetpath",
",",
"mode",
",",
"os",
".",
"makedev",
"(",
"tarinfo",
".",
"devmajor",
",",
"tarinfo",
".",
"devminor",
")",
")"
] |
Make a character or block device called targetpath.
|
[
"Make",
"a",
"character",
"or",
"block",
"device",
"called",
"targetpath",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2328-L2341
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile.makelink
|
def makelink(self, tarinfo, targetpath):
"""Make a (symbolic) link called targetpath. If it cannot be created
(platform limitation), we try to make a copy of the referenced file
instead of a link.
"""
try:
# For systems that support symbolic and hard links.
if tarinfo.issym():
os.symlink(tarinfo.linkname, targetpath)
else:
# See extract().
if os.path.exists(tarinfo._link_target):
os.link(tarinfo._link_target, targetpath)
else:
self._extract_member(self._find_link_target(tarinfo),
targetpath)
except symlink_exception:
if tarinfo.issym():
linkpath = os.path.join(os.path.dirname(tarinfo.name),
tarinfo.linkname)
else:
linkpath = tarinfo.linkname
else:
try:
self._extract_member(self._find_link_target(tarinfo),
targetpath)
except KeyError:
raise ExtractError("unable to resolve link inside archive")
|
python
|
def makelink(self, tarinfo, targetpath):
"""Make a (symbolic) link called targetpath. If it cannot be created
(platform limitation), we try to make a copy of the referenced file
instead of a link.
"""
try:
# For systems that support symbolic and hard links.
if tarinfo.issym():
os.symlink(tarinfo.linkname, targetpath)
else:
# See extract().
if os.path.exists(tarinfo._link_target):
os.link(tarinfo._link_target, targetpath)
else:
self._extract_member(self._find_link_target(tarinfo),
targetpath)
except symlink_exception:
if tarinfo.issym():
linkpath = os.path.join(os.path.dirname(tarinfo.name),
tarinfo.linkname)
else:
linkpath = tarinfo.linkname
else:
try:
self._extract_member(self._find_link_target(tarinfo),
targetpath)
except KeyError:
raise ExtractError("unable to resolve link inside archive")
|
[
"def",
"makelink",
"(",
"self",
",",
"tarinfo",
",",
"targetpath",
")",
":",
"try",
":",
"# For systems that support symbolic and hard links.",
"if",
"tarinfo",
".",
"issym",
"(",
")",
":",
"os",
".",
"symlink",
"(",
"tarinfo",
".",
"linkname",
",",
"targetpath",
")",
"else",
":",
"# See extract().",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"tarinfo",
".",
"_link_target",
")",
":",
"os",
".",
"link",
"(",
"tarinfo",
".",
"_link_target",
",",
"targetpath",
")",
"else",
":",
"self",
".",
"_extract_member",
"(",
"self",
".",
"_find_link_target",
"(",
"tarinfo",
")",
",",
"targetpath",
")",
"except",
"symlink_exception",
":",
"if",
"tarinfo",
".",
"issym",
"(",
")",
":",
"linkpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"tarinfo",
".",
"name",
")",
",",
"tarinfo",
".",
"linkname",
")",
"else",
":",
"linkpath",
"=",
"tarinfo",
".",
"linkname",
"else",
":",
"try",
":",
"self",
".",
"_extract_member",
"(",
"self",
".",
"_find_link_target",
"(",
"tarinfo",
")",
",",
"targetpath",
")",
"except",
"KeyError",
":",
"raise",
"ExtractError",
"(",
"\"unable to resolve link inside archive\"",
")"
] |
Make a (symbolic) link called targetpath. If it cannot be created
(platform limitation), we try to make a copy of the referenced file
instead of a link.
|
[
"Make",
"a",
"(",
"symbolic",
")",
"link",
"called",
"targetpath",
".",
"If",
"it",
"cannot",
"be",
"created",
"(",
"platform",
"limitation",
")",
"we",
"try",
"to",
"make",
"a",
"copy",
"of",
"the",
"referenced",
"file",
"instead",
"of",
"a",
"link",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2343-L2370
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile.chown
|
def chown(self, tarinfo, targetpath):
"""Set owner of targetpath according to tarinfo.
"""
if pwd and hasattr(os, "geteuid") and os.geteuid() == 0:
# We have to be root to do so.
try:
g = grp.getgrnam(tarinfo.gname)[2]
except KeyError:
g = tarinfo.gid
try:
u = pwd.getpwnam(tarinfo.uname)[2]
except KeyError:
u = tarinfo.uid
try:
if tarinfo.issym() and hasattr(os, "lchown"):
os.lchown(targetpath, u, g)
else:
if sys.platform != "os2emx":
os.chown(targetpath, u, g)
except EnvironmentError as e:
raise ExtractError("could not change owner")
|
python
|
def chown(self, tarinfo, targetpath):
"""Set owner of targetpath according to tarinfo.
"""
if pwd and hasattr(os, "geteuid") and os.geteuid() == 0:
# We have to be root to do so.
try:
g = grp.getgrnam(tarinfo.gname)[2]
except KeyError:
g = tarinfo.gid
try:
u = pwd.getpwnam(tarinfo.uname)[2]
except KeyError:
u = tarinfo.uid
try:
if tarinfo.issym() and hasattr(os, "lchown"):
os.lchown(targetpath, u, g)
else:
if sys.platform != "os2emx":
os.chown(targetpath, u, g)
except EnvironmentError as e:
raise ExtractError("could not change owner")
|
[
"def",
"chown",
"(",
"self",
",",
"tarinfo",
",",
"targetpath",
")",
":",
"if",
"pwd",
"and",
"hasattr",
"(",
"os",
",",
"\"geteuid\"",
")",
"and",
"os",
".",
"geteuid",
"(",
")",
"==",
"0",
":",
"# We have to be root to do so.",
"try",
":",
"g",
"=",
"grp",
".",
"getgrnam",
"(",
"tarinfo",
".",
"gname",
")",
"[",
"2",
"]",
"except",
"KeyError",
":",
"g",
"=",
"tarinfo",
".",
"gid",
"try",
":",
"u",
"=",
"pwd",
".",
"getpwnam",
"(",
"tarinfo",
".",
"uname",
")",
"[",
"2",
"]",
"except",
"KeyError",
":",
"u",
"=",
"tarinfo",
".",
"uid",
"try",
":",
"if",
"tarinfo",
".",
"issym",
"(",
")",
"and",
"hasattr",
"(",
"os",
",",
"\"lchown\"",
")",
":",
"os",
".",
"lchown",
"(",
"targetpath",
",",
"u",
",",
"g",
")",
"else",
":",
"if",
"sys",
".",
"platform",
"!=",
"\"os2emx\"",
":",
"os",
".",
"chown",
"(",
"targetpath",
",",
"u",
",",
"g",
")",
"except",
"EnvironmentError",
"as",
"e",
":",
"raise",
"ExtractError",
"(",
"\"could not change owner\"",
")"
] |
Set owner of targetpath according to tarinfo.
|
[
"Set",
"owner",
"of",
"targetpath",
"according",
"to",
"tarinfo",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2372-L2392
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile.chmod
|
def chmod(self, tarinfo, targetpath):
"""Set file permissions of targetpath according to tarinfo.
"""
if hasattr(os, 'chmod'):
try:
os.chmod(targetpath, tarinfo.mode)
except EnvironmentError as e:
raise ExtractError("could not change mode")
|
python
|
def chmod(self, tarinfo, targetpath):
"""Set file permissions of targetpath according to tarinfo.
"""
if hasattr(os, 'chmod'):
try:
os.chmod(targetpath, tarinfo.mode)
except EnvironmentError as e:
raise ExtractError("could not change mode")
|
[
"def",
"chmod",
"(",
"self",
",",
"tarinfo",
",",
"targetpath",
")",
":",
"if",
"hasattr",
"(",
"os",
",",
"'chmod'",
")",
":",
"try",
":",
"os",
".",
"chmod",
"(",
"targetpath",
",",
"tarinfo",
".",
"mode",
")",
"except",
"EnvironmentError",
"as",
"e",
":",
"raise",
"ExtractError",
"(",
"\"could not change mode\"",
")"
] |
Set file permissions of targetpath according to tarinfo.
|
[
"Set",
"file",
"permissions",
"of",
"targetpath",
"according",
"to",
"tarinfo",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2394-L2401
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile.utime
|
def utime(self, tarinfo, targetpath):
"""Set modification time of targetpath according to tarinfo.
"""
if not hasattr(os, 'utime'):
return
try:
os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime))
except EnvironmentError as e:
raise ExtractError("could not change modification time")
|
python
|
def utime(self, tarinfo, targetpath):
"""Set modification time of targetpath according to tarinfo.
"""
if not hasattr(os, 'utime'):
return
try:
os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime))
except EnvironmentError as e:
raise ExtractError("could not change modification time")
|
[
"def",
"utime",
"(",
"self",
",",
"tarinfo",
",",
"targetpath",
")",
":",
"if",
"not",
"hasattr",
"(",
"os",
",",
"'utime'",
")",
":",
"return",
"try",
":",
"os",
".",
"utime",
"(",
"targetpath",
",",
"(",
"tarinfo",
".",
"mtime",
",",
"tarinfo",
".",
"mtime",
")",
")",
"except",
"EnvironmentError",
"as",
"e",
":",
"raise",
"ExtractError",
"(",
"\"could not change modification time\"",
")"
] |
Set modification time of targetpath according to tarinfo.
|
[
"Set",
"modification",
"time",
"of",
"targetpath",
"according",
"to",
"tarinfo",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2403-L2411
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile.next
|
def next(self):
"""Return the next member of the archive as a TarInfo object, when
TarFile is opened for reading. Return None if there is no more
available.
"""
self._check("ra")
if self.firstmember is not None:
m = self.firstmember
self.firstmember = None
return m
# Read the next block.
self.fileobj.seek(self.offset)
tarinfo = None
while True:
try:
tarinfo = self.tarinfo.fromtarfile(self)
except EOFHeaderError as e:
if self.ignore_zeros:
self._dbg(2, "0x%X: %s" % (self.offset, e))
self.offset += BLOCKSIZE
continue
except InvalidHeaderError as e:
if self.ignore_zeros:
self._dbg(2, "0x%X: %s" % (self.offset, e))
self.offset += BLOCKSIZE
continue
elif self.offset == 0:
raise ReadError(str(e))
except EmptyHeaderError:
if self.offset == 0:
raise ReadError("empty file")
except TruncatedHeaderError as e:
if self.offset == 0:
raise ReadError(str(e))
except SubsequentHeaderError as e:
raise ReadError(str(e))
break
if tarinfo is not None:
self.members.append(tarinfo)
else:
self._loaded = True
return tarinfo
|
python
|
def next(self):
"""Return the next member of the archive as a TarInfo object, when
TarFile is opened for reading. Return None if there is no more
available.
"""
self._check("ra")
if self.firstmember is not None:
m = self.firstmember
self.firstmember = None
return m
# Read the next block.
self.fileobj.seek(self.offset)
tarinfo = None
while True:
try:
tarinfo = self.tarinfo.fromtarfile(self)
except EOFHeaderError as e:
if self.ignore_zeros:
self._dbg(2, "0x%X: %s" % (self.offset, e))
self.offset += BLOCKSIZE
continue
except InvalidHeaderError as e:
if self.ignore_zeros:
self._dbg(2, "0x%X: %s" % (self.offset, e))
self.offset += BLOCKSIZE
continue
elif self.offset == 0:
raise ReadError(str(e))
except EmptyHeaderError:
if self.offset == 0:
raise ReadError("empty file")
except TruncatedHeaderError as e:
if self.offset == 0:
raise ReadError(str(e))
except SubsequentHeaderError as e:
raise ReadError(str(e))
break
if tarinfo is not None:
self.members.append(tarinfo)
else:
self._loaded = True
return tarinfo
|
[
"def",
"next",
"(",
"self",
")",
":",
"self",
".",
"_check",
"(",
"\"ra\"",
")",
"if",
"self",
".",
"firstmember",
"is",
"not",
"None",
":",
"m",
"=",
"self",
".",
"firstmember",
"self",
".",
"firstmember",
"=",
"None",
"return",
"m",
"# Read the next block.",
"self",
".",
"fileobj",
".",
"seek",
"(",
"self",
".",
"offset",
")",
"tarinfo",
"=",
"None",
"while",
"True",
":",
"try",
":",
"tarinfo",
"=",
"self",
".",
"tarinfo",
".",
"fromtarfile",
"(",
"self",
")",
"except",
"EOFHeaderError",
"as",
"e",
":",
"if",
"self",
".",
"ignore_zeros",
":",
"self",
".",
"_dbg",
"(",
"2",
",",
"\"0x%X: %s\"",
"%",
"(",
"self",
".",
"offset",
",",
"e",
")",
")",
"self",
".",
"offset",
"+=",
"BLOCKSIZE",
"continue",
"except",
"InvalidHeaderError",
"as",
"e",
":",
"if",
"self",
".",
"ignore_zeros",
":",
"self",
".",
"_dbg",
"(",
"2",
",",
"\"0x%X: %s\"",
"%",
"(",
"self",
".",
"offset",
",",
"e",
")",
")",
"self",
".",
"offset",
"+=",
"BLOCKSIZE",
"continue",
"elif",
"self",
".",
"offset",
"==",
"0",
":",
"raise",
"ReadError",
"(",
"str",
"(",
"e",
")",
")",
"except",
"EmptyHeaderError",
":",
"if",
"self",
".",
"offset",
"==",
"0",
":",
"raise",
"ReadError",
"(",
"\"empty file\"",
")",
"except",
"TruncatedHeaderError",
"as",
"e",
":",
"if",
"self",
".",
"offset",
"==",
"0",
":",
"raise",
"ReadError",
"(",
"str",
"(",
"e",
")",
")",
"except",
"SubsequentHeaderError",
"as",
"e",
":",
"raise",
"ReadError",
"(",
"str",
"(",
"e",
")",
")",
"break",
"if",
"tarinfo",
"is",
"not",
"None",
":",
"self",
".",
"members",
".",
"append",
"(",
"tarinfo",
")",
"else",
":",
"self",
".",
"_loaded",
"=",
"True",
"return",
"tarinfo"
] |
Return the next member of the archive as a TarInfo object, when
TarFile is opened for reading. Return None if there is no more
available.
|
[
"Return",
"the",
"next",
"member",
"of",
"the",
"archive",
"as",
"a",
"TarInfo",
"object",
"when",
"TarFile",
"is",
"opened",
"for",
"reading",
".",
"Return",
"None",
"if",
"there",
"is",
"no",
"more",
"available",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2414-L2458
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile._getmember
|
def _getmember(self, name, tarinfo=None, normalize=False):
"""Find an archive member by name from bottom to top.
If tarinfo is given, it is used as the starting point.
"""
# Ensure that all members have been loaded.
members = self.getmembers()
# Limit the member search list up to tarinfo.
if tarinfo is not None:
members = members[:members.index(tarinfo)]
if normalize:
name = os.path.normpath(name)
for member in reversed(members):
if normalize:
member_name = os.path.normpath(member.name)
else:
member_name = member.name
if name == member_name:
return member
|
python
|
def _getmember(self, name, tarinfo=None, normalize=False):
"""Find an archive member by name from bottom to top.
If tarinfo is given, it is used as the starting point.
"""
# Ensure that all members have been loaded.
members = self.getmembers()
# Limit the member search list up to tarinfo.
if tarinfo is not None:
members = members[:members.index(tarinfo)]
if normalize:
name = os.path.normpath(name)
for member in reversed(members):
if normalize:
member_name = os.path.normpath(member.name)
else:
member_name = member.name
if name == member_name:
return member
|
[
"def",
"_getmember",
"(",
"self",
",",
"name",
",",
"tarinfo",
"=",
"None",
",",
"normalize",
"=",
"False",
")",
":",
"# Ensure that all members have been loaded.",
"members",
"=",
"self",
".",
"getmembers",
"(",
")",
"# Limit the member search list up to tarinfo.",
"if",
"tarinfo",
"is",
"not",
"None",
":",
"members",
"=",
"members",
"[",
":",
"members",
".",
"index",
"(",
"tarinfo",
")",
"]",
"if",
"normalize",
":",
"name",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"name",
")",
"for",
"member",
"in",
"reversed",
"(",
"members",
")",
":",
"if",
"normalize",
":",
"member_name",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"member",
".",
"name",
")",
"else",
":",
"member_name",
"=",
"member",
".",
"name",
"if",
"name",
"==",
"member_name",
":",
"return",
"member"
] |
Find an archive member by name from bottom to top.
If tarinfo is given, it is used as the starting point.
|
[
"Find",
"an",
"archive",
"member",
"by",
"name",
"from",
"bottom",
"to",
"top",
".",
"If",
"tarinfo",
"is",
"given",
"it",
"is",
"used",
"as",
"the",
"starting",
"point",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2463-L2484
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile._load
|
def _load(self):
"""Read through the entire archive file and look for readable
members.
"""
while True:
tarinfo = self.next()
if tarinfo is None:
break
self._loaded = True
|
python
|
def _load(self):
"""Read through the entire archive file and look for readable
members.
"""
while True:
tarinfo = self.next()
if tarinfo is None:
break
self._loaded = True
|
[
"def",
"_load",
"(",
"self",
")",
":",
"while",
"True",
":",
"tarinfo",
"=",
"self",
".",
"next",
"(",
")",
"if",
"tarinfo",
"is",
"None",
":",
"break",
"self",
".",
"_loaded",
"=",
"True"
] |
Read through the entire archive file and look for readable
members.
|
[
"Read",
"through",
"the",
"entire",
"archive",
"file",
"and",
"look",
"for",
"readable",
"members",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2486-L2494
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile._check
|
def _check(self, mode=None):
"""Check if TarFile is still open, and if the operation's mode
corresponds to TarFile's mode.
"""
if self.closed:
raise IOError("%s is closed" % self.__class__.__name__)
if mode is not None and self.mode not in mode:
raise IOError("bad operation for mode %r" % self.mode)
|
python
|
def _check(self, mode=None):
"""Check if TarFile is still open, and if the operation's mode
corresponds to TarFile's mode.
"""
if self.closed:
raise IOError("%s is closed" % self.__class__.__name__)
if mode is not None and self.mode not in mode:
raise IOError("bad operation for mode %r" % self.mode)
|
[
"def",
"_check",
"(",
"self",
",",
"mode",
"=",
"None",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"IOError",
"(",
"\"%s is closed\"",
"%",
"self",
".",
"__class__",
".",
"__name__",
")",
"if",
"mode",
"is",
"not",
"None",
"and",
"self",
".",
"mode",
"not",
"in",
"mode",
":",
"raise",
"IOError",
"(",
"\"bad operation for mode %r\"",
"%",
"self",
".",
"mode",
")"
] |
Check if TarFile is still open, and if the operation's mode
corresponds to TarFile's mode.
|
[
"Check",
"if",
"TarFile",
"is",
"still",
"open",
"and",
"if",
"the",
"operation",
"s",
"mode",
"corresponds",
"to",
"TarFile",
"s",
"mode",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2496-L2503
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile._find_link_target
|
def _find_link_target(self, tarinfo):
"""Find the target member of a symlink or hardlink member in the
archive.
"""
if tarinfo.issym():
# Always search the entire archive.
linkname = os.path.dirname(tarinfo.name) + "/" + tarinfo.linkname
limit = None
else:
# Search the archive before the link, because a hard link is
# just a reference to an already archived file.
linkname = tarinfo.linkname
limit = tarinfo
member = self._getmember(linkname, tarinfo=limit, normalize=True)
if member is None:
raise KeyError("linkname %r not found" % linkname)
return member
|
python
|
def _find_link_target(self, tarinfo):
"""Find the target member of a symlink or hardlink member in the
archive.
"""
if tarinfo.issym():
# Always search the entire archive.
linkname = os.path.dirname(tarinfo.name) + "/" + tarinfo.linkname
limit = None
else:
# Search the archive before the link, because a hard link is
# just a reference to an already archived file.
linkname = tarinfo.linkname
limit = tarinfo
member = self._getmember(linkname, tarinfo=limit, normalize=True)
if member is None:
raise KeyError("linkname %r not found" % linkname)
return member
|
[
"def",
"_find_link_target",
"(",
"self",
",",
"tarinfo",
")",
":",
"if",
"tarinfo",
".",
"issym",
"(",
")",
":",
"# Always search the entire archive.",
"linkname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"tarinfo",
".",
"name",
")",
"+",
"\"/\"",
"+",
"tarinfo",
".",
"linkname",
"limit",
"=",
"None",
"else",
":",
"# Search the archive before the link, because a hard link is",
"# just a reference to an already archived file.",
"linkname",
"=",
"tarinfo",
".",
"linkname",
"limit",
"=",
"tarinfo",
"member",
"=",
"self",
".",
"_getmember",
"(",
"linkname",
",",
"tarinfo",
"=",
"limit",
",",
"normalize",
"=",
"True",
")",
"if",
"member",
"is",
"None",
":",
"raise",
"KeyError",
"(",
"\"linkname %r not found\"",
"%",
"linkname",
")",
"return",
"member"
] |
Find the target member of a symlink or hardlink member in the
archive.
|
[
"Find",
"the",
"target",
"member",
"of",
"a",
"symlink",
"or",
"hardlink",
"member",
"in",
"the",
"archive",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2505-L2522
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/_backport/tarfile.py
|
TarFile._dbg
|
def _dbg(self, level, msg):
"""Write debugging output to sys.stderr.
"""
if level <= self.debug:
print(msg, file=sys.stderr)
|
python
|
def _dbg(self, level, msg):
"""Write debugging output to sys.stderr.
"""
if level <= self.debug:
print(msg, file=sys.stderr)
|
[
"def",
"_dbg",
"(",
"self",
",",
"level",
",",
"msg",
")",
":",
"if",
"level",
"<=",
"self",
".",
"debug",
":",
"print",
"(",
"msg",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] |
Write debugging output to sys.stderr.
|
[
"Write",
"debugging",
"output",
"to",
"sys",
".",
"stderr",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2532-L2536
|
train
|
pypa/pipenv
|
pipenv/project.py
|
Project.path_to
|
def path_to(self, p):
"""Returns the absolute path to a given relative path."""
if os.path.isabs(p):
return p
return os.sep.join([self._original_dir, p])
|
python
|
def path_to(self, p):
"""Returns the absolute path to a given relative path."""
if os.path.isabs(p):
return p
return os.sep.join([self._original_dir, p])
|
[
"def",
"path_to",
"(",
"self",
",",
"p",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"p",
")",
":",
"return",
"p",
"return",
"os",
".",
"sep",
".",
"join",
"(",
"[",
"self",
".",
"_original_dir",
",",
"p",
"]",
")"
] |
Returns the absolute path to a given relative path.
|
[
"Returns",
"the",
"absolute",
"path",
"to",
"a",
"given",
"relative",
"path",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L159-L164
|
train
|
pypa/pipenv
|
pipenv/project.py
|
Project._build_package_list
|
def _build_package_list(self, package_section):
"""Returns a list of packages for pip-tools to consume."""
from pipenv.vendor.requirementslib.utils import is_vcs
ps = {}
# TODO: Separate the logic for showing packages from the filters for supplying pip-tools
for k, v in self.parsed_pipfile.get(package_section, {}).items():
# Skip editable VCS deps.
if hasattr(v, "keys"):
# When a vcs url is gven without editable it only appears as a key
# Eliminate any vcs, path, or url entries which are not editable
# Since pip-tools can't do deep resolution on them, even setuptools-installable ones
if (
is_vcs(v)
or is_vcs(k)
or (is_installable_file(k) or is_installable_file(v))
or any(
(
prefix in v
and (os.path.isfile(v[prefix]) or is_valid_url(v[prefix]))
)
for prefix in ["path", "file"]
)
):
# If they are editable, do resolve them
if "editable" not in v:
# allow wheels to be passed through
if not (
hasattr(v, "keys")
and v.get("path", v.get("file", "")).endswith(".whl")
):
continue
ps.update({k: v})
else:
ps.update({k: v})
else:
ps.update({k: v})
else:
# Since these entries have no attributes we know they are not editable
# So we can safely exclude things that need to be editable in order to be resolved
# First exclude anything that is a vcs entry either in the key or value
if not (
any(is_vcs(i) for i in [k, v])
or
# Then exclude any installable files that are not directories
# Because pip-tools can resolve setup.py for example
any(is_installable_file(i) for i in [k, v])
or
# Then exclude any URLs because they need to be editable also
# Things that are excluded can only be 'shallow resolved'
any(is_valid_url(i) for i in [k, v])
):
ps.update({k: v})
return ps
|
python
|
def _build_package_list(self, package_section):
"""Returns a list of packages for pip-tools to consume."""
from pipenv.vendor.requirementslib.utils import is_vcs
ps = {}
# TODO: Separate the logic for showing packages from the filters for supplying pip-tools
for k, v in self.parsed_pipfile.get(package_section, {}).items():
# Skip editable VCS deps.
if hasattr(v, "keys"):
# When a vcs url is gven without editable it only appears as a key
# Eliminate any vcs, path, or url entries which are not editable
# Since pip-tools can't do deep resolution on them, even setuptools-installable ones
if (
is_vcs(v)
or is_vcs(k)
or (is_installable_file(k) or is_installable_file(v))
or any(
(
prefix in v
and (os.path.isfile(v[prefix]) or is_valid_url(v[prefix]))
)
for prefix in ["path", "file"]
)
):
# If they are editable, do resolve them
if "editable" not in v:
# allow wheels to be passed through
if not (
hasattr(v, "keys")
and v.get("path", v.get("file", "")).endswith(".whl")
):
continue
ps.update({k: v})
else:
ps.update({k: v})
else:
ps.update({k: v})
else:
# Since these entries have no attributes we know they are not editable
# So we can safely exclude things that need to be editable in order to be resolved
# First exclude anything that is a vcs entry either in the key or value
if not (
any(is_vcs(i) for i in [k, v])
or
# Then exclude any installable files that are not directories
# Because pip-tools can resolve setup.py for example
any(is_installable_file(i) for i in [k, v])
or
# Then exclude any URLs because they need to be editable also
# Things that are excluded can only be 'shallow resolved'
any(is_valid_url(i) for i in [k, v])
):
ps.update({k: v})
return ps
|
[
"def",
"_build_package_list",
"(",
"self",
",",
"package_section",
")",
":",
"from",
"pipenv",
".",
"vendor",
".",
"requirementslib",
".",
"utils",
"import",
"is_vcs",
"ps",
"=",
"{",
"}",
"# TODO: Separate the logic for showing packages from the filters for supplying pip-tools",
"for",
"k",
",",
"v",
"in",
"self",
".",
"parsed_pipfile",
".",
"get",
"(",
"package_section",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"# Skip editable VCS deps.",
"if",
"hasattr",
"(",
"v",
",",
"\"keys\"",
")",
":",
"# When a vcs url is gven without editable it only appears as a key",
"# Eliminate any vcs, path, or url entries which are not editable",
"# Since pip-tools can't do deep resolution on them, even setuptools-installable ones",
"if",
"(",
"is_vcs",
"(",
"v",
")",
"or",
"is_vcs",
"(",
"k",
")",
"or",
"(",
"is_installable_file",
"(",
"k",
")",
"or",
"is_installable_file",
"(",
"v",
")",
")",
"or",
"any",
"(",
"(",
"prefix",
"in",
"v",
"and",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"v",
"[",
"prefix",
"]",
")",
"or",
"is_valid_url",
"(",
"v",
"[",
"prefix",
"]",
")",
")",
")",
"for",
"prefix",
"in",
"[",
"\"path\"",
",",
"\"file\"",
"]",
")",
")",
":",
"# If they are editable, do resolve them",
"if",
"\"editable\"",
"not",
"in",
"v",
":",
"# allow wheels to be passed through",
"if",
"not",
"(",
"hasattr",
"(",
"v",
",",
"\"keys\"",
")",
"and",
"v",
".",
"get",
"(",
"\"path\"",
",",
"v",
".",
"get",
"(",
"\"file\"",
",",
"\"\"",
")",
")",
".",
"endswith",
"(",
"\".whl\"",
")",
")",
":",
"continue",
"ps",
".",
"update",
"(",
"{",
"k",
":",
"v",
"}",
")",
"else",
":",
"ps",
".",
"update",
"(",
"{",
"k",
":",
"v",
"}",
")",
"else",
":",
"ps",
".",
"update",
"(",
"{",
"k",
":",
"v",
"}",
")",
"else",
":",
"# Since these entries have no attributes we know they are not editable",
"# So we can safely exclude things that need to be editable in order to be resolved",
"# First exclude anything that is a vcs entry either in the key or value",
"if",
"not",
"(",
"any",
"(",
"is_vcs",
"(",
"i",
")",
"for",
"i",
"in",
"[",
"k",
",",
"v",
"]",
")",
"or",
"# Then exclude any installable files that are not directories",
"# Because pip-tools can resolve setup.py for example",
"any",
"(",
"is_installable_file",
"(",
"i",
")",
"for",
"i",
"in",
"[",
"k",
",",
"v",
"]",
")",
"or",
"# Then exclude any URLs because they need to be editable also",
"# Things that are excluded can only be 'shallow resolved'",
"any",
"(",
"is_valid_url",
"(",
"i",
")",
"for",
"i",
"in",
"[",
"k",
",",
"v",
"]",
")",
")",
":",
"ps",
".",
"update",
"(",
"{",
"k",
":",
"v",
"}",
")",
"return",
"ps"
] |
Returns a list of packages for pip-tools to consume.
|
[
"Returns",
"a",
"list",
"of",
"packages",
"for",
"pip",
"-",
"tools",
"to",
"consume",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L166-L219
|
train
|
pypa/pipenv
|
pipenv/project.py
|
Project._get_virtualenv_hash
|
def _get_virtualenv_hash(self, name):
"""Get the name of the virtualenv adjusted for windows if needed
Returns (name, encoded_hash)
"""
def get_name(name, location):
name = self._sanitize(name)
hash = hashlib.sha256(location.encode()).digest()[:6]
encoded_hash = base64.urlsafe_b64encode(hash).decode()
return name, encoded_hash[:8]
clean_name, encoded_hash = get_name(name, self.pipfile_location)
venv_name = "{0}-{1}".format(clean_name, encoded_hash)
# This should work most of the time for
# Case-sensitive filesystems,
# In-project venv
# "Proper" path casing (on non-case-sensitive filesystems).
if (
not fnmatch.fnmatch("A", "a")
or self.is_venv_in_project()
or get_workon_home().joinpath(venv_name).exists()
):
return clean_name, encoded_hash
# Check for different capitalization of the same project.
for path in get_workon_home().iterdir():
if not is_virtual_environment(path):
continue
try:
env_name, hash_ = path.name.rsplit("-", 1)
except ValueError:
continue
if len(hash_) != 8 or env_name.lower() != name.lower():
continue
return get_name(env_name, self.pipfile_location.replace(name, env_name))
# Use the default if no matching env exists.
return clean_name, encoded_hash
|
python
|
def _get_virtualenv_hash(self, name):
"""Get the name of the virtualenv adjusted for windows if needed
Returns (name, encoded_hash)
"""
def get_name(name, location):
name = self._sanitize(name)
hash = hashlib.sha256(location.encode()).digest()[:6]
encoded_hash = base64.urlsafe_b64encode(hash).decode()
return name, encoded_hash[:8]
clean_name, encoded_hash = get_name(name, self.pipfile_location)
venv_name = "{0}-{1}".format(clean_name, encoded_hash)
# This should work most of the time for
# Case-sensitive filesystems,
# In-project venv
# "Proper" path casing (on non-case-sensitive filesystems).
if (
not fnmatch.fnmatch("A", "a")
or self.is_venv_in_project()
or get_workon_home().joinpath(venv_name).exists()
):
return clean_name, encoded_hash
# Check for different capitalization of the same project.
for path in get_workon_home().iterdir():
if not is_virtual_environment(path):
continue
try:
env_name, hash_ = path.name.rsplit("-", 1)
except ValueError:
continue
if len(hash_) != 8 or env_name.lower() != name.lower():
continue
return get_name(env_name, self.pipfile_location.replace(name, env_name))
# Use the default if no matching env exists.
return clean_name, encoded_hash
|
[
"def",
"_get_virtualenv_hash",
"(",
"self",
",",
"name",
")",
":",
"def",
"get_name",
"(",
"name",
",",
"location",
")",
":",
"name",
"=",
"self",
".",
"_sanitize",
"(",
"name",
")",
"hash",
"=",
"hashlib",
".",
"sha256",
"(",
"location",
".",
"encode",
"(",
")",
")",
".",
"digest",
"(",
")",
"[",
":",
"6",
"]",
"encoded_hash",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"hash",
")",
".",
"decode",
"(",
")",
"return",
"name",
",",
"encoded_hash",
"[",
":",
"8",
"]",
"clean_name",
",",
"encoded_hash",
"=",
"get_name",
"(",
"name",
",",
"self",
".",
"pipfile_location",
")",
"venv_name",
"=",
"\"{0}-{1}\"",
".",
"format",
"(",
"clean_name",
",",
"encoded_hash",
")",
"# This should work most of the time for",
"# Case-sensitive filesystems,",
"# In-project venv",
"# \"Proper\" path casing (on non-case-sensitive filesystems).",
"if",
"(",
"not",
"fnmatch",
".",
"fnmatch",
"(",
"\"A\"",
",",
"\"a\"",
")",
"or",
"self",
".",
"is_venv_in_project",
"(",
")",
"or",
"get_workon_home",
"(",
")",
".",
"joinpath",
"(",
"venv_name",
")",
".",
"exists",
"(",
")",
")",
":",
"return",
"clean_name",
",",
"encoded_hash",
"# Check for different capitalization of the same project.",
"for",
"path",
"in",
"get_workon_home",
"(",
")",
".",
"iterdir",
"(",
")",
":",
"if",
"not",
"is_virtual_environment",
"(",
"path",
")",
":",
"continue",
"try",
":",
"env_name",
",",
"hash_",
"=",
"path",
".",
"name",
".",
"rsplit",
"(",
"\"-\"",
",",
"1",
")",
"except",
"ValueError",
":",
"continue",
"if",
"len",
"(",
"hash_",
")",
"!=",
"8",
"or",
"env_name",
".",
"lower",
"(",
")",
"!=",
"name",
".",
"lower",
"(",
")",
":",
"continue",
"return",
"get_name",
"(",
"env_name",
",",
"self",
".",
"pipfile_location",
".",
"replace",
"(",
"name",
",",
"env_name",
")",
")",
"# Use the default if no matching env exists.",
"return",
"clean_name",
",",
"encoded_hash"
] |
Get the name of the virtualenv adjusted for windows if needed
Returns (name, encoded_hash)
|
[
"Get",
"the",
"name",
"of",
"the",
"virtualenv",
"adjusted",
"for",
"windows",
"if",
"needed"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L368-L407
|
train
|
pypa/pipenv
|
pipenv/project.py
|
Project.register_proper_name
|
def register_proper_name(self, name):
"""Registers a proper name to the database."""
with self.proper_names_db_path.open("a") as f:
f.write(u"{0}\n".format(name))
|
python
|
def register_proper_name(self, name):
"""Registers a proper name to the database."""
with self.proper_names_db_path.open("a") as f:
f.write(u"{0}\n".format(name))
|
[
"def",
"register_proper_name",
"(",
"self",
",",
"name",
")",
":",
"with",
"self",
".",
"proper_names_db_path",
".",
"open",
"(",
"\"a\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"u\"{0}\\n\"",
".",
"format",
"(",
"name",
")",
")"
] |
Registers a proper name to the database.
|
[
"Registers",
"a",
"proper",
"name",
"to",
"the",
"database",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L462-L465
|
train
|
pypa/pipenv
|
pipenv/project.py
|
Project.parsed_pipfile
|
def parsed_pipfile(self):
"""Parse Pipfile into a TOMLFile and cache it
(call clear_pipfile_cache() afterwards if mutating)"""
contents = self.read_pipfile()
# use full contents to get around str/bytes 2/3 issues
cache_key = (self.pipfile_location, contents)
if cache_key not in _pipfile_cache:
parsed = self._parse_pipfile(contents)
_pipfile_cache[cache_key] = parsed
return _pipfile_cache[cache_key]
|
python
|
def parsed_pipfile(self):
"""Parse Pipfile into a TOMLFile and cache it
(call clear_pipfile_cache() afterwards if mutating)"""
contents = self.read_pipfile()
# use full contents to get around str/bytes 2/3 issues
cache_key = (self.pipfile_location, contents)
if cache_key not in _pipfile_cache:
parsed = self._parse_pipfile(contents)
_pipfile_cache[cache_key] = parsed
return _pipfile_cache[cache_key]
|
[
"def",
"parsed_pipfile",
"(",
"self",
")",
":",
"contents",
"=",
"self",
".",
"read_pipfile",
"(",
")",
"# use full contents to get around str/bytes 2/3 issues",
"cache_key",
"=",
"(",
"self",
".",
"pipfile_location",
",",
"contents",
")",
"if",
"cache_key",
"not",
"in",
"_pipfile_cache",
":",
"parsed",
"=",
"self",
".",
"_parse_pipfile",
"(",
"contents",
")",
"_pipfile_cache",
"[",
"cache_key",
"]",
"=",
"parsed",
"return",
"_pipfile_cache",
"[",
"cache_key",
"]"
] |
Parse Pipfile into a TOMLFile and cache it
(call clear_pipfile_cache() afterwards if mutating)
|
[
"Parse",
"Pipfile",
"into",
"a",
"TOMLFile",
"and",
"cache",
"it"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L491-L501
|
train
|
pypa/pipenv
|
pipenv/project.py
|
Project._lockfile
|
def _lockfile(self):
"""Pipfile.lock divided by PyPI and external dependencies."""
pfile = pipfile.load(self.pipfile_location, inject_env=False)
lockfile = json.loads(pfile.lock())
for section in ("default", "develop"):
lock_section = lockfile.get(section, {})
for key in list(lock_section.keys()):
norm_key = pep423_name(key)
lockfile[section][norm_key] = lock_section.pop(key)
return lockfile
|
python
|
def _lockfile(self):
"""Pipfile.lock divided by PyPI and external dependencies."""
pfile = pipfile.load(self.pipfile_location, inject_env=False)
lockfile = json.loads(pfile.lock())
for section in ("default", "develop"):
lock_section = lockfile.get(section, {})
for key in list(lock_section.keys()):
norm_key = pep423_name(key)
lockfile[section][norm_key] = lock_section.pop(key)
return lockfile
|
[
"def",
"_lockfile",
"(",
"self",
")",
":",
"pfile",
"=",
"pipfile",
".",
"load",
"(",
"self",
".",
"pipfile_location",
",",
"inject_env",
"=",
"False",
")",
"lockfile",
"=",
"json",
".",
"loads",
"(",
"pfile",
".",
"lock",
"(",
")",
")",
"for",
"section",
"in",
"(",
"\"default\"",
",",
"\"develop\"",
")",
":",
"lock_section",
"=",
"lockfile",
".",
"get",
"(",
"section",
",",
"{",
"}",
")",
"for",
"key",
"in",
"list",
"(",
"lock_section",
".",
"keys",
"(",
")",
")",
":",
"norm_key",
"=",
"pep423_name",
"(",
"key",
")",
"lockfile",
"[",
"section",
"]",
"[",
"norm_key",
"]",
"=",
"lock_section",
".",
"pop",
"(",
"key",
")",
"return",
"lockfile"
] |
Pipfile.lock divided by PyPI and external dependencies.
|
[
"Pipfile",
".",
"lock",
"divided",
"by",
"PyPI",
"and",
"external",
"dependencies",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L581-L590
|
train
|
pypa/pipenv
|
pipenv/project.py
|
Project.all_packages
|
def all_packages(self):
"""Returns a list of all packages."""
p = dict(self.parsed_pipfile.get("dev-packages", {}))
p.update(self.parsed_pipfile.get("packages", {}))
return p
|
python
|
def all_packages(self):
"""Returns a list of all packages."""
p = dict(self.parsed_pipfile.get("dev-packages", {}))
p.update(self.parsed_pipfile.get("packages", {}))
return p
|
[
"def",
"all_packages",
"(",
"self",
")",
":",
"p",
"=",
"dict",
"(",
"self",
".",
"parsed_pipfile",
".",
"get",
"(",
"\"dev-packages\"",
",",
"{",
"}",
")",
")",
"p",
".",
"update",
"(",
"self",
".",
"parsed_pipfile",
".",
"get",
"(",
"\"packages\"",
",",
"{",
"}",
")",
")",
"return",
"p"
] |
Returns a list of all packages.
|
[
"Returns",
"a",
"list",
"of",
"all",
"packages",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L648-L652
|
train
|
pypa/pipenv
|
pipenv/project.py
|
Project.create_pipfile
|
def create_pipfile(self, python=None):
"""Creates the Pipfile, filled with juicy defaults."""
from .vendor.pip_shims.shims import (
ConfigOptionParser, make_option_group, index_group
)
config_parser = ConfigOptionParser(name=self.name)
config_parser.add_option_group(make_option_group(index_group, config_parser))
install = config_parser.option_groups[0]
indexes = (
" ".join(install.get_option("--extra-index-url").default)
.lstrip("\n")
.split("\n")
)
sources = [DEFAULT_SOURCE,]
for i, index in enumerate(indexes):
if not index:
continue
source_name = "pip_index_{}".format(i)
verify_ssl = index.startswith("https")
sources.append(
{u"url": index, u"verify_ssl": verify_ssl, u"name": source_name}
)
data = {
u"source": sources,
# Default packages.
u"packages": {},
u"dev-packages": {},
}
# Default requires.
required_python = python
if not python:
if self.virtualenv_location:
required_python = self.which("python", self.virtualenv_location)
else:
required_python = self.which("python")
version = python_version(required_python) or PIPENV_DEFAULT_PYTHON_VERSION
if version and len(version) >= 3:
data[u"requires"] = {"python_version": version[: len("2.7")]}
self.write_toml(data)
|
python
|
def create_pipfile(self, python=None):
"""Creates the Pipfile, filled with juicy defaults."""
from .vendor.pip_shims.shims import (
ConfigOptionParser, make_option_group, index_group
)
config_parser = ConfigOptionParser(name=self.name)
config_parser.add_option_group(make_option_group(index_group, config_parser))
install = config_parser.option_groups[0]
indexes = (
" ".join(install.get_option("--extra-index-url").default)
.lstrip("\n")
.split("\n")
)
sources = [DEFAULT_SOURCE,]
for i, index in enumerate(indexes):
if not index:
continue
source_name = "pip_index_{}".format(i)
verify_ssl = index.startswith("https")
sources.append(
{u"url": index, u"verify_ssl": verify_ssl, u"name": source_name}
)
data = {
u"source": sources,
# Default packages.
u"packages": {},
u"dev-packages": {},
}
# Default requires.
required_python = python
if not python:
if self.virtualenv_location:
required_python = self.which("python", self.virtualenv_location)
else:
required_python = self.which("python")
version = python_version(required_python) or PIPENV_DEFAULT_PYTHON_VERSION
if version and len(version) >= 3:
data[u"requires"] = {"python_version": version[: len("2.7")]}
self.write_toml(data)
|
[
"def",
"create_pipfile",
"(",
"self",
",",
"python",
"=",
"None",
")",
":",
"from",
".",
"vendor",
".",
"pip_shims",
".",
"shims",
"import",
"(",
"ConfigOptionParser",
",",
"make_option_group",
",",
"index_group",
")",
"config_parser",
"=",
"ConfigOptionParser",
"(",
"name",
"=",
"self",
".",
"name",
")",
"config_parser",
".",
"add_option_group",
"(",
"make_option_group",
"(",
"index_group",
",",
"config_parser",
")",
")",
"install",
"=",
"config_parser",
".",
"option_groups",
"[",
"0",
"]",
"indexes",
"=",
"(",
"\" \"",
".",
"join",
"(",
"install",
".",
"get_option",
"(",
"\"--extra-index-url\"",
")",
".",
"default",
")",
".",
"lstrip",
"(",
"\"\\n\"",
")",
".",
"split",
"(",
"\"\\n\"",
")",
")",
"sources",
"=",
"[",
"DEFAULT_SOURCE",
",",
"]",
"for",
"i",
",",
"index",
"in",
"enumerate",
"(",
"indexes",
")",
":",
"if",
"not",
"index",
":",
"continue",
"source_name",
"=",
"\"pip_index_{}\"",
".",
"format",
"(",
"i",
")",
"verify_ssl",
"=",
"index",
".",
"startswith",
"(",
"\"https\"",
")",
"sources",
".",
"append",
"(",
"{",
"u\"url\"",
":",
"index",
",",
"u\"verify_ssl\"",
":",
"verify_ssl",
",",
"u\"name\"",
":",
"source_name",
"}",
")",
"data",
"=",
"{",
"u\"source\"",
":",
"sources",
",",
"# Default packages.",
"u\"packages\"",
":",
"{",
"}",
",",
"u\"dev-packages\"",
":",
"{",
"}",
",",
"}",
"# Default requires.",
"required_python",
"=",
"python",
"if",
"not",
"python",
":",
"if",
"self",
".",
"virtualenv_location",
":",
"required_python",
"=",
"self",
".",
"which",
"(",
"\"python\"",
",",
"self",
".",
"virtualenv_location",
")",
"else",
":",
"required_python",
"=",
"self",
".",
"which",
"(",
"\"python\"",
")",
"version",
"=",
"python_version",
"(",
"required_python",
")",
"or",
"PIPENV_DEFAULT_PYTHON_VERSION",
"if",
"version",
"and",
"len",
"(",
"version",
")",
">=",
"3",
":",
"data",
"[",
"u\"requires\"",
"]",
"=",
"{",
"\"python_version\"",
":",
"version",
"[",
":",
"len",
"(",
"\"2.7\"",
")",
"]",
"}",
"self",
".",
"write_toml",
"(",
"data",
")"
] |
Creates the Pipfile, filled with juicy defaults.
|
[
"Creates",
"the",
"Pipfile",
"filled",
"with",
"juicy",
"defaults",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L674-L715
|
train
|
pypa/pipenv
|
pipenv/project.py
|
Project.write_toml
|
def write_toml(self, data, path=None):
"""Writes the given data structure out as TOML."""
if path is None:
path = self.pipfile_location
data = convert_toml_outline_tables(data)
try:
formatted_data = tomlkit.dumps(data).rstrip()
except Exception:
document = tomlkit.document()
for section in ("packages", "dev-packages"):
document[section] = tomlkit.container.Table()
# Convert things to inline tables — fancy :)
for package in data.get(section, {}):
if hasattr(data[section][package], "keys"):
table = tomlkit.inline_table()
table.update(data[section][package])
document[section][package] = table
else:
document[section][package] = tomlkit.string(data[section][package])
formatted_data = tomlkit.dumps(document).rstrip()
if (
vistir.compat.Path(path).absolute()
== vistir.compat.Path(self.pipfile_location).absolute()
):
newlines = self._pipfile_newlines
else:
newlines = DEFAULT_NEWLINES
formatted_data = cleanup_toml(formatted_data)
with io.open(path, "w", newline=newlines) as f:
f.write(formatted_data)
# pipfile is mutated!
self.clear_pipfile_cache()
|
python
|
def write_toml(self, data, path=None):
"""Writes the given data structure out as TOML."""
if path is None:
path = self.pipfile_location
data = convert_toml_outline_tables(data)
try:
formatted_data = tomlkit.dumps(data).rstrip()
except Exception:
document = tomlkit.document()
for section in ("packages", "dev-packages"):
document[section] = tomlkit.container.Table()
# Convert things to inline tables — fancy :)
for package in data.get(section, {}):
if hasattr(data[section][package], "keys"):
table = tomlkit.inline_table()
table.update(data[section][package])
document[section][package] = table
else:
document[section][package] = tomlkit.string(data[section][package])
formatted_data = tomlkit.dumps(document).rstrip()
if (
vistir.compat.Path(path).absolute()
== vistir.compat.Path(self.pipfile_location).absolute()
):
newlines = self._pipfile_newlines
else:
newlines = DEFAULT_NEWLINES
formatted_data = cleanup_toml(formatted_data)
with io.open(path, "w", newline=newlines) as f:
f.write(formatted_data)
# pipfile is mutated!
self.clear_pipfile_cache()
|
[
"def",
"write_toml",
"(",
"self",
",",
"data",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"self",
".",
"pipfile_location",
"data",
"=",
"convert_toml_outline_tables",
"(",
"data",
")",
"try",
":",
"formatted_data",
"=",
"tomlkit",
".",
"dumps",
"(",
"data",
")",
".",
"rstrip",
"(",
")",
"except",
"Exception",
":",
"document",
"=",
"tomlkit",
".",
"document",
"(",
")",
"for",
"section",
"in",
"(",
"\"packages\"",
",",
"\"dev-packages\"",
")",
":",
"document",
"[",
"section",
"]",
"=",
"tomlkit",
".",
"container",
".",
"Table",
"(",
")",
"# Convert things to inline tables — fancy :)",
"for",
"package",
"in",
"data",
".",
"get",
"(",
"section",
",",
"{",
"}",
")",
":",
"if",
"hasattr",
"(",
"data",
"[",
"section",
"]",
"[",
"package",
"]",
",",
"\"keys\"",
")",
":",
"table",
"=",
"tomlkit",
".",
"inline_table",
"(",
")",
"table",
".",
"update",
"(",
"data",
"[",
"section",
"]",
"[",
"package",
"]",
")",
"document",
"[",
"section",
"]",
"[",
"package",
"]",
"=",
"table",
"else",
":",
"document",
"[",
"section",
"]",
"[",
"package",
"]",
"=",
"tomlkit",
".",
"string",
"(",
"data",
"[",
"section",
"]",
"[",
"package",
"]",
")",
"formatted_data",
"=",
"tomlkit",
".",
"dumps",
"(",
"document",
")",
".",
"rstrip",
"(",
")",
"if",
"(",
"vistir",
".",
"compat",
".",
"Path",
"(",
"path",
")",
".",
"absolute",
"(",
")",
"==",
"vistir",
".",
"compat",
".",
"Path",
"(",
"self",
".",
"pipfile_location",
")",
".",
"absolute",
"(",
")",
")",
":",
"newlines",
"=",
"self",
".",
"_pipfile_newlines",
"else",
":",
"newlines",
"=",
"DEFAULT_NEWLINES",
"formatted_data",
"=",
"cleanup_toml",
"(",
"formatted_data",
")",
"with",
"io",
".",
"open",
"(",
"path",
",",
"\"w\"",
",",
"newline",
"=",
"newlines",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"formatted_data",
")",
"# pipfile is mutated!",
"self",
".",
"clear_pipfile_cache",
"(",
")"
] |
Writes the given data structure out as TOML.
|
[
"Writes",
"the",
"given",
"data",
"structure",
"out",
"as",
"TOML",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L783-L815
|
train
|
pypa/pipenv
|
pipenv/project.py
|
Project.write_lockfile
|
def write_lockfile(self, content):
"""Write out the lockfile.
"""
s = self._lockfile_encoder.encode(content)
open_kwargs = {"newline": self._lockfile_newlines, "encoding": "utf-8"}
with vistir.contextmanagers.atomic_open_for_write(
self.lockfile_location, **open_kwargs
) as f:
f.write(s)
# Write newline at end of document. GH-319.
# Only need '\n' here; the file object handles the rest.
if not s.endswith(u"\n"):
f.write(u"\n")
|
python
|
def write_lockfile(self, content):
"""Write out the lockfile.
"""
s = self._lockfile_encoder.encode(content)
open_kwargs = {"newline": self._lockfile_newlines, "encoding": "utf-8"}
with vistir.contextmanagers.atomic_open_for_write(
self.lockfile_location, **open_kwargs
) as f:
f.write(s)
# Write newline at end of document. GH-319.
# Only need '\n' here; the file object handles the rest.
if not s.endswith(u"\n"):
f.write(u"\n")
|
[
"def",
"write_lockfile",
"(",
"self",
",",
"content",
")",
":",
"s",
"=",
"self",
".",
"_lockfile_encoder",
".",
"encode",
"(",
"content",
")",
"open_kwargs",
"=",
"{",
"\"newline\"",
":",
"self",
".",
"_lockfile_newlines",
",",
"\"encoding\"",
":",
"\"utf-8\"",
"}",
"with",
"vistir",
".",
"contextmanagers",
".",
"atomic_open_for_write",
"(",
"self",
".",
"lockfile_location",
",",
"*",
"*",
"open_kwargs",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"s",
")",
"# Write newline at end of document. GH-319.",
"# Only need '\\n' here; the file object handles the rest.",
"if",
"not",
"s",
".",
"endswith",
"(",
"u\"\\n\"",
")",
":",
"f",
".",
"write",
"(",
"u\"\\n\"",
")"
] |
Write out the lockfile.
|
[
"Write",
"out",
"the",
"lockfile",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L817-L829
|
train
|
pypa/pipenv
|
pipenv/project.py
|
Project.find_source
|
def find_source(self, source):
"""
Given a source, find it.
source can be a url or an index name.
"""
if not is_valid_url(source):
try:
source = self.get_source(name=source)
except SourceNotFound:
source = self.get_source(url=source)
else:
source = self.get_source(url=source)
return source
|
python
|
def find_source(self, source):
"""
Given a source, find it.
source can be a url or an index name.
"""
if not is_valid_url(source):
try:
source = self.get_source(name=source)
except SourceNotFound:
source = self.get_source(url=source)
else:
source = self.get_source(url=source)
return source
|
[
"def",
"find_source",
"(",
"self",
",",
"source",
")",
":",
"if",
"not",
"is_valid_url",
"(",
"source",
")",
":",
"try",
":",
"source",
"=",
"self",
".",
"get_source",
"(",
"name",
"=",
"source",
")",
"except",
"SourceNotFound",
":",
"source",
"=",
"self",
".",
"get_source",
"(",
"url",
"=",
"source",
")",
"else",
":",
"source",
"=",
"self",
".",
"get_source",
"(",
"url",
"=",
"source",
")",
"return",
"source"
] |
Given a source, find it.
source can be a url or an index name.
|
[
"Given",
"a",
"source",
"find",
"it",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L854-L867
|
train
|
pypa/pipenv
|
pipenv/project.py
|
Project.get_package_name_in_pipfile
|
def get_package_name_in_pipfile(self, package_name, dev=False):
"""Get the equivalent package name in pipfile"""
key = "dev-packages" if dev else "packages"
section = self.parsed_pipfile.get(key, {})
package_name = pep423_name(package_name)
for name in section.keys():
if pep423_name(name) == package_name:
return name
return None
|
python
|
def get_package_name_in_pipfile(self, package_name, dev=False):
"""Get the equivalent package name in pipfile"""
key = "dev-packages" if dev else "packages"
section = self.parsed_pipfile.get(key, {})
package_name = pep423_name(package_name)
for name in section.keys():
if pep423_name(name) == package_name:
return name
return None
|
[
"def",
"get_package_name_in_pipfile",
"(",
"self",
",",
"package_name",
",",
"dev",
"=",
"False",
")",
":",
"key",
"=",
"\"dev-packages\"",
"if",
"dev",
"else",
"\"packages\"",
"section",
"=",
"self",
".",
"parsed_pipfile",
".",
"get",
"(",
"key",
",",
"{",
"}",
")",
"package_name",
"=",
"pep423_name",
"(",
"package_name",
")",
"for",
"name",
"in",
"section",
".",
"keys",
"(",
")",
":",
"if",
"pep423_name",
"(",
"name",
")",
"==",
"package_name",
":",
"return",
"name",
"return",
"None"
] |
Get the equivalent package name in pipfile
|
[
"Get",
"the",
"equivalent",
"package",
"name",
"in",
"pipfile"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L898-L906
|
train
|
pypa/pipenv
|
pipenv/project.py
|
Project.add_index_to_pipfile
|
def add_index_to_pipfile(self, index, verify_ssl=True):
"""Adds a given index to the Pipfile."""
# Read and append Pipfile.
p = self.parsed_pipfile
try:
self.get_source(url=index)
except SourceNotFound:
source = {"url": index, "verify_ssl": verify_ssl}
else:
return
source["name"] = self.src_name_from_url(index)
# Add the package to the group.
if "source" not in p:
p["source"] = [source]
else:
p["source"].append(source)
# Write Pipfile.
self.write_toml(p)
|
python
|
def add_index_to_pipfile(self, index, verify_ssl=True):
"""Adds a given index to the Pipfile."""
# Read and append Pipfile.
p = self.parsed_pipfile
try:
self.get_source(url=index)
except SourceNotFound:
source = {"url": index, "verify_ssl": verify_ssl}
else:
return
source["name"] = self.src_name_from_url(index)
# Add the package to the group.
if "source" not in p:
p["source"] = [source]
else:
p["source"].append(source)
# Write Pipfile.
self.write_toml(p)
|
[
"def",
"add_index_to_pipfile",
"(",
"self",
",",
"index",
",",
"verify_ssl",
"=",
"True",
")",
":",
"# Read and append Pipfile.",
"p",
"=",
"self",
".",
"parsed_pipfile",
"try",
":",
"self",
".",
"get_source",
"(",
"url",
"=",
"index",
")",
"except",
"SourceNotFound",
":",
"source",
"=",
"{",
"\"url\"",
":",
"index",
",",
"\"verify_ssl\"",
":",
"verify_ssl",
"}",
"else",
":",
"return",
"source",
"[",
"\"name\"",
"]",
"=",
"self",
".",
"src_name_from_url",
"(",
"index",
")",
"# Add the package to the group.",
"if",
"\"source\"",
"not",
"in",
"p",
":",
"p",
"[",
"\"source\"",
"]",
"=",
"[",
"source",
"]",
"else",
":",
"p",
"[",
"\"source\"",
"]",
".",
"append",
"(",
"source",
")",
"# Write Pipfile.",
"self",
".",
"write_toml",
"(",
"p",
")"
] |
Adds a given index to the Pipfile.
|
[
"Adds",
"a",
"given",
"index",
"to",
"the",
"Pipfile",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L969-L986
|
train
|
pypa/pipenv
|
pipenv/project.py
|
Project.ensure_proper_casing
|
def ensure_proper_casing(self):
"""Ensures proper casing of Pipfile packages"""
pfile = self.parsed_pipfile
casing_changed = self.proper_case_section(pfile.get("packages", {}))
casing_changed |= self.proper_case_section(pfile.get("dev-packages", {}))
return casing_changed
|
python
|
def ensure_proper_casing(self):
"""Ensures proper casing of Pipfile packages"""
pfile = self.parsed_pipfile
casing_changed = self.proper_case_section(pfile.get("packages", {}))
casing_changed |= self.proper_case_section(pfile.get("dev-packages", {}))
return casing_changed
|
[
"def",
"ensure_proper_casing",
"(",
"self",
")",
":",
"pfile",
"=",
"self",
".",
"parsed_pipfile",
"casing_changed",
"=",
"self",
".",
"proper_case_section",
"(",
"pfile",
".",
"get",
"(",
"\"packages\"",
",",
"{",
"}",
")",
")",
"casing_changed",
"|=",
"self",
".",
"proper_case_section",
"(",
"pfile",
".",
"get",
"(",
"\"dev-packages\"",
",",
"{",
"}",
")",
")",
"return",
"casing_changed"
] |
Ensures proper casing of Pipfile packages
|
[
"Ensures",
"proper",
"casing",
"of",
"Pipfile",
"packages"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L1028-L1033
|
train
|
pypa/pipenv
|
pipenv/project.py
|
Project.proper_case_section
|
def proper_case_section(self, section):
"""Verify proper casing is retrieved, when available, for each
dependency in the section.
"""
# Casing for section.
changed_values = False
unknown_names = [k for k in section.keys() if k not in set(self.proper_names)]
# Replace each package with proper casing.
for dep in unknown_names:
try:
# Get new casing for package name.
new_casing = proper_case(dep)
except IOError:
# Unable to normalize package name.
continue
if new_casing != dep:
changed_values = True
self.register_proper_name(new_casing)
# Replace old value with new value.
old_value = section[dep]
section[new_casing] = old_value
del section[dep]
# Return whether or not values have been changed.
return changed_values
|
python
|
def proper_case_section(self, section):
"""Verify proper casing is retrieved, when available, for each
dependency in the section.
"""
# Casing for section.
changed_values = False
unknown_names = [k for k in section.keys() if k not in set(self.proper_names)]
# Replace each package with proper casing.
for dep in unknown_names:
try:
# Get new casing for package name.
new_casing = proper_case(dep)
except IOError:
# Unable to normalize package name.
continue
if new_casing != dep:
changed_values = True
self.register_proper_name(new_casing)
# Replace old value with new value.
old_value = section[dep]
section[new_casing] = old_value
del section[dep]
# Return whether or not values have been changed.
return changed_values
|
[
"def",
"proper_case_section",
"(",
"self",
",",
"section",
")",
":",
"# Casing for section.",
"changed_values",
"=",
"False",
"unknown_names",
"=",
"[",
"k",
"for",
"k",
"in",
"section",
".",
"keys",
"(",
")",
"if",
"k",
"not",
"in",
"set",
"(",
"self",
".",
"proper_names",
")",
"]",
"# Replace each package with proper casing.",
"for",
"dep",
"in",
"unknown_names",
":",
"try",
":",
"# Get new casing for package name.",
"new_casing",
"=",
"proper_case",
"(",
"dep",
")",
"except",
"IOError",
":",
"# Unable to normalize package name.",
"continue",
"if",
"new_casing",
"!=",
"dep",
":",
"changed_values",
"=",
"True",
"self",
".",
"register_proper_name",
"(",
"new_casing",
")",
"# Replace old value with new value.",
"old_value",
"=",
"section",
"[",
"dep",
"]",
"section",
"[",
"new_casing",
"]",
"=",
"old_value",
"del",
"section",
"[",
"dep",
"]",
"# Return whether or not values have been changed.",
"return",
"changed_values"
] |
Verify proper casing is retrieved, when available, for each
dependency in the section.
|
[
"Verify",
"proper",
"casing",
"is",
"retrieved",
"when",
"available",
"for",
"each",
"dependency",
"in",
"the",
"section",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L1035-L1059
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/nativetypes.py
|
native_concat
|
def native_concat(nodes):
"""Return a native Python type from the list of compiled nodes. If the
result is a single node, its value is returned. Otherwise, the nodes are
concatenated as strings. If the result can be parsed with
:func:`ast.literal_eval`, the parsed value is returned. Otherwise, the
string is returned.
"""
head = list(islice(nodes, 2))
if not head:
return None
if len(head) == 1:
out = head[0]
else:
out = u''.join([text_type(v) for v in chain(head, nodes)])
try:
return literal_eval(out)
except (ValueError, SyntaxError, MemoryError):
return out
|
python
|
def native_concat(nodes):
"""Return a native Python type from the list of compiled nodes. If the
result is a single node, its value is returned. Otherwise, the nodes are
concatenated as strings. If the result can be parsed with
:func:`ast.literal_eval`, the parsed value is returned. Otherwise, the
string is returned.
"""
head = list(islice(nodes, 2))
if not head:
return None
if len(head) == 1:
out = head[0]
else:
out = u''.join([text_type(v) for v in chain(head, nodes)])
try:
return literal_eval(out)
except (ValueError, SyntaxError, MemoryError):
return out
|
[
"def",
"native_concat",
"(",
"nodes",
")",
":",
"head",
"=",
"list",
"(",
"islice",
"(",
"nodes",
",",
"2",
")",
")",
"if",
"not",
"head",
":",
"return",
"None",
"if",
"len",
"(",
"head",
")",
"==",
"1",
":",
"out",
"=",
"head",
"[",
"0",
"]",
"else",
":",
"out",
"=",
"u''",
".",
"join",
"(",
"[",
"text_type",
"(",
"v",
")",
"for",
"v",
"in",
"chain",
"(",
"head",
",",
"nodes",
")",
"]",
")",
"try",
":",
"return",
"literal_eval",
"(",
"out",
")",
"except",
"(",
"ValueError",
",",
"SyntaxError",
",",
"MemoryError",
")",
":",
"return",
"out"
] |
Return a native Python type from the list of compiled nodes. If the
result is a single node, its value is returned. Otherwise, the nodes are
concatenated as strings. If the result can be parsed with
:func:`ast.literal_eval`, the parsed value is returned. Otherwise, the
string is returned.
|
[
"Return",
"a",
"native",
"Python",
"type",
"from",
"the",
"list",
"of",
"compiled",
"nodes",
".",
"If",
"the",
"result",
"is",
"a",
"single",
"node",
"its",
"value",
"is",
"returned",
".",
"Otherwise",
"the",
"nodes",
"are",
"concatenated",
"as",
"strings",
".",
"If",
"the",
"result",
"can",
"be",
"parsed",
"with",
":",
"func",
":",
"ast",
".",
"literal_eval",
"the",
"parsed",
"value",
"is",
"returned",
".",
"Otherwise",
"the",
"string",
"is",
"returned",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/nativetypes.py#L11-L31
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/nativetypes.py
|
NativeCodeGenerator.visit_Output
|
def visit_Output(self, node, frame):
"""Same as :meth:`CodeGenerator.visit_Output`, but do not call
``to_string`` on output nodes in generated code.
"""
if self.has_known_extends and frame.require_output_check:
return
finalize = self.environment.finalize
finalize_context = getattr(finalize, 'contextfunction', False)
finalize_eval = getattr(finalize, 'evalcontextfunction', False)
finalize_env = getattr(finalize, 'environmentfunction', False)
if finalize is not None:
if finalize_context or finalize_eval:
const_finalize = None
elif finalize_env:
def const_finalize(x):
return finalize(self.environment, x)
else:
const_finalize = finalize
else:
def const_finalize(x):
return x
# If we are inside a frame that requires output checking, we do so.
outdent_later = False
if frame.require_output_check:
self.writeline('if parent_template is None:')
self.indent()
outdent_later = True
# Try to evaluate as many chunks as possible into a static string at
# compile time.
body = []
for child in node.nodes:
try:
if const_finalize is None:
raise nodes.Impossible()
const = child.as_const(frame.eval_ctx)
if not has_safe_repr(const):
raise nodes.Impossible()
except nodes.Impossible:
body.append(child)
continue
# the frame can't be volatile here, because otherwise the as_const
# function would raise an Impossible exception at that point
try:
if frame.eval_ctx.autoescape:
if hasattr(const, '__html__'):
const = const.__html__()
else:
const = escape(const)
const = const_finalize(const)
except Exception:
# if something goes wrong here we evaluate the node at runtime
# for easier debugging
body.append(child)
continue
if body and isinstance(body[-1], list):
body[-1].append(const)
else:
body.append([const])
# if we have less than 3 nodes or a buffer we yield or extend/append
if len(body) < 3 or frame.buffer is not None:
if frame.buffer is not None:
# for one item we append, for more we extend
if len(body) == 1:
self.writeline('%s.append(' % frame.buffer)
else:
self.writeline('%s.extend((' % frame.buffer)
self.indent()
for item in body:
if isinstance(item, list):
val = repr(native_concat(item))
if frame.buffer is None:
self.writeline('yield ' + val)
else:
self.writeline(val + ',')
else:
if frame.buffer is None:
self.writeline('yield ', item)
else:
self.newline(item)
close = 0
if finalize is not None:
self.write('environment.finalize(')
if finalize_context:
self.write('context, ')
close += 1
self.visit(item, frame)
if close > 0:
self.write(')' * close)
if frame.buffer is not None:
self.write(',')
if frame.buffer is not None:
# close the open parentheses
self.outdent()
self.writeline(len(body) == 1 and ')' or '))')
# otherwise we create a format string as this is faster in that case
else:
format = []
arguments = []
for item in body:
if isinstance(item, list):
format.append(native_concat(item).replace('%', '%%'))
else:
format.append('%s')
arguments.append(item)
self.writeline('yield ')
self.write(repr(concat(format)) + ' % (')
self.indent()
for argument in arguments:
self.newline(argument)
close = 0
if finalize is not None:
self.write('environment.finalize(')
if finalize_context:
self.write('context, ')
elif finalize_eval:
self.write('context.eval_ctx, ')
elif finalize_env:
self.write('environment, ')
close += 1
self.visit(argument, frame)
self.write(')' * close + ', ')
self.outdent()
self.writeline(')')
if outdent_later:
self.outdent()
|
python
|
def visit_Output(self, node, frame):
"""Same as :meth:`CodeGenerator.visit_Output`, but do not call
``to_string`` on output nodes in generated code.
"""
if self.has_known_extends and frame.require_output_check:
return
finalize = self.environment.finalize
finalize_context = getattr(finalize, 'contextfunction', False)
finalize_eval = getattr(finalize, 'evalcontextfunction', False)
finalize_env = getattr(finalize, 'environmentfunction', False)
if finalize is not None:
if finalize_context or finalize_eval:
const_finalize = None
elif finalize_env:
def const_finalize(x):
return finalize(self.environment, x)
else:
const_finalize = finalize
else:
def const_finalize(x):
return x
# If we are inside a frame that requires output checking, we do so.
outdent_later = False
if frame.require_output_check:
self.writeline('if parent_template is None:')
self.indent()
outdent_later = True
# Try to evaluate as many chunks as possible into a static string at
# compile time.
body = []
for child in node.nodes:
try:
if const_finalize is None:
raise nodes.Impossible()
const = child.as_const(frame.eval_ctx)
if not has_safe_repr(const):
raise nodes.Impossible()
except nodes.Impossible:
body.append(child)
continue
# the frame can't be volatile here, because otherwise the as_const
# function would raise an Impossible exception at that point
try:
if frame.eval_ctx.autoescape:
if hasattr(const, '__html__'):
const = const.__html__()
else:
const = escape(const)
const = const_finalize(const)
except Exception:
# if something goes wrong here we evaluate the node at runtime
# for easier debugging
body.append(child)
continue
if body and isinstance(body[-1], list):
body[-1].append(const)
else:
body.append([const])
# if we have less than 3 nodes or a buffer we yield or extend/append
if len(body) < 3 or frame.buffer is not None:
if frame.buffer is not None:
# for one item we append, for more we extend
if len(body) == 1:
self.writeline('%s.append(' % frame.buffer)
else:
self.writeline('%s.extend((' % frame.buffer)
self.indent()
for item in body:
if isinstance(item, list):
val = repr(native_concat(item))
if frame.buffer is None:
self.writeline('yield ' + val)
else:
self.writeline(val + ',')
else:
if frame.buffer is None:
self.writeline('yield ', item)
else:
self.newline(item)
close = 0
if finalize is not None:
self.write('environment.finalize(')
if finalize_context:
self.write('context, ')
close += 1
self.visit(item, frame)
if close > 0:
self.write(')' * close)
if frame.buffer is not None:
self.write(',')
if frame.buffer is not None:
# close the open parentheses
self.outdent()
self.writeline(len(body) == 1 and ')' or '))')
# otherwise we create a format string as this is faster in that case
else:
format = []
arguments = []
for item in body:
if isinstance(item, list):
format.append(native_concat(item).replace('%', '%%'))
else:
format.append('%s')
arguments.append(item)
self.writeline('yield ')
self.write(repr(concat(format)) + ' % (')
self.indent()
for argument in arguments:
self.newline(argument)
close = 0
if finalize is not None:
self.write('environment.finalize(')
if finalize_context:
self.write('context, ')
elif finalize_eval:
self.write('context.eval_ctx, ')
elif finalize_env:
self.write('environment, ')
close += 1
self.visit(argument, frame)
self.write(')' * close + ', ')
self.outdent()
self.writeline(')')
if outdent_later:
self.outdent()
|
[
"def",
"visit_Output",
"(",
"self",
",",
"node",
",",
"frame",
")",
":",
"if",
"self",
".",
"has_known_extends",
"and",
"frame",
".",
"require_output_check",
":",
"return",
"finalize",
"=",
"self",
".",
"environment",
".",
"finalize",
"finalize_context",
"=",
"getattr",
"(",
"finalize",
",",
"'contextfunction'",
",",
"False",
")",
"finalize_eval",
"=",
"getattr",
"(",
"finalize",
",",
"'evalcontextfunction'",
",",
"False",
")",
"finalize_env",
"=",
"getattr",
"(",
"finalize",
",",
"'environmentfunction'",
",",
"False",
")",
"if",
"finalize",
"is",
"not",
"None",
":",
"if",
"finalize_context",
"or",
"finalize_eval",
":",
"const_finalize",
"=",
"None",
"elif",
"finalize_env",
":",
"def",
"const_finalize",
"(",
"x",
")",
":",
"return",
"finalize",
"(",
"self",
".",
"environment",
",",
"x",
")",
"else",
":",
"const_finalize",
"=",
"finalize",
"else",
":",
"def",
"const_finalize",
"(",
"x",
")",
":",
"return",
"x",
"# If we are inside a frame that requires output checking, we do so.",
"outdent_later",
"=",
"False",
"if",
"frame",
".",
"require_output_check",
":",
"self",
".",
"writeline",
"(",
"'if parent_template is None:'",
")",
"self",
".",
"indent",
"(",
")",
"outdent_later",
"=",
"True",
"# Try to evaluate as many chunks as possible into a static string at",
"# compile time.",
"body",
"=",
"[",
"]",
"for",
"child",
"in",
"node",
".",
"nodes",
":",
"try",
":",
"if",
"const_finalize",
"is",
"None",
":",
"raise",
"nodes",
".",
"Impossible",
"(",
")",
"const",
"=",
"child",
".",
"as_const",
"(",
"frame",
".",
"eval_ctx",
")",
"if",
"not",
"has_safe_repr",
"(",
"const",
")",
":",
"raise",
"nodes",
".",
"Impossible",
"(",
")",
"except",
"nodes",
".",
"Impossible",
":",
"body",
".",
"append",
"(",
"child",
")",
"continue",
"# the frame can't be volatile here, because otherwise the as_const",
"# function would raise an Impossible exception at that point",
"try",
":",
"if",
"frame",
".",
"eval_ctx",
".",
"autoescape",
":",
"if",
"hasattr",
"(",
"const",
",",
"'__html__'",
")",
":",
"const",
"=",
"const",
".",
"__html__",
"(",
")",
"else",
":",
"const",
"=",
"escape",
"(",
"const",
")",
"const",
"=",
"const_finalize",
"(",
"const",
")",
"except",
"Exception",
":",
"# if something goes wrong here we evaluate the node at runtime",
"# for easier debugging",
"body",
".",
"append",
"(",
"child",
")",
"continue",
"if",
"body",
"and",
"isinstance",
"(",
"body",
"[",
"-",
"1",
"]",
",",
"list",
")",
":",
"body",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"const",
")",
"else",
":",
"body",
".",
"append",
"(",
"[",
"const",
"]",
")",
"# if we have less than 3 nodes or a buffer we yield or extend/append",
"if",
"len",
"(",
"body",
")",
"<",
"3",
"or",
"frame",
".",
"buffer",
"is",
"not",
"None",
":",
"if",
"frame",
".",
"buffer",
"is",
"not",
"None",
":",
"# for one item we append, for more we extend",
"if",
"len",
"(",
"body",
")",
"==",
"1",
":",
"self",
".",
"writeline",
"(",
"'%s.append('",
"%",
"frame",
".",
"buffer",
")",
"else",
":",
"self",
".",
"writeline",
"(",
"'%s.extend(('",
"%",
"frame",
".",
"buffer",
")",
"self",
".",
"indent",
"(",
")",
"for",
"item",
"in",
"body",
":",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"val",
"=",
"repr",
"(",
"native_concat",
"(",
"item",
")",
")",
"if",
"frame",
".",
"buffer",
"is",
"None",
":",
"self",
".",
"writeline",
"(",
"'yield '",
"+",
"val",
")",
"else",
":",
"self",
".",
"writeline",
"(",
"val",
"+",
"','",
")",
"else",
":",
"if",
"frame",
".",
"buffer",
"is",
"None",
":",
"self",
".",
"writeline",
"(",
"'yield '",
",",
"item",
")",
"else",
":",
"self",
".",
"newline",
"(",
"item",
")",
"close",
"=",
"0",
"if",
"finalize",
"is",
"not",
"None",
":",
"self",
".",
"write",
"(",
"'environment.finalize('",
")",
"if",
"finalize_context",
":",
"self",
".",
"write",
"(",
"'context, '",
")",
"close",
"+=",
"1",
"self",
".",
"visit",
"(",
"item",
",",
"frame",
")",
"if",
"close",
">",
"0",
":",
"self",
".",
"write",
"(",
"')'",
"*",
"close",
")",
"if",
"frame",
".",
"buffer",
"is",
"not",
"None",
":",
"self",
".",
"write",
"(",
"','",
")",
"if",
"frame",
".",
"buffer",
"is",
"not",
"None",
":",
"# close the open parentheses",
"self",
".",
"outdent",
"(",
")",
"self",
".",
"writeline",
"(",
"len",
"(",
"body",
")",
"==",
"1",
"and",
"')'",
"or",
"'))'",
")",
"# otherwise we create a format string as this is faster in that case",
"else",
":",
"format",
"=",
"[",
"]",
"arguments",
"=",
"[",
"]",
"for",
"item",
"in",
"body",
":",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"format",
".",
"append",
"(",
"native_concat",
"(",
"item",
")",
".",
"replace",
"(",
"'%'",
",",
"'%%'",
")",
")",
"else",
":",
"format",
".",
"append",
"(",
"'%s'",
")",
"arguments",
".",
"append",
"(",
"item",
")",
"self",
".",
"writeline",
"(",
"'yield '",
")",
"self",
".",
"write",
"(",
"repr",
"(",
"concat",
"(",
"format",
")",
")",
"+",
"' % ('",
")",
"self",
".",
"indent",
"(",
")",
"for",
"argument",
"in",
"arguments",
":",
"self",
".",
"newline",
"(",
"argument",
")",
"close",
"=",
"0",
"if",
"finalize",
"is",
"not",
"None",
":",
"self",
".",
"write",
"(",
"'environment.finalize('",
")",
"if",
"finalize_context",
":",
"self",
".",
"write",
"(",
"'context, '",
")",
"elif",
"finalize_eval",
":",
"self",
".",
"write",
"(",
"'context.eval_ctx, '",
")",
"elif",
"finalize_env",
":",
"self",
".",
"write",
"(",
"'environment, '",
")",
"close",
"+=",
"1",
"self",
".",
"visit",
"(",
"argument",
",",
"frame",
")",
"self",
".",
"write",
"(",
"')'",
"*",
"close",
"+",
"', '",
")",
"self",
".",
"outdent",
"(",
")",
"self",
".",
"writeline",
"(",
"')'",
")",
"if",
"outdent_later",
":",
"self",
".",
"outdent",
"(",
")"
] |
Same as :meth:`CodeGenerator.visit_Output`, but do not call
``to_string`` on output nodes in generated code.
|
[
"Same",
"as",
":",
"meth",
":",
"CodeGenerator",
".",
"visit_Output",
"but",
"do",
"not",
"call",
"to_string",
"on",
"output",
"nodes",
"in",
"generated",
"code",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/nativetypes.py#L39-L195
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.load
|
def load(self, *args, **kwargs):
"""
Clear all existing key:value items and import all key:value items from
<mapping>. If multiple values exist for the same key in <mapping>, they
are all be imported.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.load([(4,4), (4,44), (5,5)])
omd.allitems() == [(4,4), (4,44), (5,5)]
Returns: <self>.
"""
self.clear()
self.updateall(*args, **kwargs)
return self
|
python
|
def load(self, *args, **kwargs):
"""
Clear all existing key:value items and import all key:value items from
<mapping>. If multiple values exist for the same key in <mapping>, they
are all be imported.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.load([(4,4), (4,44), (5,5)])
omd.allitems() == [(4,4), (4,44), (5,5)]
Returns: <self>.
"""
self.clear()
self.updateall(*args, **kwargs)
return self
|
[
"def",
"load",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"clear",
"(",
")",
"self",
".",
"updateall",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self"
] |
Clear all existing key:value items and import all key:value items from
<mapping>. If multiple values exist for the same key in <mapping>, they
are all be imported.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.load([(4,4), (4,44), (5,5)])
omd.allitems() == [(4,4), (4,44), (5,5)]
Returns: <self>.
|
[
"Clear",
"all",
"existing",
"key",
":",
"value",
"items",
"and",
"import",
"all",
"key",
":",
"value",
"items",
"from",
"<mapping",
">",
".",
"If",
"multiple",
"values",
"exist",
"for",
"the",
"same",
"key",
"in",
"<mapping",
">",
"they",
"are",
"all",
"be",
"imported",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L156-L171
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.updateall
|
def updateall(self, *args, **kwargs):
"""
Update this dictionary with the items from <mapping>, replacing
existing key:value items with shared keys before adding new key:value
items.
Example:
omd = omdict([(1,1), (2,2)])
omd.updateall([(2,'two'), (1,'one'), (2,222), (1,111)])
omd.allitems() == [(1, 'one'), (2, 'two'), (2, 222), (1, 111)]
Returns: <self>.
"""
self._update_updateall(False, *args, **kwargs)
return self
|
python
|
def updateall(self, *args, **kwargs):
"""
Update this dictionary with the items from <mapping>, replacing
existing key:value items with shared keys before adding new key:value
items.
Example:
omd = omdict([(1,1), (2,2)])
omd.updateall([(2,'two'), (1,'one'), (2,222), (1,111)])
omd.allitems() == [(1, 'one'), (2, 'two'), (2, 222), (1, 111)]
Returns: <self>.
"""
self._update_updateall(False, *args, **kwargs)
return self
|
[
"def",
"updateall",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_update_updateall",
"(",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self"
] |
Update this dictionary with the items from <mapping>, replacing
existing key:value items with shared keys before adding new key:value
items.
Example:
omd = omdict([(1,1), (2,2)])
omd.updateall([(2,'two'), (1,'one'), (2,222), (1,111)])
omd.allitems() == [(1, 'one'), (2, 'two'), (2, 222), (1, 111)]
Returns: <self>.
|
[
"Update",
"this",
"dictionary",
"with",
"the",
"items",
"from",
"<mapping",
">",
"replacing",
"existing",
"key",
":",
"value",
"items",
"with",
"shared",
"keys",
"before",
"adding",
"new",
"key",
":",
"value",
"items",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L201-L215
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict._bin_update_items
|
def _bin_update_items(self, items, replace_at_most_one,
replacements, leftovers):
"""
<replacements and <leftovers> are modified directly, ala pass by
reference.
"""
for key, value in items:
# If there are existing items with key <key> that have yet to be
# marked for replacement, mark that item's value to be replaced by
# <value> by appending it to <replacements>.
if key in self and key not in replacements:
replacements[key] = [value]
elif (key in self and not replace_at_most_one and
len(replacements[key]) < len(self.values(key))):
replacements[key].append(value)
else:
if replace_at_most_one:
replacements[key] = [value]
else:
leftovers.append((key, value))
|
python
|
def _bin_update_items(self, items, replace_at_most_one,
replacements, leftovers):
"""
<replacements and <leftovers> are modified directly, ala pass by
reference.
"""
for key, value in items:
# If there are existing items with key <key> that have yet to be
# marked for replacement, mark that item's value to be replaced by
# <value> by appending it to <replacements>.
if key in self and key not in replacements:
replacements[key] = [value]
elif (key in self and not replace_at_most_one and
len(replacements[key]) < len(self.values(key))):
replacements[key].append(value)
else:
if replace_at_most_one:
replacements[key] = [value]
else:
leftovers.append((key, value))
|
[
"def",
"_bin_update_items",
"(",
"self",
",",
"items",
",",
"replace_at_most_one",
",",
"replacements",
",",
"leftovers",
")",
":",
"for",
"key",
",",
"value",
"in",
"items",
":",
"# If there are existing items with key <key> that have yet to be",
"# marked for replacement, mark that item's value to be replaced by",
"# <value> by appending it to <replacements>.",
"if",
"key",
"in",
"self",
"and",
"key",
"not",
"in",
"replacements",
":",
"replacements",
"[",
"key",
"]",
"=",
"[",
"value",
"]",
"elif",
"(",
"key",
"in",
"self",
"and",
"not",
"replace_at_most_one",
"and",
"len",
"(",
"replacements",
"[",
"key",
"]",
")",
"<",
"len",
"(",
"self",
".",
"values",
"(",
"key",
")",
")",
")",
":",
"replacements",
"[",
"key",
"]",
".",
"append",
"(",
"value",
")",
"else",
":",
"if",
"replace_at_most_one",
":",
"replacements",
"[",
"key",
"]",
"=",
"[",
"value",
"]",
"else",
":",
"leftovers",
".",
"append",
"(",
"(",
"key",
",",
"value",
")",
")"
] |
<replacements and <leftovers> are modified directly, ala pass by
reference.
|
[
"<replacements",
"and",
"<leftovers",
">",
"are",
"modified",
"directly",
"ala",
"pass",
"by",
"reference",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L235-L254
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.getlist
|
def getlist(self, key, default=[]):
"""
Returns: The list of values for <key> if <key> is in the dictionary,
else <default>. If <default> is not provided, an empty list is
returned.
"""
if key in self:
return [node.value for node in self._map[key]]
return default
|
python
|
def getlist(self, key, default=[]):
"""
Returns: The list of values for <key> if <key> is in the dictionary,
else <default>. If <default> is not provided, an empty list is
returned.
"""
if key in self:
return [node.value for node in self._map[key]]
return default
|
[
"def",
"getlist",
"(",
"self",
",",
"key",
",",
"default",
"=",
"[",
"]",
")",
":",
"if",
"key",
"in",
"self",
":",
"return",
"[",
"node",
".",
"value",
"for",
"node",
"in",
"self",
".",
"_map",
"[",
"key",
"]",
"]",
"return",
"default"
] |
Returns: The list of values for <key> if <key> is in the dictionary,
else <default>. If <default> is not provided, an empty list is
returned.
|
[
"Returns",
":",
"The",
"list",
"of",
"values",
"for",
"<key",
">",
"if",
"<key",
">",
"is",
"in",
"the",
"dictionary",
"else",
"<default",
">",
".",
"If",
"<default",
">",
"is",
"not",
"provided",
"an",
"empty",
"list",
"is",
"returned",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L274-L282
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.setdefaultlist
|
def setdefaultlist(self, key, defaultlist=[None]):
"""
Similar to setdefault() except <defaultlist> is a list of values to set
for <key>. If <key> already exists, its existing list of values is
returned.
If <key> isn't a key and <defaultlist> is an empty list, [], no values
are added for <key> and <key> will not be added as a key.
Returns: List of <key>'s values if <key> exists in the dictionary,
otherwise <default>.
"""
if key in self:
return self.getlist(key)
self.addlist(key, defaultlist)
return defaultlist
|
python
|
def setdefaultlist(self, key, defaultlist=[None]):
"""
Similar to setdefault() except <defaultlist> is a list of values to set
for <key>. If <key> already exists, its existing list of values is
returned.
If <key> isn't a key and <defaultlist> is an empty list, [], no values
are added for <key> and <key> will not be added as a key.
Returns: List of <key>'s values if <key> exists in the dictionary,
otherwise <default>.
"""
if key in self:
return self.getlist(key)
self.addlist(key, defaultlist)
return defaultlist
|
[
"def",
"setdefaultlist",
"(",
"self",
",",
"key",
",",
"defaultlist",
"=",
"[",
"None",
"]",
")",
":",
"if",
"key",
"in",
"self",
":",
"return",
"self",
".",
"getlist",
"(",
"key",
")",
"self",
".",
"addlist",
"(",
"key",
",",
"defaultlist",
")",
"return",
"defaultlist"
] |
Similar to setdefault() except <defaultlist> is a list of values to set
for <key>. If <key> already exists, its existing list of values is
returned.
If <key> isn't a key and <defaultlist> is an empty list, [], no values
are added for <key> and <key> will not be added as a key.
Returns: List of <key>'s values if <key> exists in the dictionary,
otherwise <default>.
|
[
"Similar",
"to",
"setdefault",
"()",
"except",
"<defaultlist",
">",
"is",
"a",
"list",
"of",
"values",
"to",
"set",
"for",
"<key",
">",
".",
"If",
"<key",
">",
"already",
"exists",
"its",
"existing",
"list",
"of",
"values",
"is",
"returned",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L290-L305
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.addlist
|
def addlist(self, key, valuelist=[]):
"""
Add the values in <valuelist> to the list of values for <key>. If <key>
is not in the dictionary, the values in <valuelist> become the values
for <key>.
Example:
omd = omdict([(1,1)])
omd.addlist(1, [11, 111])
omd.allitems() == [(1, 1), (1, 11), (1, 111)]
omd.addlist(2, [2])
omd.allitems() == [(1, 1), (1, 11), (1, 111), (2, 2)]
Returns: <self>.
"""
for value in valuelist:
self.add(key, value)
return self
|
python
|
def addlist(self, key, valuelist=[]):
"""
Add the values in <valuelist> to the list of values for <key>. If <key>
is not in the dictionary, the values in <valuelist> become the values
for <key>.
Example:
omd = omdict([(1,1)])
omd.addlist(1, [11, 111])
omd.allitems() == [(1, 1), (1, 11), (1, 111)]
omd.addlist(2, [2])
omd.allitems() == [(1, 1), (1, 11), (1, 111), (2, 2)]
Returns: <self>.
"""
for value in valuelist:
self.add(key, value)
return self
|
[
"def",
"addlist",
"(",
"self",
",",
"key",
",",
"valuelist",
"=",
"[",
"]",
")",
":",
"for",
"value",
"in",
"valuelist",
":",
"self",
".",
"add",
"(",
"key",
",",
"value",
")",
"return",
"self"
] |
Add the values in <valuelist> to the list of values for <key>. If <key>
is not in the dictionary, the values in <valuelist> become the values
for <key>.
Example:
omd = omdict([(1,1)])
omd.addlist(1, [11, 111])
omd.allitems() == [(1, 1), (1, 11), (1, 111)]
omd.addlist(2, [2])
omd.allitems() == [(1, 1), (1, 11), (1, 111), (2, 2)]
Returns: <self>.
|
[
"Add",
"the",
"values",
"in",
"<valuelist",
">",
"to",
"the",
"list",
"of",
"values",
"for",
"<key",
">",
".",
"If",
"<key",
">",
"is",
"not",
"in",
"the",
"dictionary",
"the",
"values",
"in",
"<valuelist",
">",
"become",
"the",
"values",
"for",
"<key",
">",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L325-L342
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.setlist
|
def setlist(self, key, values):
"""
Sets <key>'s list of values to <values>. Existing items with key <key>
are first replaced with new values from <values>. Any remaining old
items that haven't been replaced with new values are deleted, and any
new values from <values> that don't have corresponding items with <key>
to replace are appended to the end of the list of all items.
If values is an empty list, [], <key> is deleted, equivalent in action
to del self[<key>].
Example:
omd = omdict([(1,1), (2,2)])
omd.setlist(1, [11, 111])
omd.allitems() == [(1,11), (2,2), (1,111)]
omd = omdict([(1,1), (1,11), (2,2), (1,111)])
omd.setlist(1, [None])
omd.allitems() == [(1,None), (2,2)]
omd = omdict([(1,1), (1,11), (2,2), (1,111)])
omd.setlist(1, [])
omd.allitems() == [(2,2)]
Returns: <self>.
"""
if not values and key in self:
self.pop(key)
else:
it = zip_longest(
list(self._map.get(key, [])), values, fillvalue=_absent)
for node, value in it:
if node is not _absent and value is not _absent:
node.value = value
elif node is _absent:
self.add(key, value)
elif value is _absent:
self._map[key].remove(node)
self._items.removenode(node)
return self
|
python
|
def setlist(self, key, values):
"""
Sets <key>'s list of values to <values>. Existing items with key <key>
are first replaced with new values from <values>. Any remaining old
items that haven't been replaced with new values are deleted, and any
new values from <values> that don't have corresponding items with <key>
to replace are appended to the end of the list of all items.
If values is an empty list, [], <key> is deleted, equivalent in action
to del self[<key>].
Example:
omd = omdict([(1,1), (2,2)])
omd.setlist(1, [11, 111])
omd.allitems() == [(1,11), (2,2), (1,111)]
omd = omdict([(1,1), (1,11), (2,2), (1,111)])
omd.setlist(1, [None])
omd.allitems() == [(1,None), (2,2)]
omd = omdict([(1,1), (1,11), (2,2), (1,111)])
omd.setlist(1, [])
omd.allitems() == [(2,2)]
Returns: <self>.
"""
if not values and key in self:
self.pop(key)
else:
it = zip_longest(
list(self._map.get(key, [])), values, fillvalue=_absent)
for node, value in it:
if node is not _absent and value is not _absent:
node.value = value
elif node is _absent:
self.add(key, value)
elif value is _absent:
self._map[key].remove(node)
self._items.removenode(node)
return self
|
[
"def",
"setlist",
"(",
"self",
",",
"key",
",",
"values",
")",
":",
"if",
"not",
"values",
"and",
"key",
"in",
"self",
":",
"self",
".",
"pop",
"(",
"key",
")",
"else",
":",
"it",
"=",
"zip_longest",
"(",
"list",
"(",
"self",
".",
"_map",
".",
"get",
"(",
"key",
",",
"[",
"]",
")",
")",
",",
"values",
",",
"fillvalue",
"=",
"_absent",
")",
"for",
"node",
",",
"value",
"in",
"it",
":",
"if",
"node",
"is",
"not",
"_absent",
"and",
"value",
"is",
"not",
"_absent",
":",
"node",
".",
"value",
"=",
"value",
"elif",
"node",
"is",
"_absent",
":",
"self",
".",
"add",
"(",
"key",
",",
"value",
")",
"elif",
"value",
"is",
"_absent",
":",
"self",
".",
"_map",
"[",
"key",
"]",
".",
"remove",
"(",
"node",
")",
"self",
".",
"_items",
".",
"removenode",
"(",
"node",
")",
"return",
"self"
] |
Sets <key>'s list of values to <values>. Existing items with key <key>
are first replaced with new values from <values>. Any remaining old
items that haven't been replaced with new values are deleted, and any
new values from <values> that don't have corresponding items with <key>
to replace are appended to the end of the list of all items.
If values is an empty list, [], <key> is deleted, equivalent in action
to del self[<key>].
Example:
omd = omdict([(1,1), (2,2)])
omd.setlist(1, [11, 111])
omd.allitems() == [(1,11), (2,2), (1,111)]
omd = omdict([(1,1), (1,11), (2,2), (1,111)])
omd.setlist(1, [None])
omd.allitems() == [(1,None), (2,2)]
omd = omdict([(1,1), (1,11), (2,2), (1,111)])
omd.setlist(1, [])
omd.allitems() == [(2,2)]
Returns: <self>.
|
[
"Sets",
"<key",
">",
"s",
"list",
"of",
"values",
"to",
"<values",
">",
".",
"Existing",
"items",
"with",
"key",
"<key",
">",
"are",
"first",
"replaced",
"with",
"new",
"values",
"from",
"<values",
">",
".",
"Any",
"remaining",
"old",
"items",
"that",
"haven",
"t",
"been",
"replaced",
"with",
"new",
"values",
"are",
"deleted",
"and",
"any",
"new",
"values",
"from",
"<values",
">",
"that",
"don",
"t",
"have",
"corresponding",
"items",
"with",
"<key",
">",
"to",
"replace",
"are",
"appended",
"to",
"the",
"end",
"of",
"the",
"list",
"of",
"all",
"items",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L353-L392
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.removevalues
|
def removevalues(self, key, values):
"""
Removes all <values> from the values of <key>. If <key> has no
remaining values after removevalues(), the key is popped.
Example:
omd = omdict([(1, 1), (1, 11), (1, 1), (1, 111)])
omd.removevalues(1, [1, 111])
omd.allitems() == [(1, 11)]
Returns: <self>.
"""
self.setlist(key, [v for v in self.getlist(key) if v not in values])
return self
|
python
|
def removevalues(self, key, values):
"""
Removes all <values> from the values of <key>. If <key> has no
remaining values after removevalues(), the key is popped.
Example:
omd = omdict([(1, 1), (1, 11), (1, 1), (1, 111)])
omd.removevalues(1, [1, 111])
omd.allitems() == [(1, 11)]
Returns: <self>.
"""
self.setlist(key, [v for v in self.getlist(key) if v not in values])
return self
|
[
"def",
"removevalues",
"(",
"self",
",",
"key",
",",
"values",
")",
":",
"self",
".",
"setlist",
"(",
"key",
",",
"[",
"v",
"for",
"v",
"in",
"self",
".",
"getlist",
"(",
"key",
")",
"if",
"v",
"not",
"in",
"values",
"]",
")",
"return",
"self"
] |
Removes all <values> from the values of <key>. If <key> has no
remaining values after removevalues(), the key is popped.
Example:
omd = omdict([(1, 1), (1, 11), (1, 1), (1, 111)])
omd.removevalues(1, [1, 111])
omd.allitems() == [(1, 11)]
Returns: <self>.
|
[
"Removes",
"all",
"<values",
">",
"from",
"the",
"values",
"of",
"<key",
">",
".",
"If",
"<key",
">",
"has",
"no",
"remaining",
"values",
"after",
"removevalues",
"()",
"the",
"key",
"is",
"popped",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L394-L407
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.poplist
|
def poplist(self, key, default=_absent):
"""
If <key> is in the dictionary, pop it and return its list of values. If
<key> is not in the dictionary, return <default>. KeyError is raised if
<default> is not provided and <key> is not in the dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.poplist(1) == [1, 11, 111]
omd.allitems() == [(2,2), (3,3)]
omd.poplist(2) == [2]
omd.allitems() == [(3,3)]
Raises: KeyError if <key> isn't in the dictionary and <default> isn't
provided.
Returns: List of <key>'s values.
"""
if key in self:
values = self.getlist(key)
del self._map[key]
for node, nodekey, nodevalue in self._items:
if nodekey == key:
self._items.removenode(node)
return values
elif key not in self._map and default is not _absent:
return default
raise KeyError(key)
|
python
|
def poplist(self, key, default=_absent):
"""
If <key> is in the dictionary, pop it and return its list of values. If
<key> is not in the dictionary, return <default>. KeyError is raised if
<default> is not provided and <key> is not in the dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.poplist(1) == [1, 11, 111]
omd.allitems() == [(2,2), (3,3)]
omd.poplist(2) == [2]
omd.allitems() == [(3,3)]
Raises: KeyError if <key> isn't in the dictionary and <default> isn't
provided.
Returns: List of <key>'s values.
"""
if key in self:
values = self.getlist(key)
del self._map[key]
for node, nodekey, nodevalue in self._items:
if nodekey == key:
self._items.removenode(node)
return values
elif key not in self._map and default is not _absent:
return default
raise KeyError(key)
|
[
"def",
"poplist",
"(",
"self",
",",
"key",
",",
"default",
"=",
"_absent",
")",
":",
"if",
"key",
"in",
"self",
":",
"values",
"=",
"self",
".",
"getlist",
"(",
"key",
")",
"del",
"self",
".",
"_map",
"[",
"key",
"]",
"for",
"node",
",",
"nodekey",
",",
"nodevalue",
"in",
"self",
".",
"_items",
":",
"if",
"nodekey",
"==",
"key",
":",
"self",
".",
"_items",
".",
"removenode",
"(",
"node",
")",
"return",
"values",
"elif",
"key",
"not",
"in",
"self",
".",
"_map",
"and",
"default",
"is",
"not",
"_absent",
":",
"return",
"default",
"raise",
"KeyError",
"(",
"key",
")"
] |
If <key> is in the dictionary, pop it and return its list of values. If
<key> is not in the dictionary, return <default>. KeyError is raised if
<default> is not provided and <key> is not in the dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.poplist(1) == [1, 11, 111]
omd.allitems() == [(2,2), (3,3)]
omd.poplist(2) == [2]
omd.allitems() == [(3,3)]
Raises: KeyError if <key> isn't in the dictionary and <default> isn't
provided.
Returns: List of <key>'s values.
|
[
"If",
"<key",
">",
"is",
"in",
"the",
"dictionary",
"pop",
"it",
"and",
"return",
"its",
"list",
"of",
"values",
".",
"If",
"<key",
">",
"is",
"not",
"in",
"the",
"dictionary",
"return",
"<default",
">",
".",
"KeyError",
"is",
"raised",
"if",
"<default",
">",
"is",
"not",
"provided",
"and",
"<key",
">",
"is",
"not",
"in",
"the",
"dictionary",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L416-L442
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.popvalue
|
def popvalue(self, key, value=_absent, default=_absent, last=True):
"""
If <value> is provided, pops the first or last (key,value) item in the
dictionary if <key> is in the dictionary.
If <value> is not provided, pops the first or last value for <key> if
<key> is in the dictionary.
If <key> no longer has any values after a popvalue() call, <key> is
removed from the dictionary. If <key> isn't in the dictionary and
<default> was provided, return default. KeyError is raised if <default>
is not provided and <key> is not in the dictionary. ValueError is
raised if <value> is provided but isn't a value for <key>.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3), (2,22)])
omd.popvalue(1) == 111
omd.allitems() == [(1,11), (1,111), (2,2), (3,3), (2,22)]
omd.popvalue(1, last=False) == 1
omd.allitems() == [(1,11), (2,2), (3,3), (2,22)]
omd.popvalue(2, 2) == 2
omd.allitems() == [(1,11), (3,3), (2,22)]
omd.popvalue(1, 11) == 11
omd.allitems() == [(3,3), (2,22)]
omd.popvalue('not a key', default='sup') == 'sup'
Params:
last: Boolean whether to return <key>'s first value (<last> is False)
or last value (<last> is True).
Raises:
KeyError if <key> isn't in the dictionary and <default> isn't
provided.
ValueError if <value> isn't a value for <key>.
Returns: The first or last of <key>'s values.
"""
def pop_node_with_index(key, index):
node = self._map[key].pop(index)
if not self._map[key]:
del self._map[key]
self._items.removenode(node)
return node
if key in self:
if value is not _absent:
if last:
pos = self.values(key)[::-1].index(value)
else:
pos = self.values(key).index(value)
if pos == -1:
raise ValueError(value)
else:
index = (len(self.values(key)) - 1 - pos) if last else pos
return pop_node_with_index(key, index).value
else:
return pop_node_with_index(key, -1 if last else 0).value
elif key not in self._map and default is not _absent:
return default
raise KeyError(key)
|
python
|
def popvalue(self, key, value=_absent, default=_absent, last=True):
"""
If <value> is provided, pops the first or last (key,value) item in the
dictionary if <key> is in the dictionary.
If <value> is not provided, pops the first or last value for <key> if
<key> is in the dictionary.
If <key> no longer has any values after a popvalue() call, <key> is
removed from the dictionary. If <key> isn't in the dictionary and
<default> was provided, return default. KeyError is raised if <default>
is not provided and <key> is not in the dictionary. ValueError is
raised if <value> is provided but isn't a value for <key>.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3), (2,22)])
omd.popvalue(1) == 111
omd.allitems() == [(1,11), (1,111), (2,2), (3,3), (2,22)]
omd.popvalue(1, last=False) == 1
omd.allitems() == [(1,11), (2,2), (3,3), (2,22)]
omd.popvalue(2, 2) == 2
omd.allitems() == [(1,11), (3,3), (2,22)]
omd.popvalue(1, 11) == 11
omd.allitems() == [(3,3), (2,22)]
omd.popvalue('not a key', default='sup') == 'sup'
Params:
last: Boolean whether to return <key>'s first value (<last> is False)
or last value (<last> is True).
Raises:
KeyError if <key> isn't in the dictionary and <default> isn't
provided.
ValueError if <value> isn't a value for <key>.
Returns: The first or last of <key>'s values.
"""
def pop_node_with_index(key, index):
node = self._map[key].pop(index)
if not self._map[key]:
del self._map[key]
self._items.removenode(node)
return node
if key in self:
if value is not _absent:
if last:
pos = self.values(key)[::-1].index(value)
else:
pos = self.values(key).index(value)
if pos == -1:
raise ValueError(value)
else:
index = (len(self.values(key)) - 1 - pos) if last else pos
return pop_node_with_index(key, index).value
else:
return pop_node_with_index(key, -1 if last else 0).value
elif key not in self._map and default is not _absent:
return default
raise KeyError(key)
|
[
"def",
"popvalue",
"(",
"self",
",",
"key",
",",
"value",
"=",
"_absent",
",",
"default",
"=",
"_absent",
",",
"last",
"=",
"True",
")",
":",
"def",
"pop_node_with_index",
"(",
"key",
",",
"index",
")",
":",
"node",
"=",
"self",
".",
"_map",
"[",
"key",
"]",
".",
"pop",
"(",
"index",
")",
"if",
"not",
"self",
".",
"_map",
"[",
"key",
"]",
":",
"del",
"self",
".",
"_map",
"[",
"key",
"]",
"self",
".",
"_items",
".",
"removenode",
"(",
"node",
")",
"return",
"node",
"if",
"key",
"in",
"self",
":",
"if",
"value",
"is",
"not",
"_absent",
":",
"if",
"last",
":",
"pos",
"=",
"self",
".",
"values",
"(",
"key",
")",
"[",
":",
":",
"-",
"1",
"]",
".",
"index",
"(",
"value",
")",
"else",
":",
"pos",
"=",
"self",
".",
"values",
"(",
"key",
")",
".",
"index",
"(",
"value",
")",
"if",
"pos",
"==",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"value",
")",
"else",
":",
"index",
"=",
"(",
"len",
"(",
"self",
".",
"values",
"(",
"key",
")",
")",
"-",
"1",
"-",
"pos",
")",
"if",
"last",
"else",
"pos",
"return",
"pop_node_with_index",
"(",
"key",
",",
"index",
")",
".",
"value",
"else",
":",
"return",
"pop_node_with_index",
"(",
"key",
",",
"-",
"1",
"if",
"last",
"else",
"0",
")",
".",
"value",
"elif",
"key",
"not",
"in",
"self",
".",
"_map",
"and",
"default",
"is",
"not",
"_absent",
":",
"return",
"default",
"raise",
"KeyError",
"(",
"key",
")"
] |
If <value> is provided, pops the first or last (key,value) item in the
dictionary if <key> is in the dictionary.
If <value> is not provided, pops the first or last value for <key> if
<key> is in the dictionary.
If <key> no longer has any values after a popvalue() call, <key> is
removed from the dictionary. If <key> isn't in the dictionary and
<default> was provided, return default. KeyError is raised if <default>
is not provided and <key> is not in the dictionary. ValueError is
raised if <value> is provided but isn't a value for <key>.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3), (2,22)])
omd.popvalue(1) == 111
omd.allitems() == [(1,11), (1,111), (2,2), (3,3), (2,22)]
omd.popvalue(1, last=False) == 1
omd.allitems() == [(1,11), (2,2), (3,3), (2,22)]
omd.popvalue(2, 2) == 2
omd.allitems() == [(1,11), (3,3), (2,22)]
omd.popvalue(1, 11) == 11
omd.allitems() == [(3,3), (2,22)]
omd.popvalue('not a key', default='sup') == 'sup'
Params:
last: Boolean whether to return <key>'s first value (<last> is False)
or last value (<last> is True).
Raises:
KeyError if <key> isn't in the dictionary and <default> isn't
provided.
ValueError if <value> isn't a value for <key>.
Returns: The first or last of <key>'s values.
|
[
"If",
"<value",
">",
"is",
"provided",
"pops",
"the",
"first",
"or",
"last",
"(",
"key",
"value",
")",
"item",
"in",
"the",
"dictionary",
"if",
"<key",
">",
"is",
"in",
"the",
"dictionary",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L444-L501
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.popitem
|
def popitem(self, fromall=False, last=True):
"""
Pop and return a key:value item.
If <fromall> is False, items()[0] is popped if <last> is False or
items()[-1] is popped if <last> is True. All remaining items with the
same key are removed.
If <fromall> is True, allitems()[0] is popped if <last> is False or
allitems()[-1] is popped if <last> is True. Any remaining items with
the same key remain.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.popitem() == (3,3)
omd.popitem(fromall=False, last=False) == (1,1)
omd.popitem(fromall=False, last=False) == (2,2)
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.popitem(fromall=True, last=False) == (1,1)
omd.popitem(fromall=True, last=False) == (1,11)
omd.popitem(fromall=True, last=True) == (3,3)
omd.popitem(fromall=True, last=False) == (1,111)
Params:
fromall: Whether to pop an item from items() (<fromall> is True) or
allitems() (<fromall> is False).
last: Boolean whether to pop the first item or last item of items()
or allitems().
Raises: KeyError if the dictionary is empty.
Returns: The first or last item from item() or allitem().
"""
if not self._items:
raise KeyError('popitem(): %s is empty' % self.__class__.__name__)
if fromall:
node = self._items[-1 if last else 0]
key = node.key
return key, self.popvalue(key, last=last)
else:
key = list(self._map.keys())[-1 if last else 0]
return key, self.pop(key)
|
python
|
def popitem(self, fromall=False, last=True):
"""
Pop and return a key:value item.
If <fromall> is False, items()[0] is popped if <last> is False or
items()[-1] is popped if <last> is True. All remaining items with the
same key are removed.
If <fromall> is True, allitems()[0] is popped if <last> is False or
allitems()[-1] is popped if <last> is True. Any remaining items with
the same key remain.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.popitem() == (3,3)
omd.popitem(fromall=False, last=False) == (1,1)
omd.popitem(fromall=False, last=False) == (2,2)
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.popitem(fromall=True, last=False) == (1,1)
omd.popitem(fromall=True, last=False) == (1,11)
omd.popitem(fromall=True, last=True) == (3,3)
omd.popitem(fromall=True, last=False) == (1,111)
Params:
fromall: Whether to pop an item from items() (<fromall> is True) or
allitems() (<fromall> is False).
last: Boolean whether to pop the first item or last item of items()
or allitems().
Raises: KeyError if the dictionary is empty.
Returns: The first or last item from item() or allitem().
"""
if not self._items:
raise KeyError('popitem(): %s is empty' % self.__class__.__name__)
if fromall:
node = self._items[-1 if last else 0]
key = node.key
return key, self.popvalue(key, last=last)
else:
key = list(self._map.keys())[-1 if last else 0]
return key, self.pop(key)
|
[
"def",
"popitem",
"(",
"self",
",",
"fromall",
"=",
"False",
",",
"last",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"_items",
":",
"raise",
"KeyError",
"(",
"'popitem(): %s is empty'",
"%",
"self",
".",
"__class__",
".",
"__name__",
")",
"if",
"fromall",
":",
"node",
"=",
"self",
".",
"_items",
"[",
"-",
"1",
"if",
"last",
"else",
"0",
"]",
"key",
"=",
"node",
".",
"key",
"return",
"key",
",",
"self",
".",
"popvalue",
"(",
"key",
",",
"last",
"=",
"last",
")",
"else",
":",
"key",
"=",
"list",
"(",
"self",
".",
"_map",
".",
"keys",
"(",
")",
")",
"[",
"-",
"1",
"if",
"last",
"else",
"0",
"]",
"return",
"key",
",",
"self",
".",
"pop",
"(",
"key",
")"
] |
Pop and return a key:value item.
If <fromall> is False, items()[0] is popped if <last> is False or
items()[-1] is popped if <last> is True. All remaining items with the
same key are removed.
If <fromall> is True, allitems()[0] is popped if <last> is False or
allitems()[-1] is popped if <last> is True. Any remaining items with
the same key remain.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.popitem() == (3,3)
omd.popitem(fromall=False, last=False) == (1,1)
omd.popitem(fromall=False, last=False) == (2,2)
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.popitem(fromall=True, last=False) == (1,1)
omd.popitem(fromall=True, last=False) == (1,11)
omd.popitem(fromall=True, last=True) == (3,3)
omd.popitem(fromall=True, last=False) == (1,111)
Params:
fromall: Whether to pop an item from items() (<fromall> is True) or
allitems() (<fromall> is False).
last: Boolean whether to pop the first item or last item of items()
or allitems().
Raises: KeyError if the dictionary is empty.
Returns: The first or last item from item() or allitem().
|
[
"Pop",
"and",
"return",
"a",
"key",
":",
"value",
"item",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L503-L544
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.poplistitem
|
def poplistitem(self, last=True):
"""
Pop and return a key:valuelist item comprised of a key and that key's
list of values. If <last> is False, a key:valuelist item comprised of
keys()[0] and its list of values is popped and returned. If <last> is
True, a key:valuelist item comprised of keys()[-1] and its list of
values is popped and returned.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.poplistitem(last=True) == (3,[3])
omd.poplistitem(last=False) == (1,[1,11,111])
Params:
last: Boolean whether to pop the first or last key and its associated
list of values.
Raises: KeyError if the dictionary is empty.
Returns: A two-tuple comprised of the first or last key and its
associated list of values.
"""
if not self._items:
s = 'poplistitem(): %s is empty' % self.__class__.__name__
raise KeyError(s)
key = self.keys()[-1 if last else 0]
return key, self.poplist(key)
|
python
|
def poplistitem(self, last=True):
"""
Pop and return a key:valuelist item comprised of a key and that key's
list of values. If <last> is False, a key:valuelist item comprised of
keys()[0] and its list of values is popped and returned. If <last> is
True, a key:valuelist item comprised of keys()[-1] and its list of
values is popped and returned.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.poplistitem(last=True) == (3,[3])
omd.poplistitem(last=False) == (1,[1,11,111])
Params:
last: Boolean whether to pop the first or last key and its associated
list of values.
Raises: KeyError if the dictionary is empty.
Returns: A two-tuple comprised of the first or last key and its
associated list of values.
"""
if not self._items:
s = 'poplistitem(): %s is empty' % self.__class__.__name__
raise KeyError(s)
key = self.keys()[-1 if last else 0]
return key, self.poplist(key)
|
[
"def",
"poplistitem",
"(",
"self",
",",
"last",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"_items",
":",
"s",
"=",
"'poplistitem(): %s is empty'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"raise",
"KeyError",
"(",
"s",
")",
"key",
"=",
"self",
".",
"keys",
"(",
")",
"[",
"-",
"1",
"if",
"last",
"else",
"0",
"]",
"return",
"key",
",",
"self",
".",
"poplist",
"(",
"key",
")"
] |
Pop and return a key:valuelist item comprised of a key and that key's
list of values. If <last> is False, a key:valuelist item comprised of
keys()[0] and its list of values is popped and returned. If <last> is
True, a key:valuelist item comprised of keys()[-1] and its list of
values is popped and returned.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.poplistitem(last=True) == (3,[3])
omd.poplistitem(last=False) == (1,[1,11,111])
Params:
last: Boolean whether to pop the first or last key and its associated
list of values.
Raises: KeyError if the dictionary is empty.
Returns: A two-tuple comprised of the first or last key and its
associated list of values.
|
[
"Pop",
"and",
"return",
"a",
"key",
":",
"valuelist",
"item",
"comprised",
"of",
"a",
"key",
"and",
"that",
"key",
"s",
"list",
"of",
"values",
".",
"If",
"<last",
">",
"is",
"False",
"a",
"key",
":",
"valuelist",
"item",
"comprised",
"of",
"keys",
"()",
"[",
"0",
"]",
"and",
"its",
"list",
"of",
"values",
"is",
"popped",
"and",
"returned",
".",
"If",
"<last",
">",
"is",
"True",
"a",
"key",
":",
"valuelist",
"item",
"comprised",
"of",
"keys",
"()",
"[",
"-",
"1",
"]",
"and",
"its",
"list",
"of",
"values",
"is",
"popped",
"and",
"returned",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L546-L571
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.values
|
def values(self, key=_absent):
"""
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: List created from itervalues(<key>).If <key> is provided and
is a dictionary key, only values of items with key <key> are
returned.
"""
if key is not _absent and key in self._map:
return self.getlist(key)
return list(self.itervalues())
|
python
|
def values(self, key=_absent):
"""
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: List created from itervalues(<key>).If <key> is provided and
is a dictionary key, only values of items with key <key> are
returned.
"""
if key is not _absent and key in self._map:
return self.getlist(key)
return list(self.itervalues())
|
[
"def",
"values",
"(",
"self",
",",
"key",
"=",
"_absent",
")",
":",
"if",
"key",
"is",
"not",
"_absent",
"and",
"key",
"in",
"self",
".",
"_map",
":",
"return",
"self",
".",
"getlist",
"(",
"key",
")",
"return",
"list",
"(",
"self",
".",
"itervalues",
"(",
")",
")"
] |
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: List created from itervalues(<key>).If <key> is provided and
is a dictionary key, only values of items with key <key> are
returned.
|
[
"Raises",
":",
"KeyError",
"if",
"<key",
">",
"is",
"provided",
"and",
"not",
"in",
"the",
"dictionary",
".",
"Returns",
":",
"List",
"created",
"from",
"itervalues",
"(",
"<key",
">",
")",
".",
"If",
"<key",
">",
"is",
"provided",
"and",
"is",
"a",
"dictionary",
"key",
"only",
"values",
"of",
"items",
"with",
"key",
"<key",
">",
"are",
"returned",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L584-L593
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.iteritems
|
def iteritems(self, key=_absent):
"""
Parity with dict.iteritems() except the optional <key> parameter has
been added. If <key> is provided, only items with the provided key are
iterated over. KeyError is raised if <key> is provided and not in the
dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.iteritems(1) -> (1,1) -> (1,11) -> (1,111)
omd.iteritems() -> (1,1) -> (2,2) -> (3,3)
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: An iterator over the items() of the dictionary, or only items
with the key <key> if <key> is provided.
"""
if key is not _absent:
if key in self:
items = [(node.key, node.value) for node in self._map[key]]
return iter(items)
raise KeyError(key)
items = six.iteritems(self._map)
return iter((key, nodes[0].value) for (key, nodes) in items)
|
python
|
def iteritems(self, key=_absent):
"""
Parity with dict.iteritems() except the optional <key> parameter has
been added. If <key> is provided, only items with the provided key are
iterated over. KeyError is raised if <key> is provided and not in the
dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.iteritems(1) -> (1,1) -> (1,11) -> (1,111)
omd.iteritems() -> (1,1) -> (2,2) -> (3,3)
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: An iterator over the items() of the dictionary, or only items
with the key <key> if <key> is provided.
"""
if key is not _absent:
if key in self:
items = [(node.key, node.value) for node in self._map[key]]
return iter(items)
raise KeyError(key)
items = six.iteritems(self._map)
return iter((key, nodes[0].value) for (key, nodes) in items)
|
[
"def",
"iteritems",
"(",
"self",
",",
"key",
"=",
"_absent",
")",
":",
"if",
"key",
"is",
"not",
"_absent",
":",
"if",
"key",
"in",
"self",
":",
"items",
"=",
"[",
"(",
"node",
".",
"key",
",",
"node",
".",
"value",
")",
"for",
"node",
"in",
"self",
".",
"_map",
"[",
"key",
"]",
"]",
"return",
"iter",
"(",
"items",
")",
"raise",
"KeyError",
"(",
"key",
")",
"items",
"=",
"six",
".",
"iteritems",
"(",
"self",
".",
"_map",
")",
"return",
"iter",
"(",
"(",
"key",
",",
"nodes",
"[",
"0",
"]",
".",
"value",
")",
"for",
"(",
"key",
",",
"nodes",
")",
"in",
"items",
")"
] |
Parity with dict.iteritems() except the optional <key> parameter has
been added. If <key> is provided, only items with the provided key are
iterated over. KeyError is raised if <key> is provided and not in the
dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.iteritems(1) -> (1,1) -> (1,11) -> (1,111)
omd.iteritems() -> (1,1) -> (2,2) -> (3,3)
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: An iterator over the items() of the dictionary, or only items
with the key <key> if <key> is provided.
|
[
"Parity",
"with",
"dict",
".",
"iteritems",
"()",
"except",
"the",
"optional",
"<key",
">",
"parameter",
"has",
"been",
"added",
".",
"If",
"<key",
">",
"is",
"provided",
"only",
"items",
"with",
"the",
"provided",
"key",
"are",
"iterated",
"over",
".",
"KeyError",
"is",
"raised",
"if",
"<key",
">",
"is",
"provided",
"and",
"not",
"in",
"the",
"dictionary",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L607-L629
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.itervalues
|
def itervalues(self, key=_absent):
"""
Parity with dict.itervalues() except the optional <key> parameter has
been added. If <key> is provided, only values from items with the
provided key are iterated over. KeyError is raised if <key> is provided
and not in the dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.itervalues(1) -> 1 -> 11 -> 111
omd.itervalues() -> 1 -> 11 -> 111 -> 2 -> 3
Raises: KeyError if <key> is provided and isn't in the dictionary.
Returns: An iterator over the values() of the dictionary, or only the
values of key <key> if <key> is provided.
"""
if key is not _absent:
if key in self:
return iter([node.value for node in self._map[key]])
raise KeyError(key)
return iter([nodes[0].value for nodes in six.itervalues(self._map)])
|
python
|
def itervalues(self, key=_absent):
"""
Parity with dict.itervalues() except the optional <key> parameter has
been added. If <key> is provided, only values from items with the
provided key are iterated over. KeyError is raised if <key> is provided
and not in the dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.itervalues(1) -> 1 -> 11 -> 111
omd.itervalues() -> 1 -> 11 -> 111 -> 2 -> 3
Raises: KeyError if <key> is provided and isn't in the dictionary.
Returns: An iterator over the values() of the dictionary, or only the
values of key <key> if <key> is provided.
"""
if key is not _absent:
if key in self:
return iter([node.value for node in self._map[key]])
raise KeyError(key)
return iter([nodes[0].value for nodes in six.itervalues(self._map)])
|
[
"def",
"itervalues",
"(",
"self",
",",
"key",
"=",
"_absent",
")",
":",
"if",
"key",
"is",
"not",
"_absent",
":",
"if",
"key",
"in",
"self",
":",
"return",
"iter",
"(",
"[",
"node",
".",
"value",
"for",
"node",
"in",
"self",
".",
"_map",
"[",
"key",
"]",
"]",
")",
"raise",
"KeyError",
"(",
"key",
")",
"return",
"iter",
"(",
"[",
"nodes",
"[",
"0",
"]",
".",
"value",
"for",
"nodes",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"_map",
")",
"]",
")"
] |
Parity with dict.itervalues() except the optional <key> parameter has
been added. If <key> is provided, only values from items with the
provided key are iterated over. KeyError is raised if <key> is provided
and not in the dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.itervalues(1) -> 1 -> 11 -> 111
omd.itervalues() -> 1 -> 11 -> 111 -> 2 -> 3
Raises: KeyError if <key> is provided and isn't in the dictionary.
Returns: An iterator over the values() of the dictionary, or only the
values of key <key> if <key> is provided.
|
[
"Parity",
"with",
"dict",
".",
"itervalues",
"()",
"except",
"the",
"optional",
"<key",
">",
"parameter",
"has",
"been",
"added",
".",
"If",
"<key",
">",
"is",
"provided",
"only",
"values",
"from",
"items",
"with",
"the",
"provided",
"key",
"are",
"iterated",
"over",
".",
"KeyError",
"is",
"raised",
"if",
"<key",
">",
"is",
"provided",
"and",
"not",
"in",
"the",
"dictionary",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L634-L654
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.iterallitems
|
def iterallitems(self, key=_absent):
'''
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.iterallitems() == (1,1) -> (1,11) -> (1,111) -> (2,2) -> (3,3)
omd.iterallitems(1) == (1,1) -> (1,11) -> (1,111)
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: An iterator over every item in the diciontary. If <key> is
provided, only items with the key <key> are iterated over.
'''
if key is not _absent:
# Raises KeyError if <key> is not in self._map.
return self.iteritems(key)
return self._items.iteritems()
|
python
|
def iterallitems(self, key=_absent):
'''
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.iterallitems() == (1,1) -> (1,11) -> (1,111) -> (2,2) -> (3,3)
omd.iterallitems(1) == (1,1) -> (1,11) -> (1,111)
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: An iterator over every item in the diciontary. If <key> is
provided, only items with the key <key> are iterated over.
'''
if key is not _absent:
# Raises KeyError if <key> is not in self._map.
return self.iteritems(key)
return self._items.iteritems()
|
[
"def",
"iterallitems",
"(",
"self",
",",
"key",
"=",
"_absent",
")",
":",
"if",
"key",
"is",
"not",
"_absent",
":",
"# Raises KeyError if <key> is not in self._map.",
"return",
"self",
".",
"iteritems",
"(",
"key",
")",
"return",
"self",
".",
"_items",
".",
"iteritems",
"(",
")"
] |
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.iterallitems() == (1,1) -> (1,11) -> (1,111) -> (2,2) -> (3,3)
omd.iterallitems(1) == (1,1) -> (1,11) -> (1,111)
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: An iterator over every item in the diciontary. If <key> is
provided, only items with the key <key> are iterated over.
|
[
"Example",
":",
"omd",
"=",
"omdict",
"(",
"[",
"(",
"1",
"1",
")",
"(",
"1",
"11",
")",
"(",
"1",
"111",
")",
"(",
"2",
"2",
")",
"(",
"3",
"3",
")",
"]",
")",
"omd",
".",
"iterallitems",
"()",
"==",
"(",
"1",
"1",
")",
"-",
">",
"(",
"1",
"11",
")",
"-",
">",
"(",
"1",
"111",
")",
"-",
">",
"(",
"2",
"2",
")",
"-",
">",
"(",
"3",
"3",
")",
"omd",
".",
"iterallitems",
"(",
"1",
")",
"==",
"(",
"1",
"1",
")",
"-",
">",
"(",
"1",
"11",
")",
"-",
">",
"(",
"1",
"111",
")"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L685-L699
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.iterallvalues
|
def iterallvalues(self, key=_absent):
'''
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.iterallvalues() == 1 -> 11 -> 111 -> 2 -> 3
Returns: An iterator over the values of every item in the dictionary.
'''
if key is not _absent:
if key in self:
return iter(self.getlist(key))
raise KeyError(key)
return self._items.itervalues()
|
python
|
def iterallvalues(self, key=_absent):
'''
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.iterallvalues() == 1 -> 11 -> 111 -> 2 -> 3
Returns: An iterator over the values of every item in the dictionary.
'''
if key is not _absent:
if key in self:
return iter(self.getlist(key))
raise KeyError(key)
return self._items.itervalues()
|
[
"def",
"iterallvalues",
"(",
"self",
",",
"key",
"=",
"_absent",
")",
":",
"if",
"key",
"is",
"not",
"_absent",
":",
"if",
"key",
"in",
"self",
":",
"return",
"iter",
"(",
"self",
".",
"getlist",
"(",
"key",
")",
")",
"raise",
"KeyError",
"(",
"key",
")",
"return",
"self",
".",
"_items",
".",
"itervalues",
"(",
")"
] |
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.iterallvalues() == 1 -> 11 -> 111 -> 2 -> 3
Returns: An iterator over the values of every item in the dictionary.
|
[
"Example",
":",
"omd",
"=",
"omdict",
"(",
"[",
"(",
"1",
"1",
")",
"(",
"1",
"11",
")",
"(",
"1",
"111",
")",
"(",
"2",
"2",
")",
"(",
"3",
"3",
")",
"]",
")",
"omd",
".",
"iterallvalues",
"()",
"==",
"1",
"-",
">",
"11",
"-",
">",
"111",
"-",
">",
"2",
"-",
">",
"3"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L711-L723
|
train
|
pypa/pipenv
|
pipenv/vendor/orderedmultidict/orderedmultidict.py
|
omdict.reverse
|
def reverse(self):
"""
Reverse the order of all items in the dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.reverse()
omd.allitems() == [(3,3), (2,2), (1,111), (1,11), (1,1)]
Returns: <self>.
"""
for key in six.iterkeys(self._map):
self._map[key].reverse()
self._items.reverse()
return self
|
python
|
def reverse(self):
"""
Reverse the order of all items in the dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.reverse()
omd.allitems() == [(3,3), (2,2), (1,111), (1,11), (1,1)]
Returns: <self>.
"""
for key in six.iterkeys(self._map):
self._map[key].reverse()
self._items.reverse()
return self
|
[
"def",
"reverse",
"(",
"self",
")",
":",
"for",
"key",
"in",
"six",
".",
"iterkeys",
"(",
"self",
".",
"_map",
")",
":",
"self",
".",
"_map",
"[",
"key",
"]",
".",
"reverse",
"(",
")",
"self",
".",
"_items",
".",
"reverse",
"(",
")",
"return",
"self"
] |
Reverse the order of all items in the dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.reverse()
omd.allitems() == [(3,3), (2,2), (1,111), (1,11), (1,1)]
Returns: <self>.
|
[
"Reverse",
"the",
"order",
"of",
"all",
"items",
"in",
"the",
"dictionary",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L746-L760
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/build_env.py
|
BuildEnvironment.check_requirements
|
def check_requirements(self, reqs):
# type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]]
"""Return 2 sets:
- conflicting requirements: set of (installed, wanted) reqs tuples
- missing requirements: set of reqs
"""
missing = set()
conflicting = set()
if reqs:
ws = WorkingSet(self._lib_dirs)
for req in reqs:
try:
if ws.find(Requirement.parse(req)) is None:
missing.add(req)
except VersionConflict as e:
conflicting.add((str(e.args[0].as_requirement()),
str(e.args[1])))
return conflicting, missing
|
python
|
def check_requirements(self, reqs):
# type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]]
"""Return 2 sets:
- conflicting requirements: set of (installed, wanted) reqs tuples
- missing requirements: set of reqs
"""
missing = set()
conflicting = set()
if reqs:
ws = WorkingSet(self._lib_dirs)
for req in reqs:
try:
if ws.find(Requirement.parse(req)) is None:
missing.add(req)
except VersionConflict as e:
conflicting.add((str(e.args[0].as_requirement()),
str(e.args[1])))
return conflicting, missing
|
[
"def",
"check_requirements",
"(",
"self",
",",
"reqs",
")",
":",
"# type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]]",
"missing",
"=",
"set",
"(",
")",
"conflicting",
"=",
"set",
"(",
")",
"if",
"reqs",
":",
"ws",
"=",
"WorkingSet",
"(",
"self",
".",
"_lib_dirs",
")",
"for",
"req",
"in",
"reqs",
":",
"try",
":",
"if",
"ws",
".",
"find",
"(",
"Requirement",
".",
"parse",
"(",
"req",
")",
")",
"is",
"None",
":",
"missing",
".",
"add",
"(",
"req",
")",
"except",
"VersionConflict",
"as",
"e",
":",
"conflicting",
".",
"add",
"(",
"(",
"str",
"(",
"e",
".",
"args",
"[",
"0",
"]",
".",
"as_requirement",
"(",
")",
")",
",",
"str",
"(",
"e",
".",
"args",
"[",
"1",
"]",
")",
")",
")",
"return",
"conflicting",
",",
"missing"
] |
Return 2 sets:
- conflicting requirements: set of (installed, wanted) reqs tuples
- missing requirements: set of reqs
|
[
"Return",
"2",
"sets",
":",
"-",
"conflicting",
"requirements",
":",
"set",
"of",
"(",
"installed",
"wanted",
")",
"reqs",
"tuples",
"-",
"missing",
"requirements",
":",
"set",
"of",
"reqs"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/build_env.py#L137-L154
|
train
|
pypa/pipenv
|
pipenv/vendor/click/parser.py
|
_unpack_args
|
def _unpack_args(args, nargs_spec):
"""Given an iterable of arguments and an iterable of nargs specifications,
it returns a tuple with all the unpacked arguments at the first index
and all remaining arguments as the second.
The nargs specification is the number of arguments that should be consumed
or `-1` to indicate that this position should eat up all the remainders.
Missing items are filled with `None`.
"""
args = deque(args)
nargs_spec = deque(nargs_spec)
rv = []
spos = None
def _fetch(c):
try:
if spos is None:
return c.popleft()
else:
return c.pop()
except IndexError:
return None
while nargs_spec:
nargs = _fetch(nargs_spec)
if nargs == 1:
rv.append(_fetch(args))
elif nargs > 1:
x = [_fetch(args) for _ in range(nargs)]
# If we're reversed, we're pulling in the arguments in reverse,
# so we need to turn them around.
if spos is not None:
x.reverse()
rv.append(tuple(x))
elif nargs < 0:
if spos is not None:
raise TypeError('Cannot have two nargs < 0')
spos = len(rv)
rv.append(None)
# spos is the position of the wildcard (star). If it's not `None`,
# we fill it with the remainder.
if spos is not None:
rv[spos] = tuple(args)
args = []
rv[spos + 1:] = reversed(rv[spos + 1:])
return tuple(rv), list(args)
|
python
|
def _unpack_args(args, nargs_spec):
"""Given an iterable of arguments and an iterable of nargs specifications,
it returns a tuple with all the unpacked arguments at the first index
and all remaining arguments as the second.
The nargs specification is the number of arguments that should be consumed
or `-1` to indicate that this position should eat up all the remainders.
Missing items are filled with `None`.
"""
args = deque(args)
nargs_spec = deque(nargs_spec)
rv = []
spos = None
def _fetch(c):
try:
if spos is None:
return c.popleft()
else:
return c.pop()
except IndexError:
return None
while nargs_spec:
nargs = _fetch(nargs_spec)
if nargs == 1:
rv.append(_fetch(args))
elif nargs > 1:
x = [_fetch(args) for _ in range(nargs)]
# If we're reversed, we're pulling in the arguments in reverse,
# so we need to turn them around.
if spos is not None:
x.reverse()
rv.append(tuple(x))
elif nargs < 0:
if spos is not None:
raise TypeError('Cannot have two nargs < 0')
spos = len(rv)
rv.append(None)
# spos is the position of the wildcard (star). If it's not `None`,
# we fill it with the remainder.
if spos is not None:
rv[spos] = tuple(args)
args = []
rv[spos + 1:] = reversed(rv[spos + 1:])
return tuple(rv), list(args)
|
[
"def",
"_unpack_args",
"(",
"args",
",",
"nargs_spec",
")",
":",
"args",
"=",
"deque",
"(",
"args",
")",
"nargs_spec",
"=",
"deque",
"(",
"nargs_spec",
")",
"rv",
"=",
"[",
"]",
"spos",
"=",
"None",
"def",
"_fetch",
"(",
"c",
")",
":",
"try",
":",
"if",
"spos",
"is",
"None",
":",
"return",
"c",
".",
"popleft",
"(",
")",
"else",
":",
"return",
"c",
".",
"pop",
"(",
")",
"except",
"IndexError",
":",
"return",
"None",
"while",
"nargs_spec",
":",
"nargs",
"=",
"_fetch",
"(",
"nargs_spec",
")",
"if",
"nargs",
"==",
"1",
":",
"rv",
".",
"append",
"(",
"_fetch",
"(",
"args",
")",
")",
"elif",
"nargs",
">",
"1",
":",
"x",
"=",
"[",
"_fetch",
"(",
"args",
")",
"for",
"_",
"in",
"range",
"(",
"nargs",
")",
"]",
"# If we're reversed, we're pulling in the arguments in reverse,",
"# so we need to turn them around.",
"if",
"spos",
"is",
"not",
"None",
":",
"x",
".",
"reverse",
"(",
")",
"rv",
".",
"append",
"(",
"tuple",
"(",
"x",
")",
")",
"elif",
"nargs",
"<",
"0",
":",
"if",
"spos",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"'Cannot have two nargs < 0'",
")",
"spos",
"=",
"len",
"(",
"rv",
")",
"rv",
".",
"append",
"(",
"None",
")",
"# spos is the position of the wildcard (star). If it's not `None`,",
"# we fill it with the remainder.",
"if",
"spos",
"is",
"not",
"None",
":",
"rv",
"[",
"spos",
"]",
"=",
"tuple",
"(",
"args",
")",
"args",
"=",
"[",
"]",
"rv",
"[",
"spos",
"+",
"1",
":",
"]",
"=",
"reversed",
"(",
"rv",
"[",
"spos",
"+",
"1",
":",
"]",
")",
"return",
"tuple",
"(",
"rv",
")",
",",
"list",
"(",
"args",
")"
] |
Given an iterable of arguments and an iterable of nargs specifications,
it returns a tuple with all the unpacked arguments at the first index
and all remaining arguments as the second.
The nargs specification is the number of arguments that should be consumed
or `-1` to indicate that this position should eat up all the remainders.
Missing items are filled with `None`.
|
[
"Given",
"an",
"iterable",
"of",
"arguments",
"and",
"an",
"iterable",
"of",
"nargs",
"specifications",
"it",
"returns",
"a",
"tuple",
"with",
"all",
"the",
"unpacked",
"arguments",
"at",
"the",
"first",
"index",
"and",
"all",
"remaining",
"arguments",
"as",
"the",
"second",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/parser.py#L25-L73
|
train
|
pypa/pipenv
|
pipenv/vendor/click/parser.py
|
split_arg_string
|
def split_arg_string(string):
"""Given an argument string this attempts to split it into small parts."""
rv = []
for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'"
r'|"([^"\\]*(?:\\.[^"\\]*)*)"'
r'|\S+)\s*', string, re.S):
arg = match.group().strip()
if arg[:1] == arg[-1:] and arg[:1] in '"\'':
arg = arg[1:-1].encode('ascii', 'backslashreplace') \
.decode('unicode-escape')
try:
arg = type(string)(arg)
except UnicodeError:
pass
rv.append(arg)
return rv
|
python
|
def split_arg_string(string):
"""Given an argument string this attempts to split it into small parts."""
rv = []
for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'"
r'|"([^"\\]*(?:\\.[^"\\]*)*)"'
r'|\S+)\s*', string, re.S):
arg = match.group().strip()
if arg[:1] == arg[-1:] and arg[:1] in '"\'':
arg = arg[1:-1].encode('ascii', 'backslashreplace') \
.decode('unicode-escape')
try:
arg = type(string)(arg)
except UnicodeError:
pass
rv.append(arg)
return rv
|
[
"def",
"split_arg_string",
"(",
"string",
")",
":",
"rv",
"=",
"[",
"]",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"r\"('([^'\\\\]*(?:\\\\.[^'\\\\]*)*)'\"",
"r'|\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"'",
"r'|\\S+)\\s*'",
",",
"string",
",",
"re",
".",
"S",
")",
":",
"arg",
"=",
"match",
".",
"group",
"(",
")",
".",
"strip",
"(",
")",
"if",
"arg",
"[",
":",
"1",
"]",
"==",
"arg",
"[",
"-",
"1",
":",
"]",
"and",
"arg",
"[",
":",
"1",
"]",
"in",
"'\"\\''",
":",
"arg",
"=",
"arg",
"[",
"1",
":",
"-",
"1",
"]",
".",
"encode",
"(",
"'ascii'",
",",
"'backslashreplace'",
")",
".",
"decode",
"(",
"'unicode-escape'",
")",
"try",
":",
"arg",
"=",
"type",
"(",
"string",
")",
"(",
"arg",
")",
"except",
"UnicodeError",
":",
"pass",
"rv",
".",
"append",
"(",
"arg",
")",
"return",
"rv"
] |
Given an argument string this attempts to split it into small parts.
|
[
"Given",
"an",
"argument",
"string",
"this",
"attempts",
"to",
"split",
"it",
"into",
"small",
"parts",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/parser.py#L98-L113
|
train
|
pypa/pipenv
|
pipenv/vendor/click/parser.py
|
OptionParser.add_option
|
def add_option(self, opts, dest, action=None, nargs=1, const=None,
obj=None):
"""Adds a new option named `dest` to the parser. The destination
is not inferred (unlike with optparse) and needs to be explicitly
provided. Action can be any of ``store``, ``store_const``,
``append``, ``appnd_const`` or ``count``.
The `obj` can be used to identify the option in the order list
that is returned from the parser.
"""
if obj is None:
obj = dest
opts = [normalize_opt(opt, self.ctx) for opt in opts]
option = Option(opts, dest, action=action, nargs=nargs,
const=const, obj=obj)
self._opt_prefixes.update(option.prefixes)
for opt in option._short_opts:
self._short_opt[opt] = option
for opt in option._long_opts:
self._long_opt[opt] = option
|
python
|
def add_option(self, opts, dest, action=None, nargs=1, const=None,
obj=None):
"""Adds a new option named `dest` to the parser. The destination
is not inferred (unlike with optparse) and needs to be explicitly
provided. Action can be any of ``store``, ``store_const``,
``append``, ``appnd_const`` or ``count``.
The `obj` can be used to identify the option in the order list
that is returned from the parser.
"""
if obj is None:
obj = dest
opts = [normalize_opt(opt, self.ctx) for opt in opts]
option = Option(opts, dest, action=action, nargs=nargs,
const=const, obj=obj)
self._opt_prefixes.update(option.prefixes)
for opt in option._short_opts:
self._short_opt[opt] = option
for opt in option._long_opts:
self._long_opt[opt] = option
|
[
"def",
"add_option",
"(",
"self",
",",
"opts",
",",
"dest",
",",
"action",
"=",
"None",
",",
"nargs",
"=",
"1",
",",
"const",
"=",
"None",
",",
"obj",
"=",
"None",
")",
":",
"if",
"obj",
"is",
"None",
":",
"obj",
"=",
"dest",
"opts",
"=",
"[",
"normalize_opt",
"(",
"opt",
",",
"self",
".",
"ctx",
")",
"for",
"opt",
"in",
"opts",
"]",
"option",
"=",
"Option",
"(",
"opts",
",",
"dest",
",",
"action",
"=",
"action",
",",
"nargs",
"=",
"nargs",
",",
"const",
"=",
"const",
",",
"obj",
"=",
"obj",
")",
"self",
".",
"_opt_prefixes",
".",
"update",
"(",
"option",
".",
"prefixes",
")",
"for",
"opt",
"in",
"option",
".",
"_short_opts",
":",
"self",
".",
"_short_opt",
"[",
"opt",
"]",
"=",
"option",
"for",
"opt",
"in",
"option",
".",
"_long_opts",
":",
"self",
".",
"_long_opt",
"[",
"opt",
"]",
"=",
"option"
] |
Adds a new option named `dest` to the parser. The destination
is not inferred (unlike with optparse) and needs to be explicitly
provided. Action can be any of ``store``, ``store_const``,
``append``, ``appnd_const`` or ``count``.
The `obj` can be used to identify the option in the order list
that is returned from the parser.
|
[
"Adds",
"a",
"new",
"option",
"named",
"dest",
"to",
"the",
"parser",
".",
"The",
"destination",
"is",
"not",
"inferred",
"(",
"unlike",
"with",
"optparse",
")",
"and",
"needs",
"to",
"be",
"explicitly",
"provided",
".",
"Action",
"can",
"be",
"any",
"of",
"store",
"store_const",
"append",
"appnd_const",
"or",
"count",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/parser.py#L228-L247
|
train
|
pypa/pipenv
|
pipenv/vendor/click/parser.py
|
OptionParser.add_argument
|
def add_argument(self, dest, nargs=1, obj=None):
"""Adds a positional argument named `dest` to the parser.
The `obj` can be used to identify the option in the order list
that is returned from the parser.
"""
if obj is None:
obj = dest
self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))
|
python
|
def add_argument(self, dest, nargs=1, obj=None):
"""Adds a positional argument named `dest` to the parser.
The `obj` can be used to identify the option in the order list
that is returned from the parser.
"""
if obj is None:
obj = dest
self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))
|
[
"def",
"add_argument",
"(",
"self",
",",
"dest",
",",
"nargs",
"=",
"1",
",",
"obj",
"=",
"None",
")",
":",
"if",
"obj",
"is",
"None",
":",
"obj",
"=",
"dest",
"self",
".",
"_args",
".",
"append",
"(",
"Argument",
"(",
"dest",
"=",
"dest",
",",
"nargs",
"=",
"nargs",
",",
"obj",
"=",
"obj",
")",
")"
] |
Adds a positional argument named `dest` to the parser.
The `obj` can be used to identify the option in the order list
that is returned from the parser.
|
[
"Adds",
"a",
"positional",
"argument",
"named",
"dest",
"to",
"the",
"parser",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/parser.py#L249-L257
|
train
|
pypa/pipenv
|
pipenv/vendor/click/parser.py
|
OptionParser.parse_args
|
def parse_args(self, args):
"""Parses positional arguments and returns ``(values, args, order)``
for the parsed options and arguments as well as the leftover
arguments if there are any. The order is a list of objects as they
appear on the command line. If arguments appear multiple times they
will be memorized multiple times as well.
"""
state = ParsingState(args)
try:
self._process_args_for_options(state)
self._process_args_for_args(state)
except UsageError:
if self.ctx is None or not self.ctx.resilient_parsing:
raise
return state.opts, state.largs, state.order
|
python
|
def parse_args(self, args):
"""Parses positional arguments and returns ``(values, args, order)``
for the parsed options and arguments as well as the leftover
arguments if there are any. The order is a list of objects as they
appear on the command line. If arguments appear multiple times they
will be memorized multiple times as well.
"""
state = ParsingState(args)
try:
self._process_args_for_options(state)
self._process_args_for_args(state)
except UsageError:
if self.ctx is None or not self.ctx.resilient_parsing:
raise
return state.opts, state.largs, state.order
|
[
"def",
"parse_args",
"(",
"self",
",",
"args",
")",
":",
"state",
"=",
"ParsingState",
"(",
"args",
")",
"try",
":",
"self",
".",
"_process_args_for_options",
"(",
"state",
")",
"self",
".",
"_process_args_for_args",
"(",
"state",
")",
"except",
"UsageError",
":",
"if",
"self",
".",
"ctx",
"is",
"None",
"or",
"not",
"self",
".",
"ctx",
".",
"resilient_parsing",
":",
"raise",
"return",
"state",
".",
"opts",
",",
"state",
".",
"largs",
",",
"state",
".",
"order"
] |
Parses positional arguments and returns ``(values, args, order)``
for the parsed options and arguments as well as the leftover
arguments if there are any. The order is a list of objects as they
appear on the command line. If arguments appear multiple times they
will be memorized multiple times as well.
|
[
"Parses",
"positional",
"arguments",
"and",
"returns",
"(",
"values",
"args",
"order",
")",
"for",
"the",
"parsed",
"options",
"and",
"arguments",
"as",
"well",
"as",
"the",
"leftover",
"arguments",
"if",
"there",
"are",
"any",
".",
"The",
"order",
"is",
"a",
"list",
"of",
"objects",
"as",
"they",
"appear",
"on",
"the",
"command",
"line",
".",
"If",
"arguments",
"appear",
"multiple",
"times",
"they",
"will",
"be",
"memorized",
"multiple",
"times",
"as",
"well",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/parser.py#L259-L273
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
make_graph
|
def make_graph(dists, scheme='default'):
"""Makes a dependency graph from the given distributions.
:parameter dists: a list of distributions
:type dists: list of :class:`distutils2.database.InstalledDistribution` and
:class:`distutils2.database.EggInfoDistribution` instances
:rtype: a :class:`DependencyGraph` instance
"""
scheme = get_scheme(scheme)
graph = DependencyGraph()
provided = {} # maps names to lists of (version, dist) tuples
# first, build the graph and find out what's provided
for dist in dists:
graph.add_distribution(dist)
for p in dist.provides:
name, version = parse_name_and_version(p)
logger.debug('Add to provided: %s, %s, %s', name, version, dist)
provided.setdefault(name, []).append((version, dist))
# now make the edges
for dist in dists:
requires = (dist.run_requires | dist.meta_requires |
dist.build_requires | dist.dev_requires)
for req in requires:
try:
matcher = scheme.matcher(req)
except UnsupportedVersionError:
# XXX compat-mode if cannot read the version
logger.warning('could not read version %r - using name only',
req)
name = req.split()[0]
matcher = scheme.matcher(name)
name = matcher.key # case-insensitive
matched = False
if name in provided:
for version, provider in provided[name]:
try:
match = matcher.match(version)
except UnsupportedVersionError:
match = False
if match:
graph.add_edge(dist, provider, req)
matched = True
break
if not matched:
graph.add_missing(dist, req)
return graph
|
python
|
def make_graph(dists, scheme='default'):
"""Makes a dependency graph from the given distributions.
:parameter dists: a list of distributions
:type dists: list of :class:`distutils2.database.InstalledDistribution` and
:class:`distutils2.database.EggInfoDistribution` instances
:rtype: a :class:`DependencyGraph` instance
"""
scheme = get_scheme(scheme)
graph = DependencyGraph()
provided = {} # maps names to lists of (version, dist) tuples
# first, build the graph and find out what's provided
for dist in dists:
graph.add_distribution(dist)
for p in dist.provides:
name, version = parse_name_and_version(p)
logger.debug('Add to provided: %s, %s, %s', name, version, dist)
provided.setdefault(name, []).append((version, dist))
# now make the edges
for dist in dists:
requires = (dist.run_requires | dist.meta_requires |
dist.build_requires | dist.dev_requires)
for req in requires:
try:
matcher = scheme.matcher(req)
except UnsupportedVersionError:
# XXX compat-mode if cannot read the version
logger.warning('could not read version %r - using name only',
req)
name = req.split()[0]
matcher = scheme.matcher(name)
name = matcher.key # case-insensitive
matched = False
if name in provided:
for version, provider in provided[name]:
try:
match = matcher.match(version)
except UnsupportedVersionError:
match = False
if match:
graph.add_edge(dist, provider, req)
matched = True
break
if not matched:
graph.add_missing(dist, req)
return graph
|
[
"def",
"make_graph",
"(",
"dists",
",",
"scheme",
"=",
"'default'",
")",
":",
"scheme",
"=",
"get_scheme",
"(",
"scheme",
")",
"graph",
"=",
"DependencyGraph",
"(",
")",
"provided",
"=",
"{",
"}",
"# maps names to lists of (version, dist) tuples",
"# first, build the graph and find out what's provided",
"for",
"dist",
"in",
"dists",
":",
"graph",
".",
"add_distribution",
"(",
"dist",
")",
"for",
"p",
"in",
"dist",
".",
"provides",
":",
"name",
",",
"version",
"=",
"parse_name_and_version",
"(",
"p",
")",
"logger",
".",
"debug",
"(",
"'Add to provided: %s, %s, %s'",
",",
"name",
",",
"version",
",",
"dist",
")",
"provided",
".",
"setdefault",
"(",
"name",
",",
"[",
"]",
")",
".",
"append",
"(",
"(",
"version",
",",
"dist",
")",
")",
"# now make the edges",
"for",
"dist",
"in",
"dists",
":",
"requires",
"=",
"(",
"dist",
".",
"run_requires",
"|",
"dist",
".",
"meta_requires",
"|",
"dist",
".",
"build_requires",
"|",
"dist",
".",
"dev_requires",
")",
"for",
"req",
"in",
"requires",
":",
"try",
":",
"matcher",
"=",
"scheme",
".",
"matcher",
"(",
"req",
")",
"except",
"UnsupportedVersionError",
":",
"# XXX compat-mode if cannot read the version",
"logger",
".",
"warning",
"(",
"'could not read version %r - using name only'",
",",
"req",
")",
"name",
"=",
"req",
".",
"split",
"(",
")",
"[",
"0",
"]",
"matcher",
"=",
"scheme",
".",
"matcher",
"(",
"name",
")",
"name",
"=",
"matcher",
".",
"key",
"# case-insensitive",
"matched",
"=",
"False",
"if",
"name",
"in",
"provided",
":",
"for",
"version",
",",
"provider",
"in",
"provided",
"[",
"name",
"]",
":",
"try",
":",
"match",
"=",
"matcher",
".",
"match",
"(",
"version",
")",
"except",
"UnsupportedVersionError",
":",
"match",
"=",
"False",
"if",
"match",
":",
"graph",
".",
"add_edge",
"(",
"dist",
",",
"provider",
",",
"req",
")",
"matched",
"=",
"True",
"break",
"if",
"not",
"matched",
":",
"graph",
".",
"add_missing",
"(",
"dist",
",",
"req",
")",
"return",
"graph"
] |
Makes a dependency graph from the given distributions.
:parameter dists: a list of distributions
:type dists: list of :class:`distutils2.database.InstalledDistribution` and
:class:`distutils2.database.EggInfoDistribution` instances
:rtype: a :class:`DependencyGraph` instance
|
[
"Makes",
"a",
"dependency",
"graph",
"from",
"the",
"given",
"distributions",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1225-L1276
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
get_dependent_dists
|
def get_dependent_dists(dists, dist):
"""Recursively generate a list of distributions from *dists* that are
dependent on *dist*.
:param dists: a list of distributions
:param dist: a distribution, member of *dists* for which we are interested
"""
if dist not in dists:
raise DistlibException('given distribution %r is not a member '
'of the list' % dist.name)
graph = make_graph(dists)
dep = [dist] # dependent distributions
todo = graph.reverse_list[dist] # list of nodes we should inspect
while todo:
d = todo.pop()
dep.append(d)
for succ in graph.reverse_list[d]:
if succ not in dep:
todo.append(succ)
dep.pop(0) # remove dist from dep, was there to prevent infinite loops
return dep
|
python
|
def get_dependent_dists(dists, dist):
"""Recursively generate a list of distributions from *dists* that are
dependent on *dist*.
:param dists: a list of distributions
:param dist: a distribution, member of *dists* for which we are interested
"""
if dist not in dists:
raise DistlibException('given distribution %r is not a member '
'of the list' % dist.name)
graph = make_graph(dists)
dep = [dist] # dependent distributions
todo = graph.reverse_list[dist] # list of nodes we should inspect
while todo:
d = todo.pop()
dep.append(d)
for succ in graph.reverse_list[d]:
if succ not in dep:
todo.append(succ)
dep.pop(0) # remove dist from dep, was there to prevent infinite loops
return dep
|
[
"def",
"get_dependent_dists",
"(",
"dists",
",",
"dist",
")",
":",
"if",
"dist",
"not",
"in",
"dists",
":",
"raise",
"DistlibException",
"(",
"'given distribution %r is not a member '",
"'of the list'",
"%",
"dist",
".",
"name",
")",
"graph",
"=",
"make_graph",
"(",
"dists",
")",
"dep",
"=",
"[",
"dist",
"]",
"# dependent distributions",
"todo",
"=",
"graph",
".",
"reverse_list",
"[",
"dist",
"]",
"# list of nodes we should inspect",
"while",
"todo",
":",
"d",
"=",
"todo",
".",
"pop",
"(",
")",
"dep",
".",
"append",
"(",
"d",
")",
"for",
"succ",
"in",
"graph",
".",
"reverse_list",
"[",
"d",
"]",
":",
"if",
"succ",
"not",
"in",
"dep",
":",
"todo",
".",
"append",
"(",
"succ",
")",
"dep",
".",
"pop",
"(",
"0",
")",
"# remove dist from dep, was there to prevent infinite loops",
"return",
"dep"
] |
Recursively generate a list of distributions from *dists* that are
dependent on *dist*.
:param dists: a list of distributions
:param dist: a distribution, member of *dists* for which we are interested
|
[
"Recursively",
"generate",
"a",
"list",
"of",
"distributions",
"from",
"*",
"dists",
"*",
"that",
"are",
"dependent",
"on",
"*",
"dist",
"*",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1279-L1302
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
get_required_dists
|
def get_required_dists(dists, dist):
"""Recursively generate a list of distributions from *dists* that are
required by *dist*.
:param dists: a list of distributions
:param dist: a distribution, member of *dists* for which we are interested
"""
if dist not in dists:
raise DistlibException('given distribution %r is not a member '
'of the list' % dist.name)
graph = make_graph(dists)
req = [] # required distributions
todo = graph.adjacency_list[dist] # list of nodes we should inspect
while todo:
d = todo.pop()[0]
req.append(d)
for pred in graph.adjacency_list[d]:
if pred not in req:
todo.append(pred)
return req
|
python
|
def get_required_dists(dists, dist):
"""Recursively generate a list of distributions from *dists* that are
required by *dist*.
:param dists: a list of distributions
:param dist: a distribution, member of *dists* for which we are interested
"""
if dist not in dists:
raise DistlibException('given distribution %r is not a member '
'of the list' % dist.name)
graph = make_graph(dists)
req = [] # required distributions
todo = graph.adjacency_list[dist] # list of nodes we should inspect
while todo:
d = todo.pop()[0]
req.append(d)
for pred in graph.adjacency_list[d]:
if pred not in req:
todo.append(pred)
return req
|
[
"def",
"get_required_dists",
"(",
"dists",
",",
"dist",
")",
":",
"if",
"dist",
"not",
"in",
"dists",
":",
"raise",
"DistlibException",
"(",
"'given distribution %r is not a member '",
"'of the list'",
"%",
"dist",
".",
"name",
")",
"graph",
"=",
"make_graph",
"(",
"dists",
")",
"req",
"=",
"[",
"]",
"# required distributions",
"todo",
"=",
"graph",
".",
"adjacency_list",
"[",
"dist",
"]",
"# list of nodes we should inspect",
"while",
"todo",
":",
"d",
"=",
"todo",
".",
"pop",
"(",
")",
"[",
"0",
"]",
"req",
".",
"append",
"(",
"d",
")",
"for",
"pred",
"in",
"graph",
".",
"adjacency_list",
"[",
"d",
"]",
":",
"if",
"pred",
"not",
"in",
"req",
":",
"todo",
".",
"append",
"(",
"pred",
")",
"return",
"req"
] |
Recursively generate a list of distributions from *dists* that are
required by *dist*.
:param dists: a list of distributions
:param dist: a distribution, member of *dists* for which we are interested
|
[
"Recursively",
"generate",
"a",
"list",
"of",
"distributions",
"from",
"*",
"dists",
"*",
"that",
"are",
"required",
"by",
"*",
"dist",
"*",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1305-L1327
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
make_dist
|
def make_dist(name, version, **kwargs):
"""
A convenience method for making a dist given just a name and version.
"""
summary = kwargs.pop('summary', 'Placeholder for summary')
md = Metadata(**kwargs)
md.name = name
md.version = version
md.summary = summary or 'Placeholder for summary'
return Distribution(md)
|
python
|
def make_dist(name, version, **kwargs):
"""
A convenience method for making a dist given just a name and version.
"""
summary = kwargs.pop('summary', 'Placeholder for summary')
md = Metadata(**kwargs)
md.name = name
md.version = version
md.summary = summary or 'Placeholder for summary'
return Distribution(md)
|
[
"def",
"make_dist",
"(",
"name",
",",
"version",
",",
"*",
"*",
"kwargs",
")",
":",
"summary",
"=",
"kwargs",
".",
"pop",
"(",
"'summary'",
",",
"'Placeholder for summary'",
")",
"md",
"=",
"Metadata",
"(",
"*",
"*",
"kwargs",
")",
"md",
".",
"name",
"=",
"name",
"md",
".",
"version",
"=",
"version",
"md",
".",
"summary",
"=",
"summary",
"or",
"'Placeholder for summary'",
"return",
"Distribution",
"(",
"md",
")"
] |
A convenience method for making a dist given just a name and version.
|
[
"A",
"convenience",
"method",
"for",
"making",
"a",
"dist",
"given",
"just",
"a",
"name",
"and",
"version",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1330-L1339
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
_Cache.clear
|
def clear(self):
"""
Clear the cache, setting it to its initial state.
"""
self.name.clear()
self.path.clear()
self.generated = False
|
python
|
def clear(self):
"""
Clear the cache, setting it to its initial state.
"""
self.name.clear()
self.path.clear()
self.generated = False
|
[
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"name",
".",
"clear",
"(",
")",
"self",
".",
"path",
".",
"clear",
"(",
")",
"self",
".",
"generated",
"=",
"False"
] |
Clear the cache, setting it to its initial state.
|
[
"Clear",
"the",
"cache",
"setting",
"it",
"to",
"its",
"initial",
"state",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L57-L63
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
_Cache.add
|
def add(self, dist):
"""
Add a distribution to the cache.
:param dist: The distribution to add.
"""
if dist.path not in self.path:
self.path[dist.path] = dist
self.name.setdefault(dist.key, []).append(dist)
|
python
|
def add(self, dist):
"""
Add a distribution to the cache.
:param dist: The distribution to add.
"""
if dist.path not in self.path:
self.path[dist.path] = dist
self.name.setdefault(dist.key, []).append(dist)
|
[
"def",
"add",
"(",
"self",
",",
"dist",
")",
":",
"if",
"dist",
".",
"path",
"not",
"in",
"self",
".",
"path",
":",
"self",
".",
"path",
"[",
"dist",
".",
"path",
"]",
"=",
"dist",
"self",
".",
"name",
".",
"setdefault",
"(",
"dist",
".",
"key",
",",
"[",
"]",
")",
".",
"append",
"(",
"dist",
")"
] |
Add a distribution to the cache.
:param dist: The distribution to add.
|
[
"Add",
"a",
"distribution",
"to",
"the",
"cache",
".",
":",
"param",
"dist",
":",
"The",
"distribution",
"to",
"add",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L65-L72
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
DistributionPath._generate_cache
|
def _generate_cache(self):
"""
Scan the path for distributions and populate the cache with
those that are found.
"""
gen_dist = not self._cache.generated
gen_egg = self._include_egg and not self._cache_egg.generated
if gen_dist or gen_egg:
for dist in self._yield_distributions():
if isinstance(dist, InstalledDistribution):
self._cache.add(dist)
else:
self._cache_egg.add(dist)
if gen_dist:
self._cache.generated = True
if gen_egg:
self._cache_egg.generated = True
|
python
|
def _generate_cache(self):
"""
Scan the path for distributions and populate the cache with
those that are found.
"""
gen_dist = not self._cache.generated
gen_egg = self._include_egg and not self._cache_egg.generated
if gen_dist or gen_egg:
for dist in self._yield_distributions():
if isinstance(dist, InstalledDistribution):
self._cache.add(dist)
else:
self._cache_egg.add(dist)
if gen_dist:
self._cache.generated = True
if gen_egg:
self._cache_egg.generated = True
|
[
"def",
"_generate_cache",
"(",
"self",
")",
":",
"gen_dist",
"=",
"not",
"self",
".",
"_cache",
".",
"generated",
"gen_egg",
"=",
"self",
".",
"_include_egg",
"and",
"not",
"self",
".",
"_cache_egg",
".",
"generated",
"if",
"gen_dist",
"or",
"gen_egg",
":",
"for",
"dist",
"in",
"self",
".",
"_yield_distributions",
"(",
")",
":",
"if",
"isinstance",
"(",
"dist",
",",
"InstalledDistribution",
")",
":",
"self",
".",
"_cache",
".",
"add",
"(",
"dist",
")",
"else",
":",
"self",
".",
"_cache_egg",
".",
"add",
"(",
"dist",
")",
"if",
"gen_dist",
":",
"self",
".",
"_cache",
".",
"generated",
"=",
"True",
"if",
"gen_egg",
":",
"self",
".",
"_cache_egg",
".",
"generated",
"=",
"True"
] |
Scan the path for distributions and populate the cache with
those that are found.
|
[
"Scan",
"the",
"path",
"for",
"distributions",
"and",
"populate",
"the",
"cache",
"with",
"those",
"that",
"are",
"found",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L159-L176
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
DistributionPath.distinfo_dirname
|
def distinfo_dirname(cls, name, version):
"""
The *name* and *version* parameters are converted into their
filename-escaped form, i.e. any ``'-'`` characters are replaced
with ``'_'`` other than the one in ``'dist-info'`` and the one
separating the name from the version number.
:parameter name: is converted to a standard distribution name by replacing
any runs of non- alphanumeric characters with a single
``'-'``.
:type name: string
:parameter version: is converted to a standard version string. Spaces
become dots, and all other non-alphanumeric characters
(except dots) become dashes, with runs of multiple
dashes condensed to a single dash.
:type version: string
:returns: directory name
:rtype: string"""
name = name.replace('-', '_')
return '-'.join([name, version]) + DISTINFO_EXT
|
python
|
def distinfo_dirname(cls, name, version):
"""
The *name* and *version* parameters are converted into their
filename-escaped form, i.e. any ``'-'`` characters are replaced
with ``'_'`` other than the one in ``'dist-info'`` and the one
separating the name from the version number.
:parameter name: is converted to a standard distribution name by replacing
any runs of non- alphanumeric characters with a single
``'-'``.
:type name: string
:parameter version: is converted to a standard version string. Spaces
become dots, and all other non-alphanumeric characters
(except dots) become dashes, with runs of multiple
dashes condensed to a single dash.
:type version: string
:returns: directory name
:rtype: string"""
name = name.replace('-', '_')
return '-'.join([name, version]) + DISTINFO_EXT
|
[
"def",
"distinfo_dirname",
"(",
"cls",
",",
"name",
",",
"version",
")",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"return",
"'-'",
".",
"join",
"(",
"[",
"name",
",",
"version",
"]",
")",
"+",
"DISTINFO_EXT"
] |
The *name* and *version* parameters are converted into their
filename-escaped form, i.e. any ``'-'`` characters are replaced
with ``'_'`` other than the one in ``'dist-info'`` and the one
separating the name from the version number.
:parameter name: is converted to a standard distribution name by replacing
any runs of non- alphanumeric characters with a single
``'-'``.
:type name: string
:parameter version: is converted to a standard version string. Spaces
become dots, and all other non-alphanumeric characters
(except dots) become dashes, with runs of multiple
dashes condensed to a single dash.
:type version: string
:returns: directory name
:rtype: string
|
[
"The",
"*",
"name",
"*",
"and",
"*",
"version",
"*",
"parameters",
"are",
"converted",
"into",
"their",
"filename",
"-",
"escaped",
"form",
"i",
".",
"e",
".",
"any",
"-",
"characters",
"are",
"replaced",
"with",
"_",
"other",
"than",
"the",
"one",
"in",
"dist",
"-",
"info",
"and",
"the",
"one",
"separating",
"the",
"name",
"from",
"the",
"version",
"number",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L179-L198
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
DistributionPath.get_distributions
|
def get_distributions(self):
"""
Provides an iterator that looks for distributions and returns
:class:`InstalledDistribution` or
:class:`EggInfoDistribution` instances for each one of them.
:rtype: iterator of :class:`InstalledDistribution` and
:class:`EggInfoDistribution` instances
"""
if not self._cache_enabled:
for dist in self._yield_distributions():
yield dist
else:
self._generate_cache()
for dist in self._cache.path.values():
yield dist
if self._include_egg:
for dist in self._cache_egg.path.values():
yield dist
|
python
|
def get_distributions(self):
"""
Provides an iterator that looks for distributions and returns
:class:`InstalledDistribution` or
:class:`EggInfoDistribution` instances for each one of them.
:rtype: iterator of :class:`InstalledDistribution` and
:class:`EggInfoDistribution` instances
"""
if not self._cache_enabled:
for dist in self._yield_distributions():
yield dist
else:
self._generate_cache()
for dist in self._cache.path.values():
yield dist
if self._include_egg:
for dist in self._cache_egg.path.values():
yield dist
|
[
"def",
"get_distributions",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_cache_enabled",
":",
"for",
"dist",
"in",
"self",
".",
"_yield_distributions",
"(",
")",
":",
"yield",
"dist",
"else",
":",
"self",
".",
"_generate_cache",
"(",
")",
"for",
"dist",
"in",
"self",
".",
"_cache",
".",
"path",
".",
"values",
"(",
")",
":",
"yield",
"dist",
"if",
"self",
".",
"_include_egg",
":",
"for",
"dist",
"in",
"self",
".",
"_cache_egg",
".",
"path",
".",
"values",
"(",
")",
":",
"yield",
"dist"
] |
Provides an iterator that looks for distributions and returns
:class:`InstalledDistribution` or
:class:`EggInfoDistribution` instances for each one of them.
:rtype: iterator of :class:`InstalledDistribution` and
:class:`EggInfoDistribution` instances
|
[
"Provides",
"an",
"iterator",
"that",
"looks",
"for",
"distributions",
"and",
"returns",
":",
"class",
":",
"InstalledDistribution",
"or",
":",
"class",
":",
"EggInfoDistribution",
"instances",
"for",
"each",
"one",
"of",
"them",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L200-L220
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
DistributionPath.get_distribution
|
def get_distribution(self, name):
"""
Looks for a named distribution on the path.
This function only returns the first result found, as no more than one
value is expected. If nothing is found, ``None`` is returned.
:rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution`
or ``None``
"""
result = None
name = name.lower()
if not self._cache_enabled:
for dist in self._yield_distributions():
if dist.key == name:
result = dist
break
else:
self._generate_cache()
if name in self._cache.name:
result = self._cache.name[name][0]
elif self._include_egg and name in self._cache_egg.name:
result = self._cache_egg.name[name][0]
return result
|
python
|
def get_distribution(self, name):
"""
Looks for a named distribution on the path.
This function only returns the first result found, as no more than one
value is expected. If nothing is found, ``None`` is returned.
:rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution`
or ``None``
"""
result = None
name = name.lower()
if not self._cache_enabled:
for dist in self._yield_distributions():
if dist.key == name:
result = dist
break
else:
self._generate_cache()
if name in self._cache.name:
result = self._cache.name[name][0]
elif self._include_egg and name in self._cache_egg.name:
result = self._cache_egg.name[name][0]
return result
|
[
"def",
"get_distribution",
"(",
"self",
",",
"name",
")",
":",
"result",
"=",
"None",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"not",
"self",
".",
"_cache_enabled",
":",
"for",
"dist",
"in",
"self",
".",
"_yield_distributions",
"(",
")",
":",
"if",
"dist",
".",
"key",
"==",
"name",
":",
"result",
"=",
"dist",
"break",
"else",
":",
"self",
".",
"_generate_cache",
"(",
")",
"if",
"name",
"in",
"self",
".",
"_cache",
".",
"name",
":",
"result",
"=",
"self",
".",
"_cache",
".",
"name",
"[",
"name",
"]",
"[",
"0",
"]",
"elif",
"self",
".",
"_include_egg",
"and",
"name",
"in",
"self",
".",
"_cache_egg",
".",
"name",
":",
"result",
"=",
"self",
".",
"_cache_egg",
".",
"name",
"[",
"name",
"]",
"[",
"0",
"]",
"return",
"result"
] |
Looks for a named distribution on the path.
This function only returns the first result found, as no more than one
value is expected. If nothing is found, ``None`` is returned.
:rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution`
or ``None``
|
[
"Looks",
"for",
"a",
"named",
"distribution",
"on",
"the",
"path",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L222-L246
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
DistributionPath.provides_distribution
|
def provides_distribution(self, name, version=None):
"""
Iterates over all distributions to find which distributions provide *name*.
If a *version* is provided, it will be used to filter the results.
This function only returns the first result found, since no more than
one values are expected. If the directory is not found, returns ``None``.
:parameter version: a version specifier that indicates the version
required, conforming to the format in ``PEP-345``
:type name: string
:type version: string
"""
matcher = None
if version is not None:
try:
matcher = self._scheme.matcher('%s (%s)' % (name, version))
except ValueError:
raise DistlibException('invalid name or version: %r, %r' %
(name, version))
for dist in self.get_distributions():
# We hit a problem on Travis where enum34 was installed and doesn't
# have a provides attribute ...
if not hasattr(dist, 'provides'):
logger.debug('No "provides": %s', dist)
else:
provided = dist.provides
for p in provided:
p_name, p_ver = parse_name_and_version(p)
if matcher is None:
if p_name == name:
yield dist
break
else:
if p_name == name and matcher.match(p_ver):
yield dist
break
|
python
|
def provides_distribution(self, name, version=None):
"""
Iterates over all distributions to find which distributions provide *name*.
If a *version* is provided, it will be used to filter the results.
This function only returns the first result found, since no more than
one values are expected. If the directory is not found, returns ``None``.
:parameter version: a version specifier that indicates the version
required, conforming to the format in ``PEP-345``
:type name: string
:type version: string
"""
matcher = None
if version is not None:
try:
matcher = self._scheme.matcher('%s (%s)' % (name, version))
except ValueError:
raise DistlibException('invalid name or version: %r, %r' %
(name, version))
for dist in self.get_distributions():
# We hit a problem on Travis where enum34 was installed and doesn't
# have a provides attribute ...
if not hasattr(dist, 'provides'):
logger.debug('No "provides": %s', dist)
else:
provided = dist.provides
for p in provided:
p_name, p_ver = parse_name_and_version(p)
if matcher is None:
if p_name == name:
yield dist
break
else:
if p_name == name and matcher.match(p_ver):
yield dist
break
|
[
"def",
"provides_distribution",
"(",
"self",
",",
"name",
",",
"version",
"=",
"None",
")",
":",
"matcher",
"=",
"None",
"if",
"version",
"is",
"not",
"None",
":",
"try",
":",
"matcher",
"=",
"self",
".",
"_scheme",
".",
"matcher",
"(",
"'%s (%s)'",
"%",
"(",
"name",
",",
"version",
")",
")",
"except",
"ValueError",
":",
"raise",
"DistlibException",
"(",
"'invalid name or version: %r, %r'",
"%",
"(",
"name",
",",
"version",
")",
")",
"for",
"dist",
"in",
"self",
".",
"get_distributions",
"(",
")",
":",
"# We hit a problem on Travis where enum34 was installed and doesn't",
"# have a provides attribute ...",
"if",
"not",
"hasattr",
"(",
"dist",
",",
"'provides'",
")",
":",
"logger",
".",
"debug",
"(",
"'No \"provides\": %s'",
",",
"dist",
")",
"else",
":",
"provided",
"=",
"dist",
".",
"provides",
"for",
"p",
"in",
"provided",
":",
"p_name",
",",
"p_ver",
"=",
"parse_name_and_version",
"(",
"p",
")",
"if",
"matcher",
"is",
"None",
":",
"if",
"p_name",
"==",
"name",
":",
"yield",
"dist",
"break",
"else",
":",
"if",
"p_name",
"==",
"name",
"and",
"matcher",
".",
"match",
"(",
"p_ver",
")",
":",
"yield",
"dist",
"break"
] |
Iterates over all distributions to find which distributions provide *name*.
If a *version* is provided, it will be used to filter the results.
This function only returns the first result found, since no more than
one values are expected. If the directory is not found, returns ``None``.
:parameter version: a version specifier that indicates the version
required, conforming to the format in ``PEP-345``
:type name: string
:type version: string
|
[
"Iterates",
"over",
"all",
"distributions",
"to",
"find",
"which",
"distributions",
"provide",
"*",
"name",
"*",
".",
"If",
"a",
"*",
"version",
"*",
"is",
"provided",
"it",
"will",
"be",
"used",
"to",
"filter",
"the",
"results",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L248-L287
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
DistributionPath.get_file_path
|
def get_file_path(self, name, relative_path):
"""
Return the path to a resource file.
"""
dist = self.get_distribution(name)
if dist is None:
raise LookupError('no distribution named %r found' % name)
return dist.get_resource_path(relative_path)
|
python
|
def get_file_path(self, name, relative_path):
"""
Return the path to a resource file.
"""
dist = self.get_distribution(name)
if dist is None:
raise LookupError('no distribution named %r found' % name)
return dist.get_resource_path(relative_path)
|
[
"def",
"get_file_path",
"(",
"self",
",",
"name",
",",
"relative_path",
")",
":",
"dist",
"=",
"self",
".",
"get_distribution",
"(",
"name",
")",
"if",
"dist",
"is",
"None",
":",
"raise",
"LookupError",
"(",
"'no distribution named %r found'",
"%",
"name",
")",
"return",
"dist",
".",
"get_resource_path",
"(",
"relative_path",
")"
] |
Return the path to a resource file.
|
[
"Return",
"the",
"path",
"to",
"a",
"resource",
"file",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L289-L296
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
DistributionPath.get_exported_entries
|
def get_exported_entries(self, category, name=None):
"""
Return all of the exported entries in a particular category.
:param category: The category to search for entries.
:param name: If specified, only entries with that name are returned.
"""
for dist in self.get_distributions():
r = dist.exports
if category in r:
d = r[category]
if name is not None:
if name in d:
yield d[name]
else:
for v in d.values():
yield v
|
python
|
def get_exported_entries(self, category, name=None):
"""
Return all of the exported entries in a particular category.
:param category: The category to search for entries.
:param name: If specified, only entries with that name are returned.
"""
for dist in self.get_distributions():
r = dist.exports
if category in r:
d = r[category]
if name is not None:
if name in d:
yield d[name]
else:
for v in d.values():
yield v
|
[
"def",
"get_exported_entries",
"(",
"self",
",",
"category",
",",
"name",
"=",
"None",
")",
":",
"for",
"dist",
"in",
"self",
".",
"get_distributions",
"(",
")",
":",
"r",
"=",
"dist",
".",
"exports",
"if",
"category",
"in",
"r",
":",
"d",
"=",
"r",
"[",
"category",
"]",
"if",
"name",
"is",
"not",
"None",
":",
"if",
"name",
"in",
"d",
":",
"yield",
"d",
"[",
"name",
"]",
"else",
":",
"for",
"v",
"in",
"d",
".",
"values",
"(",
")",
":",
"yield",
"v"
] |
Return all of the exported entries in a particular category.
:param category: The category to search for entries.
:param name: If specified, only entries with that name are returned.
|
[
"Return",
"all",
"of",
"the",
"exported",
"entries",
"in",
"a",
"particular",
"category",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L298-L314
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
Distribution.provides
|
def provides(self):
"""
A set of distribution names and versions provided by this distribution.
:return: A set of "name (version)" strings.
"""
plist = self.metadata.provides
s = '%s (%s)' % (self.name, self.version)
if s not in plist:
plist.append(s)
return plist
|
python
|
def provides(self):
"""
A set of distribution names and versions provided by this distribution.
:return: A set of "name (version)" strings.
"""
plist = self.metadata.provides
s = '%s (%s)' % (self.name, self.version)
if s not in plist:
plist.append(s)
return plist
|
[
"def",
"provides",
"(",
"self",
")",
":",
"plist",
"=",
"self",
".",
"metadata",
".",
"provides",
"s",
"=",
"'%s (%s)'",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"version",
")",
"if",
"s",
"not",
"in",
"plist",
":",
"plist",
".",
"append",
"(",
"s",
")",
"return",
"plist"
] |
A set of distribution names and versions provided by this distribution.
:return: A set of "name (version)" strings.
|
[
"A",
"set",
"of",
"distribution",
"names",
"and",
"versions",
"provided",
"by",
"this",
"distribution",
".",
":",
"return",
":",
"A",
"set",
"of",
"name",
"(",
"version",
")",
"strings",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L369-L378
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
Distribution.matches_requirement
|
def matches_requirement(self, req):
"""
Say if this instance matches (fulfills) a requirement.
:param req: The requirement to match.
:rtype req: str
:return: True if it matches, else False.
"""
# Requirement may contain extras - parse to lose those
# from what's passed to the matcher
r = parse_requirement(req)
scheme = get_scheme(self.metadata.scheme)
try:
matcher = scheme.matcher(r.requirement)
except UnsupportedVersionError:
# XXX compat-mode if cannot read the version
logger.warning('could not read version %r - using name only',
req)
name = req.split()[0]
matcher = scheme.matcher(name)
name = matcher.key # case-insensitive
result = False
for p in self.provides:
p_name, p_ver = parse_name_and_version(p)
if p_name != name:
continue
try:
result = matcher.match(p_ver)
break
except UnsupportedVersionError:
pass
return result
|
python
|
def matches_requirement(self, req):
"""
Say if this instance matches (fulfills) a requirement.
:param req: The requirement to match.
:rtype req: str
:return: True if it matches, else False.
"""
# Requirement may contain extras - parse to lose those
# from what's passed to the matcher
r = parse_requirement(req)
scheme = get_scheme(self.metadata.scheme)
try:
matcher = scheme.matcher(r.requirement)
except UnsupportedVersionError:
# XXX compat-mode if cannot read the version
logger.warning('could not read version %r - using name only',
req)
name = req.split()[0]
matcher = scheme.matcher(name)
name = matcher.key # case-insensitive
result = False
for p in self.provides:
p_name, p_ver = parse_name_and_version(p)
if p_name != name:
continue
try:
result = matcher.match(p_ver)
break
except UnsupportedVersionError:
pass
return result
|
[
"def",
"matches_requirement",
"(",
"self",
",",
"req",
")",
":",
"# Requirement may contain extras - parse to lose those",
"# from what's passed to the matcher",
"r",
"=",
"parse_requirement",
"(",
"req",
")",
"scheme",
"=",
"get_scheme",
"(",
"self",
".",
"metadata",
".",
"scheme",
")",
"try",
":",
"matcher",
"=",
"scheme",
".",
"matcher",
"(",
"r",
".",
"requirement",
")",
"except",
"UnsupportedVersionError",
":",
"# XXX compat-mode if cannot read the version",
"logger",
".",
"warning",
"(",
"'could not read version %r - using name only'",
",",
"req",
")",
"name",
"=",
"req",
".",
"split",
"(",
")",
"[",
"0",
"]",
"matcher",
"=",
"scheme",
".",
"matcher",
"(",
"name",
")",
"name",
"=",
"matcher",
".",
"key",
"# case-insensitive",
"result",
"=",
"False",
"for",
"p",
"in",
"self",
".",
"provides",
":",
"p_name",
",",
"p_ver",
"=",
"parse_name_and_version",
"(",
"p",
")",
"if",
"p_name",
"!=",
"name",
":",
"continue",
"try",
":",
"result",
"=",
"matcher",
".",
"match",
"(",
"p_ver",
")",
"break",
"except",
"UnsupportedVersionError",
":",
"pass",
"return",
"result"
] |
Say if this instance matches (fulfills) a requirement.
:param req: The requirement to match.
:rtype req: str
:return: True if it matches, else False.
|
[
"Say",
"if",
"this",
"instance",
"matches",
"(",
"fulfills",
")",
"a",
"requirement",
".",
":",
"param",
"req",
":",
"The",
"requirement",
"to",
"match",
".",
":",
"rtype",
"req",
":",
"str",
":",
"return",
":",
"True",
"if",
"it",
"matches",
"else",
"False",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L407-L439
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
BaseInstalledDistribution.get_hash
|
def get_hash(self, data, hasher=None):
"""
Get the hash of some data, using a particular hash algorithm, if
specified.
:param data: The data to be hashed.
:type data: bytes
:param hasher: The name of a hash implementation, supported by hashlib,
or ``None``. Examples of valid values are ``'sha1'``,
``'sha224'``, ``'sha384'``, '``sha256'``, ``'md5'`` and
``'sha512'``. If no hasher is specified, the ``hasher``
attribute of the :class:`InstalledDistribution` instance
is used. If the hasher is determined to be ``None``, MD5
is used as the hashing algorithm.
:returns: The hash of the data. If a hasher was explicitly specified,
the returned hash will be prefixed with the specified hasher
followed by '='.
:rtype: str
"""
if hasher is None:
hasher = self.hasher
if hasher is None:
hasher = hashlib.md5
prefix = ''
else:
hasher = getattr(hashlib, hasher)
prefix = '%s=' % self.hasher
digest = hasher(data).digest()
digest = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii')
return '%s%s' % (prefix, digest)
|
python
|
def get_hash(self, data, hasher=None):
"""
Get the hash of some data, using a particular hash algorithm, if
specified.
:param data: The data to be hashed.
:type data: bytes
:param hasher: The name of a hash implementation, supported by hashlib,
or ``None``. Examples of valid values are ``'sha1'``,
``'sha224'``, ``'sha384'``, '``sha256'``, ``'md5'`` and
``'sha512'``. If no hasher is specified, the ``hasher``
attribute of the :class:`InstalledDistribution` instance
is used. If the hasher is determined to be ``None``, MD5
is used as the hashing algorithm.
:returns: The hash of the data. If a hasher was explicitly specified,
the returned hash will be prefixed with the specified hasher
followed by '='.
:rtype: str
"""
if hasher is None:
hasher = self.hasher
if hasher is None:
hasher = hashlib.md5
prefix = ''
else:
hasher = getattr(hashlib, hasher)
prefix = '%s=' % self.hasher
digest = hasher(data).digest()
digest = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii')
return '%s%s' % (prefix, digest)
|
[
"def",
"get_hash",
"(",
"self",
",",
"data",
",",
"hasher",
"=",
"None",
")",
":",
"if",
"hasher",
"is",
"None",
":",
"hasher",
"=",
"self",
".",
"hasher",
"if",
"hasher",
"is",
"None",
":",
"hasher",
"=",
"hashlib",
".",
"md5",
"prefix",
"=",
"''",
"else",
":",
"hasher",
"=",
"getattr",
"(",
"hashlib",
",",
"hasher",
")",
"prefix",
"=",
"'%s='",
"%",
"self",
".",
"hasher",
"digest",
"=",
"hasher",
"(",
"data",
")",
".",
"digest",
"(",
")",
"digest",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"digest",
")",
".",
"rstrip",
"(",
"b'='",
")",
".",
"decode",
"(",
"'ascii'",
")",
"return",
"'%s%s'",
"%",
"(",
"prefix",
",",
"digest",
")"
] |
Get the hash of some data, using a particular hash algorithm, if
specified.
:param data: The data to be hashed.
:type data: bytes
:param hasher: The name of a hash implementation, supported by hashlib,
or ``None``. Examples of valid values are ``'sha1'``,
``'sha224'``, ``'sha384'``, '``sha256'``, ``'md5'`` and
``'sha512'``. If no hasher is specified, the ``hasher``
attribute of the :class:`InstalledDistribution` instance
is used. If the hasher is determined to be ``None``, MD5
is used as the hashing algorithm.
:returns: The hash of the data. If a hasher was explicitly specified,
the returned hash will be prefixed with the specified hasher
followed by '='.
:rtype: str
|
[
"Get",
"the",
"hash",
"of",
"some",
"data",
"using",
"a",
"particular",
"hash",
"algorithm",
"if",
"specified",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L497-L526
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
InstalledDistribution._get_records
|
def _get_records(self):
"""
Get the list of installed files for the distribution
:return: A list of tuples of path, hash and size. Note that hash and
size might be ``None`` for some entries. The path is exactly
as stored in the file (which is as in PEP 376).
"""
results = []
r = self.get_distinfo_resource('RECORD')
with contextlib.closing(r.as_stream()) as stream:
with CSVReader(stream=stream) as record_reader:
# Base location is parent dir of .dist-info dir
#base_location = os.path.dirname(self.path)
#base_location = os.path.abspath(base_location)
for row in record_reader:
missing = [None for i in range(len(row), 3)]
path, checksum, size = row + missing
#if not os.path.isabs(path):
# path = path.replace('/', os.sep)
# path = os.path.join(base_location, path)
results.append((path, checksum, size))
return results
|
python
|
def _get_records(self):
"""
Get the list of installed files for the distribution
:return: A list of tuples of path, hash and size. Note that hash and
size might be ``None`` for some entries. The path is exactly
as stored in the file (which is as in PEP 376).
"""
results = []
r = self.get_distinfo_resource('RECORD')
with contextlib.closing(r.as_stream()) as stream:
with CSVReader(stream=stream) as record_reader:
# Base location is parent dir of .dist-info dir
#base_location = os.path.dirname(self.path)
#base_location = os.path.abspath(base_location)
for row in record_reader:
missing = [None for i in range(len(row), 3)]
path, checksum, size = row + missing
#if not os.path.isabs(path):
# path = path.replace('/', os.sep)
# path = os.path.join(base_location, path)
results.append((path, checksum, size))
return results
|
[
"def",
"_get_records",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"r",
"=",
"self",
".",
"get_distinfo_resource",
"(",
"'RECORD'",
")",
"with",
"contextlib",
".",
"closing",
"(",
"r",
".",
"as_stream",
"(",
")",
")",
"as",
"stream",
":",
"with",
"CSVReader",
"(",
"stream",
"=",
"stream",
")",
"as",
"record_reader",
":",
"# Base location is parent dir of .dist-info dir",
"#base_location = os.path.dirname(self.path)",
"#base_location = os.path.abspath(base_location)",
"for",
"row",
"in",
"record_reader",
":",
"missing",
"=",
"[",
"None",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"row",
")",
",",
"3",
")",
"]",
"path",
",",
"checksum",
",",
"size",
"=",
"row",
"+",
"missing",
"#if not os.path.isabs(path):",
"# path = path.replace('/', os.sep)",
"# path = os.path.join(base_location, path)",
"results",
".",
"append",
"(",
"(",
"path",
",",
"checksum",
",",
"size",
")",
")",
"return",
"results"
] |
Get the list of installed files for the distribution
:return: A list of tuples of path, hash and size. Note that hash and
size might be ``None`` for some entries. The path is exactly
as stored in the file (which is as in PEP 376).
|
[
"Get",
"the",
"list",
"of",
"installed",
"files",
"for",
"the",
"distribution",
":",
"return",
":",
"A",
"list",
"of",
"tuples",
"of",
"path",
"hash",
"and",
"size",
".",
"Note",
"that",
"hash",
"and",
"size",
"might",
"be",
"None",
"for",
"some",
"entries",
".",
"The",
"path",
"is",
"exactly",
"as",
"stored",
"in",
"the",
"file",
"(",
"which",
"is",
"as",
"in",
"PEP",
"376",
")",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L580-L601
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
InstalledDistribution.exports
|
def exports(self):
"""
Return the information exported by this distribution.
:return: A dictionary of exports, mapping an export category to a dict
of :class:`ExportEntry` instances describing the individual
export entries, and keyed by name.
"""
result = {}
r = self.get_distinfo_resource(EXPORTS_FILENAME)
if r:
result = self.read_exports()
return result
|
python
|
def exports(self):
"""
Return the information exported by this distribution.
:return: A dictionary of exports, mapping an export category to a dict
of :class:`ExportEntry` instances describing the individual
export entries, and keyed by name.
"""
result = {}
r = self.get_distinfo_resource(EXPORTS_FILENAME)
if r:
result = self.read_exports()
return result
|
[
"def",
"exports",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"r",
"=",
"self",
".",
"get_distinfo_resource",
"(",
"EXPORTS_FILENAME",
")",
"if",
"r",
":",
"result",
"=",
"self",
".",
"read_exports",
"(",
")",
"return",
"result"
] |
Return the information exported by this distribution.
:return: A dictionary of exports, mapping an export category to a dict
of :class:`ExportEntry` instances describing the individual
export entries, and keyed by name.
|
[
"Return",
"the",
"information",
"exported",
"by",
"this",
"distribution",
".",
":",
"return",
":",
"A",
"dictionary",
"of",
"exports",
"mapping",
"an",
"export",
"category",
"to",
"a",
"dict",
"of",
":",
"class",
":",
"ExportEntry",
"instances",
"describing",
"the",
"individual",
"export",
"entries",
"and",
"keyed",
"by",
"name",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L604-L615
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
InstalledDistribution.read_exports
|
def read_exports(self):
"""
Read exports data from a file in .ini format.
:return: A dictionary of exports, mapping an export category to a list
of :class:`ExportEntry` instances describing the individual
export entries.
"""
result = {}
r = self.get_distinfo_resource(EXPORTS_FILENAME)
if r:
with contextlib.closing(r.as_stream()) as stream:
result = read_exports(stream)
return result
|
python
|
def read_exports(self):
"""
Read exports data from a file in .ini format.
:return: A dictionary of exports, mapping an export category to a list
of :class:`ExportEntry` instances describing the individual
export entries.
"""
result = {}
r = self.get_distinfo_resource(EXPORTS_FILENAME)
if r:
with contextlib.closing(r.as_stream()) as stream:
result = read_exports(stream)
return result
|
[
"def",
"read_exports",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"r",
"=",
"self",
".",
"get_distinfo_resource",
"(",
"EXPORTS_FILENAME",
")",
"if",
"r",
":",
"with",
"contextlib",
".",
"closing",
"(",
"r",
".",
"as_stream",
"(",
")",
")",
"as",
"stream",
":",
"result",
"=",
"read_exports",
"(",
"stream",
")",
"return",
"result"
] |
Read exports data from a file in .ini format.
:return: A dictionary of exports, mapping an export category to a list
of :class:`ExportEntry` instances describing the individual
export entries.
|
[
"Read",
"exports",
"data",
"from",
"a",
"file",
"in",
".",
"ini",
"format",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L617-L630
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
InstalledDistribution.write_exports
|
def write_exports(self, exports):
"""
Write a dictionary of exports to a file in .ini format.
:param exports: A dictionary of exports, mapping an export category to
a list of :class:`ExportEntry` instances describing the
individual export entries.
"""
rf = self.get_distinfo_file(EXPORTS_FILENAME)
with open(rf, 'w') as f:
write_exports(exports, f)
|
python
|
def write_exports(self, exports):
"""
Write a dictionary of exports to a file in .ini format.
:param exports: A dictionary of exports, mapping an export category to
a list of :class:`ExportEntry` instances describing the
individual export entries.
"""
rf = self.get_distinfo_file(EXPORTS_FILENAME)
with open(rf, 'w') as f:
write_exports(exports, f)
|
[
"def",
"write_exports",
"(",
"self",
",",
"exports",
")",
":",
"rf",
"=",
"self",
".",
"get_distinfo_file",
"(",
"EXPORTS_FILENAME",
")",
"with",
"open",
"(",
"rf",
",",
"'w'",
")",
"as",
"f",
":",
"write_exports",
"(",
"exports",
",",
"f",
")"
] |
Write a dictionary of exports to a file in .ini format.
:param exports: A dictionary of exports, mapping an export category to
a list of :class:`ExportEntry` instances describing the
individual export entries.
|
[
"Write",
"a",
"dictionary",
"of",
"exports",
"to",
"a",
"file",
"in",
".",
"ini",
"format",
".",
":",
"param",
"exports",
":",
"A",
"dictionary",
"of",
"exports",
"mapping",
"an",
"export",
"category",
"to",
"a",
"list",
"of",
":",
"class",
":",
"ExportEntry",
"instances",
"describing",
"the",
"individual",
"export",
"entries",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L632-L641
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
InstalledDistribution.get_resource_path
|
def get_resource_path(self, relative_path):
"""
NOTE: This API may change in the future.
Return the absolute path to a resource file with the given relative
path.
:param relative_path: The path, relative to .dist-info, of the resource
of interest.
:return: The absolute path where the resource is to be found.
"""
r = self.get_distinfo_resource('RESOURCES')
with contextlib.closing(r.as_stream()) as stream:
with CSVReader(stream=stream) as resources_reader:
for relative, destination in resources_reader:
if relative == relative_path:
return destination
raise KeyError('no resource file with relative path %r '
'is installed' % relative_path)
|
python
|
def get_resource_path(self, relative_path):
"""
NOTE: This API may change in the future.
Return the absolute path to a resource file with the given relative
path.
:param relative_path: The path, relative to .dist-info, of the resource
of interest.
:return: The absolute path where the resource is to be found.
"""
r = self.get_distinfo_resource('RESOURCES')
with contextlib.closing(r.as_stream()) as stream:
with CSVReader(stream=stream) as resources_reader:
for relative, destination in resources_reader:
if relative == relative_path:
return destination
raise KeyError('no resource file with relative path %r '
'is installed' % relative_path)
|
[
"def",
"get_resource_path",
"(",
"self",
",",
"relative_path",
")",
":",
"r",
"=",
"self",
".",
"get_distinfo_resource",
"(",
"'RESOURCES'",
")",
"with",
"contextlib",
".",
"closing",
"(",
"r",
".",
"as_stream",
"(",
")",
")",
"as",
"stream",
":",
"with",
"CSVReader",
"(",
"stream",
"=",
"stream",
")",
"as",
"resources_reader",
":",
"for",
"relative",
",",
"destination",
"in",
"resources_reader",
":",
"if",
"relative",
"==",
"relative_path",
":",
"return",
"destination",
"raise",
"KeyError",
"(",
"'no resource file with relative path %r '",
"'is installed'",
"%",
"relative_path",
")"
] |
NOTE: This API may change in the future.
Return the absolute path to a resource file with the given relative
path.
:param relative_path: The path, relative to .dist-info, of the resource
of interest.
:return: The absolute path where the resource is to be found.
|
[
"NOTE",
":",
"This",
"API",
"may",
"change",
"in",
"the",
"future",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L643-L661
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
InstalledDistribution.write_installed_files
|
def write_installed_files(self, paths, prefix, dry_run=False):
"""
Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any
existing ``RECORD`` file is silently overwritten.
prefix is used to determine when to write absolute paths.
"""
prefix = os.path.join(prefix, '')
base = os.path.dirname(self.path)
base_under_prefix = base.startswith(prefix)
base = os.path.join(base, '')
record_path = self.get_distinfo_file('RECORD')
logger.info('creating %s', record_path)
if dry_run:
return None
with CSVWriter(record_path) as writer:
for path in paths:
if os.path.isdir(path) or path.endswith(('.pyc', '.pyo')):
# do not put size and hash, as in PEP-376
hash_value = size = ''
else:
size = '%d' % os.path.getsize(path)
with open(path, 'rb') as fp:
hash_value = self.get_hash(fp.read())
if path.startswith(base) or (base_under_prefix and
path.startswith(prefix)):
path = os.path.relpath(path, base)
writer.writerow((path, hash_value, size))
# add the RECORD file itself
if record_path.startswith(base):
record_path = os.path.relpath(record_path, base)
writer.writerow((record_path, '', ''))
return record_path
|
python
|
def write_installed_files(self, paths, prefix, dry_run=False):
"""
Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any
existing ``RECORD`` file is silently overwritten.
prefix is used to determine when to write absolute paths.
"""
prefix = os.path.join(prefix, '')
base = os.path.dirname(self.path)
base_under_prefix = base.startswith(prefix)
base = os.path.join(base, '')
record_path = self.get_distinfo_file('RECORD')
logger.info('creating %s', record_path)
if dry_run:
return None
with CSVWriter(record_path) as writer:
for path in paths:
if os.path.isdir(path) or path.endswith(('.pyc', '.pyo')):
# do not put size and hash, as in PEP-376
hash_value = size = ''
else:
size = '%d' % os.path.getsize(path)
with open(path, 'rb') as fp:
hash_value = self.get_hash(fp.read())
if path.startswith(base) or (base_under_prefix and
path.startswith(prefix)):
path = os.path.relpath(path, base)
writer.writerow((path, hash_value, size))
# add the RECORD file itself
if record_path.startswith(base):
record_path = os.path.relpath(record_path, base)
writer.writerow((record_path, '', ''))
return record_path
|
[
"def",
"write_installed_files",
"(",
"self",
",",
"paths",
",",
"prefix",
",",
"dry_run",
"=",
"False",
")",
":",
"prefix",
"=",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"''",
")",
"base",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"path",
")",
"base_under_prefix",
"=",
"base",
".",
"startswith",
"(",
"prefix",
")",
"base",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"''",
")",
"record_path",
"=",
"self",
".",
"get_distinfo_file",
"(",
"'RECORD'",
")",
"logger",
".",
"info",
"(",
"'creating %s'",
",",
"record_path",
")",
"if",
"dry_run",
":",
"return",
"None",
"with",
"CSVWriter",
"(",
"record_path",
")",
"as",
"writer",
":",
"for",
"path",
"in",
"paths",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
"or",
"path",
".",
"endswith",
"(",
"(",
"'.pyc'",
",",
"'.pyo'",
")",
")",
":",
"# do not put size and hash, as in PEP-376",
"hash_value",
"=",
"size",
"=",
"''",
"else",
":",
"size",
"=",
"'%d'",
"%",
"os",
".",
"path",
".",
"getsize",
"(",
"path",
")",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"fp",
":",
"hash_value",
"=",
"self",
".",
"get_hash",
"(",
"fp",
".",
"read",
"(",
")",
")",
"if",
"path",
".",
"startswith",
"(",
"base",
")",
"or",
"(",
"base_under_prefix",
"and",
"path",
".",
"startswith",
"(",
"prefix",
")",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
",",
"base",
")",
"writer",
".",
"writerow",
"(",
"(",
"path",
",",
"hash_value",
",",
"size",
")",
")",
"# add the RECORD file itself",
"if",
"record_path",
".",
"startswith",
"(",
"base",
")",
":",
"record_path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"record_path",
",",
"base",
")",
"writer",
".",
"writerow",
"(",
"(",
"record_path",
",",
"''",
",",
"''",
")",
")",
"return",
"record_path"
] |
Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any
existing ``RECORD`` file is silently overwritten.
prefix is used to determine when to write absolute paths.
|
[
"Writes",
"the",
"RECORD",
"file",
"using",
"the",
"paths",
"iterable",
"passed",
"in",
".",
"Any",
"existing",
"RECORD",
"file",
"is",
"silently",
"overwritten",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L673-L706
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
InstalledDistribution.check_installed_files
|
def check_installed_files(self):
"""
Checks that the hashes and sizes of the files in ``RECORD`` are
matched by the files themselves. Returns a (possibly empty) list of
mismatches. Each entry in the mismatch list will be a tuple consisting
of the path, 'exists', 'size' or 'hash' according to what didn't match
(existence is checked first, then size, then hash), the expected
value and the actual value.
"""
mismatches = []
base = os.path.dirname(self.path)
record_path = self.get_distinfo_file('RECORD')
for path, hash_value, size in self.list_installed_files():
if not os.path.isabs(path):
path = os.path.join(base, path)
if path == record_path:
continue
if not os.path.exists(path):
mismatches.append((path, 'exists', True, False))
elif os.path.isfile(path):
actual_size = str(os.path.getsize(path))
if size and actual_size != size:
mismatches.append((path, 'size', size, actual_size))
elif hash_value:
if '=' in hash_value:
hasher = hash_value.split('=', 1)[0]
else:
hasher = None
with open(path, 'rb') as f:
actual_hash = self.get_hash(f.read(), hasher)
if actual_hash != hash_value:
mismatches.append((path, 'hash', hash_value, actual_hash))
return mismatches
|
python
|
def check_installed_files(self):
"""
Checks that the hashes and sizes of the files in ``RECORD`` are
matched by the files themselves. Returns a (possibly empty) list of
mismatches. Each entry in the mismatch list will be a tuple consisting
of the path, 'exists', 'size' or 'hash' according to what didn't match
(existence is checked first, then size, then hash), the expected
value and the actual value.
"""
mismatches = []
base = os.path.dirname(self.path)
record_path = self.get_distinfo_file('RECORD')
for path, hash_value, size in self.list_installed_files():
if not os.path.isabs(path):
path = os.path.join(base, path)
if path == record_path:
continue
if not os.path.exists(path):
mismatches.append((path, 'exists', True, False))
elif os.path.isfile(path):
actual_size = str(os.path.getsize(path))
if size and actual_size != size:
mismatches.append((path, 'size', size, actual_size))
elif hash_value:
if '=' in hash_value:
hasher = hash_value.split('=', 1)[0]
else:
hasher = None
with open(path, 'rb') as f:
actual_hash = self.get_hash(f.read(), hasher)
if actual_hash != hash_value:
mismatches.append((path, 'hash', hash_value, actual_hash))
return mismatches
|
[
"def",
"check_installed_files",
"(",
"self",
")",
":",
"mismatches",
"=",
"[",
"]",
"base",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"path",
")",
"record_path",
"=",
"self",
".",
"get_distinfo_file",
"(",
"'RECORD'",
")",
"for",
"path",
",",
"hash_value",
",",
"size",
"in",
"self",
".",
"list_installed_files",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"path",
")",
"if",
"path",
"==",
"record_path",
":",
"continue",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"mismatches",
".",
"append",
"(",
"(",
"path",
",",
"'exists'",
",",
"True",
",",
"False",
")",
")",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"actual_size",
"=",
"str",
"(",
"os",
".",
"path",
".",
"getsize",
"(",
"path",
")",
")",
"if",
"size",
"and",
"actual_size",
"!=",
"size",
":",
"mismatches",
".",
"append",
"(",
"(",
"path",
",",
"'size'",
",",
"size",
",",
"actual_size",
")",
")",
"elif",
"hash_value",
":",
"if",
"'='",
"in",
"hash_value",
":",
"hasher",
"=",
"hash_value",
".",
"split",
"(",
"'='",
",",
"1",
")",
"[",
"0",
"]",
"else",
":",
"hasher",
"=",
"None",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
"actual_hash",
"=",
"self",
".",
"get_hash",
"(",
"f",
".",
"read",
"(",
")",
",",
"hasher",
")",
"if",
"actual_hash",
"!=",
"hash_value",
":",
"mismatches",
".",
"append",
"(",
"(",
"path",
",",
"'hash'",
",",
"hash_value",
",",
"actual_hash",
")",
")",
"return",
"mismatches"
] |
Checks that the hashes and sizes of the files in ``RECORD`` are
matched by the files themselves. Returns a (possibly empty) list of
mismatches. Each entry in the mismatch list will be a tuple consisting
of the path, 'exists', 'size' or 'hash' according to what didn't match
(existence is checked first, then size, then hash), the expected
value and the actual value.
|
[
"Checks",
"that",
"the",
"hashes",
"and",
"sizes",
"of",
"the",
"files",
"in",
"RECORD",
"are",
"matched",
"by",
"the",
"files",
"themselves",
".",
"Returns",
"a",
"(",
"possibly",
"empty",
")",
"list",
"of",
"mismatches",
".",
"Each",
"entry",
"in",
"the",
"mismatch",
"list",
"will",
"be",
"a",
"tuple",
"consisting",
"of",
"the",
"path",
"exists",
"size",
"or",
"hash",
"according",
"to",
"what",
"didn",
"t",
"match",
"(",
"existence",
"is",
"checked",
"first",
"then",
"size",
"then",
"hash",
")",
"the",
"expected",
"value",
"and",
"the",
"actual",
"value",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L708-L741
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
InstalledDistribution.shared_locations
|
def shared_locations(self):
"""
A dictionary of shared locations whose keys are in the set 'prefix',
'purelib', 'platlib', 'scripts', 'headers', 'data' and 'namespace'.
The corresponding value is the absolute path of that category for
this distribution, and takes into account any paths selected by the
user at installation time (e.g. via command-line arguments). In the
case of the 'namespace' key, this would be a list of absolute paths
for the roots of namespace packages in this distribution.
The first time this property is accessed, the relevant information is
read from the SHARED file in the .dist-info directory.
"""
result = {}
shared_path = os.path.join(self.path, 'SHARED')
if os.path.isfile(shared_path):
with codecs.open(shared_path, 'r', encoding='utf-8') as f:
lines = f.read().splitlines()
for line in lines:
key, value = line.split('=', 1)
if key == 'namespace':
result.setdefault(key, []).append(value)
else:
result[key] = value
return result
|
python
|
def shared_locations(self):
"""
A dictionary of shared locations whose keys are in the set 'prefix',
'purelib', 'platlib', 'scripts', 'headers', 'data' and 'namespace'.
The corresponding value is the absolute path of that category for
this distribution, and takes into account any paths selected by the
user at installation time (e.g. via command-line arguments). In the
case of the 'namespace' key, this would be a list of absolute paths
for the roots of namespace packages in this distribution.
The first time this property is accessed, the relevant information is
read from the SHARED file in the .dist-info directory.
"""
result = {}
shared_path = os.path.join(self.path, 'SHARED')
if os.path.isfile(shared_path):
with codecs.open(shared_path, 'r', encoding='utf-8') as f:
lines = f.read().splitlines()
for line in lines:
key, value = line.split('=', 1)
if key == 'namespace':
result.setdefault(key, []).append(value)
else:
result[key] = value
return result
|
[
"def",
"shared_locations",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"shared_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"'SHARED'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"shared_path",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"shared_path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"read",
"(",
")",
".",
"splitlines",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"key",
",",
"value",
"=",
"line",
".",
"split",
"(",
"'='",
",",
"1",
")",
"if",
"key",
"==",
"'namespace'",
":",
"result",
".",
"setdefault",
"(",
"key",
",",
"[",
"]",
")",
".",
"append",
"(",
"value",
")",
"else",
":",
"result",
"[",
"key",
"]",
"=",
"value",
"return",
"result"
] |
A dictionary of shared locations whose keys are in the set 'prefix',
'purelib', 'platlib', 'scripts', 'headers', 'data' and 'namespace'.
The corresponding value is the absolute path of that category for
this distribution, and takes into account any paths selected by the
user at installation time (e.g. via command-line arguments). In the
case of the 'namespace' key, this would be a list of absolute paths
for the roots of namespace packages in this distribution.
The first time this property is accessed, the relevant information is
read from the SHARED file in the .dist-info directory.
|
[
"A",
"dictionary",
"of",
"shared",
"locations",
"whose",
"keys",
"are",
"in",
"the",
"set",
"prefix",
"purelib",
"platlib",
"scripts",
"headers",
"data",
"and",
"namespace",
".",
"The",
"corresponding",
"value",
"is",
"the",
"absolute",
"path",
"of",
"that",
"category",
"for",
"this",
"distribution",
"and",
"takes",
"into",
"account",
"any",
"paths",
"selected",
"by",
"the",
"user",
"at",
"installation",
"time",
"(",
"e",
".",
"g",
".",
"via",
"command",
"-",
"line",
"arguments",
")",
".",
"In",
"the",
"case",
"of",
"the",
"namespace",
"key",
"this",
"would",
"be",
"a",
"list",
"of",
"absolute",
"paths",
"for",
"the",
"roots",
"of",
"namespace",
"packages",
"in",
"this",
"distribution",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L744-L768
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
InstalledDistribution.write_shared_locations
|
def write_shared_locations(self, paths, dry_run=False):
"""
Write shared location information to the SHARED file in .dist-info.
:param paths: A dictionary as described in the documentation for
:meth:`shared_locations`.
:param dry_run: If True, the action is logged but no file is actually
written.
:return: The path of the file written to.
"""
shared_path = os.path.join(self.path, 'SHARED')
logger.info('creating %s', shared_path)
if dry_run:
return None
lines = []
for key in ('prefix', 'lib', 'headers', 'scripts', 'data'):
path = paths[key]
if os.path.isdir(paths[key]):
lines.append('%s=%s' % (key, path))
for ns in paths.get('namespace', ()):
lines.append('namespace=%s' % ns)
with codecs.open(shared_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(lines))
return shared_path
|
python
|
def write_shared_locations(self, paths, dry_run=False):
"""
Write shared location information to the SHARED file in .dist-info.
:param paths: A dictionary as described in the documentation for
:meth:`shared_locations`.
:param dry_run: If True, the action is logged but no file is actually
written.
:return: The path of the file written to.
"""
shared_path = os.path.join(self.path, 'SHARED')
logger.info('creating %s', shared_path)
if dry_run:
return None
lines = []
for key in ('prefix', 'lib', 'headers', 'scripts', 'data'):
path = paths[key]
if os.path.isdir(paths[key]):
lines.append('%s=%s' % (key, path))
for ns in paths.get('namespace', ()):
lines.append('namespace=%s' % ns)
with codecs.open(shared_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(lines))
return shared_path
|
[
"def",
"write_shared_locations",
"(",
"self",
",",
"paths",
",",
"dry_run",
"=",
"False",
")",
":",
"shared_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"'SHARED'",
")",
"logger",
".",
"info",
"(",
"'creating %s'",
",",
"shared_path",
")",
"if",
"dry_run",
":",
"return",
"None",
"lines",
"=",
"[",
"]",
"for",
"key",
"in",
"(",
"'prefix'",
",",
"'lib'",
",",
"'headers'",
",",
"'scripts'",
",",
"'data'",
")",
":",
"path",
"=",
"paths",
"[",
"key",
"]",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"paths",
"[",
"key",
"]",
")",
":",
"lines",
".",
"append",
"(",
"'%s=%s'",
"%",
"(",
"key",
",",
"path",
")",
")",
"for",
"ns",
"in",
"paths",
".",
"get",
"(",
"'namespace'",
",",
"(",
")",
")",
":",
"lines",
".",
"append",
"(",
"'namespace=%s'",
"%",
"ns",
")",
"with",
"codecs",
".",
"open",
"(",
"shared_path",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"'\\n'",
".",
"join",
"(",
"lines",
")",
")",
"return",
"shared_path"
] |
Write shared location information to the SHARED file in .dist-info.
:param paths: A dictionary as described in the documentation for
:meth:`shared_locations`.
:param dry_run: If True, the action is logged but no file is actually
written.
:return: The path of the file written to.
|
[
"Write",
"shared",
"location",
"information",
"to",
"the",
"SHARED",
"file",
"in",
".",
"dist",
"-",
"info",
".",
":",
"param",
"paths",
":",
"A",
"dictionary",
"as",
"described",
"in",
"the",
"documentation",
"for",
":",
"meth",
":",
"shared_locations",
".",
":",
"param",
"dry_run",
":",
"If",
"True",
"the",
"action",
"is",
"logged",
"but",
"no",
"file",
"is",
"actually",
"written",
".",
":",
"return",
":",
"The",
"path",
"of",
"the",
"file",
"written",
"to",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L770-L793
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
InstalledDistribution.get_distinfo_file
|
def get_distinfo_file(self, path):
"""
Returns a path located under the ``.dist-info`` directory. Returns a
string representing the path.
:parameter path: a ``'/'``-separated path relative to the
``.dist-info`` directory or an absolute path;
If *path* is an absolute path and doesn't start
with the ``.dist-info`` directory path,
a :class:`DistlibException` is raised
:type path: str
:rtype: str
"""
# Check if it is an absolute path # XXX use relpath, add tests
if path.find(os.sep) >= 0:
# it's an absolute path?
distinfo_dirname, path = path.split(os.sep)[-2:]
if distinfo_dirname != self.path.split(os.sep)[-1]:
raise DistlibException(
'dist-info file %r does not belong to the %r %s '
'distribution' % (path, self.name, self.version))
# The file must be relative
if path not in DIST_FILES:
raise DistlibException('invalid path for a dist-info file: '
'%r at %r' % (path, self.path))
return os.path.join(self.path, path)
|
python
|
def get_distinfo_file(self, path):
"""
Returns a path located under the ``.dist-info`` directory. Returns a
string representing the path.
:parameter path: a ``'/'``-separated path relative to the
``.dist-info`` directory or an absolute path;
If *path* is an absolute path and doesn't start
with the ``.dist-info`` directory path,
a :class:`DistlibException` is raised
:type path: str
:rtype: str
"""
# Check if it is an absolute path # XXX use relpath, add tests
if path.find(os.sep) >= 0:
# it's an absolute path?
distinfo_dirname, path = path.split(os.sep)[-2:]
if distinfo_dirname != self.path.split(os.sep)[-1]:
raise DistlibException(
'dist-info file %r does not belong to the %r %s '
'distribution' % (path, self.name, self.version))
# The file must be relative
if path not in DIST_FILES:
raise DistlibException('invalid path for a dist-info file: '
'%r at %r' % (path, self.path))
return os.path.join(self.path, path)
|
[
"def",
"get_distinfo_file",
"(",
"self",
",",
"path",
")",
":",
"# Check if it is an absolute path # XXX use relpath, add tests",
"if",
"path",
".",
"find",
"(",
"os",
".",
"sep",
")",
">=",
"0",
":",
"# it's an absolute path?",
"distinfo_dirname",
",",
"path",
"=",
"path",
".",
"split",
"(",
"os",
".",
"sep",
")",
"[",
"-",
"2",
":",
"]",
"if",
"distinfo_dirname",
"!=",
"self",
".",
"path",
".",
"split",
"(",
"os",
".",
"sep",
")",
"[",
"-",
"1",
"]",
":",
"raise",
"DistlibException",
"(",
"'dist-info file %r does not belong to the %r %s '",
"'distribution'",
"%",
"(",
"path",
",",
"self",
".",
"name",
",",
"self",
".",
"version",
")",
")",
"# The file must be relative",
"if",
"path",
"not",
"in",
"DIST_FILES",
":",
"raise",
"DistlibException",
"(",
"'invalid path for a dist-info file: '",
"'%r at %r'",
"%",
"(",
"path",
",",
"self",
".",
"path",
")",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"path",
")"
] |
Returns a path located under the ``.dist-info`` directory. Returns a
string representing the path.
:parameter path: a ``'/'``-separated path relative to the
``.dist-info`` directory or an absolute path;
If *path* is an absolute path and doesn't start
with the ``.dist-info`` directory path,
a :class:`DistlibException` is raised
:type path: str
:rtype: str
|
[
"Returns",
"a",
"path",
"located",
"under",
"the",
".",
"dist",
"-",
"info",
"directory",
".",
"Returns",
"a",
"string",
"representing",
"the",
"path",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L804-L831
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
InstalledDistribution.list_distinfo_files
|
def list_distinfo_files(self):
"""
Iterates over the ``RECORD`` entries and returns paths for each line if
the path is pointing to a file located in the ``.dist-info`` directory
or one of its subdirectories.
:returns: iterator of paths
"""
base = os.path.dirname(self.path)
for path, checksum, size in self._get_records():
# XXX add separator or use real relpath algo
if not os.path.isabs(path):
path = os.path.join(base, path)
if path.startswith(self.path):
yield path
|
python
|
def list_distinfo_files(self):
"""
Iterates over the ``RECORD`` entries and returns paths for each line if
the path is pointing to a file located in the ``.dist-info`` directory
or one of its subdirectories.
:returns: iterator of paths
"""
base = os.path.dirname(self.path)
for path, checksum, size in self._get_records():
# XXX add separator or use real relpath algo
if not os.path.isabs(path):
path = os.path.join(base, path)
if path.startswith(self.path):
yield path
|
[
"def",
"list_distinfo_files",
"(",
"self",
")",
":",
"base",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"path",
")",
"for",
"path",
",",
"checksum",
",",
"size",
"in",
"self",
".",
"_get_records",
"(",
")",
":",
"# XXX add separator or use real relpath algo",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"path",
")",
"if",
"path",
".",
"startswith",
"(",
"self",
".",
"path",
")",
":",
"yield",
"path"
] |
Iterates over the ``RECORD`` entries and returns paths for each line if
the path is pointing to a file located in the ``.dist-info`` directory
or one of its subdirectories.
:returns: iterator of paths
|
[
"Iterates",
"over",
"the",
"RECORD",
"entries",
"and",
"returns",
"paths",
"for",
"each",
"line",
"if",
"the",
"path",
"is",
"pointing",
"to",
"a",
"file",
"located",
"in",
"the",
".",
"dist",
"-",
"info",
"directory",
"or",
"one",
"of",
"its",
"subdirectories",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L833-L847
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
EggInfoDistribution.check_installed_files
|
def check_installed_files(self):
"""
Checks that the hashes and sizes of the files in ``RECORD`` are
matched by the files themselves. Returns a (possibly empty) list of
mismatches. Each entry in the mismatch list will be a tuple consisting
of the path, 'exists', 'size' or 'hash' according to what didn't match
(existence is checked first, then size, then hash), the expected
value and the actual value.
"""
mismatches = []
record_path = os.path.join(self.path, 'installed-files.txt')
if os.path.exists(record_path):
for path, _, _ in self.list_installed_files():
if path == record_path:
continue
if not os.path.exists(path):
mismatches.append((path, 'exists', True, False))
return mismatches
|
python
|
def check_installed_files(self):
"""
Checks that the hashes and sizes of the files in ``RECORD`` are
matched by the files themselves. Returns a (possibly empty) list of
mismatches. Each entry in the mismatch list will be a tuple consisting
of the path, 'exists', 'size' or 'hash' according to what didn't match
(existence is checked first, then size, then hash), the expected
value and the actual value.
"""
mismatches = []
record_path = os.path.join(self.path, 'installed-files.txt')
if os.path.exists(record_path):
for path, _, _ in self.list_installed_files():
if path == record_path:
continue
if not os.path.exists(path):
mismatches.append((path, 'exists', True, False))
return mismatches
|
[
"def",
"check_installed_files",
"(",
"self",
")",
":",
"mismatches",
"=",
"[",
"]",
"record_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"'installed-files.txt'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"record_path",
")",
":",
"for",
"path",
",",
"_",
",",
"_",
"in",
"self",
".",
"list_installed_files",
"(",
")",
":",
"if",
"path",
"==",
"record_path",
":",
"continue",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"mismatches",
".",
"append",
"(",
"(",
"path",
",",
"'exists'",
",",
"True",
",",
"False",
")",
")",
"return",
"mismatches"
] |
Checks that the hashes and sizes of the files in ``RECORD`` are
matched by the files themselves. Returns a (possibly empty) list of
mismatches. Each entry in the mismatch list will be a tuple consisting
of the path, 'exists', 'size' or 'hash' according to what didn't match
(existence is checked first, then size, then hash), the expected
value and the actual value.
|
[
"Checks",
"that",
"the",
"hashes",
"and",
"sizes",
"of",
"the",
"files",
"in",
"RECORD",
"are",
"matched",
"by",
"the",
"files",
"themselves",
".",
"Returns",
"a",
"(",
"possibly",
"empty",
")",
"list",
"of",
"mismatches",
".",
"Each",
"entry",
"in",
"the",
"mismatch",
"list",
"will",
"be",
"a",
"tuple",
"consisting",
"of",
"the",
"path",
"exists",
"size",
"or",
"hash",
"according",
"to",
"what",
"didn",
"t",
"match",
"(",
"existence",
"is",
"checked",
"first",
"then",
"size",
"then",
"hash",
")",
"the",
"expected",
"value",
"and",
"the",
"actual",
"value",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L984-L1001
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
EggInfoDistribution.list_installed_files
|
def list_installed_files(self):
"""
Iterates over the ``installed-files.txt`` entries and returns a tuple
``(path, hash, size)`` for each line.
:returns: a list of (path, hash, size)
"""
def _md5(path):
f = open(path, 'rb')
try:
content = f.read()
finally:
f.close()
return hashlib.md5(content).hexdigest()
def _size(path):
return os.stat(path).st_size
record_path = os.path.join(self.path, 'installed-files.txt')
result = []
if os.path.exists(record_path):
with codecs.open(record_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
p = os.path.normpath(os.path.join(self.path, line))
# "./" is present as a marker between installed files
# and installation metadata files
if not os.path.exists(p):
logger.warning('Non-existent file: %s', p)
if p.endswith(('.pyc', '.pyo')):
continue
#otherwise fall through and fail
if not os.path.isdir(p):
result.append((p, _md5(p), _size(p)))
result.append((record_path, None, None))
return result
|
python
|
def list_installed_files(self):
"""
Iterates over the ``installed-files.txt`` entries and returns a tuple
``(path, hash, size)`` for each line.
:returns: a list of (path, hash, size)
"""
def _md5(path):
f = open(path, 'rb')
try:
content = f.read()
finally:
f.close()
return hashlib.md5(content).hexdigest()
def _size(path):
return os.stat(path).st_size
record_path = os.path.join(self.path, 'installed-files.txt')
result = []
if os.path.exists(record_path):
with codecs.open(record_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
p = os.path.normpath(os.path.join(self.path, line))
# "./" is present as a marker between installed files
# and installation metadata files
if not os.path.exists(p):
logger.warning('Non-existent file: %s', p)
if p.endswith(('.pyc', '.pyo')):
continue
#otherwise fall through and fail
if not os.path.isdir(p):
result.append((p, _md5(p), _size(p)))
result.append((record_path, None, None))
return result
|
[
"def",
"list_installed_files",
"(",
"self",
")",
":",
"def",
"_md5",
"(",
"path",
")",
":",
"f",
"=",
"open",
"(",
"path",
",",
"'rb'",
")",
"try",
":",
"content",
"=",
"f",
".",
"read",
"(",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"return",
"hashlib",
".",
"md5",
"(",
"content",
")",
".",
"hexdigest",
"(",
")",
"def",
"_size",
"(",
"path",
")",
":",
"return",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_size",
"record_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"'installed-files.txt'",
")",
"result",
"=",
"[",
"]",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"record_path",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"record_path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"p",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"line",
")",
")",
"# \"./\" is present as a marker between installed files",
"# and installation metadata files",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"p",
")",
":",
"logger",
".",
"warning",
"(",
"'Non-existent file: %s'",
",",
"p",
")",
"if",
"p",
".",
"endswith",
"(",
"(",
"'.pyc'",
",",
"'.pyo'",
")",
")",
":",
"continue",
"#otherwise fall through and fail",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"p",
")",
":",
"result",
".",
"append",
"(",
"(",
"p",
",",
"_md5",
"(",
"p",
")",
",",
"_size",
"(",
"p",
")",
")",
")",
"result",
".",
"append",
"(",
"(",
"record_path",
",",
"None",
",",
"None",
")",
")",
"return",
"result"
] |
Iterates over the ``installed-files.txt`` entries and returns a tuple
``(path, hash, size)`` for each line.
:returns: a list of (path, hash, size)
|
[
"Iterates",
"over",
"the",
"installed",
"-",
"files",
".",
"txt",
"entries",
"and",
"returns",
"a",
"tuple",
"(",
"path",
"hash",
"size",
")",
"for",
"each",
"line",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1003-L1039
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
EggInfoDistribution.list_distinfo_files
|
def list_distinfo_files(self, absolute=False):
"""
Iterates over the ``installed-files.txt`` entries and returns paths for
each line if the path is pointing to a file located in the
``.egg-info`` directory or one of its subdirectories.
:parameter absolute: If *absolute* is ``True``, each returned path is
transformed into a local absolute path. Otherwise the
raw value from ``installed-files.txt`` is returned.
:type absolute: boolean
:returns: iterator of paths
"""
record_path = os.path.join(self.path, 'installed-files.txt')
if os.path.exists(record_path):
skip = True
with codecs.open(record_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line == './':
skip = False
continue
if not skip:
p = os.path.normpath(os.path.join(self.path, line))
if p.startswith(self.path):
if absolute:
yield p
else:
yield line
|
python
|
def list_distinfo_files(self, absolute=False):
"""
Iterates over the ``installed-files.txt`` entries and returns paths for
each line if the path is pointing to a file located in the
``.egg-info`` directory or one of its subdirectories.
:parameter absolute: If *absolute* is ``True``, each returned path is
transformed into a local absolute path. Otherwise the
raw value from ``installed-files.txt`` is returned.
:type absolute: boolean
:returns: iterator of paths
"""
record_path = os.path.join(self.path, 'installed-files.txt')
if os.path.exists(record_path):
skip = True
with codecs.open(record_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line == './':
skip = False
continue
if not skip:
p = os.path.normpath(os.path.join(self.path, line))
if p.startswith(self.path):
if absolute:
yield p
else:
yield line
|
[
"def",
"list_distinfo_files",
"(",
"self",
",",
"absolute",
"=",
"False",
")",
":",
"record_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"'installed-files.txt'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"record_path",
")",
":",
"skip",
"=",
"True",
"with",
"codecs",
".",
"open",
"(",
"record_path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
"==",
"'./'",
":",
"skip",
"=",
"False",
"continue",
"if",
"not",
"skip",
":",
"p",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"line",
")",
")",
"if",
"p",
".",
"startswith",
"(",
"self",
".",
"path",
")",
":",
"if",
"absolute",
":",
"yield",
"p",
"else",
":",
"yield",
"line"
] |
Iterates over the ``installed-files.txt`` entries and returns paths for
each line if the path is pointing to a file located in the
``.egg-info`` directory or one of its subdirectories.
:parameter absolute: If *absolute* is ``True``, each returned path is
transformed into a local absolute path. Otherwise the
raw value from ``installed-files.txt`` is returned.
:type absolute: boolean
:returns: iterator of paths
|
[
"Iterates",
"over",
"the",
"installed",
"-",
"files",
".",
"txt",
"entries",
"and",
"returns",
"paths",
"for",
"each",
"line",
"if",
"the",
"path",
"is",
"pointing",
"to",
"a",
"file",
"located",
"in",
"the",
".",
"egg",
"-",
"info",
"directory",
"or",
"one",
"of",
"its",
"subdirectories",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1041-L1068
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
DependencyGraph.add_edge
|
def add_edge(self, x, y, label=None):
"""Add an edge from distribution *x* to distribution *y* with the given
*label*.
:type x: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type y: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type label: ``str`` or ``None``
"""
self.adjacency_list[x].append((y, label))
# multiple edges are allowed, so be careful
if x not in self.reverse_list[y]:
self.reverse_list[y].append(x)
|
python
|
def add_edge(self, x, y, label=None):
"""Add an edge from distribution *x* to distribution *y* with the given
*label*.
:type x: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type y: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type label: ``str`` or ``None``
"""
self.adjacency_list[x].append((y, label))
# multiple edges are allowed, so be careful
if x not in self.reverse_list[y]:
self.reverse_list[y].append(x)
|
[
"def",
"add_edge",
"(",
"self",
",",
"x",
",",
"y",
",",
"label",
"=",
"None",
")",
":",
"self",
".",
"adjacency_list",
"[",
"x",
"]",
".",
"append",
"(",
"(",
"y",
",",
"label",
")",
")",
"# multiple edges are allowed, so be careful",
"if",
"x",
"not",
"in",
"self",
".",
"reverse_list",
"[",
"y",
"]",
":",
"self",
".",
"reverse_list",
"[",
"y",
"]",
".",
"append",
"(",
"x",
")"
] |
Add an edge from distribution *x* to distribution *y* with the given
*label*.
:type x: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type y: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type label: ``str`` or ``None``
|
[
"Add",
"an",
"edge",
"from",
"distribution",
"*",
"x",
"*",
"to",
"distribution",
"*",
"y",
"*",
"with",
"the",
"given",
"*",
"label",
"*",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1112-L1125
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
DependencyGraph.add_missing
|
def add_missing(self, distribution, requirement):
"""
Add a missing *requirement* for the given *distribution*.
:type distribution: :class:`distutils2.database.InstalledDistribution`
or :class:`distutils2.database.EggInfoDistribution`
:type requirement: ``str``
"""
logger.debug('%s missing %r', distribution, requirement)
self.missing.setdefault(distribution, []).append(requirement)
|
python
|
def add_missing(self, distribution, requirement):
"""
Add a missing *requirement* for the given *distribution*.
:type distribution: :class:`distutils2.database.InstalledDistribution`
or :class:`distutils2.database.EggInfoDistribution`
:type requirement: ``str``
"""
logger.debug('%s missing %r', distribution, requirement)
self.missing.setdefault(distribution, []).append(requirement)
|
[
"def",
"add_missing",
"(",
"self",
",",
"distribution",
",",
"requirement",
")",
":",
"logger",
".",
"debug",
"(",
"'%s missing %r'",
",",
"distribution",
",",
"requirement",
")",
"self",
".",
"missing",
".",
"setdefault",
"(",
"distribution",
",",
"[",
"]",
")",
".",
"append",
"(",
"requirement",
")"
] |
Add a missing *requirement* for the given *distribution*.
:type distribution: :class:`distutils2.database.InstalledDistribution`
or :class:`distutils2.database.EggInfoDistribution`
:type requirement: ``str``
|
[
"Add",
"a",
"missing",
"*",
"requirement",
"*",
"for",
"the",
"given",
"*",
"distribution",
"*",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1127-L1136
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
DependencyGraph.repr_node
|
def repr_node(self, dist, level=1):
"""Prints only a subgraph"""
output = [self._repr_dist(dist)]
for other, label in self.adjacency_list[dist]:
dist = self._repr_dist(other)
if label is not None:
dist = '%s [%s]' % (dist, label)
output.append(' ' * level + str(dist))
suboutput = self.repr_node(other, level + 1)
subs = suboutput.split('\n')
output.extend(subs[1:])
return '\n'.join(output)
|
python
|
def repr_node(self, dist, level=1):
"""Prints only a subgraph"""
output = [self._repr_dist(dist)]
for other, label in self.adjacency_list[dist]:
dist = self._repr_dist(other)
if label is not None:
dist = '%s [%s]' % (dist, label)
output.append(' ' * level + str(dist))
suboutput = self.repr_node(other, level + 1)
subs = suboutput.split('\n')
output.extend(subs[1:])
return '\n'.join(output)
|
[
"def",
"repr_node",
"(",
"self",
",",
"dist",
",",
"level",
"=",
"1",
")",
":",
"output",
"=",
"[",
"self",
".",
"_repr_dist",
"(",
"dist",
")",
"]",
"for",
"other",
",",
"label",
"in",
"self",
".",
"adjacency_list",
"[",
"dist",
"]",
":",
"dist",
"=",
"self",
".",
"_repr_dist",
"(",
"other",
")",
"if",
"label",
"is",
"not",
"None",
":",
"dist",
"=",
"'%s [%s]'",
"%",
"(",
"dist",
",",
"label",
")",
"output",
".",
"append",
"(",
"' '",
"*",
"level",
"+",
"str",
"(",
"dist",
")",
")",
"suboutput",
"=",
"self",
".",
"repr_node",
"(",
"other",
",",
"level",
"+",
"1",
")",
"subs",
"=",
"suboutput",
".",
"split",
"(",
"'\\n'",
")",
"output",
".",
"extend",
"(",
"subs",
"[",
"1",
":",
"]",
")",
"return",
"'\\n'",
".",
"join",
"(",
"output",
")"
] |
Prints only a subgraph
|
[
"Prints",
"only",
"a",
"subgraph"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1141-L1152
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
DependencyGraph.to_dot
|
def to_dot(self, f, skip_disconnected=True):
"""Writes a DOT output for the graph to the provided file *f*.
If *skip_disconnected* is set to ``True``, then all distributions
that are not dependent on any other distribution are skipped.
:type f: has to support ``file``-like operations
:type skip_disconnected: ``bool``
"""
disconnected = []
f.write("digraph dependencies {\n")
for dist, adjs in self.adjacency_list.items():
if len(adjs) == 0 and not skip_disconnected:
disconnected.append(dist)
for other, label in adjs:
if not label is None:
f.write('"%s" -> "%s" [label="%s"]\n' %
(dist.name, other.name, label))
else:
f.write('"%s" -> "%s"\n' % (dist.name, other.name))
if not skip_disconnected and len(disconnected) > 0:
f.write('subgraph disconnected {\n')
f.write('label = "Disconnected"\n')
f.write('bgcolor = red\n')
for dist in disconnected:
f.write('"%s"' % dist.name)
f.write('\n')
f.write('}\n')
f.write('}\n')
|
python
|
def to_dot(self, f, skip_disconnected=True):
"""Writes a DOT output for the graph to the provided file *f*.
If *skip_disconnected* is set to ``True``, then all distributions
that are not dependent on any other distribution are skipped.
:type f: has to support ``file``-like operations
:type skip_disconnected: ``bool``
"""
disconnected = []
f.write("digraph dependencies {\n")
for dist, adjs in self.adjacency_list.items():
if len(adjs) == 0 and not skip_disconnected:
disconnected.append(dist)
for other, label in adjs:
if not label is None:
f.write('"%s" -> "%s" [label="%s"]\n' %
(dist.name, other.name, label))
else:
f.write('"%s" -> "%s"\n' % (dist.name, other.name))
if not skip_disconnected and len(disconnected) > 0:
f.write('subgraph disconnected {\n')
f.write('label = "Disconnected"\n')
f.write('bgcolor = red\n')
for dist in disconnected:
f.write('"%s"' % dist.name)
f.write('\n')
f.write('}\n')
f.write('}\n')
|
[
"def",
"to_dot",
"(",
"self",
",",
"f",
",",
"skip_disconnected",
"=",
"True",
")",
":",
"disconnected",
"=",
"[",
"]",
"f",
".",
"write",
"(",
"\"digraph dependencies {\\n\"",
")",
"for",
"dist",
",",
"adjs",
"in",
"self",
".",
"adjacency_list",
".",
"items",
"(",
")",
":",
"if",
"len",
"(",
"adjs",
")",
"==",
"0",
"and",
"not",
"skip_disconnected",
":",
"disconnected",
".",
"append",
"(",
"dist",
")",
"for",
"other",
",",
"label",
"in",
"adjs",
":",
"if",
"not",
"label",
"is",
"None",
":",
"f",
".",
"write",
"(",
"'\"%s\" -> \"%s\" [label=\"%s\"]\\n'",
"%",
"(",
"dist",
".",
"name",
",",
"other",
".",
"name",
",",
"label",
")",
")",
"else",
":",
"f",
".",
"write",
"(",
"'\"%s\" -> \"%s\"\\n'",
"%",
"(",
"dist",
".",
"name",
",",
"other",
".",
"name",
")",
")",
"if",
"not",
"skip_disconnected",
"and",
"len",
"(",
"disconnected",
")",
">",
"0",
":",
"f",
".",
"write",
"(",
"'subgraph disconnected {\\n'",
")",
"f",
".",
"write",
"(",
"'label = \"Disconnected\"\\n'",
")",
"f",
".",
"write",
"(",
"'bgcolor = red\\n'",
")",
"for",
"dist",
"in",
"disconnected",
":",
"f",
".",
"write",
"(",
"'\"%s\"'",
"%",
"dist",
".",
"name",
")",
"f",
".",
"write",
"(",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'}\\n'",
")",
"f",
".",
"write",
"(",
"'}\\n'",
")"
] |
Writes a DOT output for the graph to the provided file *f*.
If *skip_disconnected* is set to ``True``, then all distributions
that are not dependent on any other distribution are skipped.
:type f: has to support ``file``-like operations
:type skip_disconnected: ``bool``
|
[
"Writes",
"a",
"DOT",
"output",
"for",
"the",
"graph",
"to",
"the",
"provided",
"file",
"*",
"f",
"*",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1154-L1184
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/database.py
|
DependencyGraph.topological_sort
|
def topological_sort(self):
"""
Perform a topological sort of the graph.
:return: A tuple, the first element of which is a topologically sorted
list of distributions, and the second element of which is a
list of distributions that cannot be sorted because they have
circular dependencies and so form a cycle.
"""
result = []
# Make a shallow copy of the adjacency list
alist = {}
for k, v in self.adjacency_list.items():
alist[k] = v[:]
while True:
# See what we can remove in this run
to_remove = []
for k, v in list(alist.items())[:]:
if not v:
to_remove.append(k)
del alist[k]
if not to_remove:
# What's left in alist (if anything) is a cycle.
break
# Remove from the adjacency list of others
for k, v in alist.items():
alist[k] = [(d, r) for d, r in v if d not in to_remove]
logger.debug('Moving to result: %s',
['%s (%s)' % (d.name, d.version) for d in to_remove])
result.extend(to_remove)
return result, list(alist.keys())
|
python
|
def topological_sort(self):
"""
Perform a topological sort of the graph.
:return: A tuple, the first element of which is a topologically sorted
list of distributions, and the second element of which is a
list of distributions that cannot be sorted because they have
circular dependencies and so form a cycle.
"""
result = []
# Make a shallow copy of the adjacency list
alist = {}
for k, v in self.adjacency_list.items():
alist[k] = v[:]
while True:
# See what we can remove in this run
to_remove = []
for k, v in list(alist.items())[:]:
if not v:
to_remove.append(k)
del alist[k]
if not to_remove:
# What's left in alist (if anything) is a cycle.
break
# Remove from the adjacency list of others
for k, v in alist.items():
alist[k] = [(d, r) for d, r in v if d not in to_remove]
logger.debug('Moving to result: %s',
['%s (%s)' % (d.name, d.version) for d in to_remove])
result.extend(to_remove)
return result, list(alist.keys())
|
[
"def",
"topological_sort",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"# Make a shallow copy of the adjacency list",
"alist",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"adjacency_list",
".",
"items",
"(",
")",
":",
"alist",
"[",
"k",
"]",
"=",
"v",
"[",
":",
"]",
"while",
"True",
":",
"# See what we can remove in this run",
"to_remove",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"alist",
".",
"items",
"(",
")",
")",
"[",
":",
"]",
":",
"if",
"not",
"v",
":",
"to_remove",
".",
"append",
"(",
"k",
")",
"del",
"alist",
"[",
"k",
"]",
"if",
"not",
"to_remove",
":",
"# What's left in alist (if anything) is a cycle.",
"break",
"# Remove from the adjacency list of others",
"for",
"k",
",",
"v",
"in",
"alist",
".",
"items",
"(",
")",
":",
"alist",
"[",
"k",
"]",
"=",
"[",
"(",
"d",
",",
"r",
")",
"for",
"d",
",",
"r",
"in",
"v",
"if",
"d",
"not",
"in",
"to_remove",
"]",
"logger",
".",
"debug",
"(",
"'Moving to result: %s'",
",",
"[",
"'%s (%s)'",
"%",
"(",
"d",
".",
"name",
",",
"d",
".",
"version",
")",
"for",
"d",
"in",
"to_remove",
"]",
")",
"result",
".",
"extend",
"(",
"to_remove",
")",
"return",
"result",
",",
"list",
"(",
"alist",
".",
"keys",
"(",
")",
")"
] |
Perform a topological sort of the graph.
:return: A tuple, the first element of which is a topologically sorted
list of distributions, and the second element of which is a
list of distributions that cannot be sorted because they have
circular dependencies and so form a cycle.
|
[
"Perform",
"a",
"topological",
"sort",
"of",
"the",
"graph",
".",
":",
"return",
":",
"A",
"tuple",
"the",
"first",
"element",
"of",
"which",
"is",
"a",
"topologically",
"sorted",
"list",
"of",
"distributions",
"and",
"the",
"second",
"element",
"of",
"which",
"is",
"a",
"list",
"of",
"distributions",
"that",
"cannot",
"be",
"sorted",
"because",
"they",
"have",
"circular",
"dependencies",
"and",
"so",
"form",
"a",
"cycle",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1186-L1215
|
train
|
pypa/pipenv
|
pipenv/vendor/cerberus/errors.py
|
encode_unicode
|
def encode_unicode(f):
"""Cerberus error messages expect regular binary strings.
If unicode is used in a ValidationError message can't be printed.
This decorator ensures that if legacy Python is used unicode
strings are encoded before passing to a function.
"""
@wraps(f)
def wrapped(obj, error):
def _encode(value):
"""Helper encoding unicode strings into binary utf-8"""
if isinstance(value, unicode): # noqa: F821
return value.encode('utf-8')
return value
error = copy(error)
error.document_path = _encode(error.document_path)
error.schema_path = _encode(error.schema_path)
error.constraint = _encode(error.constraint)
error.value = _encode(error.value)
error.info = _encode(error.info)
return f(obj, error)
return wrapped if PYTHON_VERSION < 3 else f
|
python
|
def encode_unicode(f):
"""Cerberus error messages expect regular binary strings.
If unicode is used in a ValidationError message can't be printed.
This decorator ensures that if legacy Python is used unicode
strings are encoded before passing to a function.
"""
@wraps(f)
def wrapped(obj, error):
def _encode(value):
"""Helper encoding unicode strings into binary utf-8"""
if isinstance(value, unicode): # noqa: F821
return value.encode('utf-8')
return value
error = copy(error)
error.document_path = _encode(error.document_path)
error.schema_path = _encode(error.schema_path)
error.constraint = _encode(error.constraint)
error.value = _encode(error.value)
error.info = _encode(error.info)
return f(obj, error)
return wrapped if PYTHON_VERSION < 3 else f
|
[
"def",
"encode_unicode",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"obj",
",",
"error",
")",
":",
"def",
"_encode",
"(",
"value",
")",
":",
"\"\"\"Helper encoding unicode strings into binary utf-8\"\"\"",
"if",
"isinstance",
"(",
"value",
",",
"unicode",
")",
":",
"# noqa: F821",
"return",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"value",
"error",
"=",
"copy",
"(",
"error",
")",
"error",
".",
"document_path",
"=",
"_encode",
"(",
"error",
".",
"document_path",
")",
"error",
".",
"schema_path",
"=",
"_encode",
"(",
"error",
".",
"schema_path",
")",
"error",
".",
"constraint",
"=",
"_encode",
"(",
"error",
".",
"constraint",
")",
"error",
".",
"value",
"=",
"_encode",
"(",
"error",
".",
"value",
")",
"error",
".",
"info",
"=",
"_encode",
"(",
"error",
".",
"info",
")",
"return",
"f",
"(",
"obj",
",",
"error",
")",
"return",
"wrapped",
"if",
"PYTHON_VERSION",
"<",
"3",
"else",
"f"
] |
Cerberus error messages expect regular binary strings.
If unicode is used in a ValidationError message can't be printed.
This decorator ensures that if legacy Python is used unicode
strings are encoded before passing to a function.
|
[
"Cerberus",
"error",
"messages",
"expect",
"regular",
"binary",
"strings",
".",
"If",
"unicode",
"is",
"used",
"in",
"a",
"ValidationError",
"message",
"can",
"t",
"be",
"printed",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L407-L431
|
train
|
pypa/pipenv
|
pipenv/vendor/cerberus/errors.py
|
ValidationError.definitions_errors
|
def definitions_errors(self):
""" Dictionary with errors of an *of-rule mapped to the index of the
definition it occurred in. Returns :obj:`None` if not applicable.
"""
if not self.is_logic_error:
return None
result = defaultdict(list)
for error in self.child_errors:
i = error.schema_path[len(self.schema_path)]
result[i].append(error)
return result
|
python
|
def definitions_errors(self):
""" Dictionary with errors of an *of-rule mapped to the index of the
definition it occurred in. Returns :obj:`None` if not applicable.
"""
if not self.is_logic_error:
return None
result = defaultdict(list)
for error in self.child_errors:
i = error.schema_path[len(self.schema_path)]
result[i].append(error)
return result
|
[
"def",
"definitions_errors",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_logic_error",
":",
"return",
"None",
"result",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"error",
"in",
"self",
".",
"child_errors",
":",
"i",
"=",
"error",
".",
"schema_path",
"[",
"len",
"(",
"self",
".",
"schema_path",
")",
"]",
"result",
"[",
"i",
"]",
".",
"append",
"(",
"error",
")",
"return",
"result"
] |
Dictionary with errors of an *of-rule mapped to the index of the
definition it occurred in. Returns :obj:`None` if not applicable.
|
[
"Dictionary",
"with",
"errors",
"of",
"an",
"*",
"of",
"-",
"rule",
"mapped",
"to",
"the",
"index",
"of",
"the",
"definition",
"it",
"occurred",
"in",
".",
"Returns",
":",
"obj",
":",
"None",
"if",
"not",
"applicable",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L151-L162
|
train
|
pypa/pipenv
|
pipenv/vendor/cerberus/errors.py
|
ErrorTree.add
|
def add(self, error):
""" Add an error to the tree.
:param error: :class:`~cerberus.errors.ValidationError`
"""
if not self._path_of_(error):
self.errors.append(error)
self.errors.sort()
else:
super(ErrorTree, self).add(error)
|
python
|
def add(self, error):
""" Add an error to the tree.
:param error: :class:`~cerberus.errors.ValidationError`
"""
if not self._path_of_(error):
self.errors.append(error)
self.errors.sort()
else:
super(ErrorTree, self).add(error)
|
[
"def",
"add",
"(",
"self",
",",
"error",
")",
":",
"if",
"not",
"self",
".",
"_path_of_",
"(",
"error",
")",
":",
"self",
".",
"errors",
".",
"append",
"(",
"error",
")",
"self",
".",
"errors",
".",
"sort",
"(",
")",
"else",
":",
"super",
"(",
"ErrorTree",
",",
"self",
")",
".",
"add",
"(",
"error",
")"
] |
Add an error to the tree.
:param error: :class:`~cerberus.errors.ValidationError`
|
[
"Add",
"an",
"error",
"to",
"the",
"tree",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L286-L295
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.