zipfile.py 90 KB

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