Cleanup some zipfile code

This commit is contained in:
Kovid Goyal 2025-04-07 08:18:35 +05:30
parent 1ebbf424c2
commit b4251ab1be
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C

View File

@ -1147,7 +1147,7 @@ class ZipFile:
if upperdirs and not os.path.exists(upperdirs): if upperdirs and not os.path.exists(upperdirs):
try: try:
os.makedirs(upperdirs) os.makedirs(upperdirs)
except: # Added by Kovid except OSError: # Added by Kovid
targetpath = os.path.join(base_target, targetpath = os.path.join(base_target,
sanitize_file_name(fname)) sanitize_file_name(fname))
upperdirs = os.path.dirname(targetpath) upperdirs = os.path.dirname(targetpath)
@ -1158,7 +1158,7 @@ class ZipFile:
if not os.path.isdir(targetpath): if not os.path.isdir(targetpath):
try: try:
os.mkdir(targetpath) os.mkdir(targetpath)
except Exception: # Added by Kovid except OSError: # Added by Kovid
targetpath = os.path.join(base_target, sanitize_file_name(fname)) targetpath = os.path.join(base_target, sanitize_file_name(fname))
os.mkdir(targetpath) os.mkdir(targetpath)
return targetpath return targetpath
@ -1166,17 +1166,16 @@ class ZipFile:
if not os.path.exists(targetpath): if not os.path.exists(targetpath):
# Kovid: Could be a previously automatically created directory # Kovid: Could be a previously automatically created directory
# in which case it is ignored # in which case it is ignored
with closing(self.open(member, pwd=pwd)) as source: try:
try: target = open(targetpath, 'wb')
with open(targetpath, 'wb') as target: except OSError:
shutil.copyfileobj(source, target) components = list(os.path.split(targetpath))
except: components[-1] = sanitize_file_name(components[-1])
# Try sanitizing the file name to remove invalid characters targetpath = os.sep.join(components)
components = list(os.path.split(targetpath)) target = open(targetpath, 'wb')
components[-1] = sanitize_file_name(components[-1])
targetpath = os.sep.join(components) with target, closing(self.open(member, pwd=pwd)) as source:
with open(targetpath, 'wb') as target: shutil.copyfileobj(source, target)
shutil.copyfileobj(source, target)
# Kovid: Try to preserve the timestamps in the ZIP file # Kovid: Try to preserve the timestamps in the ZIP file
try: try:
mtime = time.localtime() mtime = time.localtime()