Aluode/PerceptionLabPortable
0
1import os2import zipfile3 4import fsspec5from fsspec.archive import AbstractArchiveFileSystem6 7 8class ZipFileSystem(AbstractArchiveFileSystem):9 """Read/Write contents of ZIP archive as a file-system10 11 Keeps file object open while instance lives.12 13 This class is pickleable, but not necessarily thread-safe14 """15 16 root_marker = ""17 protocol = "zip"18 cachable = False19 20 def __init__(21 self,22 fo="",23 mode="r",24 target_protocol=None,25 target_options=None,26 compression=zipfile.ZIP_STORED,27 allowZip64=True,28 compresslevel=None,29 **kwargs,30 ):31 """32 Parameters33 ----------34 fo: str or file-like35 Contains ZIP, and must exist. If a str, will fetch file using36 :meth:`~fsspec.open_files`, which must return one file exactly.37 mode: str38 Accept: "r", "w", "a"39 target_protocol: str (optional)40 If ``fo`` is a string, this value can be used to override the41 FS protocol inferred from a URL42 target_options: dict (optional)43 Kwargs passed when instantiating the target FS, if ``fo`` is44 a string.45 compression, allowZip64, compresslevel: passed to ZipFile46 Only relevant when creating a ZIP47 """48 super().__init__(self, **kwargs)49 if mode not in set("rwa"):50 raise ValueError(f"mode '{mode}' no understood")51 self.mode = mode52 if isinstance(fo, (str, os.PathLike)):53 if mode == "a":54 m = "r+b"55 else:56 m = mode + "b"57 fo = fsspec.open(58 fo, mode=m, protocol=target_protocol, **(target_options or {})59 )60 self.force_zip_64 = allowZip6461 self.of = fo62 self.fo = fo.__enter__() # the whole instance is a context63 self.zip = zipfile.ZipFile(64 self.fo,65 mode=mode,66 compression=compression,67 allowZip64=allowZip64,68 compresslevel=compresslevel,69 )70 self.dir_cache = None71 72 @classmethod73 def _strip_protocol(cls, path):74 # zip file paths are always relative to the archive root75 return super()._strip_protocol(path).lstrip("/")76 77 def __del__(self):78 if hasattr(self, "zip"):79 self.close()80 del self.zip81 82 def close(self):83 """Commits any write changes to the file. Done on ``del`` too."""84 self.zip.close()85 86 def _get_dirs(self):87 if self.dir_cache is None or self.mode in set("wa"):88 # when writing, dir_cache is always in the ZipFile's attributes,89 # not read from the file.90 files = self.zip.infolist()91 self.dir_cache = {92 dirname.rstrip("/"): {93 "name": dirname.rstrip("/"),94 "size": 0,95 "type": "directory",96 }97 for dirname in self._all_dirnames(self.zip.namelist())98 }99 for z in files:100 f = {s: getattr(z, s, None) for s in zipfile.ZipInfo.__slots__}101 f.update(102 {103 "name": z.filename.rstrip("/"),104 "size": z.file_size,105 "type": ("directory" if z.is_dir() else "file"),106 }107 )108 self.dir_cache[f["name"]] = f109 110 def pipe_file(self, path, value, **kwargs):111 # override upstream, because we know the exact file size in this case112 self.zip.writestr(path, value, **kwargs)113 114 def _open(115 self,116 path,117 mode="rb",118 block_size=None,119 autocommit=True,120 cache_options=None,121 **kwargs,122 ):123 path = self._strip_protocol(path)124 if "r" in mode and self.mode in set("wa"):125 if self.exists(path):126 raise OSError("ZipFS can only be open for reading or writing, not both")127 raise FileNotFoundError(path)128 if "r" in self.mode and "w" in mode:129 raise OSError("ZipFS can only be open for reading or writing, not both")130 out = self.zip.open(path, mode.strip("b"), force_zip64=self.force_zip_64)131 if "r" in mode:132 info = self.info(path)133 out.size = info["size"]134 out.name = info["name"]135 return out136 137 def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):138 if maxdepth is not None and maxdepth < 1:139 raise ValueError("maxdepth must be at least 1")140 141 # Remove the leading slash, as the zip file paths are always142 # given without a leading slash143 path = path.lstrip("/")144 path_parts = list(filter(lambda s: bool(s), path.split("/")))145 146 def _matching_starts(file_path):147 file_parts = filter(lambda s: bool(s), file_path.split("/"))148 return all(a == b for a, b in zip(path_parts, file_parts))149 150 self._get_dirs()151 152 result = {}153 # To match posix find, if an exact file name is given, we should154 # return only that file155 if path in self.dir_cache and self.dir_cache[path]["type"] == "file":156 result[path] = self.dir_cache[path]157 return result if detail else [path]158 159 for file_path, file_info in self.dir_cache.items():160 if not (path == "" or _matching_starts(file_path)):161 continue162 163 if file_info["type"] == "directory":164 if withdirs:165 if file_path not in result:166 result[file_path.strip("/")] = file_info167 continue168 169 if file_path not in result:170 result[file_path] = file_info if detail else None171 172 if maxdepth:173 path_depth = path.count("/")174 result = {175 k: v for k, v in result.items() if k.count("/") - path_depth < maxdepth176 }177 return result if detail else sorted(result)178 