Skip to content

gh-121402: Fix ZipFile.open() to set current time by default, add .newfile() #121405

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 20 additions & 6 deletions Lib/zipfile/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import sys
import threading
import time
import datetime

try:
import zlib # We may need its compression method
Expand Down Expand Up @@ -404,11 +405,13 @@ def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)):
# Terminate the file name at the first null byte and
# ensure paths always use forward slashes as the directory separator.
filename = _sanitize_filename(filename)

self.filename = filename # Normalized file name
self.date_time = date_time # year, month, day, hour, min, sec

if date_time[0] < 1980:
# Use current time if year parameter is set to zero or None
self.date_time = date_time # year, month, day, hour, min, sec
if not self.date_time[0]:
self.date_time = datetime.datetime.now().timetuple()
if self.date_time[0] < 1980:
raise ValueError('ZIP does not support timestamps before 1980')

# Standard values:
Expand Down Expand Up @@ -1565,6 +1568,19 @@ def getinfo(self, name):

return info

def newinfo(self, name):
"""Return new instance of ZipInfo for file 'name'.
It will be set to the currently configured compression algorithm of this archive.
The timestamp for the new file will be set to the current time.
"""
info = ZipInfo(name, [None]) # passing None defaults to now instead of 1980
if self.compression is not None:
info.compress_type = self.compression
if self.compresslevel is not None:
info.compress_level = self.compresslevel

return info

def setpassword(self, pwd):
"""Set default password for encrypted files."""
if pwd and not isinstance(pwd, bytes):
Expand Down Expand Up @@ -1627,9 +1643,7 @@ def open(self, name, mode="r", pwd=None, *, force_zip64=False):
# 'name' is already an info object
zinfo = name
elif mode == 'w':
zinfo = ZipInfo(name)
zinfo.compress_type = self.compression
zinfo.compress_level = self.compresslevel
zinfo = self.newinfo(name)
else:
# Get info object for name
zinfo = self.getinfo(name)
Expand Down
Loading