|
| 1 | +from collections.abc import MutableMapping |
| 2 | +from typing import Any, List, Optional, Union |
| 3 | + |
| 4 | +from zarr.util import normalize_storage_path |
| 5 | + |
| 6 | +# v2 store keys |
| 7 | +array_meta_key = '.zarray' |
| 8 | +group_meta_key = '.zgroup' |
| 9 | +attrs_key = '.zattrs' |
| 10 | + |
| 11 | + |
| 12 | +class BaseStore(MutableMapping): |
| 13 | + """Abstract base class for store implementations. |
| 14 | +
|
| 15 | + This is a thin wrapper over MutableMapping that provides methods to check |
| 16 | + whether a store is readable, writeable, eraseable and or listable. |
| 17 | +
|
| 18 | + Stores cannot be mutable mapping as they do have a couple of other |
| 19 | + requirements that would break Liskov substitution principle (stores only |
| 20 | + allow strings as keys, mutable mapping are more generic). |
| 21 | +
|
| 22 | + Having no-op base method also helps simplifying store usage and do not need |
| 23 | + to check the presence of attributes and methods, like `close()`. |
| 24 | +
|
| 25 | + Stores can be used as context manager to make sure they close on exit. |
| 26 | +
|
| 27 | + .. added: 2.11.0 |
| 28 | +
|
| 29 | + """ |
| 30 | + |
| 31 | + _readable = True |
| 32 | + _writeable = True |
| 33 | + _erasable = True |
| 34 | + _listable = True |
| 35 | + |
| 36 | + def is_readable(self): |
| 37 | + return self._readable |
| 38 | + |
| 39 | + def is_writeable(self): |
| 40 | + return self._writeable |
| 41 | + |
| 42 | + def is_listable(self): |
| 43 | + return self._listable |
| 44 | + |
| 45 | + def is_erasable(self): |
| 46 | + return self._erasable |
| 47 | + |
| 48 | + def __enter__(self): |
| 49 | + if not hasattr(self, "_open_count"): |
| 50 | + self._open_count = 0 |
| 51 | + self._open_count += 1 |
| 52 | + return self |
| 53 | + |
| 54 | + def __exit__(self, exc_type, exc_value, traceback): |
| 55 | + self._open_count -= 1 |
| 56 | + if self._open_count == 0: |
| 57 | + self.close() |
| 58 | + |
| 59 | + def close(self) -> None: |
| 60 | + """Do nothing by default""" |
| 61 | + pass |
| 62 | + |
| 63 | + def rename(self, src_path: str, dst_path: str) -> None: |
| 64 | + if not self.is_erasable(): |
| 65 | + raise NotImplementedError( |
| 66 | + f'{type(self)} is not erasable, cannot call "rename"' |
| 67 | + ) # pragma: no cover |
| 68 | + _rename_from_keys(self, src_path, dst_path) |
| 69 | + |
| 70 | + @staticmethod |
| 71 | + def _ensure_store(store: Any): |
| 72 | + """ |
| 73 | + We want to make sure internally that zarr stores are always a class |
| 74 | + with a specific interface derived from ``BaseStore``, which is slightly |
| 75 | + different than ``MutableMapping``. |
| 76 | +
|
| 77 | + We'll do this conversion in a few places automatically |
| 78 | + """ |
| 79 | + from zarr.storage import KVStore # avoid circular import |
| 80 | + |
| 81 | + if store is None: |
| 82 | + return None |
| 83 | + elif isinstance(store, BaseStore): |
| 84 | + return store |
| 85 | + elif isinstance(store, MutableMapping): |
| 86 | + return KVStore(store) |
| 87 | + else: |
| 88 | + for attr in [ |
| 89 | + "keys", |
| 90 | + "values", |
| 91 | + "get", |
| 92 | + "__setitem__", |
| 93 | + "__getitem__", |
| 94 | + "__delitem__", |
| 95 | + "__contains__", |
| 96 | + ]: |
| 97 | + if not hasattr(store, attr): |
| 98 | + break |
| 99 | + else: |
| 100 | + return KVStore(store) |
| 101 | + |
| 102 | + raise ValueError( |
| 103 | + "Starting with Zarr 2.11.0, stores must be subclasses of " |
| 104 | + "BaseStore, if your store exposes the MutableMapping interface " |
| 105 | + f"wrap it in Zarr.storage.KVStore. Got {store}" |
| 106 | + ) |
| 107 | + |
| 108 | + |
| 109 | +class Store(BaseStore): |
| 110 | + """Abstract store class used by implementations following the Zarr v2 spec. |
| 111 | +
|
| 112 | + Adds public `listdir`, `rename`, and `rmdir` methods on top of BaseStore. |
| 113 | +
|
| 114 | + .. added: 2.11.0 |
| 115 | +
|
| 116 | + """ |
| 117 | + def listdir(self, path: str = "") -> List[str]: |
| 118 | + path = normalize_storage_path(path) |
| 119 | + return _listdir_from_keys(self, path) |
| 120 | + |
| 121 | + def rmdir(self, path: str = "") -> None: |
| 122 | + if not self.is_erasable(): |
| 123 | + raise NotImplementedError( |
| 124 | + f'{type(self)} is not erasable, cannot call "rmdir"' |
| 125 | + ) # pragma: no cover |
| 126 | + path = normalize_storage_path(path) |
| 127 | + _rmdir_from_keys(self, path) |
| 128 | + |
| 129 | + |
| 130 | +def _path_to_prefix(path: Optional[str]) -> str: |
| 131 | + # assume path already normalized |
| 132 | + if path: |
| 133 | + prefix = path + '/' |
| 134 | + else: |
| 135 | + prefix = '' |
| 136 | + return prefix |
| 137 | + |
| 138 | + |
| 139 | +def _rename_from_keys(store: BaseStore, src_path: str, dst_path: str) -> None: |
| 140 | + # assume path already normalized |
| 141 | + src_prefix = _path_to_prefix(src_path) |
| 142 | + dst_prefix = _path_to_prefix(dst_path) |
| 143 | + for key in list(store.keys()): |
| 144 | + if key.startswith(src_prefix): |
| 145 | + new_key = dst_prefix + key.lstrip(src_prefix) |
| 146 | + store[new_key] = store.pop(key) |
| 147 | + |
| 148 | + |
| 149 | +def _rmdir_from_keys(store: Union[BaseStore, MutableMapping], path: Optional[str] = None) -> None: |
| 150 | + # assume path already normalized |
| 151 | + prefix = _path_to_prefix(path) |
| 152 | + for key in list(store.keys()): |
| 153 | + if key.startswith(prefix): |
| 154 | + del store[key] |
| 155 | + |
| 156 | + |
| 157 | +def _listdir_from_keys(store: BaseStore, path: Optional[str] = None) -> List[str]: |
| 158 | + # assume path already normalized |
| 159 | + prefix = _path_to_prefix(path) |
| 160 | + children = set() |
| 161 | + for key in list(store.keys()): |
| 162 | + if key.startswith(prefix) and len(key) > len(prefix): |
| 163 | + suffix = key[len(prefix):] |
| 164 | + child = suffix.split('/')[0] |
| 165 | + children.add(child) |
| 166 | + return sorted(children) |
0 commit comments