ยปCore Development>Code coverage>Lib/zipfile.py

Python code coverage for Lib/zipfile.py

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