Delete zipfile.py
Browse files- zipfile.py +0 -1966
zipfile.py
DELETED
|
@@ -1,1966 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Read and write ZIP files.
|
| 3 |
-
|
| 4 |
-
XXX references to utf-8 need further investigation.
|
| 5 |
-
"""
|
| 6 |
-
import io
|
| 7 |
-
import os
|
| 8 |
-
import re
|
| 9 |
-
import importlib.util
|
| 10 |
-
import sys
|
| 11 |
-
import time
|
| 12 |
-
import stat
|
| 13 |
-
import shutil
|
| 14 |
-
import struct
|
| 15 |
-
import binascii
|
| 16 |
-
|
| 17 |
-
try:
|
| 18 |
-
import threading
|
| 19 |
-
except ImportError:
|
| 20 |
-
import dummy_threading as threading
|
| 21 |
-
|
| 22 |
-
try:
|
| 23 |
-
import zlib # We may need its compression method
|
| 24 |
-
crc32 = zlib.crc32
|
| 25 |
-
except ImportError:
|
| 26 |
-
zlib = None
|
| 27 |
-
crc32 = binascii.crc32
|
| 28 |
-
|
| 29 |
-
try:
|
| 30 |
-
import bz2 # We may need its compression method
|
| 31 |
-
except ImportError:
|
| 32 |
-
bz2 = None
|
| 33 |
-
|
| 34 |
-
try:
|
| 35 |
-
import lzma # We may need its compression method
|
| 36 |
-
except ImportError:
|
| 37 |
-
lzma = None
|
| 38 |
-
|
| 39 |
-
__all__ = ["BadZipFile", "BadZipfile", "error",
|
| 40 |
-
"ZIP_STORED", "ZIP_DEFLATED", "ZIP_BZIP2", "ZIP_LZMA",
|
| 41 |
-
"is_zipfile", "ZipInfo", "ZipFile", "PyZipFile", "LargeZipFile"]
|
| 42 |
-
|
| 43 |
-
class BadZipFile(Exception):
|
| 44 |
-
pass
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
class LargeZipFile(Exception):
|
| 48 |
-
"""
|
| 49 |
-
Raised when writing a zipfile, the zipfile requires ZIP64 extensions
|
| 50 |
-
and those extensions are disabled.
|
| 51 |
-
"""
|
| 52 |
-
|
| 53 |
-
error = BadZipfile = BadZipFile # Pre-3.2 compatibility names
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
ZIP64_LIMIT = (1 << 31) - 1
|
| 57 |
-
ZIP_FILECOUNT_LIMIT = (1 << 16) - 1
|
| 58 |
-
ZIP_MAX_COMMENT = (1 << 16) - 1
|
| 59 |
-
|
| 60 |
-
# constants for Zip file compression methods
|
| 61 |
-
ZIP_STORED = 0
|
| 62 |
-
ZIP_DEFLATED = 8
|
| 63 |
-
ZIP_BZIP2 = 12
|
| 64 |
-
ZIP_LZMA = 14
|
| 65 |
-
# Other ZIP compression methods not supported
|
| 66 |
-
|
| 67 |
-
DEFAULT_VERSION = 20
|
| 68 |
-
ZIP64_VERSION = 45
|
| 69 |
-
BZIP2_VERSION = 46
|
| 70 |
-
LZMA_VERSION = 63
|
| 71 |
-
# we recognize (but not necessarily support) all features up to that version
|
| 72 |
-
MAX_EXTRACT_VERSION = 63
|
| 73 |
-
|
| 74 |
-
# Below are some formats and associated data for reading/writing headers using
|
| 75 |
-
# the struct module. The names and structures of headers/records are those used
|
| 76 |
-
# in the PKWARE description of the ZIP file format:
|
| 77 |
-
# http://www.pkware.com/documents/casestudies/APPNOTE.TXT
|
| 78 |
-
# (URL valid as of January 2008)
|
| 79 |
-
|
| 80 |
-
# The "end of central directory" structure, magic number, size, and indices
|
| 81 |
-
# (section V.I in the format document)
|
| 82 |
-
structEndArchive = b"<4s4H2LH"
|
| 83 |
-
stringEndArchive = b"PK\005\006"
|
| 84 |
-
sizeEndCentDir = struct.calcsize(structEndArchive)
|
| 85 |
-
|
| 86 |
-
_ECD_SIGNATURE = 0
|
| 87 |
-
_ECD_DISK_NUMBER = 1
|
| 88 |
-
_ECD_DISK_START = 2
|
| 89 |
-
_ECD_ENTRIES_THIS_DISK = 3
|
| 90 |
-
_ECD_ENTRIES_TOTAL = 4
|
| 91 |
-
_ECD_SIZE = 5
|
| 92 |
-
_ECD_OFFSET = 6
|
| 93 |
-
_ECD_COMMENT_SIZE = 7
|
| 94 |
-
# These last two indices are not part of the structure as defined in the
|
| 95 |
-
# spec, but they are used internally by this module as a convenience
|
| 96 |
-
_ECD_COMMENT = 8
|
| 97 |
-
_ECD_LOCATION = 9
|
| 98 |
-
|
| 99 |
-
# The "central directory" structure, magic number, size, and indices
|
| 100 |
-
# of entries in the structure (section V.F in the format document)
|
| 101 |
-
structCentralDir = "<4s4B4HL2L5H2L"
|
| 102 |
-
stringCentralDir = b"PK\001\002"
|
| 103 |
-
sizeCentralDir = struct.calcsize(structCentralDir)
|
| 104 |
-
|
| 105 |
-
# indexes of entries in the central directory structure
|
| 106 |
-
_CD_SIGNATURE = 0
|
| 107 |
-
_CD_CREATE_VERSION = 1
|
| 108 |
-
_CD_CREATE_SYSTEM = 2
|
| 109 |
-
_CD_EXTRACT_VERSION = 3
|
| 110 |
-
_CD_EXTRACT_SYSTEM = 4
|
| 111 |
-
_CD_FLAG_BITS = 5
|
| 112 |
-
_CD_COMPRESS_TYPE = 6
|
| 113 |
-
_CD_TIME = 7
|
| 114 |
-
_CD_DATE = 8
|
| 115 |
-
_CD_CRC = 9
|
| 116 |
-
_CD_COMPRESSED_SIZE = 10
|
| 117 |
-
_CD_UNCOMPRESSED_SIZE = 11
|
| 118 |
-
_CD_FILENAME_LENGTH = 12
|
| 119 |
-
_CD_EXTRA_FIELD_LENGTH = 13
|
| 120 |
-
_CD_COMMENT_LENGTH = 14
|
| 121 |
-
_CD_DISK_NUMBER_START = 15
|
| 122 |
-
_CD_INTERNAL_FILE_ATTRIBUTES = 16
|
| 123 |
-
_CD_EXTERNAL_FILE_ATTRIBUTES = 17
|
| 124 |
-
_CD_LOCAL_HEADER_OFFSET = 18
|
| 125 |
-
|
| 126 |
-
# The "local file header" structure, magic number, size, and indices
|
| 127 |
-
# (section V.A in the format document)
|
| 128 |
-
structFileHeader = "<4s2B4HL2L2H"
|
| 129 |
-
stringFileHeader = b"PK\003\004"
|
| 130 |
-
sizeFileHeader = struct.calcsize(structFileHeader)
|
| 131 |
-
|
| 132 |
-
_FH_SIGNATURE = 0
|
| 133 |
-
_FH_EXTRACT_VERSION = 1
|
| 134 |
-
_FH_EXTRACT_SYSTEM = 2
|
| 135 |
-
_FH_GENERAL_PURPOSE_FLAG_BITS = 3
|
| 136 |
-
_FH_COMPRESSION_METHOD = 4
|
| 137 |
-
_FH_LAST_MOD_TIME = 5
|
| 138 |
-
_FH_LAST_MOD_DATE = 6
|
| 139 |
-
_FH_CRC = 7
|
| 140 |
-
_FH_COMPRESSED_SIZE = 8
|
| 141 |
-
_FH_UNCOMPRESSED_SIZE = 9
|
| 142 |
-
_FH_FILENAME_LENGTH = 10
|
| 143 |
-
_FH_EXTRA_FIELD_LENGTH = 11
|
| 144 |
-
|
| 145 |
-
# The "Zip64 end of central directory locator" structure, magic number, and size
|
| 146 |
-
structEndArchive64Locator = "<4sLQL"
|
| 147 |
-
stringEndArchive64Locator = b"PK\x06\x07"
|
| 148 |
-
sizeEndCentDir64Locator = struct.calcsize(structEndArchive64Locator)
|
| 149 |
-
|
| 150 |
-
# The "Zip64 end of central directory" record, magic number, size, and indices
|
| 151 |
-
# (section V.G in the format document)
|
| 152 |
-
structEndArchive64 = "<4sQ2H2L4Q"
|
| 153 |
-
stringEndArchive64 = b"PK\x06\x06"
|
| 154 |
-
sizeEndCentDir64 = struct.calcsize(structEndArchive64)
|
| 155 |
-
|
| 156 |
-
_CD64_SIGNATURE = 0
|
| 157 |
-
_CD64_DIRECTORY_RECSIZE = 1
|
| 158 |
-
_CD64_CREATE_VERSION = 2
|
| 159 |
-
_CD64_EXTRACT_VERSION = 3
|
| 160 |
-
_CD64_DISK_NUMBER = 4
|
| 161 |
-
_CD64_DISK_NUMBER_START = 5
|
| 162 |
-
_CD64_NUMBER_ENTRIES_THIS_DISK = 6
|
| 163 |
-
_CD64_NUMBER_ENTRIES_TOTAL = 7
|
| 164 |
-
_CD64_DIRECTORY_SIZE = 8
|
| 165 |
-
_CD64_OFFSET_START_CENTDIR = 9
|
| 166 |
-
|
| 167 |
-
def _check_zipfile(fp):
|
| 168 |
-
try:
|
| 169 |
-
if _EndRecData(fp):
|
| 170 |
-
return True # file has correct magic number
|
| 171 |
-
except OSError:
|
| 172 |
-
pass
|
| 173 |
-
return False
|
| 174 |
-
|
| 175 |
-
def is_zipfile(filename):
|
| 176 |
-
"""Quickly see if a file is a ZIP file by checking the magic number.
|
| 177 |
-
|
| 178 |
-
The filename argument may be a file or file-like object too.
|
| 179 |
-
"""
|
| 180 |
-
result = False
|
| 181 |
-
try:
|
| 182 |
-
if hasattr(filename, "read"):
|
| 183 |
-
result = _check_zipfile(fp=filename)
|
| 184 |
-
else:
|
| 185 |
-
with open(filename, "rb") as fp:
|
| 186 |
-
result = _check_zipfile(fp)
|
| 187 |
-
except OSError:
|
| 188 |
-
pass
|
| 189 |
-
return result
|
| 190 |
-
|
| 191 |
-
def _EndRecData64(fpin, offset, endrec):
|
| 192 |
-
"""
|
| 193 |
-
Read the ZIP64 end-of-archive records and use that to update endrec
|
| 194 |
-
"""
|
| 195 |
-
try:
|
| 196 |
-
fpin.seek(offset - sizeEndCentDir64Locator, 2)
|
| 197 |
-
except OSError:
|
| 198 |
-
# If the seek fails, the file is not large enough to contain a ZIP64
|
| 199 |
-
# end-of-archive record, so just return the end record we were given.
|
| 200 |
-
return endrec
|
| 201 |
-
|
| 202 |
-
data = fpin.read(sizeEndCentDir64Locator)
|
| 203 |
-
if len(data) != sizeEndCentDir64Locator:
|
| 204 |
-
return endrec
|
| 205 |
-
sig, diskno, reloff, disks = struct.unpack(structEndArchive64Locator, data)
|
| 206 |
-
if sig != stringEndArchive64Locator:
|
| 207 |
-
return endrec
|
| 208 |
-
|
| 209 |
-
if diskno != 0 or disks != 1:
|
| 210 |
-
raise BadZipFile("zipfiles that span multiple disks are not supported")
|
| 211 |
-
|
| 212 |
-
# Assume no 'zip64 extensible data'
|
| 213 |
-
fpin.seek(offset - sizeEndCentDir64Locator - sizeEndCentDir64, 2)
|
| 214 |
-
data = fpin.read(sizeEndCentDir64)
|
| 215 |
-
if len(data) != sizeEndCentDir64:
|
| 216 |
-
return endrec
|
| 217 |
-
sig, sz, create_version, read_version, disk_num, disk_dir, \
|
| 218 |
-
dircount, dircount2, dirsize, diroffset = \
|
| 219 |
-
struct.unpack(structEndArchive64, data)
|
| 220 |
-
if sig != stringEndArchive64:
|
| 221 |
-
return endrec
|
| 222 |
-
|
| 223 |
-
# Update the original endrec using data from the ZIP64 record
|
| 224 |
-
endrec[_ECD_SIGNATURE] = sig
|
| 225 |
-
endrec[_ECD_DISK_NUMBER] = disk_num
|
| 226 |
-
endrec[_ECD_DISK_START] = disk_dir
|
| 227 |
-
endrec[_ECD_ENTRIES_THIS_DISK] = dircount
|
| 228 |
-
endrec[_ECD_ENTRIES_TOTAL] = dircount2
|
| 229 |
-
endrec[_ECD_SIZE] = dirsize
|
| 230 |
-
endrec[_ECD_OFFSET] = diroffset
|
| 231 |
-
return endrec
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
def _EndRecData(fpin):
|
| 235 |
-
"""Return data from the "End of Central Directory" record, or None.
|
| 236 |
-
|
| 237 |
-
The data is a list of the nine items in the ZIP "End of central dir"
|
| 238 |
-
record followed by a tenth item, the file seek offset of this record."""
|
| 239 |
-
|
| 240 |
-
# Determine file size
|
| 241 |
-
fpin.seek(0, 2)
|
| 242 |
-
filesize = fpin.tell()
|
| 243 |
-
|
| 244 |
-
# Check to see if this is ZIP file with no archive comment (the
|
| 245 |
-
# "end of central directory" structure should be the last item in the
|
| 246 |
-
# file if this is the case).
|
| 247 |
-
try:
|
| 248 |
-
fpin.seek(-sizeEndCentDir, 2)
|
| 249 |
-
except OSError:
|
| 250 |
-
return None
|
| 251 |
-
data = fpin.read()
|
| 252 |
-
if (len(data) == sizeEndCentDir and
|
| 253 |
-
data[0:4] == stringEndArchive and
|
| 254 |
-
data[-2:] == b"\000\000"):
|
| 255 |
-
# the signature is correct and there's no comment, unpack structure
|
| 256 |
-
endrec = struct.unpack(structEndArchive, data)
|
| 257 |
-
endrec=list(endrec)
|
| 258 |
-
|
| 259 |
-
# Append a blank comment and record start offset
|
| 260 |
-
endrec.append(b"")
|
| 261 |
-
endrec.append(filesize - sizeEndCentDir)
|
| 262 |
-
|
| 263 |
-
# Try to read the "Zip64 end of central directory" structure
|
| 264 |
-
return _EndRecData64(fpin, -sizeEndCentDir, endrec)
|
| 265 |
-
|
| 266 |
-
# Either this is not a ZIP file, or it is a ZIP file with an archive
|
| 267 |
-
# comment. Search the end of the file for the "end of central directory"
|
| 268 |
-
# record signature. The comment is the last item in the ZIP file and may be
|
| 269 |
-
# up to 64K long. It is assumed that the "end of central directory" magic
|
| 270 |
-
# number does not appear in the comment.
|
| 271 |
-
maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0)
|
| 272 |
-
fpin.seek(maxCommentStart, 0)
|
| 273 |
-
data = fpin.read()
|
| 274 |
-
start = data.rfind(stringEndArchive)
|
| 275 |
-
if start >= 0:
|
| 276 |
-
# found the magic number; attempt to unpack and interpret
|
| 277 |
-
recData = data[start:start+sizeEndCentDir]
|
| 278 |
-
if len(recData) != sizeEndCentDir:
|
| 279 |
-
# Zip file is corrupted.
|
| 280 |
-
return None
|
| 281 |
-
endrec = list(struct.unpack(structEndArchive, recData))
|
| 282 |
-
commentSize = endrec[_ECD_COMMENT_SIZE] #as claimed by the zip file
|
| 283 |
-
comment = data[start+sizeEndCentDir:start+sizeEndCentDir+commentSize]
|
| 284 |
-
endrec.append(comment)
|
| 285 |
-
endrec.append(maxCommentStart + start)
|
| 286 |
-
|
| 287 |
-
# Try to read the "Zip64 end of central directory" structure
|
| 288 |
-
return _EndRecData64(fpin, maxCommentStart + start - filesize,
|
| 289 |
-
endrec)
|
| 290 |
-
|
| 291 |
-
# Unable to find a valid end of central directory structure
|
| 292 |
-
return None
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
class ZipInfo (object):
|
| 296 |
-
"""Class with attributes describing each file in the ZIP archive."""
|
| 297 |
-
|
| 298 |
-
__slots__ = (
|
| 299 |
-
'orig_filename',
|
| 300 |
-
'filename',
|
| 301 |
-
'date_time',
|
| 302 |
-
'compress_type',
|
| 303 |
-
'comment',
|
| 304 |
-
'extra',
|
| 305 |
-
'create_system',
|
| 306 |
-
'create_version',
|
| 307 |
-
'extract_version',
|
| 308 |
-
'reserved',
|
| 309 |
-
'flag_bits',
|
| 310 |
-
'volume',
|
| 311 |
-
'internal_attr',
|
| 312 |
-
'external_attr',
|
| 313 |
-
'header_offset',
|
| 314 |
-
'CRC',
|
| 315 |
-
'compress_size',
|
| 316 |
-
'file_size',
|
| 317 |
-
'_raw_time',
|
| 318 |
-
)
|
| 319 |
-
|
| 320 |
-
def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)):
|
| 321 |
-
self.orig_filename = filename # Original file name in archive
|
| 322 |
-
|
| 323 |
-
# Terminate the file name at the first null byte. Null bytes in file
|
| 324 |
-
# names are used as tricks by viruses in archives.
|
| 325 |
-
null_byte = filename.find(chr(0))
|
| 326 |
-
if null_byte >= 0:
|
| 327 |
-
filename = filename[0:null_byte]
|
| 328 |
-
# This is used to ensure paths in generated ZIP files always use
|
| 329 |
-
# forward slashes as the directory separator, as required by the
|
| 330 |
-
# ZIP format specification.
|
| 331 |
-
if os.sep != "/" and os.sep in filename:
|
| 332 |
-
filename = filename.replace(os.sep, "/")
|
| 333 |
-
|
| 334 |
-
self.filename = filename # Normalized file name
|
| 335 |
-
self.date_time = date_time # year, month, day, hour, min, sec
|
| 336 |
-
|
| 337 |
-
if date_time[0] < 1980:
|
| 338 |
-
raise ValueError('ZIP does not support timestamps before 1980')
|
| 339 |
-
|
| 340 |
-
# Standard values:
|
| 341 |
-
self.compress_type = ZIP_STORED # Type of compression for the file
|
| 342 |
-
self.comment = b"" # Comment for each file
|
| 343 |
-
self.extra = b"" # ZIP extra data
|
| 344 |
-
if sys.platform == 'win32':
|
| 345 |
-
self.create_system = 0 # System which created ZIP archive
|
| 346 |
-
else:
|
| 347 |
-
# Assume everything else is unix-y
|
| 348 |
-
self.create_system = 3 # System which created ZIP archive
|
| 349 |
-
self.create_version = DEFAULT_VERSION # Version which created ZIP archive
|
| 350 |
-
self.extract_version = DEFAULT_VERSION # Version needed to extract archive
|
| 351 |
-
self.reserved = 0 # Must be zero
|
| 352 |
-
self.flag_bits = 0 # ZIP flag bits
|
| 353 |
-
self.volume = 0 # Volume number of file header
|
| 354 |
-
self.internal_attr = 0 # Internal attributes
|
| 355 |
-
self.external_attr = 0 # External file attributes
|
| 356 |
-
# Other attributes are set by class ZipFile:
|
| 357 |
-
# header_offset Byte offset to the file header
|
| 358 |
-
# CRC CRC-32 of the uncompressed file
|
| 359 |
-
# compress_size Size of the compressed file
|
| 360 |
-
# file_size Size of the uncompressed file
|
| 361 |
-
|
| 362 |
-
def __repr__(self):
|
| 363 |
-
result = ['<%s filename=%r' % (self.__class__.__name__, self.filename)]
|
| 364 |
-
if self.compress_type != ZIP_STORED:
|
| 365 |
-
result.append(' compress_type=%s' %
|
| 366 |
-
compressor_names.get(self.compress_type,
|
| 367 |
-
self.compress_type))
|
| 368 |
-
hi = self.external_attr >> 16
|
| 369 |
-
lo = self.external_attr & 0xFFFF
|
| 370 |
-
if hi:
|
| 371 |
-
result.append(' filemode=%r' % stat.filemode(hi))
|
| 372 |
-
if lo:
|
| 373 |
-
result.append(' external_attr=%#x' % lo)
|
| 374 |
-
isdir = self.filename[-1:] == '/'
|
| 375 |
-
if not isdir or self.file_size:
|
| 376 |
-
result.append(' file_size=%r' % self.file_size)
|
| 377 |
-
if ((not isdir or self.compress_size) and
|
| 378 |
-
(self.compress_type != ZIP_STORED or
|
| 379 |
-
self.file_size != self.compress_size)):
|
| 380 |
-
result.append(' compress_size=%r' % self.compress_size)
|
| 381 |
-
result.append('>')
|
| 382 |
-
return ''.join(result)
|
| 383 |
-
|
| 384 |
-
def FileHeader(self, zip64=None):
|
| 385 |
-
"""Return the per-file header as a string."""
|
| 386 |
-
dt = self.date_time
|
| 387 |
-
dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
|
| 388 |
-
dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
|
| 389 |
-
if self.flag_bits & 0x08:
|
| 390 |
-
# Set these to zero because we write them after the file data
|
| 391 |
-
CRC = compress_size = file_size = 0
|
| 392 |
-
else:
|
| 393 |
-
CRC = self.CRC
|
| 394 |
-
compress_size = self.compress_size
|
| 395 |
-
file_size = self.file_size
|
| 396 |
-
|
| 397 |
-
extra = self.extra
|
| 398 |
-
|
| 399 |
-
min_version = 0
|
| 400 |
-
if zip64 is None:
|
| 401 |
-
zip64 = file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT
|
| 402 |
-
if zip64:
|
| 403 |
-
fmt = '<HHQQ'
|
| 404 |
-
extra = extra + struct.pack(fmt,
|
| 405 |
-
1, struct.calcsize(fmt)-4, file_size, compress_size)
|
| 406 |
-
if file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT:
|
| 407 |
-
if not zip64:
|
| 408 |
-
raise LargeZipFile("Filesize would require ZIP64 extensions")
|
| 409 |
-
# File is larger than what fits into a 4 byte integer,
|
| 410 |
-
# fall back to the ZIP64 extension
|
| 411 |
-
file_size = 0xffffffff
|
| 412 |
-
compress_size = 0xffffffff
|
| 413 |
-
min_version = ZIP64_VERSION
|
| 414 |
-
|
| 415 |
-
if self.compress_type == ZIP_BZIP2:
|
| 416 |
-
min_version = max(BZIP2_VERSION, min_version)
|
| 417 |
-
elif self.compress_type == ZIP_LZMA:
|
| 418 |
-
min_version = max(LZMA_VERSION, min_version)
|
| 419 |
-
|
| 420 |
-
self.extract_version = max(min_version, self.extract_version)
|
| 421 |
-
self.create_version = max(min_version, self.create_version)
|
| 422 |
-
filename, flag_bits = self._encodeFilenameFlags()
|
| 423 |
-
header = struct.pack(structFileHeader, stringFileHeader,
|
| 424 |
-
self.extract_version, self.reserved, flag_bits,
|
| 425 |
-
self.compress_type, dostime, dosdate, CRC,
|
| 426 |
-
compress_size, file_size,
|
| 427 |
-
len(filename), len(extra))
|
| 428 |
-
return header + filename + extra
|
| 429 |
-
|
| 430 |
-
def _encodeFilenameFlags(self):
|
| 431 |
-
try:
|
| 432 |
-
return self.filename.encode('ascii'), self.flag_bits
|
| 433 |
-
except UnicodeEncodeError:
|
| 434 |
-
return self.filename.encode('utf-8'), self.flag_bits | 0x800
|
| 435 |
-
|
| 436 |
-
def _decodeExtra(self):
|
| 437 |
-
# Try to decode the extra field.
|
| 438 |
-
extra = self.extra
|
| 439 |
-
unpack = struct.unpack
|
| 440 |
-
while len(extra) >= 4:
|
| 441 |
-
tp, ln = unpack('<HH', extra[:4])
|
| 442 |
-
if tp == 1:
|
| 443 |
-
if ln >= 24:
|
| 444 |
-
counts = unpack('<QQQ', extra[4:28])
|
| 445 |
-
elif ln == 16:
|
| 446 |
-
counts = unpack('<QQ', extra[4:20])
|
| 447 |
-
elif ln == 8:
|
| 448 |
-
counts = unpack('<Q', extra[4:12])
|
| 449 |
-
elif ln == 0:
|
| 450 |
-
counts = ()
|
| 451 |
-
else:
|
| 452 |
-
raise RuntimeError("Corrupt extra field %s"%(ln,))
|
| 453 |
-
|
| 454 |
-
idx = 0
|
| 455 |
-
|
| 456 |
-
# ZIP64 extension (large files and/or large archives)
|
| 457 |
-
if self.file_size in (0xffffffffffffffff, 0xffffffff):
|
| 458 |
-
self.file_size = counts[idx]
|
| 459 |
-
idx += 1
|
| 460 |
-
|
| 461 |
-
if self.compress_size == 0xFFFFFFFF:
|
| 462 |
-
self.compress_size = counts[idx]
|
| 463 |
-
idx += 1
|
| 464 |
-
|
| 465 |
-
if self.header_offset == 0xffffffff:
|
| 466 |
-
old = self.header_offset
|
| 467 |
-
self.header_offset = counts[idx]
|
| 468 |
-
idx+=1
|
| 469 |
-
|
| 470 |
-
extra = extra[ln+4:]
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
class _ZipDecrypter:
|
| 474 |
-
"""Class to handle decryption of files stored within a ZIP archive.
|
| 475 |
-
|
| 476 |
-
ZIP supports a password-based form of encryption. Even though known
|
| 477 |
-
plaintext attacks have been found against it, it is still useful
|
| 478 |
-
to be able to get data out of such a file.
|
| 479 |
-
|
| 480 |
-
Usage:
|
| 481 |
-
zd = _ZipDecrypter(mypwd)
|
| 482 |
-
plain_char = zd(cypher_char)
|
| 483 |
-
plain_text = map(zd, cypher_text)
|
| 484 |
-
"""
|
| 485 |
-
|
| 486 |
-
def _GenerateCRCTable():
|
| 487 |
-
"""Generate a CRC-32 table.
|
| 488 |
-
|
| 489 |
-
ZIP encryption uses the CRC32 one-byte primitive for scrambling some
|
| 490 |
-
internal keys. We noticed that a direct implementation is faster than
|
| 491 |
-
relying on binascii.crc32().
|
| 492 |
-
"""
|
| 493 |
-
poly = 0xedb88320
|
| 494 |
-
table = [0] * 256
|
| 495 |
-
for i in range(256):
|
| 496 |
-
crc = i
|
| 497 |
-
for j in range(8):
|
| 498 |
-
if crc & 1:
|
| 499 |
-
crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly
|
| 500 |
-
else:
|
| 501 |
-
crc = ((crc >> 1) & 0x7FFFFFFF)
|
| 502 |
-
table[i] = crc
|
| 503 |
-
return table
|
| 504 |
-
crctable = None
|
| 505 |
-
|
| 506 |
-
def _crc32(self, ch, crc):
|
| 507 |
-
"""Compute the CRC32 primitive on one byte."""
|
| 508 |
-
return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ch) & 0xff]
|
| 509 |
-
|
| 510 |
-
def __init__(self, pwd):
|
| 511 |
-
if _ZipDecrypter.crctable is None:
|
| 512 |
-
_ZipDecrypter.crctable = _ZipDecrypter._GenerateCRCTable()
|
| 513 |
-
self.key0 = 305419896
|
| 514 |
-
self.key1 = 591751049
|
| 515 |
-
self.key2 = 878082192
|
| 516 |
-
for p in pwd:
|
| 517 |
-
self._UpdateKeys(p)
|
| 518 |
-
|
| 519 |
-
def _UpdateKeys(self, c):
|
| 520 |
-
self.key0 = self._crc32(c, self.key0)
|
| 521 |
-
self.key1 = (self.key1 + (self.key0 & 255)) & 4294967295
|
| 522 |
-
self.key1 = (self.key1 * 134775813 + 1) & 4294967295
|
| 523 |
-
self.key2 = self._crc32((self.key1 >> 24) & 255, self.key2)
|
| 524 |
-
|
| 525 |
-
def __call__(self, c):
|
| 526 |
-
"""Decrypt a single character."""
|
| 527 |
-
assert isinstance(c, int)
|
| 528 |
-
k = self.key2 | 2
|
| 529 |
-
c = c ^ (((k * (k^1)) >> 8) & 255)
|
| 530 |
-
self._UpdateKeys(c)
|
| 531 |
-
return c
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
class LZMACompressor:
|
| 535 |
-
|
| 536 |
-
def __init__(self):
|
| 537 |
-
self._comp = None
|
| 538 |
-
|
| 539 |
-
def _init(self):
|
| 540 |
-
props = lzma._encode_filter_properties({'id': lzma.FILTER_LZMA1})
|
| 541 |
-
self._comp = lzma.LZMACompressor(lzma.FORMAT_RAW, filters=[
|
| 542 |
-
lzma._decode_filter_properties(lzma.FILTER_LZMA1, props)
|
| 543 |
-
])
|
| 544 |
-
return struct.pack('<BBH', 9, 4, len(props)) + props
|
| 545 |
-
|
| 546 |
-
def compress(self, data):
|
| 547 |
-
if self._comp is None:
|
| 548 |
-
return self._init() + self._comp.compress(data)
|
| 549 |
-
return self._comp.compress(data)
|
| 550 |
-
|
| 551 |
-
def flush(self):
|
| 552 |
-
if self._comp is None:
|
| 553 |
-
return self._init() + self._comp.flush()
|
| 554 |
-
return self._comp.flush()
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
class LZMADecompressor:
|
| 558 |
-
|
| 559 |
-
def __init__(self):
|
| 560 |
-
self._decomp = None
|
| 561 |
-
self._unconsumed = b''
|
| 562 |
-
self.eof = False
|
| 563 |
-
|
| 564 |
-
def decompress(self, data):
|
| 565 |
-
if self._decomp is None:
|
| 566 |
-
self._unconsumed += data
|
| 567 |
-
if len(self._unconsumed) <= 4:
|
| 568 |
-
return b''
|
| 569 |
-
psize, = struct.unpack('<H', self._unconsumed[2:4])
|
| 570 |
-
if len(self._unconsumed) <= 4 + psize:
|
| 571 |
-
return b''
|
| 572 |
-
|
| 573 |
-
self._decomp = lzma.LZMADecompressor(lzma.FORMAT_RAW, filters=[
|
| 574 |
-
lzma._decode_filter_properties(lzma.FILTER_LZMA1,
|
| 575 |
-
self._unconsumed[4:4 + psize])
|
| 576 |
-
])
|
| 577 |
-
data = self._unconsumed[4 + psize:]
|
| 578 |
-
del self._unconsumed
|
| 579 |
-
|
| 580 |
-
result = self._decomp.decompress(data)
|
| 581 |
-
self.eof = self._decomp.eof
|
| 582 |
-
return result
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
compressor_names = {
|
| 586 |
-
0: 'store',
|
| 587 |
-
1: 'shrink',
|
| 588 |
-
2: 'reduce',
|
| 589 |
-
3: 'reduce',
|
| 590 |
-
4: 'reduce',
|
| 591 |
-
5: 'reduce',
|
| 592 |
-
6: 'implode',
|
| 593 |
-
7: 'tokenize',
|
| 594 |
-
8: 'deflate',
|
| 595 |
-
9: 'deflate64',
|
| 596 |
-
10: 'implode',
|
| 597 |
-
12: 'bzip2',
|
| 598 |
-
14: 'lzma',
|
| 599 |
-
18: 'terse',
|
| 600 |
-
19: 'lz77',
|
| 601 |
-
97: 'wavpack',
|
| 602 |
-
98: 'ppmd',
|
| 603 |
-
}
|
| 604 |
-
|
| 605 |
-
def _check_compression(compression):
|
| 606 |
-
if compression == ZIP_STORED:
|
| 607 |
-
pass
|
| 608 |
-
elif compression == ZIP_DEFLATED:
|
| 609 |
-
if not zlib:
|
| 610 |
-
raise RuntimeError(
|
| 611 |
-
"Compression requires the (missing) zlib module")
|
| 612 |
-
elif compression == ZIP_BZIP2:
|
| 613 |
-
if not bz2:
|
| 614 |
-
raise RuntimeError(
|
| 615 |
-
"Compression requires the (missing) bz2 module")
|
| 616 |
-
elif compression == ZIP_LZMA:
|
| 617 |
-
if not lzma:
|
| 618 |
-
raise RuntimeError(
|
| 619 |
-
"Compression requires the (missing) lzma module")
|
| 620 |
-
else:
|
| 621 |
-
raise RuntimeError("That compression method is not supported")
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
def _get_compressor(compress_type):
|
| 625 |
-
if compress_type == ZIP_DEFLATED:
|
| 626 |
-
return zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
|
| 627 |
-
zlib.DEFLATED, -15)
|
| 628 |
-
elif compress_type == ZIP_BZIP2:
|
| 629 |
-
return bz2.BZ2Compressor()
|
| 630 |
-
elif compress_type == ZIP_LZMA:
|
| 631 |
-
return LZMACompressor()
|
| 632 |
-
else:
|
| 633 |
-
return None
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
def _get_decompressor(compress_type):
|
| 637 |
-
if compress_type == ZIP_STORED:
|
| 638 |
-
return None
|
| 639 |
-
elif compress_type == ZIP_DEFLATED:
|
| 640 |
-
return zlib.decompressobj(-15)
|
| 641 |
-
elif compress_type == ZIP_BZIP2:
|
| 642 |
-
return bz2.BZ2Decompressor()
|
| 643 |
-
elif compress_type == ZIP_LZMA:
|
| 644 |
-
return LZMADecompressor()
|
| 645 |
-
else:
|
| 646 |
-
descr = compressor_names.get(compress_type)
|
| 647 |
-
if descr:
|
| 648 |
-
raise NotImplementedError("compression type %d (%s)" % (compress_type, descr))
|
| 649 |
-
else:
|
| 650 |
-
raise NotImplementedError("compression type %d" % (compress_type,))
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
class _SharedFile:
|
| 654 |
-
def __init__(self, file, pos, close, lock):
|
| 655 |
-
self._file = file
|
| 656 |
-
self._pos = pos
|
| 657 |
-
self._close = close
|
| 658 |
-
self._lock = lock
|
| 659 |
-
|
| 660 |
-
def read(self, n=-1):
|
| 661 |
-
with self._lock:
|
| 662 |
-
self._file.seek(self._pos)
|
| 663 |
-
data = self._file.read(n)
|
| 664 |
-
self._pos = self._file.tell()
|
| 665 |
-
return data
|
| 666 |
-
|
| 667 |
-
def close(self):
|
| 668 |
-
if self._file is not None:
|
| 669 |
-
fileobj = self._file
|
| 670 |
-
self._file = None
|
| 671 |
-
self._close(fileobj)
|
| 672 |
-
|
| 673 |
-
# Provide the tell method for unseekable stream
|
| 674 |
-
class _Tellable:
|
| 675 |
-
def __init__(self, fp):
|
| 676 |
-
self.fp = fp
|
| 677 |
-
self.offset = 0
|
| 678 |
-
|
| 679 |
-
def write(self, data):
|
| 680 |
-
n = self.fp.write(data)
|
| 681 |
-
self.offset += n
|
| 682 |
-
return n
|
| 683 |
-
|
| 684 |
-
def tell(self):
|
| 685 |
-
return self.offset
|
| 686 |
-
|
| 687 |
-
def flush(self):
|
| 688 |
-
self.fp.flush()
|
| 689 |
-
|
| 690 |
-
def close(self):
|
| 691 |
-
self.fp.close()
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
class ZipExtFile(io.BufferedIOBase):
|
| 695 |
-
"""File-like object for reading an archive member.
|
| 696 |
-
Is returned by ZipFile.open().
|
| 697 |
-
"""
|
| 698 |
-
|
| 699 |
-
# Max size supported by decompressor.
|
| 700 |
-
MAX_N = 1 << 31 - 1
|
| 701 |
-
|
| 702 |
-
# Read from compressed files in 4k blocks.
|
| 703 |
-
MIN_READ_SIZE = 4096
|
| 704 |
-
|
| 705 |
-
# Search for universal newlines or line chunks.
|
| 706 |
-
PATTERN = re.compile(br'^(?P<chunk>[^\r\n]+)|(?P<newline>\n|\r\n?)')
|
| 707 |
-
|
| 708 |
-
def __init__(self, fileobj, mode, zipinfo, decrypter=None,
|
| 709 |
-
close_fileobj=False):
|
| 710 |
-
self._fileobj = fileobj
|
| 711 |
-
self._decrypter = decrypter
|
| 712 |
-
self._close_fileobj = close_fileobj
|
| 713 |
-
|
| 714 |
-
self._compress_type = zipinfo.compress_type
|
| 715 |
-
self._compress_left = zipinfo.compress_size
|
| 716 |
-
self._left = zipinfo.file_size
|
| 717 |
-
|
| 718 |
-
self._decompressor = _get_decompressor(self._compress_type)
|
| 719 |
-
|
| 720 |
-
self._eof = False
|
| 721 |
-
self._readbuffer = b''
|
| 722 |
-
self._offset = 0
|
| 723 |
-
|
| 724 |
-
self._universal = 'U' in mode
|
| 725 |
-
self.newlines = None
|
| 726 |
-
|
| 727 |
-
# Adjust read size for encrypted files since the first 12 bytes
|
| 728 |
-
# are for the encryption/password information.
|
| 729 |
-
if self._decrypter is not None:
|
| 730 |
-
self._compress_left -= 12
|
| 731 |
-
|
| 732 |
-
self.mode = mode
|
| 733 |
-
self.name = zipinfo.filename
|
| 734 |
-
|
| 735 |
-
if hasattr(zipinfo, 'CRC'):
|
| 736 |
-
self._expected_crc = zipinfo.CRC
|
| 737 |
-
self._running_crc = crc32(b'')
|
| 738 |
-
else:
|
| 739 |
-
self._expected_crc = None
|
| 740 |
-
|
| 741 |
-
def __repr__(self):
|
| 742 |
-
result = ['<%s.%s' % (self.__class__.__module__,
|
| 743 |
-
self.__class__.__qualname__)]
|
| 744 |
-
if not self.closed:
|
| 745 |
-
result.append(' name=%r mode=%r' % (self.name, self.mode))
|
| 746 |
-
if self._compress_type != ZIP_STORED:
|
| 747 |
-
result.append(' compress_type=%s' %
|
| 748 |
-
compressor_names.get(self._compress_type,
|
| 749 |
-
self._compress_type))
|
| 750 |
-
else:
|
| 751 |
-
result.append(' [closed]')
|
| 752 |
-
result.append('>')
|
| 753 |
-
return ''.join(result)
|
| 754 |
-
|
| 755 |
-
def readline(self, limit=-1):
|
| 756 |
-
"""Read and return a line from the stream.
|
| 757 |
-
|
| 758 |
-
If limit is specified, at most limit bytes will be read.
|
| 759 |
-
"""
|
| 760 |
-
|
| 761 |
-
if not self._universal and limit < 0:
|
| 762 |
-
# Shortcut common case - newline found in buffer.
|
| 763 |
-
i = self._readbuffer.find(b'\n', self._offset) + 1
|
| 764 |
-
if i > 0:
|
| 765 |
-
line = self._readbuffer[self._offset: i]
|
| 766 |
-
self._offset = i
|
| 767 |
-
return line
|
| 768 |
-
|
| 769 |
-
if not self._universal:
|
| 770 |
-
return io.BufferedIOBase.readline(self, limit)
|
| 771 |
-
|
| 772 |
-
line = b''
|
| 773 |
-
while limit < 0 or len(line) < limit:
|
| 774 |
-
readahead = self.peek(2)
|
| 775 |
-
if readahead == b'':
|
| 776 |
-
return line
|
| 777 |
-
|
| 778 |
-
#
|
| 779 |
-
# Search for universal newlines or line chunks.
|
| 780 |
-
#
|
| 781 |
-
# The pattern returns either a line chunk or a newline, but not
|
| 782 |
-
# both. Combined with peek(2), we are assured that the sequence
|
| 783 |
-
# '\r\n' is always retrieved completely and never split into
|
| 784 |
-
# separate newlines - '\r', '\n' due to coincidental readaheads.
|
| 785 |
-
#
|
| 786 |
-
match = self.PATTERN.search(readahead)
|
| 787 |
-
newline = match.group('newline')
|
| 788 |
-
if newline is not None:
|
| 789 |
-
if self.newlines is None:
|
| 790 |
-
self.newlines = []
|
| 791 |
-
if newline not in self.newlines:
|
| 792 |
-
self.newlines.append(newline)
|
| 793 |
-
self._offset += len(newline)
|
| 794 |
-
return line + b'\n'
|
| 795 |
-
|
| 796 |
-
chunk = match.group('chunk')
|
| 797 |
-
if limit >= 0:
|
| 798 |
-
chunk = chunk[: limit - len(line)]
|
| 799 |
-
|
| 800 |
-
self._offset += len(chunk)
|
| 801 |
-
line += chunk
|
| 802 |
-
|
| 803 |
-
return line
|
| 804 |
-
|
| 805 |
-
def peek(self, n=1):
|
| 806 |
-
"""Returns buffered bytes without advancing the position."""
|
| 807 |
-
if n > len(self._readbuffer) - self._offset:
|
| 808 |
-
chunk = self.read(n)
|
| 809 |
-
if len(chunk) > self._offset:
|
| 810 |
-
self._readbuffer = chunk + self._readbuffer[self._offset:]
|
| 811 |
-
self._offset = 0
|
| 812 |
-
else:
|
| 813 |
-
self._offset -= len(chunk)
|
| 814 |
-
|
| 815 |
-
# Return up to 512 bytes to reduce allocation overhead for tight loops.
|
| 816 |
-
return self._readbuffer[self._offset: self._offset + 512]
|
| 817 |
-
|
| 818 |
-
def readable(self):
|
| 819 |
-
return True
|
| 820 |
-
|
| 821 |
-
def read(self, n=-1):
|
| 822 |
-
"""Read and return up to n bytes.
|
| 823 |
-
If the argument is omitted, None, or negative, data is read and returned until EOF is reached..
|
| 824 |
-
"""
|
| 825 |
-
if n is None or n < 0:
|
| 826 |
-
buf = self._readbuffer[self._offset:]
|
| 827 |
-
self._readbuffer = b''
|
| 828 |
-
self._offset = 0
|
| 829 |
-
while not self._eof:
|
| 830 |
-
buf += self._read1(self.MAX_N)
|
| 831 |
-
return buf
|
| 832 |
-
|
| 833 |
-
end = n + self._offset
|
| 834 |
-
if end < len(self._readbuffer):
|
| 835 |
-
buf = self._readbuffer[self._offset:end]
|
| 836 |
-
self._offset = end
|
| 837 |
-
return buf
|
| 838 |
-
|
| 839 |
-
n = end - len(self._readbuffer)
|
| 840 |
-
buf = self._readbuffer[self._offset:]
|
| 841 |
-
self._readbuffer = b''
|
| 842 |
-
self._offset = 0
|
| 843 |
-
while n > 0 and not self._eof:
|
| 844 |
-
data = self._read1(n)
|
| 845 |
-
if n < len(data):
|
| 846 |
-
self._readbuffer = data
|
| 847 |
-
self._offset = n
|
| 848 |
-
buf += data[:n]
|
| 849 |
-
break
|
| 850 |
-
buf += data
|
| 851 |
-
n -= len(data)
|
| 852 |
-
return buf
|
| 853 |
-
|
| 854 |
-
def _update_crc(self, newdata):
|
| 855 |
-
# Update the CRC using the given data.
|
| 856 |
-
if self._expected_crc is None:
|
| 857 |
-
# No need to compute the CRC if we don't have a reference value
|
| 858 |
-
return
|
| 859 |
-
self._running_crc = crc32(newdata, self._running_crc)
|
| 860 |
-
# Check the CRC if we're at the end of the file
|
| 861 |
-
if self._eof and self._running_crc != self._expected_crc:
|
| 862 |
-
raise BadZipFile("Bad CRC-32 for file %r" % self.name)
|
| 863 |
-
|
| 864 |
-
def read1(self, n):
|
| 865 |
-
"""Read up to n bytes with at most one read() system call."""
|
| 866 |
-
|
| 867 |
-
if n is None or n < 0:
|
| 868 |
-
buf = self._readbuffer[self._offset:]
|
| 869 |
-
self._readbuffer = b''
|
| 870 |
-
self._offset = 0
|
| 871 |
-
while not self._eof:
|
| 872 |
-
data = self._read1(self.MAX_N)
|
| 873 |
-
if data:
|
| 874 |
-
buf += data
|
| 875 |
-
break
|
| 876 |
-
return buf
|
| 877 |
-
|
| 878 |
-
end = n + self._offset
|
| 879 |
-
if end < len(self._readbuffer):
|
| 880 |
-
buf = self._readbuffer[self._offset:end]
|
| 881 |
-
self._offset = end
|
| 882 |
-
return buf
|
| 883 |
-
|
| 884 |
-
n = end - len(self._readbuffer)
|
| 885 |
-
buf = self._readbuffer[self._offset:]
|
| 886 |
-
self._readbuffer = b''
|
| 887 |
-
self._offset = 0
|
| 888 |
-
if n > 0:
|
| 889 |
-
while not self._eof:
|
| 890 |
-
data = self._read1(n)
|
| 891 |
-
if n < len(data):
|
| 892 |
-
self._readbuffer = data
|
| 893 |
-
self._offset = n
|
| 894 |
-
buf += data[:n]
|
| 895 |
-
break
|
| 896 |
-
if data:
|
| 897 |
-
buf += data
|
| 898 |
-
break
|
| 899 |
-
return buf
|
| 900 |
-
|
| 901 |
-
def _read1(self, n):
|
| 902 |
-
# Read up to n compressed bytes with at most one read() system call,
|
| 903 |
-
# decrypt and decompress them.
|
| 904 |
-
if self._eof or n <= 0:
|
| 905 |
-
return b''
|
| 906 |
-
|
| 907 |
-
# Read from file.
|
| 908 |
-
if self._compress_type == ZIP_DEFLATED:
|
| 909 |
-
## Handle unconsumed data.
|
| 910 |
-
data = self._decompressor.unconsumed_tail
|
| 911 |
-
if n > len(data):
|
| 912 |
-
data += self._read2(n - len(data))
|
| 913 |
-
else:
|
| 914 |
-
data = self._read2(n)
|
| 915 |
-
|
| 916 |
-
if self._compress_type == ZIP_STORED:
|
| 917 |
-
self._eof = self._compress_left <= 0
|
| 918 |
-
elif self._compress_type == ZIP_DEFLATED:
|
| 919 |
-
n = max(n, self.MIN_READ_SIZE)
|
| 920 |
-
data = self._decompressor.decompress(data, n)
|
| 921 |
-
self._eof = (self._decompressor.eof or
|
| 922 |
-
self._compress_left <= 0 and
|
| 923 |
-
not self._decompressor.unconsumed_tail)
|
| 924 |
-
if self._eof:
|
| 925 |
-
data += self._decompressor.flush()
|
| 926 |
-
else:
|
| 927 |
-
data = self._decompressor.decompress(data)
|
| 928 |
-
self._eof = self._decompressor.eof or self._compress_left <= 0
|
| 929 |
-
|
| 930 |
-
data = data[:self._left]
|
| 931 |
-
self._left -= len(data)
|
| 932 |
-
if self._left <= 0:
|
| 933 |
-
self._eof = True
|
| 934 |
-
self._update_crc(data)
|
| 935 |
-
return data
|
| 936 |
-
|
| 937 |
-
def _read2(self, n):
|
| 938 |
-
if self._compress_left <= 0:
|
| 939 |
-
return b''
|
| 940 |
-
|
| 941 |
-
n = max(n, self.MIN_READ_SIZE)
|
| 942 |
-
n = min(n, self._compress_left)
|
| 943 |
-
|
| 944 |
-
data = self._fileobj.read(n)
|
| 945 |
-
self._compress_left -= len(data)
|
| 946 |
-
if not data:
|
| 947 |
-
raise EOFError
|
| 948 |
-
|
| 949 |
-
if self._decrypter is not None:
|
| 950 |
-
data = bytes(map(self._decrypter, data))
|
| 951 |
-
return data
|
| 952 |
-
|
| 953 |
-
def close(self):
|
| 954 |
-
try:
|
| 955 |
-
if self._close_fileobj:
|
| 956 |
-
self._fileobj.close()
|
| 957 |
-
finally:
|
| 958 |
-
super().close()
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
class ZipFile:
|
| 962 |
-
""" Class with methods to open, read, write, close, list zip files.
|
| 963 |
-
|
| 964 |
-
z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=True)
|
| 965 |
-
|
| 966 |
-
file: Either the path to the file, or a file-like object.
|
| 967 |
-
If it is a path, the file will be opened and closed by ZipFile.
|
| 968 |
-
mode: The mode can be either read 'r', write 'w', exclusive create 'x',
|
| 969 |
-
or append 'a'.
|
| 970 |
-
compression: ZIP_STORED (no compression), ZIP_DEFLATED (requires zlib),
|
| 971 |
-
ZIP_BZIP2 (requires bz2) or ZIP_LZMA (requires lzma).
|
| 972 |
-
allowZip64: if True ZipFile will create files with ZIP64 extensions when
|
| 973 |
-
needed, otherwise it will raise an exception when this would
|
| 974 |
-
be necessary.
|
| 975 |
-
|
| 976 |
-
"""
|
| 977 |
-
|
| 978 |
-
fp = None # Set here since __del__ checks it
|
| 979 |
-
_windows_illegal_name_trans_table = None
|
| 980 |
-
|
| 981 |
-
def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=True):
|
| 982 |
-
"""Open the ZIP file with mode read 'r', write 'w', exclusive create 'x',
|
| 983 |
-
or append 'a'."""
|
| 984 |
-
if mode not in ('r', 'w', 'x', 'a'):
|
| 985 |
-
raise RuntimeError("ZipFile requires mode 'r', 'w', 'x', or 'a'")
|
| 986 |
-
|
| 987 |
-
_check_compression(compression)
|
| 988 |
-
|
| 989 |
-
self._allowZip64 = allowZip64
|
| 990 |
-
self._didModify = False
|
| 991 |
-
self.debug = 0 # Level of printing: 0 through 3
|
| 992 |
-
self.NameToInfo = {} # Find file info given name
|
| 993 |
-
self.filelist = [] # List of ZipInfo instances for archive
|
| 994 |
-
self.compression = compression # Method of compression
|
| 995 |
-
self.mode = mode
|
| 996 |
-
self.pwd = None
|
| 997 |
-
self._comment = b''
|
| 998 |
-
|
| 999 |
-
# Check if we were passed a file-like object
|
| 1000 |
-
if isinstance(file, str):
|
| 1001 |
-
# No, it's a filename
|
| 1002 |
-
self._filePassed = 0
|
| 1003 |
-
self.filename = file
|
| 1004 |
-
modeDict = {'r' : 'rb', 'w': 'w+b', 'x': 'x+b', 'a' : 'r+b',
|
| 1005 |
-
'r+b': 'w+b', 'w+b': 'wb', 'x+b': 'xb'}
|
| 1006 |
-
filemode = modeDict[mode]
|
| 1007 |
-
while True:
|
| 1008 |
-
try:
|
| 1009 |
-
self.fp = io.open(file, filemode)
|
| 1010 |
-
except OSError:
|
| 1011 |
-
if filemode in modeDict:
|
| 1012 |
-
filemode = modeDict[filemode]
|
| 1013 |
-
continue
|
| 1014 |
-
raise
|
| 1015 |
-
break
|
| 1016 |
-
else:
|
| 1017 |
-
self._filePassed = 1
|
| 1018 |
-
self.fp = file
|
| 1019 |
-
self.filename = getattr(file, 'name', None)
|
| 1020 |
-
self._fileRefCnt = 1
|
| 1021 |
-
self._lock = threading.RLock()
|
| 1022 |
-
self._seekable = True
|
| 1023 |
-
|
| 1024 |
-
try:
|
| 1025 |
-
if mode == 'r':
|
| 1026 |
-
self._RealGetContents()
|
| 1027 |
-
elif mode in ('w', 'x'):
|
| 1028 |
-
# set the modified flag so central directory gets written
|
| 1029 |
-
# even if no files are added to the archive
|
| 1030 |
-
self._didModify = True
|
| 1031 |
-
try:
|
| 1032 |
-
self.start_dir = self.fp.tell()
|
| 1033 |
-
except (AttributeError, OSError):
|
| 1034 |
-
self.fp = _Tellable(self.fp)
|
| 1035 |
-
self.start_dir = 0
|
| 1036 |
-
self._seekable = False
|
| 1037 |
-
else:
|
| 1038 |
-
# Some file-like objects can provide tell() but not seek()
|
| 1039 |
-
try:
|
| 1040 |
-
self.fp.seek(self.start_dir)
|
| 1041 |
-
except (AttributeError, OSError):
|
| 1042 |
-
self._seekable = False
|
| 1043 |
-
elif mode == 'a':
|
| 1044 |
-
try:
|
| 1045 |
-
# See if file is a zip file
|
| 1046 |
-
self._RealGetContents()
|
| 1047 |
-
# seek to start of directory and overwrite
|
| 1048 |
-
self.fp.seek(self.start_dir)
|
| 1049 |
-
except BadZipFile:
|
| 1050 |
-
# file is not a zip file, just append
|
| 1051 |
-
self.fp.seek(0, 2)
|
| 1052 |
-
|
| 1053 |
-
# set the modified flag so central directory gets written
|
| 1054 |
-
# even if no files are added to the archive
|
| 1055 |
-
self._didModify = True
|
| 1056 |
-
self.start_dir = self.fp.tell()
|
| 1057 |
-
else:
|
| 1058 |
-
raise RuntimeError("Mode must be 'r', 'w', 'x', or 'a'")
|
| 1059 |
-
except:
|
| 1060 |
-
fp = self.fp
|
| 1061 |
-
self.fp = None
|
| 1062 |
-
self._fpclose(fp)
|
| 1063 |
-
raise
|
| 1064 |
-
|
| 1065 |
-
def __enter__(self):
|
| 1066 |
-
return self
|
| 1067 |
-
|
| 1068 |
-
def __exit__(self, type, value, traceback):
|
| 1069 |
-
self.close()
|
| 1070 |
-
|
| 1071 |
-
def __repr__(self):
|
| 1072 |
-
result = ['<%s.%s' % (self.__class__.__module__,
|
| 1073 |
-
self.__class__.__qualname__)]
|
| 1074 |
-
if self.fp is not None:
|
| 1075 |
-
if self._filePassed:
|
| 1076 |
-
result.append(' file=%r' % self.fp)
|
| 1077 |
-
elif self.filename is not None:
|
| 1078 |
-
result.append(' filename=%r' % self.filename)
|
| 1079 |
-
result.append(' mode=%r' % self.mode)
|
| 1080 |
-
else:
|
| 1081 |
-
result.append(' [closed]')
|
| 1082 |
-
result.append('>')
|
| 1083 |
-
return ''.join(result)
|
| 1084 |
-
|
| 1085 |
-
def _RealGetContents(self):
|
| 1086 |
-
"""Read in the table of contents for the ZIP file."""
|
| 1087 |
-
fp = self.fp
|
| 1088 |
-
try:
|
| 1089 |
-
endrec = _EndRecData(fp)
|
| 1090 |
-
except OSError:
|
| 1091 |
-
raise BadZipFile("File is not a zip file")
|
| 1092 |
-
if not endrec:
|
| 1093 |
-
raise BadZipFile("File is not a zip file")
|
| 1094 |
-
if self.debug > 1:
|
| 1095 |
-
print(endrec)
|
| 1096 |
-
size_cd = endrec[_ECD_SIZE] # bytes in central directory
|
| 1097 |
-
offset_cd = endrec[_ECD_OFFSET] # offset of central directory
|
| 1098 |
-
self._comment = endrec[_ECD_COMMENT] # archive comment
|
| 1099 |
-
|
| 1100 |
-
# "concat" is zero, unless zip was concatenated to another file
|
| 1101 |
-
concat = endrec[_ECD_LOCATION] - size_cd - offset_cd
|
| 1102 |
-
if endrec[_ECD_SIGNATURE] == stringEndArchive64:
|
| 1103 |
-
# If Zip64 extension structures are present, account for them
|
| 1104 |
-
concat -= (sizeEndCentDir64 + sizeEndCentDir64Locator)
|
| 1105 |
-
|
| 1106 |
-
if self.debug > 2:
|
| 1107 |
-
inferred = concat + offset_cd
|
| 1108 |
-
print("given, inferred, offset", offset_cd, inferred, concat)
|
| 1109 |
-
# self.start_dir: Position of start of central directory
|
| 1110 |
-
self.start_dir = offset_cd + concat
|
| 1111 |
-
fp.seek(self.start_dir, 0)
|
| 1112 |
-
data = fp.read(size_cd)
|
| 1113 |
-
fp = io.BytesIO(data)
|
| 1114 |
-
total = 0
|
| 1115 |
-
while total < size_cd:
|
| 1116 |
-
centdir = fp.read(sizeCentralDir)
|
| 1117 |
-
if len(centdir) != sizeCentralDir:
|
| 1118 |
-
raise BadZipFile("Truncated central directory")
|
| 1119 |
-
centdir = struct.unpack(structCentralDir, centdir)
|
| 1120 |
-
if centdir[_CD_SIGNATURE] != stringCentralDir:
|
| 1121 |
-
raise BadZipFile("Bad magic number for central directory")
|
| 1122 |
-
if self.debug > 2:
|
| 1123 |
-
print(centdir)
|
| 1124 |
-
filename = fp.read(centdir[_CD_FILENAME_LENGTH])
|
| 1125 |
-
flags = centdir[5]
|
| 1126 |
-
if flags & 0x800:
|
| 1127 |
-
# UTF-8 file names extension
|
| 1128 |
-
filename = filename.decode('utf-8')
|
| 1129 |
-
else:
|
| 1130 |
-
# Historical ZIP filename encoding
|
| 1131 |
-
filename = filename.decode('gbk')
|
| 1132 |
-
# filename = filename.encode("cp437").decode('gbk')
|
| 1133 |
-
|
| 1134 |
-
# Create ZipInfo instance to store file information
|
| 1135 |
-
x = ZipInfo(filename)
|
| 1136 |
-
x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])
|
| 1137 |
-
x.comment = fp.read(centdir[_CD_COMMENT_LENGTH])
|
| 1138 |
-
x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET]
|
| 1139 |
-
(x.create_version, x.create_system, x.extract_version, x.reserved,
|
| 1140 |
-
x.flag_bits, x.compress_type, t, d,
|
| 1141 |
-
x.CRC, x.compress_size, x.file_size) = centdir[1:12]
|
| 1142 |
-
if x.extract_version > MAX_EXTRACT_VERSION:
|
| 1143 |
-
raise NotImplementedError("zip file version %.1f" %
|
| 1144 |
-
(x.extract_version / 10))
|
| 1145 |
-
x.volume, x.internal_attr, x.external_attr = centdir[15:18]
|
| 1146 |
-
# Convert date/time code to (year, month, day, hour, min, sec)
|
| 1147 |
-
x._raw_time = t
|
| 1148 |
-
x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F,
|
| 1149 |
-
t>>11, (t>>5)&0x3F, (t&0x1F) * 2 )
|
| 1150 |
-
|
| 1151 |
-
x._decodeExtra()
|
| 1152 |
-
x.header_offset = x.header_offset + concat
|
| 1153 |
-
self.filelist.append(x)
|
| 1154 |
-
self.NameToInfo[x.filename] = x
|
| 1155 |
-
|
| 1156 |
-
# update total bytes read from central directory
|
| 1157 |
-
total = (total + sizeCentralDir + centdir[_CD_FILENAME_LENGTH]
|
| 1158 |
-
+ centdir[_CD_EXTRA_FIELD_LENGTH]
|
| 1159 |
-
+ centdir[_CD_COMMENT_LENGTH])
|
| 1160 |
-
|
| 1161 |
-
if self.debug > 2:
|
| 1162 |
-
print("total", total)
|
| 1163 |
-
|
| 1164 |
-
|
| 1165 |
-
def namelist(self):
|
| 1166 |
-
"""Return a list of file names in the archive."""
|
| 1167 |
-
return [data.filename for data in self.filelist]
|
| 1168 |
-
|
| 1169 |
-
def infolist(self):
|
| 1170 |
-
"""Return a list of class ZipInfo instances for files in the
|
| 1171 |
-
archive."""
|
| 1172 |
-
return self.filelist
|
| 1173 |
-
|
| 1174 |
-
def printdir(self, file=None):
|
| 1175 |
-
"""Print a table of contents for the zip file."""
|
| 1176 |
-
print("%-46s %19s %12s" % ("File Name", "Modified ", "Size"),
|
| 1177 |
-
file=file)
|
| 1178 |
-
for zinfo in self.filelist:
|
| 1179 |
-
date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6]
|
| 1180 |
-
print("%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size),
|
| 1181 |
-
file=file)
|
| 1182 |
-
|
| 1183 |
-
def testzip(self):
|
| 1184 |
-
"""Read all the files and check the CRC."""
|
| 1185 |
-
chunk_size = 2 ** 20
|
| 1186 |
-
for zinfo in self.filelist:
|
| 1187 |
-
try:
|
| 1188 |
-
# Read by chunks, to avoid an OverflowError or a
|
| 1189 |
-
# MemoryError with very large embedded files.
|
| 1190 |
-
with self.open(zinfo.filename, "r") as f:
|
| 1191 |
-
while f.read(chunk_size): # Check CRC-32
|
| 1192 |
-
pass
|
| 1193 |
-
except BadZipFile:
|
| 1194 |
-
return zinfo.filename
|
| 1195 |
-
|
| 1196 |
-
def getinfo(self, name):
|
| 1197 |
-
"""Return the instance of ZipInfo given 'name'."""
|
| 1198 |
-
info = self.NameToInfo.get(name)
|
| 1199 |
-
if info is None:
|
| 1200 |
-
raise KeyError(
|
| 1201 |
-
'There is no item named %r in the archive' % name)
|
| 1202 |
-
|
| 1203 |
-
return info
|
| 1204 |
-
|
| 1205 |
-
def setpassword(self, pwd):
|
| 1206 |
-
"""Set default password for encrypted files."""
|
| 1207 |
-
if pwd and not isinstance(pwd, bytes):
|
| 1208 |
-
raise TypeError("pwd: expected bytes, got %s" % type(pwd))
|
| 1209 |
-
if pwd:
|
| 1210 |
-
self.pwd = pwd
|
| 1211 |
-
else:
|
| 1212 |
-
self.pwd = None
|
| 1213 |
-
|
| 1214 |
-
@property
|
| 1215 |
-
def comment(self):
|
| 1216 |
-
"""The comment text associated with the ZIP file."""
|
| 1217 |
-
return self._comment
|
| 1218 |
-
|
| 1219 |
-
@comment.setter
|
| 1220 |
-
def comment(self, comment):
|
| 1221 |
-
if not isinstance(comment, bytes):
|
| 1222 |
-
raise TypeError("comment: expected bytes, got %s" % type(comment))
|
| 1223 |
-
# check for valid comment length
|
| 1224 |
-
if len(comment) > ZIP_MAX_COMMENT:
|
| 1225 |
-
import warnings
|
| 1226 |
-
warnings.warn('Archive comment is too long; truncating to %d bytes'
|
| 1227 |
-
% ZIP_MAX_COMMENT, stacklevel=2)
|
| 1228 |
-
comment = comment[:ZIP_MAX_COMMENT]
|
| 1229 |
-
self._comment = comment
|
| 1230 |
-
self._didModify = True
|
| 1231 |
-
|
| 1232 |
-
def read(self, name, pwd=None):
|
| 1233 |
-
"""Return file bytes (as a string) for name."""
|
| 1234 |
-
with self.open(name, "r", pwd) as fp:
|
| 1235 |
-
return fp.read()
|
| 1236 |
-
|
| 1237 |
-
def open(self, name, mode="r", pwd=None):
|
| 1238 |
-
"""Return file-like object for 'name'."""
|
| 1239 |
-
if mode not in ("r", "U", "rU"):
|
| 1240 |
-
raise RuntimeError('open() requires mode "r", "U", or "rU"')
|
| 1241 |
-
if 'U' in mode:
|
| 1242 |
-
import warnings
|
| 1243 |
-
warnings.warn("'U' mode is deprecated",
|
| 1244 |
-
DeprecationWarning, 2)
|
| 1245 |
-
if pwd and not isinstance(pwd, bytes):
|
| 1246 |
-
raise TypeError("pwd: expected bytes, got %s" % type(pwd))
|
| 1247 |
-
if not self.fp:
|
| 1248 |
-
raise RuntimeError(
|
| 1249 |
-
"Attempt to read ZIP archive that was already closed")
|
| 1250 |
-
|
| 1251 |
-
# Make sure we have an info object
|
| 1252 |
-
if isinstance(name, ZipInfo):
|
| 1253 |
-
# 'name' is already an info object
|
| 1254 |
-
zinfo = name
|
| 1255 |
-
else:
|
| 1256 |
-
# Get info object for name
|
| 1257 |
-
zinfo = self.getinfo(name)
|
| 1258 |
-
|
| 1259 |
-
self._fileRefCnt += 1
|
| 1260 |
-
zef_file = _SharedFile(self.fp, zinfo.header_offset, self._fpclose, self._lock)
|
| 1261 |
-
try:
|
| 1262 |
-
# Skip the file header:
|
| 1263 |
-
fheader = zef_file.read(sizeFileHeader)
|
| 1264 |
-
if len(fheader) != sizeFileHeader:
|
| 1265 |
-
raise BadZipFile("Truncated file header")
|
| 1266 |
-
fheader = struct.unpack(structFileHeader, fheader)
|
| 1267 |
-
if fheader[_FH_SIGNATURE] != stringFileHeader:
|
| 1268 |
-
raise BadZipFile("Bad magic number for file header")
|
| 1269 |
-
|
| 1270 |
-
fname = zef_file.read(fheader[_FH_FILENAME_LENGTH])
|
| 1271 |
-
if fheader[_FH_EXTRA_FIELD_LENGTH]:
|
| 1272 |
-
zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH])
|
| 1273 |
-
|
| 1274 |
-
if zinfo.flag_bits & 0x20:
|
| 1275 |
-
# Zip 2.7: compressed patched data
|
| 1276 |
-
raise NotImplementedError("compressed patched data (flag bit 5)")
|
| 1277 |
-
|
| 1278 |
-
if zinfo.flag_bits & 0x40:
|
| 1279 |
-
# strong encryption
|
| 1280 |
-
raise NotImplementedError("strong encryption (flag bit 6)")
|
| 1281 |
-
|
| 1282 |
-
if zinfo.flag_bits & 0x800:
|
| 1283 |
-
# UTF-8 filename
|
| 1284 |
-
fname_str = fname.decode("utf-8")
|
| 1285 |
-
else:
|
| 1286 |
-
fname_str = fname.decode("cp437")
|
| 1287 |
-
fname_str = fname_str.encode("cp437").decode('gbk')
|
| 1288 |
-
|
| 1289 |
-
|
| 1290 |
-
if fname_str != zinfo.orig_filename:
|
| 1291 |
-
raise BadZipFile(
|
| 1292 |
-
'File name in directory %r and header %r differ.'
|
| 1293 |
-
% (zinfo.orig_filename, fname))
|
| 1294 |
-
|
| 1295 |
-
# check for encrypted flag & handle password
|
| 1296 |
-
is_encrypted = zinfo.flag_bits & 0x1
|
| 1297 |
-
zd = None
|
| 1298 |
-
if is_encrypted:
|
| 1299 |
-
if not pwd:
|
| 1300 |
-
pwd = self.pwd
|
| 1301 |
-
if not pwd:
|
| 1302 |
-
raise RuntimeError("File %s is encrypted, password "
|
| 1303 |
-
"required for extraction" % name)
|
| 1304 |
-
|
| 1305 |
-
zd = _ZipDecrypter(pwd)
|
| 1306 |
-
# The first 12 bytes in the cypher stream is an encryption header
|
| 1307 |
-
# used to strengthen the algorithm. The first 11 bytes are
|
| 1308 |
-
# completely random, while the 12th contains the MSB of the CRC,
|
| 1309 |
-
# or the MSB of the file time depending on the header type
|
| 1310 |
-
# and is used to check the correctness of the password.
|
| 1311 |
-
header = zef_file.read(12)
|
| 1312 |
-
h = list(map(zd, header[0:12]))
|
| 1313 |
-
if zinfo.flag_bits & 0x8:
|
| 1314 |
-
# compare against the file type from extended local headers
|
| 1315 |
-
check_byte = (zinfo._raw_time >> 8) & 0xff
|
| 1316 |
-
else:
|
| 1317 |
-
# compare against the CRC otherwise
|
| 1318 |
-
check_byte = (zinfo.CRC >> 24) & 0xff
|
| 1319 |
-
if h[11] != check_byte:
|
| 1320 |
-
raise RuntimeError("Bad password for file", name)
|
| 1321 |
-
|
| 1322 |
-
return ZipExtFile(zef_file, mode, zinfo, zd, True)
|
| 1323 |
-
except:
|
| 1324 |
-
zef_file.close()
|
| 1325 |
-
raise
|
| 1326 |
-
|
| 1327 |
-
def extract(self, member, path=None, pwd=None):
|
| 1328 |
-
"""Extract a member from the archive to the current working directory,
|
| 1329 |
-
using its full name. Its file information is extracted as accurately
|
| 1330 |
-
as possible. `member' may be a filename or a ZipInfo object. You can
|
| 1331 |
-
specify a different directory using `path'.
|
| 1332 |
-
"""
|
| 1333 |
-
if not isinstance(member, ZipInfo):
|
| 1334 |
-
member = self.getinfo(member)
|
| 1335 |
-
|
| 1336 |
-
if path is None:
|
| 1337 |
-
path = os.getcwd()
|
| 1338 |
-
|
| 1339 |
-
return self._extract_member(member, path, pwd)
|
| 1340 |
-
|
| 1341 |
-
def extractall(self, path=None, members=None, pwd=None):
|
| 1342 |
-
"""Extract all members from the archive to the current working
|
| 1343 |
-
directory. `path' specifies a different directory to extract to.
|
| 1344 |
-
`members' is optional and must be a subset of the list returned
|
| 1345 |
-
by namelist().
|
| 1346 |
-
"""
|
| 1347 |
-
if members is None:
|
| 1348 |
-
members = self.namelist()
|
| 1349 |
-
|
| 1350 |
-
for zipinfo in members:
|
| 1351 |
-
self.extract(zipinfo, path, pwd)
|
| 1352 |
-
|
| 1353 |
-
@classmethod
|
| 1354 |
-
def _sanitize_windows_name(cls, arcname, pathsep):
|
| 1355 |
-
"""Replace bad characters and remove trailing dots from parts."""
|
| 1356 |
-
table = cls._windows_illegal_name_trans_table
|
| 1357 |
-
if not table:
|
| 1358 |
-
illegal = ':<>|"?*'
|
| 1359 |
-
table = str.maketrans(illegal, '_' * len(illegal))
|
| 1360 |
-
cls._windows_illegal_name_trans_table = table
|
| 1361 |
-
arcname = arcname.translate(table)
|
| 1362 |
-
# remove trailing dots
|
| 1363 |
-
arcname = (x.rstrip('.') for x in arcname.split(pathsep))
|
| 1364 |
-
# rejoin, removing empty parts.
|
| 1365 |
-
arcname = pathsep.join(x for x in arcname if x)
|
| 1366 |
-
return arcname
|
| 1367 |
-
|
| 1368 |
-
def _extract_member(self, member, targetpath, pwd):
|
| 1369 |
-
"""Extract the ZipInfo object 'member' to a physical
|
| 1370 |
-
file on the path targetpath.
|
| 1371 |
-
"""
|
| 1372 |
-
# build the destination pathname, replacing
|
| 1373 |
-
# forward slashes to platform specific separators.
|
| 1374 |
-
arcname = member.filename.replace('/', os.path.sep)
|
| 1375 |
-
|
| 1376 |
-
if os.path.altsep:
|
| 1377 |
-
arcname = arcname.replace(os.path.altsep, os.path.sep)
|
| 1378 |
-
# interpret absolute pathname as relative, remove drive letter or
|
| 1379 |
-
# UNC path, redundant separators, "." and ".." components.
|
| 1380 |
-
arcname = os.path.splitdrive(arcname)[1]
|
| 1381 |
-
invalid_path_parts = ('', os.path.curdir, os.path.pardir)
|
| 1382 |
-
arcname = os.path.sep.join(x for x in arcname.split(os.path.sep)
|
| 1383 |
-
if x not in invalid_path_parts)
|
| 1384 |
-
if os.path.sep == '\\':
|
| 1385 |
-
# filter illegal characters on Windows
|
| 1386 |
-
arcname = self._sanitize_windows_name(arcname, os.path.sep)
|
| 1387 |
-
|
| 1388 |
-
targetpath = os.path.join(targetpath, arcname)
|
| 1389 |
-
targetpath = os.path.normpath(targetpath)
|
| 1390 |
-
|
| 1391 |
-
# Create all upper directories if necessary.
|
| 1392 |
-
upperdirs = os.path.dirname(targetpath)
|
| 1393 |
-
if upperdirs and not os.path.exists(upperdirs):
|
| 1394 |
-
os.makedirs(upperdirs)
|
| 1395 |
-
|
| 1396 |
-
if member.filename[-1] == '/':
|
| 1397 |
-
if not os.path.isdir(targetpath):
|
| 1398 |
-
os.mkdir(targetpath)
|
| 1399 |
-
return targetpath
|
| 1400 |
-
|
| 1401 |
-
with self.open(member, pwd=pwd) as source, \
|
| 1402 |
-
open(targetpath, "wb") as target:
|
| 1403 |
-
shutil.copyfileobj(source, target)
|
| 1404 |
-
|
| 1405 |
-
return targetpath
|
| 1406 |
-
|
| 1407 |
-
def _writecheck(self, zinfo):
|
| 1408 |
-
"""Check for errors before writing a file to the archive."""
|
| 1409 |
-
if zinfo.filename in self.NameToInfo:
|
| 1410 |
-
import warnings
|
| 1411 |
-
warnings.warn('Duplicate name: %r' % zinfo.filename, stacklevel=3)
|
| 1412 |
-
if self.mode not in ('w', 'x', 'a'):
|
| 1413 |
-
raise RuntimeError("write() requires mode 'w', 'x', or 'a'")
|
| 1414 |
-
if not self.fp:
|
| 1415 |
-
raise RuntimeError(
|
| 1416 |
-
"Attempt to write ZIP archive that was already closed")
|
| 1417 |
-
_check_compression(zinfo.compress_type)
|
| 1418 |
-
if not self._allowZip64:
|
| 1419 |
-
requires_zip64 = None
|
| 1420 |
-
if len(self.filelist) >= ZIP_FILECOUNT_LIMIT:
|
| 1421 |
-
requires_zip64 = "Files count"
|
| 1422 |
-
elif zinfo.file_size > ZIP64_LIMIT:
|
| 1423 |
-
requires_zip64 = "Filesize"
|
| 1424 |
-
elif zinfo.header_offset > ZIP64_LIMIT:
|
| 1425 |
-
requires_zip64 = "Zipfile size"
|
| 1426 |
-
if requires_zip64:
|
| 1427 |
-
raise LargeZipFile(requires_zip64 +
|
| 1428 |
-
" would require ZIP64 extensions")
|
| 1429 |
-
|
| 1430 |
-
def write(self, filename, arcname=None, compress_type=None):
|
| 1431 |
-
"""Put the bytes from filename into the archive under the name
|
| 1432 |
-
arcname."""
|
| 1433 |
-
if not self.fp:
|
| 1434 |
-
raise RuntimeError(
|
| 1435 |
-
"Attempt to write to ZIP archive that was already closed")
|
| 1436 |
-
|
| 1437 |
-
st = os.stat(filename)
|
| 1438 |
-
isdir = stat.S_ISDIR(st.st_mode)
|
| 1439 |
-
mtime = time.localtime(st.st_mtime)
|
| 1440 |
-
date_time = mtime[0:6]
|
| 1441 |
-
# Create ZipInfo instance to store file information
|
| 1442 |
-
if arcname is None:
|
| 1443 |
-
arcname = filename
|
| 1444 |
-
arcname = os.path.normpath(os.path.splitdrive(arcname)[1])
|
| 1445 |
-
while arcname[0] in (os.sep, os.altsep):
|
| 1446 |
-
arcname = arcname[1:]
|
| 1447 |
-
if isdir:
|
| 1448 |
-
arcname += '/'
|
| 1449 |
-
zinfo = ZipInfo(arcname, date_time)
|
| 1450 |
-
zinfo.external_attr = (st[0] & 0xFFFF) << 16 # Unix attributes
|
| 1451 |
-
if isdir:
|
| 1452 |
-
zinfo.compress_type = ZIP_STORED
|
| 1453 |
-
elif compress_type is None:
|
| 1454 |
-
zinfo.compress_type = self.compression
|
| 1455 |
-
else:
|
| 1456 |
-
zinfo.compress_type = compress_type
|
| 1457 |
-
|
| 1458 |
-
zinfo.file_size = st.st_size
|
| 1459 |
-
zinfo.flag_bits = 0x00
|
| 1460 |
-
with self._lock:
|
| 1461 |
-
if self._seekable:
|
| 1462 |
-
self.fp.seek(self.start_dir)
|
| 1463 |
-
zinfo.header_offset = self.fp.tell() # Start of header bytes
|
| 1464 |
-
if zinfo.compress_type == ZIP_LZMA:
|
| 1465 |
-
# Compressed data includes an end-of-stream (EOS) marker
|
| 1466 |
-
zinfo.flag_bits |= 0x02
|
| 1467 |
-
|
| 1468 |
-
self._writecheck(zinfo)
|
| 1469 |
-
self._didModify = True
|
| 1470 |
-
|
| 1471 |
-
if isdir:
|
| 1472 |
-
zinfo.file_size = 0
|
| 1473 |
-
zinfo.compress_size = 0
|
| 1474 |
-
zinfo.CRC = 0
|
| 1475 |
-
zinfo.external_attr |= 0x10 # MS-DOS directory flag
|
| 1476 |
-
self.filelist.append(zinfo)
|
| 1477 |
-
self.NameToInfo[zinfo.filename] = zinfo
|
| 1478 |
-
self.fp.write(zinfo.FileHeader(False))
|
| 1479 |
-
self.start_dir = self.fp.tell()
|
| 1480 |
-
return
|
| 1481 |
-
|
| 1482 |
-
cmpr = _get_compressor(zinfo.compress_type)
|
| 1483 |
-
if not self._seekable:
|
| 1484 |
-
zinfo.flag_bits |= 0x08
|
| 1485 |
-
with open(filename, "rb") as fp:
|
| 1486 |
-
# Must overwrite CRC and sizes with correct data later
|
| 1487 |
-
zinfo.CRC = CRC = 0
|
| 1488 |
-
zinfo.compress_size = compress_size = 0
|
| 1489 |
-
# Compressed size can be larger than uncompressed size
|
| 1490 |
-
zip64 = self._allowZip64 and \
|
| 1491 |
-
zinfo.file_size * 1.05 > ZIP64_LIMIT
|
| 1492 |
-
self.fp.write(zinfo.FileHeader(zip64))
|
| 1493 |
-
file_size = 0
|
| 1494 |
-
while 1:
|
| 1495 |
-
buf = fp.read(1024 * 8)
|
| 1496 |
-
if not buf:
|
| 1497 |
-
break
|
| 1498 |
-
file_size = file_size + len(buf)
|
| 1499 |
-
CRC = crc32(buf, CRC)
|
| 1500 |
-
if cmpr:
|
| 1501 |
-
buf = cmpr.compress(buf)
|
| 1502 |
-
compress_size = compress_size + len(buf)
|
| 1503 |
-
self.fp.write(buf)
|
| 1504 |
-
if cmpr:
|
| 1505 |
-
buf = cmpr.flush()
|
| 1506 |
-
compress_size = compress_size + len(buf)
|
| 1507 |
-
self.fp.write(buf)
|
| 1508 |
-
zinfo.compress_size = compress_size
|
| 1509 |
-
else:
|
| 1510 |
-
zinfo.compress_size = file_size
|
| 1511 |
-
zinfo.CRC = CRC
|
| 1512 |
-
zinfo.file_size = file_size
|
| 1513 |
-
if zinfo.flag_bits & 0x08:
|
| 1514 |
-
# Write CRC and file sizes after the file data
|
| 1515 |
-
fmt = '<LQQ' if zip64 else '<LLL'
|
| 1516 |
-
self.fp.write(struct.pack(fmt, zinfo.CRC, zinfo.compress_size,
|
| 1517 |
-
zinfo.file_size))
|
| 1518 |
-
self.start_dir = self.fp.tell()
|
| 1519 |
-
else:
|
| 1520 |
-
if not zip64 and self._allowZip64:
|
| 1521 |
-
if file_size > ZIP64_LIMIT:
|
| 1522 |
-
raise RuntimeError('File size has increased during compressing')
|
| 1523 |
-
if compress_size > ZIP64_LIMIT:
|
| 1524 |
-
raise RuntimeError('Compressed size larger than uncompressed size')
|
| 1525 |
-
# Seek backwards and write file header (which will now include
|
| 1526 |
-
# correct CRC and file sizes)
|
| 1527 |
-
self.start_dir = self.fp.tell() # Preserve current position in file
|
| 1528 |
-
self.fp.seek(zinfo.header_offset)
|
| 1529 |
-
self.fp.write(zinfo.FileHeader(zip64))
|
| 1530 |
-
self.fp.seek(self.start_dir)
|
| 1531 |
-
self.filelist.append(zinfo)
|
| 1532 |
-
self.NameToInfo[zinfo.filename] = zinfo
|
| 1533 |
-
|
| 1534 |
-
def writestr(self, zinfo_or_arcname, data, compress_type=None):
|
| 1535 |
-
"""Write a file into the archive. The contents is 'data', which
|
| 1536 |
-
may be either a 'str' or a 'bytes' instance; if it is a 'str',
|
| 1537 |
-
it is encoded as UTF-8 first.
|
| 1538 |
-
'zinfo_or_arcname' is either a ZipInfo instance or
|
| 1539 |
-
the name of the file in the archive."""
|
| 1540 |
-
if isinstance(data, str):
|
| 1541 |
-
data = data.encode("utf-8")
|
| 1542 |
-
if not isinstance(zinfo_or_arcname, ZipInfo):
|
| 1543 |
-
zinfo = ZipInfo(filename=zinfo_or_arcname,
|
| 1544 |
-
date_time=time.localtime(time.time())[:6])
|
| 1545 |
-
zinfo.compress_type = self.compression
|
| 1546 |
-
if zinfo.filename[-1] == '/':
|
| 1547 |
-
zinfo.external_attr = 0o40775 << 16 # drwxrwxr-x
|
| 1548 |
-
zinfo.external_attr |= 0x10 # MS-DOS directory flag
|
| 1549 |
-
else:
|
| 1550 |
-
zinfo.external_attr = 0o600 << 16 # ?rw-------
|
| 1551 |
-
else:
|
| 1552 |
-
zinfo = zinfo_or_arcname
|
| 1553 |
-
|
| 1554 |
-
if not self.fp:
|
| 1555 |
-
raise RuntimeError(
|
| 1556 |
-
"Attempt to write to ZIP archive that was already closed")
|
| 1557 |
-
|
| 1558 |
-
zinfo.file_size = len(data) # Uncompressed size
|
| 1559 |
-
with self._lock:
|
| 1560 |
-
if self._seekable:
|
| 1561 |
-
self.fp.seek(self.start_dir)
|
| 1562 |
-
zinfo.header_offset = self.fp.tell() # Start of header data
|
| 1563 |
-
if compress_type is not None:
|
| 1564 |
-
zinfo.compress_type = compress_type
|
| 1565 |
-
zinfo.header_offset = self.fp.tell() # Start of header data
|
| 1566 |
-
if compress_type is not None:
|
| 1567 |
-
zinfo.compress_type = compress_type
|
| 1568 |
-
if zinfo.compress_type == ZIP_LZMA:
|
| 1569 |
-
# Compressed data includes an end-of-stream (EOS) marker
|
| 1570 |
-
zinfo.flag_bits |= 0x02
|
| 1571 |
-
|
| 1572 |
-
self._writecheck(zinfo)
|
| 1573 |
-
self._didModify = True
|
| 1574 |
-
zinfo.CRC = crc32(data) # CRC-32 checksum
|
| 1575 |
-
co = _get_compressor(zinfo.compress_type)
|
| 1576 |
-
if co:
|
| 1577 |
-
data = co.compress(data) + co.flush()
|
| 1578 |
-
zinfo.compress_size = len(data) # Compressed size
|
| 1579 |
-
else:
|
| 1580 |
-
zinfo.compress_size = zinfo.file_size
|
| 1581 |
-
zip64 = zinfo.file_size > ZIP64_LIMIT or \
|
| 1582 |
-
zinfo.compress_size > ZIP64_LIMIT
|
| 1583 |
-
if zip64 and not self._allowZip64:
|
| 1584 |
-
raise LargeZipFile("Filesize would require ZIP64 extensions")
|
| 1585 |
-
self.fp.write(zinfo.FileHeader(zip64))
|
| 1586 |
-
self.fp.write(data)
|
| 1587 |
-
if zinfo.flag_bits & 0x08:
|
| 1588 |
-
# Write CRC and file sizes after the file data
|
| 1589 |
-
fmt = '<LQQ' if zip64 else '<LLL'
|
| 1590 |
-
self.fp.write(struct.pack(fmt, zinfo.CRC, zinfo.compress_size,
|
| 1591 |
-
zinfo.file_size))
|
| 1592 |
-
self.fp.flush()
|
| 1593 |
-
self.start_dir = self.fp.tell()
|
| 1594 |
-
self.filelist.append(zinfo)
|
| 1595 |
-
self.NameToInfo[zinfo.filename] = zinfo
|
| 1596 |
-
|
| 1597 |
-
def __del__(self):
|
| 1598 |
-
"""Call the "close()" method in case the user forgot."""
|
| 1599 |
-
self.close()
|
| 1600 |
-
|
| 1601 |
-
def close(self):
|
| 1602 |
-
"""Close the file, and for mode 'w', 'x' and 'a' write the ending
|
| 1603 |
-
records."""
|
| 1604 |
-
if self.fp is None:
|
| 1605 |
-
return
|
| 1606 |
-
|
| 1607 |
-
try:
|
| 1608 |
-
if self.mode in ('w', 'x', 'a') and self._didModify: # write ending records
|
| 1609 |
-
with self._lock:
|
| 1610 |
-
if self._seekable:
|
| 1611 |
-
self.fp.seek(self.start_dir)
|
| 1612 |
-
self._write_end_record()
|
| 1613 |
-
finally:
|
| 1614 |
-
fp = self.fp
|
| 1615 |
-
self.fp = None
|
| 1616 |
-
self._fpclose(fp)
|
| 1617 |
-
|
| 1618 |
-
def _write_end_record(self):
|
| 1619 |
-
for zinfo in self.filelist: # write central directory
|
| 1620 |
-
dt = zinfo.date_time
|
| 1621 |
-
dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
|
| 1622 |
-
dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
|
| 1623 |
-
extra = []
|
| 1624 |
-
if zinfo.file_size > ZIP64_LIMIT \
|
| 1625 |
-
or zinfo.compress_size > ZIP64_LIMIT:
|
| 1626 |
-
extra.append(zinfo.file_size)
|
| 1627 |
-
extra.append(zinfo.compress_size)
|
| 1628 |
-
file_size = 0xffffffff
|
| 1629 |
-
compress_size = 0xffffffff
|
| 1630 |
-
else:
|
| 1631 |
-
file_size = zinfo.file_size
|
| 1632 |
-
compress_size = zinfo.compress_size
|
| 1633 |
-
|
| 1634 |
-
if zinfo.header_offset > ZIP64_LIMIT:
|
| 1635 |
-
extra.append(zinfo.header_offset)
|
| 1636 |
-
header_offset = 0xffffffff
|
| 1637 |
-
else:
|
| 1638 |
-
header_offset = zinfo.header_offset
|
| 1639 |
-
|
| 1640 |
-
extra_data = zinfo.extra
|
| 1641 |
-
min_version = 0
|
| 1642 |
-
if extra:
|
| 1643 |
-
# Append a ZIP64 field to the extra's
|
| 1644 |
-
extra_data = struct.pack(
|
| 1645 |
-
'<HH' + 'Q'*len(extra),
|
| 1646 |
-
1, 8*len(extra), *extra) + extra_data
|
| 1647 |
-
|
| 1648 |
-
min_version = ZIP64_VERSION
|
| 1649 |
-
|
| 1650 |
-
if zinfo.compress_type == ZIP_BZIP2:
|
| 1651 |
-
min_version = max(BZIP2_VERSION, min_version)
|
| 1652 |
-
elif zinfo.compress_type == ZIP_LZMA:
|
| 1653 |
-
min_version = max(LZMA_VERSION, min_version)
|
| 1654 |
-
|
| 1655 |
-
extract_version = max(min_version, zinfo.extract_version)
|
| 1656 |
-
create_version = max(min_version, zinfo.create_version)
|
| 1657 |
-
try:
|
| 1658 |
-
filename, flag_bits = zinfo._encodeFilenameFlags()
|
| 1659 |
-
centdir = struct.pack(structCentralDir,
|
| 1660 |
-
stringCentralDir, create_version,
|
| 1661 |
-
zinfo.create_system, extract_version, zinfo.reserved,
|
| 1662 |
-
flag_bits, zinfo.compress_type, dostime, dosdate,
|
| 1663 |
-
zinfo.CRC, compress_size, file_size,
|
| 1664 |
-
len(filename), len(extra_data), len(zinfo.comment),
|
| 1665 |
-
0, zinfo.internal_attr, zinfo.external_attr,
|
| 1666 |
-
header_offset)
|
| 1667 |
-
except DeprecationWarning:
|
| 1668 |
-
print((structCentralDir, stringCentralDir, create_version,
|
| 1669 |
-
zinfo.create_system, extract_version, zinfo.reserved,
|
| 1670 |
-
zinfo.flag_bits, zinfo.compress_type, dostime, dosdate,
|
| 1671 |
-
zinfo.CRC, compress_size, file_size,
|
| 1672 |
-
len(zinfo.filename), len(extra_data), len(zinfo.comment),
|
| 1673 |
-
0, zinfo.internal_attr, zinfo.external_attr,
|
| 1674 |
-
header_offset), file=sys.stderr)
|
| 1675 |
-
raise
|
| 1676 |
-
self.fp.write(centdir)
|
| 1677 |
-
self.fp.write(filename)
|
| 1678 |
-
self.fp.write(extra_data)
|
| 1679 |
-
self.fp.write(zinfo.comment)
|
| 1680 |
-
|
| 1681 |
-
pos2 = self.fp.tell()
|
| 1682 |
-
# Write end-of-zip-archive record
|
| 1683 |
-
centDirCount = len(self.filelist)
|
| 1684 |
-
centDirSize = pos2 - self.start_dir
|
| 1685 |
-
centDirOffset = self.start_dir
|
| 1686 |
-
requires_zip64 = None
|
| 1687 |
-
if centDirCount > ZIP_FILECOUNT_LIMIT:
|
| 1688 |
-
requires_zip64 = "Files count"
|
| 1689 |
-
elif centDirOffset > ZIP64_LIMIT:
|
| 1690 |
-
requires_zip64 = "Central directory offset"
|
| 1691 |
-
elif centDirSize > ZIP64_LIMIT:
|
| 1692 |
-
requires_zip64 = "Central directory size"
|
| 1693 |
-
if requires_zip64:
|
| 1694 |
-
# Need to write the ZIP64 end-of-archive records
|
| 1695 |
-
if not self._allowZip64:
|
| 1696 |
-
raise LargeZipFile(requires_zip64 +
|
| 1697 |
-
" would require ZIP64 extensions")
|
| 1698 |
-
zip64endrec = struct.pack(
|
| 1699 |
-
structEndArchive64, stringEndArchive64,
|
| 1700 |
-
44, 45, 45, 0, 0, centDirCount, centDirCount,
|
| 1701 |
-
centDirSize, centDirOffset)
|
| 1702 |
-
self.fp.write(zip64endrec)
|
| 1703 |
-
|
| 1704 |
-
zip64locrec = struct.pack(
|
| 1705 |
-
structEndArchive64Locator,
|
| 1706 |
-
stringEndArchive64Locator, 0, pos2, 1)
|
| 1707 |
-
self.fp.write(zip64locrec)
|
| 1708 |
-
centDirCount = min(centDirCount, 0xFFFF)
|
| 1709 |
-
centDirSize = min(centDirSize, 0xFFFFFFFF)
|
| 1710 |
-
centDirOffset = min(centDirOffset, 0xFFFFFFFF)
|
| 1711 |
-
|
| 1712 |
-
endrec = struct.pack(structEndArchive, stringEndArchive,
|
| 1713 |
-
0, 0, centDirCount, centDirCount,
|
| 1714 |
-
centDirSize, centDirOffset, len(self._comment))
|
| 1715 |
-
self.fp.write(endrec)
|
| 1716 |
-
self.fp.write(self._comment)
|
| 1717 |
-
self.fp.flush()
|
| 1718 |
-
|
| 1719 |
-
def _fpclose(self, fp):
|
| 1720 |
-
assert self._fileRefCnt > 0
|
| 1721 |
-
self._fileRefCnt -= 1
|
| 1722 |
-
if not self._fileRefCnt and not self._filePassed:
|
| 1723 |
-
fp.close()
|
| 1724 |
-
|
| 1725 |
-
|
| 1726 |
-
class PyZipFile(ZipFile):
|
| 1727 |
-
"""Class to create ZIP archives with Python library files and packages."""
|
| 1728 |
-
|
| 1729 |
-
def __init__(self, file, mode="r", compression=ZIP_STORED,
|
| 1730 |
-
allowZip64=True, optimize=-1):
|
| 1731 |
-
ZipFile.__init__(self, file, mode=mode, compression=compression,
|
| 1732 |
-
allowZip64=allowZip64)
|
| 1733 |
-
self._optimize = optimize
|
| 1734 |
-
|
| 1735 |
-
def writepy(self, pathname, basename="", filterfunc=None):
|
| 1736 |
-
"""Add all files from "pathname" to the ZIP archive.
|
| 1737 |
-
|
| 1738 |
-
If pathname is a package directory, search the directory and
|
| 1739 |
-
all package subdirectories recursively for all *.py and enter
|
| 1740 |
-
the modules into the archive. If pathname is a plain
|
| 1741 |
-
directory, listdir *.py and enter all modules. Else, pathname
|
| 1742 |
-
must be a Python *.py file and the module will be put into the
|
| 1743 |
-
archive. Added modules are always module.pyc.
|
| 1744 |
-
This method will compile the module.py into module.pyc if
|
| 1745 |
-
necessary.
|
| 1746 |
-
If filterfunc(pathname) is given, it is called with every argument.
|
| 1747 |
-
When it is False, the file or directory is skipped.
|
| 1748 |
-
"""
|
| 1749 |
-
if filterfunc and not filterfunc(pathname):
|
| 1750 |
-
if self.debug:
|
| 1751 |
-
label = 'path' if os.path.isdir(pathname) else 'file'
|
| 1752 |
-
print('%s "%s" skipped by filterfunc' % (label, pathname))
|
| 1753 |
-
return
|
| 1754 |
-
dir, name = os.path.split(pathname)
|
| 1755 |
-
if os.path.isdir(pathname):
|
| 1756 |
-
initname = os.path.join(pathname, "__init__.py")
|
| 1757 |
-
if os.path.isfile(initname):
|
| 1758 |
-
# This is a package directory, add it
|
| 1759 |
-
if basename:
|
| 1760 |
-
basename = "%s/%s" % (basename, name)
|
| 1761 |
-
else:
|
| 1762 |
-
basename = name
|
| 1763 |
-
if self.debug:
|
| 1764 |
-
print("Adding package in", pathname, "as", basename)
|
| 1765 |
-
fname, arcname = self._get_codename(initname[0:-3], basename)
|
| 1766 |
-
if self.debug:
|
| 1767 |
-
print("Adding", arcname)
|
| 1768 |
-
self.write(fname, arcname)
|
| 1769 |
-
dirlist = os.listdir(pathname)
|
| 1770 |
-
dirlist.remove("__init__.py")
|
| 1771 |
-
# Add all *.py files and package subdirectories
|
| 1772 |
-
for filename in dirlist:
|
| 1773 |
-
path = os.path.join(pathname, filename)
|
| 1774 |
-
root, ext = os.path.splitext(filename)
|
| 1775 |
-
if os.path.isdir(path):
|
| 1776 |
-
if os.path.isfile(os.path.join(path, "__init__.py")):
|
| 1777 |
-
# This is a package directory, add it
|
| 1778 |
-
self.writepy(path, basename,
|
| 1779 |
-
filterfunc=filterfunc) # Recursive call
|
| 1780 |
-
elif ext == ".py":
|
| 1781 |
-
if filterfunc and not filterfunc(path):
|
| 1782 |
-
if self.debug:
|
| 1783 |
-
print('file "%s" skipped by filterfunc' % path)
|
| 1784 |
-
continue
|
| 1785 |
-
fname, arcname = self._get_codename(path[0:-3],
|
| 1786 |
-
basename)
|
| 1787 |
-
if self.debug:
|
| 1788 |
-
print("Adding", arcname)
|
| 1789 |
-
self.write(fname, arcname)
|
| 1790 |
-
else:
|
| 1791 |
-
# This is NOT a package directory, add its files at top level
|
| 1792 |
-
if self.debug:
|
| 1793 |
-
print("Adding files from directory", pathname)
|
| 1794 |
-
for filename in os.listdir(pathname):
|
| 1795 |
-
path = os.path.join(pathname, filename)
|
| 1796 |
-
root, ext = os.path.splitext(filename)
|
| 1797 |
-
if ext == ".py":
|
| 1798 |
-
if filterfunc and not filterfunc(path):
|
| 1799 |
-
if self.debug:
|
| 1800 |
-
print('file "%s" skipped by filterfunc' % path)
|
| 1801 |
-
continue
|
| 1802 |
-
fname, arcname = self._get_codename(path[0:-3],
|
| 1803 |
-
basename)
|
| 1804 |
-
if self.debug:
|
| 1805 |
-
print("Adding", arcname)
|
| 1806 |
-
self.write(fname, arcname)
|
| 1807 |
-
else:
|
| 1808 |
-
if pathname[-3:] != ".py":
|
| 1809 |
-
raise RuntimeError(
|
| 1810 |
-
'Files added with writepy() must end with ".py"')
|
| 1811 |
-
fname, arcname = self._get_codename(pathname[0:-3], basename)
|
| 1812 |
-
if self.debug:
|
| 1813 |
-
print("Adding file", arcname)
|
| 1814 |
-
self.write(fname, arcname)
|
| 1815 |
-
|
| 1816 |
-
def _get_codename(self, pathname, basename):
|
| 1817 |
-
"""Return (filename, archivename) for the path.
|
| 1818 |
-
|
| 1819 |
-
Given a module name path, return the correct file path and
|
| 1820 |
-
archive name, compiling if necessary. For example, given
|
| 1821 |
-
/python/lib/string, return (/python/lib/string.pyc, string).
|
| 1822 |
-
"""
|
| 1823 |
-
def _compile(file, optimize=-1):
|
| 1824 |
-
import py_compile
|
| 1825 |
-
if self.debug:
|
| 1826 |
-
print("Compiling", file)
|
| 1827 |
-
try:
|
| 1828 |
-
py_compile.compile(file, doraise=True, optimize=optimize)
|
| 1829 |
-
except py_compile.PyCompileError as err:
|
| 1830 |
-
print(err.msg)
|
| 1831 |
-
return False
|
| 1832 |
-
return True
|
| 1833 |
-
|
| 1834 |
-
file_py = pathname + ".py"
|
| 1835 |
-
file_pyc = pathname + ".pyc"
|
| 1836 |
-
pycache_opt0 = importlib.util.cache_from_source(file_py, optimization='')
|
| 1837 |
-
pycache_opt1 = importlib.util.cache_from_source(file_py, optimization=1)
|
| 1838 |
-
pycache_opt2 = importlib.util.cache_from_source(file_py, optimization=2)
|
| 1839 |
-
if self._optimize == -1:
|
| 1840 |
-
# legacy mode: use whatever file is present
|
| 1841 |
-
if (os.path.isfile(file_pyc) and
|
| 1842 |
-
os.stat(file_pyc).st_mtime >= os.stat(file_py).st_mtime):
|
| 1843 |
-
# Use .pyc file.
|
| 1844 |
-
arcname = fname = file_pyc
|
| 1845 |
-
elif (os.path.isfile(pycache_opt0) and
|
| 1846 |
-
os.stat(pycache_opt0).st_mtime >= os.stat(file_py).st_mtime):
|
| 1847 |
-
# Use the __pycache__/*.pyc file, but write it to the legacy pyc
|
| 1848 |
-
# file name in the archive.
|
| 1849 |
-
fname = pycache_opt0
|
| 1850 |
-
arcname = file_pyc
|
| 1851 |
-
elif (os.path.isfile(pycache_opt1) and
|
| 1852 |
-
os.stat(pycache_opt1).st_mtime >= os.stat(file_py).st_mtime):
|
| 1853 |
-
# Use the __pycache__/*.pyc file, but write it to the legacy pyc
|
| 1854 |
-
# file name in the archive.
|
| 1855 |
-
fname = pycache_opt1
|
| 1856 |
-
arcname = file_pyc
|
| 1857 |
-
elif (os.path.isfile(pycache_opt2) and
|
| 1858 |
-
os.stat(pycache_opt2).st_mtime >= os.stat(file_py).st_mtime):
|
| 1859 |
-
# Use the __pycache__/*.pyc file, but write it to the legacy pyc
|
| 1860 |
-
# file name in the archive.
|
| 1861 |
-
fname = pycache_opt2
|
| 1862 |
-
arcname = file_pyc
|
| 1863 |
-
else:
|
| 1864 |
-
# Compile py into PEP 3147 pyc file.
|
| 1865 |
-
if _compile(file_py):
|
| 1866 |
-
if sys.flags.optimize == 0:
|
| 1867 |
-
fname = pycache_opt0
|
| 1868 |
-
elif sys.flags.optimize == 1:
|
| 1869 |
-
fname = pycache_opt1
|
| 1870 |
-
else:
|
| 1871 |
-
fname = pycache_opt2
|
| 1872 |
-
arcname = file_pyc
|
| 1873 |
-
else:
|
| 1874 |
-
fname = arcname = file_py
|
| 1875 |
-
else:
|
| 1876 |
-
# new mode: use given optimization level
|
| 1877 |
-
if self._optimize == 0:
|
| 1878 |
-
fname = pycache_opt0
|
| 1879 |
-
arcname = file_pyc
|
| 1880 |
-
else:
|
| 1881 |
-
arcname = file_pyc
|
| 1882 |
-
if self._optimize == 1:
|
| 1883 |
-
fname = pycache_opt1
|
| 1884 |
-
elif self._optimize == 2:
|
| 1885 |
-
fname = pycache_opt2
|
| 1886 |
-
else:
|
| 1887 |
-
msg = "invalid value for 'optimize': {!r}".format(self._optimize)
|
| 1888 |
-
raise ValueError(msg)
|
| 1889 |
-
if not (os.path.isfile(fname) and
|
| 1890 |
-
os.stat(fname).st_mtime >= os.stat(file_py).st_mtime):
|
| 1891 |
-
if not _compile(file_py, optimize=self._optimize):
|
| 1892 |
-
fname = arcname = file_py
|
| 1893 |
-
archivename = os.path.split(arcname)[1]
|
| 1894 |
-
if basename:
|
| 1895 |
-
archivename = "%s/%s" % (basename, archivename)
|
| 1896 |
-
return (fname, archivename)
|
| 1897 |
-
|
| 1898 |
-
|
| 1899 |
-
def main(args = None):
|
| 1900 |
-
import textwrap
|
| 1901 |
-
USAGE=textwrap.dedent("""\
|
| 1902 |
-
Usage:
|
| 1903 |
-
zipfile.py -l zipfile.zip # Show listing of a zipfile
|
| 1904 |
-
zipfile.py -t zipfile.zip # Test if a zipfile is valid
|
| 1905 |
-
zipfile.py -e zipfile.zip target # Extract zipfile into target dir
|
| 1906 |
-
zipfile.py -c zipfile.zip src ... # Create zipfile from sources
|
| 1907 |
-
""")
|
| 1908 |
-
if args is None:
|
| 1909 |
-
args = sys.argv[1:]
|
| 1910 |
-
|
| 1911 |
-
if not args or args[0] not in ('-l', '-c', '-e', '-t'):
|
| 1912 |
-
print(USAGE)
|
| 1913 |
-
sys.exit(1)
|
| 1914 |
-
|
| 1915 |
-
if args[0] == '-l':
|
| 1916 |
-
if len(args) != 2:
|
| 1917 |
-
print(USAGE)
|
| 1918 |
-
sys.exit(1)
|
| 1919 |
-
with ZipFile(args[1], 'r') as zf:
|
| 1920 |
-
zf.printdir()
|
| 1921 |
-
|
| 1922 |
-
elif args[0] == '-t':
|
| 1923 |
-
if len(args) != 2:
|
| 1924 |
-
print(USAGE)
|
| 1925 |
-
sys.exit(1)
|
| 1926 |
-
with ZipFile(args[1], 'r') as zf:
|
| 1927 |
-
badfile = zf.testzip()
|
| 1928 |
-
if badfile:
|
| 1929 |
-
print("The following enclosed file is corrupted: {!r}".format(badfile))
|
| 1930 |
-
print("Done testing")
|
| 1931 |
-
|
| 1932 |
-
elif args[0] == '-e':
|
| 1933 |
-
if len(args) != 3:
|
| 1934 |
-
print(USAGE)
|
| 1935 |
-
sys.exit(1)
|
| 1936 |
-
|
| 1937 |
-
with ZipFile(args[1], 'r') as zf:
|
| 1938 |
-
zf.extractall(args[2])
|
| 1939 |
-
|
| 1940 |
-
elif args[0] == '-c':
|
| 1941 |
-
if len(args) < 3:
|
| 1942 |
-
print(USAGE)
|
| 1943 |
-
sys.exit(1)
|
| 1944 |
-
|
| 1945 |
-
def addToZip(zf, path, zippath):
|
| 1946 |
-
if os.path.isfile(path):
|
| 1947 |
-
zf.write(path, zippath, ZIP_DEFLATED)
|
| 1948 |
-
elif os.path.isdir(path):
|
| 1949 |
-
if zippath:
|
| 1950 |
-
zf.write(path, zippath)
|
| 1951 |
-
for nm in os.listdir(path):
|
| 1952 |
-
addToZip(zf,
|
| 1953 |
-
os.path.join(path, nm), os.path.join(zippath, nm))
|
| 1954 |
-
# else: ignore
|
| 1955 |
-
|
| 1956 |
-
with ZipFile(args[1], 'w') as zf:
|
| 1957 |
-
for path in args[2:]:
|
| 1958 |
-
zippath = os.path.basename(path)
|
| 1959 |
-
if not zippath:
|
| 1960 |
-
zippath = os.path.basename(os.path.dirname(path))
|
| 1961 |
-
if zippath in ('', os.curdir, os.pardir):
|
| 1962 |
-
zippath = ''
|
| 1963 |
-
addToZip(zf, path, zippath)
|
| 1964 |
-
|
| 1965 |
-
if __name__ == "__main__":
|
| 1966 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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