zipfileutils.py (2395B)
1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\packages\brennivin\zipfileutils.py 2 import os as _os 3 import zipfile as _zipfile 4 from zipfile import ZipFile 5 if not hasattr(ZipFile, '__enter__'): 6 7 class ZipFile27(ZipFile): 8 9 def __enter__(self): 10 return self 11 12 def __exit__(self, *_): 13 self.close() 14 15 16 ZipFile = ZipFile27 17 from . import dochelpers, osutils 18 19 class FileComparisonError(Exception): 20 pass 21 22 23 ALL = dochelpers.pretty_func(lambda _: True, 'ALL') 24 NONE = dochelpers.pretty_func(lambda _: False, 'NONE') 25 26 def write_files(fullpaths, zfile, include = ALL, exclude = NONE, subdir = None, rootpath = None): 27 for path in fullpaths: 28 if include(path) and not exclude(path): 29 arcname = None 30 if rootpath: 31 arcname = _os.path.relpath(path, rootpath) 32 if subdir: 33 arcname = _os.path.join(subdir, arcname) 34 zfile.write(path, arcname) 35 36 37 def write_dir(rootpath, zfile, include = ALL, exclude = NONE, subdir = None): 38 write_files(osutils.iter_files(rootpath), zfile, include, exclude, subdir, rootpath) 39 40 41 def zip_dir(rootdir, outfile, include = ALL, exclude = NONE, subdir = None): 42 outdir = _os.path.dirname(outfile) 43 if not _os.path.exists(outdir): 44 _os.makedirs(outdir) 45 with ZipFile(outfile, 'w', _zipfile.ZIP_DEFLATED) as zfile: 46 write_dir(rootdir, zfile, include, exclude, subdir) 47 48 49 def is_inside_zipfile(filepath): 50 folderpath, filename = _os.path.split(filepath) 51 is_zip = False 52 while folderpath and filename: 53 if _os.path.exists(folderpath): 54 if _zipfile.is_zipfile(folderpath): 55 is_zip = True 56 break 57 folderpath, filename = _os.path.split(folderpath) 58 59 return is_zip 60 61 62 def _sorted_infolist(zippath): 63 return sorted(_zipfile.ZipFile(zippath).infolist(), key=lambda zi: zi.filename) 64 65 66 def compare_zip_files(z1, z2): 67 f1infos = _sorted_infolist(z1) 68 f2infos = _sorted_infolist(z2) 69 f1names = [ f.filename for f in f1infos ] 70 f2names = [ f.filename for f in f2infos ] 71 if f1names != f2names: 72 raise FileComparisonError('File lists differ: %s, %s' % (f1names, f2names)) 73 for f1i, f2i in zip(f1infos, f2infos): 74 if f1i.CRC != f2i.CRC: 75 raise FileComparisonError('%s CRCs different.' % f1i.filename)