a z4f2X@sdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZzddlZejZWneydZejZYn0z ddlZWneydZYn0z ddlZWneydZYn0gdZGdddeZGdddeZeZZdZd Zd ZdZd Zd Zd Z d Z!dZ"dZ#dZ$dZ%dZ&dZ'e (e&Z)dZ*dZ+dZ,dZ-dZ.dZ/dZ0dZ1d Z2dZ3dZ4dZ5e (e4Z6dZ7dZ8dZ9dZ:dZ;dZd Z?dZ@dZAdZBd ZCdZDd ZEd ZFd!ZGd"ZHd#ZId$ZJd%ZKe (eJZLdZMdZNdZOdZPdZQdZRdZSdZTd ZUdZVdZWdZXd&ZYd'ZZe (eYZ[d(Z\d)Z]e (e\Z^dZ_dZ`dZadZbdZcdZddZedZfd ZgdZhd*Zie jd+Zkd,d-Zld.d/Zmd0d1Znd2d3Zod4d5ZpGd6d7d7eqZrdasd8d9Ztd:d;ZuGdd?d?Zwd@dAdBdBdBdBdCdDdEdFdCdGdHdIdJdKdLdMZxdNdOZydodPdQZzdRdSZ{GdTdUdUZ|GdVdWdWZ}GdXdYdYej~ZGdZd[d[ej~ZGd\d]d]ZGd^d_d_eZd`daZdbdcZejZdddeZGdfdgdgeZGdhdidieZGdjdkdkZdpdldmZednkredS)qzP Read and write ZIP files. XXX references to utf-8 need further investigation. N) BadZipFile BadZipfileerror ZIP_STORED ZIP_DEFLATED ZIP_BZIP2ZIP_LZMA is_zipfileZipInfoZipFile PyZipFile LargeZipFilePathc@s eZdZdS)rN)__name__ __module__ __qualname__rr/usr/lib64/python3.9/zipfile.pyr*src@seZdZdZdS)r zu Raised when writing a zipfile, the zipfile requires ZIP64 extensions and those extensions are disabled. N)rrr__doc__rrrrr .sr i -.?s<4s4H2LHsPK z<4s4B4HL2L5H2LsPK z <4s2B4HL2L2HsPKz<4sLQLsPKz <4sQ2H2L4QsPKiPK)filenameresultr@rrrr s   * r c Csz||tdWnty*|YS0|t}t|tkrF|Stt|\}}}}|tkrf|S|dksv|dkr~t d||tt d|t }t|t kr|Stt |\ }}} } } } } }}}|t kr|S||t <| |t<| |t<| |t<||t<||t<||t<|S)zM Read the ZIP64 end-of-archive records and use that to update endrec rrrz3zipfiles that span multiple disks are not supported)seeksizeEndCentDir64Locatorr>rBr0structr/structEndArchive64LocatorstringEndArchive64LocatorrsizeEndCentDir64structEndArchive64stringEndArchive64_ECD_SIGNATURE_ECD_DISK_NUMBER_ECD_DISK_START_ECD_ENTRIES_THIS_DISK_ECD_ENTRIES_TOTAL _ECD_SIZE _ECD_OFFSET)fpinoffsetendrecdatasigdisknoreloffdisksszcreate_version read_versiondisk_numdisk_dirdircount dircount2dirsize diroffsetrrr _EndRecData64s:       rhc Csf|dd|}z|t dWnty:YdS0|}t|tkr|ddtkr|dddkrtt |}t |}| d| |tt |t |St |dtd}||d|}|t}|dkrb|||t}t|tkrdSt tt |}|t}||t|t|}| || ||t |||||SdS) zReturn data from the "End of Central Directory" record, or None. The data is a list of the nine items in the ZIP "End of central dir" record followed by a tenth item, the file seek offset of this record.rrNr sr-i)rHtellsizeEndCentDirr>rBr0stringEndArchiverJr/structEndArchivelistr1rhmaxrfind_ECD_COMMENT_SIZE) rWfilesizerZrYmaxCommentStartr7recData commentSizecommentrrrr=sD         r=c@s\eZdZdZdZdddZddZdd d Zd d ZddZ e dddddZ ddZ d S)r z>Class with attributes describing each file in the ZIP archive.) orig_filenamerF date_time compress_type_compresslevelrvr3 create_systemr`extract_versionreserved flag_bitsvolume internal_attr external_attr header_offsetCRC compress_size file_size _raw_time _end_offsetNoNamerrrrrcCs||_|td}|dkr(|d|}tjdkrJtj|vrJ|tjd}||_||_|ddkrjtdt |_ d|_ d|_ d|_ tjdkrd|_nd|_t|_t|_d|_d|_d|_d|_d|_d|_d|_d|_dS)Nr/rz+ZIP does not support timestamps before 1980r-win32r)rwfindchrossepreplacerFrx ValueErrorrryrzrvr3sysplatformr{DEFAULT_VERSIONr`r|r}r~rrrrrr)selfrFrx null_byterrr__init__Xs6   zZipInfo.__init__cCsd|jj|jfg}|jtkr8|dt|j|j|jd?}|jd@}|rd|dt ||rv|d|| }|r|j r|d|j |r|j r|jtks|j |j kr|d|j |d d |S) Nz<%s filename=%r compress_type=%sr)rz filemode=%rz external_attr=%#xz file_size=%rz compress_size=%r>) __class__rrFryrr1compressor_namesgetrstatfilemodeis_dirrrr2)rrGhiloisdirrrr__repr__s0       zZipInfo.__repr__NcCs||j}|ddd>|dd>B|dB}|dd>|d d>B|ddB}|jd @rfd}}}n|j}|j}|j}|j}d} |d ur|tkp|tk}|rd } |t| dt | d ||}|tks|tkr|st d d}d}t } |j t krtt| } n|j tkrtt| } t| |j|_t| |j|_|\} } ttt|j|j| |j |||||t| t| } | | |S)z-Return the per-file header as a bytes object.rrr$rr!rrr&r rNz|_|rd|_|jd O_n|j|_|S) a_Construct an appropriate ZipInfo for a file on the filesystem. filename should be the path to a file or directory on the filesystem. arcname is the name which it will have within the archive (by default, this will be the same as filename, but without a drive letter and with leading path separators removed). rr"rr;)rr;rNrrrr)) isinstancerPathLikefspathrS_ISDIRst_modetime localtimest_mtimepathnormpath splitdriveraltseprrst_size) clsrFarcnamerstrmtimerxzinforrr from_files0       zZipInfo.from_filecCs|jddkS)z2Return True if this archive member is a directory.rrFrrrrrszZipInfo.is_dir)rr)N)N) rrrr __slots__rrrrr classmethodrrrrrrr =s , .%r cCs0tdD]"}|d@r"|d?dA}q|dL}q|S)Nrrl q[)range)crcr;rrr_gen_crcs   rcsldddtdur&ttttdatfddfdd|D] }|qLfd d }|S) NixV4igE#ixV4cs|d?||Ad@AS)z(Compute the CRC32 primitive on one byte.rr)chr)crctablerrcrc325sz_ZipDecrypter..crc32cs<|d@d@ddd@d?dS)Nrrirr)c)rkey0key1key2rr update_keys9s z"_ZipDecrypter..update_keyscsNt}|j}|D]4}dB}|||dAd?d@N}|||qt|S)zDecrypt a bytes object.rrrr) bytearrayr1bytes)rZrGr1rk)rrrr decrypterCs z _ZipDecrypter..decrypter) _crctablernmaprr)pwdprr)rrrrrrr _ZipDecrypter+s   rc@s,eZdZddZddZddZddZd S) LZMACompressorcCs d|_dSN)_comprrrrrSszLZMACompressor.__init__cCsFtdtji}tjtjttj|gd|_tdddt ||S)Nidfiltersz|jd|jd}|dkr>|j|j|}||_|Stj||S)zrRead and return a line from the stream. If limit is specified, at most limit bytes will be read. r r)rIrrJioBufferedIOBasereadline)rlimitr8linerrrrccszZipExtFile.readlinercCsr|t|j|jkr\||}t||jkrJ||j|jd|_d|_n|jt|8_|j|j|jdS)z6Returns buffered bytes without advancing the position.Nri)r0rIrJrB)rr:chunkrrrpeekss zZipExtFile.peekcCs|jrtddS)NI/O operation on closed file.T)r^rrrrrreadableszZipExtFile.readablecCs|jrtd|dus|dkrV|j|jd}d|_d|_|jsR|||j7}q:|S||j}|t|jkr|j|j|}||_|S|t|j}|j|jd}d|_d|_|dkr|js||}|t|kr||_||_||d|7}q||7}|t|8}q|S)zRead and return up to n bytes. If the argument is omitted, None, or negative, data is read and returned until EOF is reached. zread from closed file.Nrr-)r^rrIrJrH_read1MAX_Nr0)rr:bufendrZrrrrBs8   zZipExtFile.readcCs@|jdurdSt||j|_|jr<|j|jkr     zZipExtFile.read1cCs"|js|dkrdS|jtkrH|jj}|t|krR|||t|7}n ||}|jtkrj|jdk|_nx|jtkrt ||j }|j ||}|jj p|jdko|jj |_|jr||j 7}n |j |}|jj p|jdk|_|d|j}|jt|8_|jdkrd|_|||S)Nrr-T)rHrDrrGunconsumed_tailr0_read2rrEro MIN_READ_SIZEr rrrFror9rrrrjs4          zZipExtFile._read1cCsd|jdkrdSt||j}t||j}|j|}|jt|8_|sLt|jdur`||}|S)Nrr-) rErorsminrArBr0EOFErrorrVr9rrrrrs      zZipExtFile._read2cs0z|jr|jWtn t0dSr)rCrAr4superrrrrr4 s zZipExtFile.closecCs|jrtd|jSNrh)r^rrPrrrrr1szZipExtFile.seekablercCsL|jrtd|jstd|}|dkr4|}n.|dkrF||}n|dkrZ|j|}ntd||jkrr|j}|dkr~d}||}||j}|dkr|t|j kr||_d}nf|dkr|j |j |j |_|j|_|j|_d|_ d|_t|j|_d|_|}|jdur||dkrDt|j|}||||8}q|S) Nzseek on closed file.!underlying stream is not seekablerrrzCwhence must be os.SEEK_SET (0), os.SEEK_CUR (1), or os.SEEK_END (2)r-F)r^rrPraUnsupportedOperationrjrSrJr0rIrArHrQrTrOrRrErFr*rDrGrHrVrWrt MAX_SEEK_READrB)rrXr7curr_posnew_pos read_offset buff_offsetread_lenrrrrHsL            zZipExtFile.seekcCs>|jrtd|jstd|j|jt|j|j }|S)Nztell on closed file.ry) r^rrPrarzrSrFr0rIrJ)rfileposrrrrjIs  zZipExtFile.tell)NF)r)r)r)r)rrrrrkrsr{rrWrrcrgrirBrorprjrrr4r1rHrj __classcell__rrrwrr@ s* 3    # %$  2r@cs@eZdZddZeddZddZddZfd d ZZ S) _ZipWriteFilecCs8||_||_||_t|j|j|_d|_d|_d|_ dSr=) _zinfo_zip64_zipfiler&ryrz _compressor _file_size_compress_size_crc)rzfrrrrrrSsz_ZipWriteFile.__init__cCs|jjSr)rr@rrrrrA]sz_ZipWriteFile._fileobjcCsdS)NTrrrrrwritableasz_ZipWriteFile.writablecCs|jrtdt|ttfr&t|}nt|}|j}|j|7_t ||j |_ |j rt|j |}|j t|7_ |j||Srx)r^rrrrr0 memoryviewnbytesrrrrrrrAr?)rrZrrrrr?ds   z_ZipWriteFile.writec sj|jr dSzNt|jrR|j}|jt|7_|j||j|j _ n |j |j _ |j |j _ |j |j _|j jd@r|jrdnd}|jt|t|j j |j j |j j|j|j_nn|js|j tkrtd|jtkrtd|j|j_|j|j j|j|j |j|j|jj|jj|j |j |jj|j j<Wd|j_ n d|j_ 0dS)Nrzdd Zd?d!d"d#d$Zd@d%d&ZdAd'd(ZdBd)d*Zed+d,Zd-d.Zd/d0ZdCd1d2ZdDd3d4Zd5d6Z d7d8Z!d9d:Z"d;d<Z#dS)Er ai Class with methods to open, read, write, close, list zip files. z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=True, compresslevel=None) file: Either the path to the file, or a file-like object. If it is a path, the file will be opened and closed by ZipFile. mode: The mode can be either read 'r', write 'w', exclusive create 'x', or append 'a'. compression: ZIP_STORED (no compression), ZIP_DEFLATED (requires zlib), ZIP_BZIP2 (requires bz2) or ZIP_LZMA (requires lzma). allowZip64: if True ZipFile will create files with ZIP64 extensions when needed, otherwise it will raise an exception when this would be necessary. compresslevel: None (default for the given compression type) or an integer specifying the level to pass to the compressor. When using ZIP_STORED or ZIP_LZMA this keyword has no effect. When using ZIP_DEFLATED integers 0 through 9 are accepted. When using ZIP_BZIP2 integers 1 through 9 are accepted. NrTrc CsH|dvrtdt|||_d|_d|_i|_g|_||_||_||_ d|_ d|_ ||_ t |tjrpt|}t |trd|_||_ddd d dd d d }||}zt|||_Wqty||vr||}YqYq0qqnd|_||_t|dd|_d|_t|_d|_d|_z|dkr2|n|dvrd|_z|j |_!Wn0t"tfyt#|j|_d|_!d|_Yn40z|j$|j!Wnt"tfyd|_Yn0nd|dkrz||j$|j!Wn4t%y|j$ddd|_|j |_!Yn0ntdWn$|j} d|_|&| Yn0dS)z]Open the ZIP file with mode read 'r', write 'w', exclusive create 'x', or append 'a'.)rwxaz+ZipFile requires mode 'r', 'w', 'x', or 'a'FrNr-rCw+bx+br+bwbxb)rrrrrrrrrMTr)rrrrz"Mode must be 'r', 'w', 'x', or 'a')'rr _allowZip64 _didModifydebugrrrr%rLr_comment_strict_timestampsrrrrstr _filePassedrFrarEr@r>getattr _fileRefCnt threadingRLockr/rPr0_RealGetContentsrjrrUr<rHr_fpclose) rr2rLr allowZip64r%rmodeDictrr@rrrrs             zZipFile.__init__cCs|Srrrrrr __enter__szZipFile.__enter__cCs |dSrr4)rtypevalue tracebackrrr__exit__szZipFile.__exit__cCsd|jj|jjfg}|jdurd|jr8|d|jn|jdurR|d|j|d|jn |d|dd|S)Nr\z file=%rz filename=%rz mode=%rr]rr) rrrr@rr1rFrLr2r_rrrr!s    zZipFile.__repr__c Cs|j}z t|}Wnty,tdYn0|s:td|jdkrLt||t}|t}|t|_ |t ||}|t t kr|t t8}|jdkr||}td||||||_||jd||}t|}d}||kr|t} t| tkrtdtt| } | ttkr*td|jdkr>t| || t} | d} | d @rj| d } n | d } t| } || t| _|| t | _!| t"| _#| dd \ | _$| _%| _&| _'| _(| _)} }| _*| _+| _,| j&t-krt.d | j&d| dd\| _/| _0| _1| | _2|d?d|d?d@|d@| d?| d?d@| d@df| _3| 4| j#|| _#|j56| | |j7| j8<|t| t| t| t }|jdkrtd|q|j}t9|j5ddddD]}||_:|j#}qdS)z/Read in the table of contents for the ZIP file.zFile is not a zip filerrzgiven, inferred, offsetrzTruncated central directoryz&Bad magic number for central directoryr!rrcp437rzzip file version %.1fr%r(r+r$rrr&rtotalcSs|jSr)r)rrrr~r-z*ZipFile._RealGetContents..T)keyreverseN);r@r=r>rrprintrUrV _ECD_COMMENTr _ECD_LOCATIONrPrOrMrIrrHrBraBytesIOsizeCentralDirr0rJr/structCentralDir _CD_SIGNATUREstringCentralDir_CD_FILENAME_LENGTHdecoder _CD_EXTRA_FIELD_LENGTHr3_CD_COMMENT_LENGTHrv_CD_LOCAL_HEADER_OFFSETrr`r{r|r}r~ryrrrMAX_EXTRACT_VERSIONrrrrrrxrrr1rrFsortedr)rr@rYsize_cd offset_cdconcatinferredrZrcentdirrFflagsrtd end_offsetrrrrr/s                            zZipFile._RealGetContentscCsdd|jDS)z+Return a list of file names in the archive.cSsg|] }|jqSrr).0rZrrr r-z$ZipFile.namelist..rrrrrnamelistszZipFile.namelistcCs|jS)zJReturn a list of class ZipInfo instances for files in the archive.rrrrrinfolistszZipFile.infolistcCsLtdd|d|jD]0}d|jdd}td|j||jf|dqdS)z+Print a table of contents for the zip file.z%-46s %19s %12s)z File Namez Modified Size)r2z%d-%02d-%02d %02d:%02d:%02dNr"z %-46s %s %12d)rrrxrFr)rr2rdaterrrprintdirs zZipFile.printdirc Cspd}|jD]`}z>||jd}||r,q Wdn1s@0YWq tyh|jYS0q dS)z%Read all the files and check the CRC.irN)rrErFrBr)r chunk_sizerfrrrtestzips  $ zZipFile.testzipcCs$|j|}|dur td||S)z,Return the instance of ZipInfo given 'name'.Nz(There is no item named %r in the archive)rrKeyError)rrMinforrrgetinfos  zZipFile.getinfocCs6|r t|ts tdt|j|r,||_nd|_dS)z)Set default password for encrypted files.pwd: expected bytes, got %sN)rr TypeErrorrrr)rrrrr setpasswords zZipFile.setpasswordcCs|jS)z.The comment text associated with the ZIP file.)rrrrrrvszZipFile.commentcCs^t|tstdt|jt|tkrNddl}|jdtdd|dt}||_ d|_ dS)Nzcomment: expected bytes, got %srz3Archive comment is too long; truncating to %d bytesr stacklevelT) rrrrrr0ZIP_MAX_COMMENTwarningswarnrr)rrvrrrrrvs   cCs:||d|}|WdS1s,0YdS)zReturn file bytes for name.rNrErB)rrMrr@rrrrBsz ZipFile.readF force_zip64c sJ|dvrtd|r0t|ts0tdt|j|rD|dkrDtdjsRtdt|trb|}n,|dkrt|}j|_ j |_ n |}|dkrj ||dSjrtdjd 7_tj|jjjfd d }zL|t}t|tkrtd tt|}|ttkr&td ||t}|trL||t|jd@r`t d|jd@rtt d|t!d@r|"d} n |"d} | |j#krtd|j#|f|j$dur|%|j&|j$krtd|j#d|jd @} | r|sj'}|st(d|nd}t)||||dWS|*Yn0dS)auReturn file-like object for 'name'. name is a string for the file name within the ZIP file, or a ZipInfo object. mode should be 'r' to read a file already in the ZIP file, or 'w' to write to a file newly added to the archive. pwd is the password to decrypt files (only used for reading). When writing, if the file size is not known in advance but may exceed 2 GiB, pass force_zip64 to use the ZIP64 format, which can handle large files. If the size is known in advance, it is best to pass a ZipInfo instance for name, with zinfo.file_size set. >rrzopen() requires mode "r" or "w"rrz'pwd is only supported for reading filesz2Attempt to use ZIP archive that was already closedrr8rcsjSr)r0rrrrrr-zZipFile.open..zTruncated file headerz Bad magic number for file header z$compressed patched data (flag bit 5)@zstrong encryption (flag bit 6)rrrz/File name in directory %r and header %r differ.NzOverlapped entries: z (possible zip bomb)z6File %r is encrypted, password required for extractionT)+rrrrrrr@r rryr%rzr_open_to_writer0rr+rrr/rBsizeFileHeaderr0rrJr/r _FH_SIGNATUREr_FH_FILENAME_LENGTH_FH_EXTRA_FIELD_LENGTHr~r_FH_GENERAL_PURPOSE_FLAG_BITSrrwrrjrrrr@r4) rrMrLrrrzef_filefheaderfname fname_str is_encryptedrrrrEs               z ZipFile.opencCs|r|jstd|jr tdd|_d|_d|_|jtkrJ|jdO_|js^|jdO_|j sjd|_ |jo|p|j dt k}|jr|j |j|j |_||d|_|j ||d|_t|||S) NzHforce_zip64 is True, but allowZip64 was False when opening the ZIP file.zzCan't write to the ZIP file while there is another write handle open on it. Close the first handle before opening another.rrrg?T)rrr0rrr~ryrrPrrrr@rHrrjr _writecheckrr?rr)rrrrrrrr1s4    zZipFile._open_to_writecCs*|durt}n t|}||||S)a#Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. `member' may be a filename or a ZipInfo object. You can specify a different directory using `path'. N)rgetcwdr_extract_member)rmemberrrrrrextractZs  zZipFile.extractcCsH|dur|}|dur"t}n t|}|D]}||||q0dS)zExtract all members from the archive to the current working directory. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by namelist(). N)rrrrr)rrmembersrrXrrr extractallgs  zZipFile.extractallcCs^|j}|s(d}t|dt|}||_||}dd||D}|dd|D}|S)z;Replace bad characters and remove trailing dots from parts.z:<>|"?*_css|]}|dVqdS).N)rstriprrrrr r-z1ZipFile._sanitize_windows_name..css|]}|r|VqdSrrrrrrrr-)!_windows_illegal_name_trans_tabler maketransr0 translatesplitr2)rrpathseptableillegalrrr_sanitize_windows_namexs zZipFile._sanitize_windows_namec sxt|ts||}|jdtjj}tjjrB|tjjtjj}tj |d}dtjj tjj ftjj fdd| tjjD}tjjdkr||tjj}tj ||}tj|}tj|}|rtj|st||r tj|st||S|j||dH}t|d}t||Wd n1sJ0YWd n1sj0Y|S) zbExtract the ZipInfo object 'member' to a physical file on the path targetpath. rrrc3s|]}|vr|VqdSrrrinvalid_path_partsrrrsz*ZipFile._extract_member..\rrN)rr rrFrrrrrrcurdirpardirr2rr rdirnameexistsmakedirsrrmkdirrEshutil copyfileobj)rr targetpathrr upperdirssourcetargetrr rrs2  &      LzZipFile._extract_membercCs|j|jvr(ddl}|jd|jdd|jdvr:td|jsHtdt|j|j sd}t |j t krpd }n|j tkrd }n|jtkrd }|rt|d dS) z6Check for errors before writing a file to the archive.rNzDuplicate name: %rrrrrrz&write() requires mode 'w', 'x', or 'a'z4Attempt to write ZIP archive that was already closed Files countFilesizez Zipfile size would require ZIP64 extensions)rFrrrrLrr@rryrr0rZIP_FILECOUNT_LIMITrrrr )rrrrequires_zip64rrrrs,     zZipFile._writecheckc Cs|jstd|jrtdtj|||jd}|rDd|_d|_n0|durT||_ n|j |_ |durl||_ n|j |_ |r&|j |jr|j|j|j|_|j tkr|jdO_||d|_|j|||j|j<|j|d|j|_Wdn1s0Ynht|d L}||d }t||d Wdn1sd0YWdn1s0YdS) zLPut the bytes from filename into the archive under the name arcname.7Attempt to write to ZIP archive that was already closedz>Can't write to ZIP archive while an open writing handle existsrrNrTFrCri ) r@rr0r rrrrrryrrzr%r/rPrHrrjrrr~rrrr1rrFr?rrErr)rrFrryr%rsrcdestrrrr?sF      .z ZipFile.writec Cs"t|tr|d}t|tsxt|ttddd}|j|_|j|_ |j ddkrpd|_ |j dO_ q|d |_ n|}|j st d |jrt d |dur||_|dur||_ t||_|jH|j|d d }||Wdn1s0YWdn1s0YdS)aWrite a file into the archive. The contents is 'data', which may be either a 'str' or a 'bytes' instance; if it is a 'str', it is encoded as UTF-8 first. 'zinfo_or_arcname' is either a ZipInfo instance or the name of the file in the archive.rNr")rFrxrriAr)rr z?Can't write to ZIP archive while an open writing handle exists.r)rL)rrrr rrrryr%rzrFrr@rr0r0rr/rEr?)rzinfo_or_arcnamerZryr%rr"rrrwritestrs:    zZipFile.writestrcCs |dS)z2Call the "close()" method in case the user forgot.Nrrrrr__del__"szZipFile.__del__c Cs|jdurdS|jrtdzl|jdvrp|jrp|j,|jrJ|j|j| Wdn1sf0YW|j}d|_| |n|j}d|_| |0dS)zOClose the file, and for mode 'w', 'x' and 'a' write the ending records.NzvCan't close the ZIP file while there is an open writing handle on it. Close the writing handle before closing the zip.r) r@r0rrLrr/rPrHr_write_end_recordrr>rrrr4&s  ( z ZipFile.closecCs|jD]}|j}|ddd>|dd>B|dB}|dd>|d d>B|ddB}g}|jtksr|jtkr||j||jd }d }n |j}|j}|jtkr||jd }n|j}|j} d} |rt| d } t j d d t |ddt |g|R| } t } |j tkr&tt| } n|j tkrrrrrs zZipFile._fpclose)N)N)rN)F)NN)NNN)NNN)NN)$rrrrr@rrrrrrrrrrrrrrrvsetterrBrErrrrr rrr?r$r%r4r&rrrrrr sP ZT      f )  * 2 )^r c@s4eZdZdZdeddfddZd d d Zd d ZdS)r zDClass to create ZIP archives with Python library files and packages.rTrcCstj|||||d||_dS)N)rLrr)r r _optimize)rr2rLrroptimizerrrrs zPyZipFile.__init__rNcCst|}|rD||sD|jr@tj|r,dnd}td||fdStj|\}}tj|rhtj|d}tj|r|rd||f}n|}|jrtd|d|| |d d |\}} |jrtd | | || t t |} | d| D]} tj|| } tj| \} }tj| rRtjtj| dr|j| ||d q|d kr|r~|| s~|jrtd| q| | d d |\}} |jrtd | | || qn|jrtd|t t |D]} tj|| } tj| \} }|d kr|r,|| s,|jrtd| q| | d d |\}} |jrVtd | | || qnP|d dd krtd| |d d |\}} |jrtd| | || dS)aAdd all files from "pathname" to the ZIP archive. If pathname is a package directory, search the directory and all package subdirectories recursively for all *.py and enter the modules into the archive. If pathname is a plain directory, listdir *.py and enter all modules. Else, pathname must be a Python *.py file and the module will be put into the archive. Added modules are always module.pyc. This method will compile the module.py into module.pyc if necessary. If filterfunc(pathname) is given, it is called with every argument. When it is False, the file or directory is skipped. rr2z%s %r skipped by filterfuncNz __init__.py%s/%szAdding package inasrAdding) filterfunc.pyzfile %r skipped by filterfunczAdding files from directoryz.Files added with writepy() must end with ".py"z Adding file)rrrrrrrr2isfile _get_codenamer?rlistdirremovesplitextwritepyr)rpathnamebasenamer8labeldirrMinitnamerrdirlistrFrrootextrrrr?s            zPyZipFile.writepyc sdfdd }|d}|d}tjj|dd}tjj|dd}tjj|d d}jdkr\tj|rt|jt|jkr|} } ntj|rt|jt|jkr|} |} ntj|rt|jt|jkr|} |} nvtj|rt|jt|jkr|} |} nD||rRt j j d kr4|} nt j j dkrH|} n|} |} n|} } njd krr|} |} n<|} jdkr|} n&jd kr|} nd j} t | tj| rt| jt|jks||jd s|} } tj| d} |rd || f} | | fS)aReturn (filename, archivename) for the path. Given a module name path, return the correct file path and archive name, compiling if necessary. For example, given /python/lib/string, return (/python/lib/string.pyc, string). rc sdddl}jrtd|z|j|d|dWn2|jy^}zt|jWYd}~dSd}~00dS)Nr CompilingT)doraiser3F) py_compilerrcompilePyCompileErrormsg)r2r3rJerrrrr_compiles  z)PyZipFile._get_codename.._compiler9z.pycr) optimizationrrrz"invalid value for 'optimize': {!r})r3r4)r) importlibutilcache_from_sourcer2rrr:rrrrr3formatrr) rr@rArOfile_pyfile_pyc pycache_opt0 pycache_opt1 pycache_opt2rrrM archivenamerrrr;sj             zPyZipFile._get_codename)rN)rrrrrrr?r;rrrrr s   Rr cCstt|ddS)a2 Given a path with elements separated by posixpath.sep, generate all parents of that path. >>> list(_parents('b/d')) ['b'] >>> list(_parents('/b/d/')) ['/b'] >>> list(_parents('b/d/f/')) ['b/d', 'b'] >>> list(_parents('b')) [] >>> list(_parents('')) [] rN) itertoolsislice _ancestry)rrrr_parentsOsr^ccs4|tj}|r0|tjkr0|Vt|\}}q dS)aR Given a path with elements separated by posixpath.sep, generate all elements of that path >>> list(_ancestry('b/d')) ['b/d', 'b'] >>> list(_ancestry('/b/d/')) ['/b/d', '/b'] >>> list(_ancestry('b/d/f/')) ['b/d/f', 'b/d', 'b'] >>> list(_ancestry('b')) ['b'] >>> list(_ancestry('')) [] N)r posixpathrr)rtailrrrr]bs r]cCstt|j|S)zZ Return items in minuend not in subtrahend, retaining order with O(1) lookup. )r[ filterfalseset __contains__)minuend subtrahendrrr _difference|srfcsHeZdZdZeddZfddZddZdd Ze d d Z Z S) CompleteDirszk A ZipFile subclass that ensures that implied directories are always included in the namelist. cCs.tjtt|}dd|D}tt||S)Ncss|]}|tjVqdSr)r_r)rrrrrrr-z-CompleteDirs._implied_dirs..)r[chain from_iterablerr^_deduperf)namesparentsas_dirsrrr _implied_dirsszCompleteDirs._implied_dirscs tt|}|t||Sr)rvrgrrnrn)rrkrwrrrszCompleteDirs.namelistcCs t|Sr)rbrrrrr _name_setszCompleteDirs._name_setcCs,|}|d}||vo||v}|r(|S|S)zx If the name represents a directory, return that name as a directory (with the trailing slash). r)ro)rrMrkr dir_matchrrr resolve_dirszCompleteDirs.resolve_dircCsNt|tr|St|ts ||Sd|jvr.t}||}t|t||S)zl Given a source (filename or zipfile), return an appropriate CompleteDirs subclass. r)rrgr rL__new__varsupdate)rrresrrrmakes    zCompleteDirs.make) rrrr staticmethodrnrrorqrrvrrrrwrrgs   rgcs,eZdZdZfddZfddZZS) FastLookupzV ZipFile subclass to ensure implicit dirs exist and are resolved rapidly. csFtt|jWdS1s&0Ytt||_|jSr) contextlibsuppressrU_FastLookup__namesrvrxrrrwrrrs $zFastLookup.namelistcsFtt|jWdS1s&0Ytt||_|jSr)ryrzrU_FastLookup__lookuprvrxrorrwrrros $zFastLookup._name_set)rrrrrrorrrrwrrxs rxc@seZdZdZdZd$ddZd%ddZed d Zd d Z d dZ ddZ ddZ ddZ ddZddZddZddZddZdd ZeZed!d"Zd#S)&ru A pathlib-compatible interface for zip files. Consider a zip file with this structure:: . ├── a.txt └── b ├── c.txt └── d └── e.txt >>> data = io.BytesIO() >>> zf = ZipFile(data, 'w') >>> zf.writestr('a.txt', 'content of a') >>> zf.writestr('b/c.txt', 'content of c') >>> zf.writestr('b/d/e.txt', 'content of e') >>> zf.filename = 'abcde.zip' Path accepts the zipfile object itself or a filename >>> root = Path(zf) From there, several path operations are available. Directory iteration (including the zip file itself): >>> a, b = root.iterdir() >>> a Path('abcde.zip', 'a.txt') >>> b Path('abcde.zip', 'b/') name property: >>> b.name 'b' join with divide operator: >>> c = b / 'c.txt' >>> c Path('abcde.zip', 'b/c.txt') >>> c.name 'c.txt' Read text: >>> c.read_text() 'content of c' existence: >>> c.exists() True >>> (b / 'missing.txt').exists() False Coercion to string: >>> str(c) 'abcde.zip/b/c.txt' z>{self.__class__.__name__}({self.root.filename!r}, {self.at!r})rcCst||_||_dSr)rxrvrFat)rrFr}rrrr s z Path.__init__rcOs\|dd}|d}|jj|j||d}d|vrD|s8|r@td|Stj|g|Ri|S)z Open this entry as text or binary following the semantics of ``pathlib.Path.open()`` by passing arguments through to io.TextIOWrapper(). rNrr bz*encoding args invalid for binary operation)poprFrEr}rra TextIOWrapper)rrLargskwargsrzip_modestreamrrrrE s z Path.opencCst|jdSNr)r_rAr}rrrrrrM sz Path.namecOsD|jdg|Ri|}|WdS1s60YdS)Nrr)rrrstrmrrr read_text" szPath.read_textcCs6|d}|WdS1s(0YdS)NrCr)rrrrr read_bytes& s zPath.read_bytescCst|jd|jdkSr)r_rr}r)rrrrr _is_child* szPath._is_childcCs t|j|Sr)rrF)rr}rrr_next- sz Path._nextcCs|j p|jdSr)r}endswithrrrrr0 sz Path.is_dircCs | Sr)rrrrris_file3 sz Path.is_filecCs|j|jvSr)r}rFrorrrrr6 sz Path.existscCs.|stdt|j|j}t|j|S)NzCan't listdir a file)rrrrrFrfilterr)rsubsrrriterdir9 sz Path.iterdircCst|jj|jSr)r_r2rFrFr}rrrr__str__? sz Path.__str__cCs|jj|dS)Nr) _Path__reprrTrrrrrB sz Path.__repr__cCs t|j|}||j|Sr)r_r2r}rrFrq)raddnextrrrjoinpathE sz Path.joinpathcCs(t|jd}|r|d7}||Sr)r_rr}rr)r parent_atrrrparentK sz Path.parentN)r)r)rrrrrrrErrMrrrrrrrrrrr __truediv__rrrrrrs(@   rc s ddl}d}|j|d}|jdd}|jdddd d |jd d d ddd|jdddddd|jddddd ||}|jdur|j}t|d}|}Wdn1s0Y|rtd |tdnB|j dur"|j }t|d}| Wdn1s0Yn|j durp|j \}}t|d}| |Wdn1sd0Yn|jdur|jd} |j} fddt| df}| D]P} tj| } | stjtj| } | dtjtjfvrd} || | qWdn1s0YdS) Nrz3A simple command-line interface for zipfile module.) descriptionT)requiredz-lz--list zShow listing of a zipfile)metavarhelpz-ez --extractr)rz zExtract zipfile into target dir)nargsrrz-cz--create+)zzzCreate zipfile from sourcesz-tz--testzTest if a zipfile is validrz.The following enclosed file is corrupted: {!r}z Done testingcsptj|r|||tnPtj|rl|r8|||tt|D]$}|tj||tj||qFdSr) rrr:r?rrrr<r2)rrzippathnmaddToZiprrr{ s   zmain..addToZiprr)argparseArgumentParseradd_mutually_exclusive_group add_argument parse_argstestr rrrTrnrrrcreaterrrrArrr) rrrparsergroupr!rbadfilerzip_namefilesrrrrrmainS s\         &   *   ,    r__main__)N)N)rbinasciiimportlib.utilrQrar[rr_rrrJrrrryrr ImportErrorrr__all__ Exceptionrr rrrrrrrrrrrrrrrmrlrrkrPrQrRrSrTrUrVrqrrrrrr_CD_CREATE_VERSION_CD_CREATE_SYSTEM_CD_EXTRACT_VERSION_CD_EXTRACT_SYSTEM _CD_FLAG_BITS_CD_COMPRESS_TYPE_CD_TIME_CD_DATE_CD_CRC_CD_COMPRESSED_SIZE_CD_UNCOMPRESSED_SIZErrr_CD_DISK_NUMBER_START_CD_INTERNAL_FILE_ATTRIBUTES_CD_EXTERNAL_FILE_ATTRIBUTESrrrrr_FH_EXTRACT_VERSION_FH_EXTRACT_SYSTEMr_FH_COMPRESSION_METHOD_FH_LAST_MOD_TIME_FH_LAST_MOD_DATE_FH_CRC_FH_COMPRESSED_SIZE_FH_UNCOMPRESSED_SIZErrrKrLrIrNrOrM_CD64_SIGNATURE_CD64_DIRECTORY_RECSIZE_CD64_CREATE_VERSION_CD64_EXTRACT_VERSION_CD64_DISK_NUMBER_CD64_DISK_NUMBER_START_CD64_NUMBER_ENTRIES_THIS_DISK_CD64_NUMBER_ENTRIES_TOTAL_CD64_DIRECTORY_SIZE_CD64_OFFSET_START_CENTDIRrStructr.r<rAr rhr=objectr rrrrrrrr&r*r+r<rbr@rr r r^r]dictfromkeysrjrfrgrxrrrrrrrsT                +=^& (KU/2 =