Merge "Change function ZipDelete to use Python module zipinfo instead of command 'zip'."

This commit is contained in:
Wei Li 2022-10-16 05:55:00 +00:00 committed by Gerrit Code Review
commit ddfc1ebf14

View file

@ -2868,30 +2868,32 @@ def ZipWriteStr(zip_file, zinfo_or_arcname, data, perms=None,
def ZipDelete(zip_filename, entries, force=False): def ZipDelete(zip_filename, entries, force=False):
"""Deletes entries from a ZIP file. """Deletes entries from a ZIP file.
Since deleting entries from a ZIP file is not supported, it shells out to
'zip -d'.
Args: Args:
zip_filename: The name of the ZIP file. zip_filename: The name of the ZIP file.
entries: The name of the entry, or the list of names to be deleted. entries: The name of the entry, or the list of names to be deleted.
Raises:
AssertionError: In case of non-zero return from 'zip'.
""" """
if isinstance(entries, str): if isinstance(entries, str):
entries = [entries] entries = [entries]
# If list is empty, nothing to do # If list is empty, nothing to do
if not entries: if not entries:
return return
if force:
cmd = ["zip", "-q", "-d", zip_filename] + entries with zipfile.ZipFile(zip_filename, 'r') as zin:
else: if not force and len(set(zin.namelist()).intersection(entries)) == 0:
cmd = ["zip", "-d", zip_filename] + entries raise ExternalError(
if force: "Failed to delete zip entries, name not matched: %s" % entries)
p = Run(cmd)
p.wait() fd, new_zipfile = tempfile.mkstemp(dir=os.path.dirname(zip_filename))
else: os.close(fd)
RunAndCheckOutput(cmd)
with zipfile.ZipFile(new_zipfile, 'w') as zout:
for item in zin.infolist():
if item.filename in entries:
continue
buffer = zin.read(item.filename)
zout.writestr(item, buffer)
os.replace(new_zipfile, zip_filename)
def ZipClose(zip_file): def ZipClose(zip_file):