-
-
Notifications
You must be signed in to change notification settings - Fork 304
/
Copy pathstorage.py
2712 lines (2232 loc) · 86.8 KB
/
storage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""This module contains storage classes for use with Zarr arrays and groups.
Note that any object implementing the :class:`MutableMapping` interface from the
:mod:`collections` module in the Python standard library can be used as a Zarr
array store, as long as it accepts string (str) keys and bytes values.
In addition to the :class:`MutableMapping` interface, store classes may also implement
optional methods `listdir` (list members of a "directory") and `rmdir` (remove all
members of a "directory"). These methods should be implemented if the store class is
aware of the hierarchical organisation of resources within the store and can provide
efficient implementations. If these methods are not available, Zarr will fall back to
slower implementations that work via the :class:`MutableMapping` interface. Store
classes may also optionally implement a `rename` method (rename all members under a given
path) and a `getsize` method (return the size in bytes of a given value).
"""
import atexit
import errno
import glob
import multiprocessing
import operator
import os
import re
import shutil
import sys
import tempfile
import warnings
import zipfile
from collections import OrderedDict
from collections.abc import MutableMapping
from os import scandir
from pickle import PicklingError
from threading import Lock, RLock
from typing import Optional, Union, List, Tuple, Dict
import uuid
import time
from numcodecs.compat import (
ensure_bytes,
ensure_text,
ensure_contiguous_ndarray
)
from numcodecs.registry import codec_registry
from zarr.errors import (
MetadataError,
BadCompressorError,
ContainsArrayError,
ContainsGroupError,
FSPathExistNotDir,
ReadOnlyError,
)
from zarr.meta import encode_array_metadata, encode_group_metadata
from zarr.util import (buffer_size, json_loads, nolock, normalize_chunks,
normalize_dtype, normalize_fill_value, normalize_order,
normalize_shape, normalize_storage_path)
__doctest_requires__ = {
('RedisStore', 'RedisStore.*'): ['redis'],
('MongoDBStore', 'MongoDBStore.*'): ['pymongo'],
('ABSStore', 'ABSStore.*'): ['azure.storage.blob'],
('LRUStoreCache', 'LRUStoreCache.*'): ['s3fs'],
}
array_meta_key = '.zarray'
group_meta_key = '.zgroup'
attrs_key = '.zattrs'
try:
# noinspection PyUnresolvedReferences
from zarr.codecs import Blosc
default_compressor = Blosc()
except ImportError: # pragma: no cover
from zarr.codecs import Zlib
default_compressor = Zlib()
Path = Union[str, bytes, None]
def _path_to_prefix(path: Optional[str]) -> str:
# assume path already normalized
if path:
prefix = path + '/'
else:
prefix = ''
return prefix
def contains_array(store: MutableMapping, path: Path = None) -> bool:
"""Return True if the store contains an array at the given logical path."""
path = normalize_storage_path(path)
prefix = _path_to_prefix(path)
key = prefix + array_meta_key
return key in store
def contains_group(store: MutableMapping, path: Path = None) -> bool:
"""Return True if the store contains a group at the given logical path."""
path = normalize_storage_path(path)
prefix = _path_to_prefix(path)
key = prefix + group_meta_key
return key in store
def _rmdir_from_keys(store: MutableMapping, path: Optional[str] = None) -> None:
# assume path already normalized
prefix = _path_to_prefix(path)
for key in list(store.keys()):
if key.startswith(prefix):
del store[key]
def rmdir(store, path: Path = None):
"""Remove all items under the given path. If `store` provides a `rmdir` method,
this will be called, otherwise will fall back to implementation via the
`MutableMapping` interface."""
path = normalize_storage_path(path)
if hasattr(store, 'rmdir'):
# pass through
store.rmdir(path)
else:
# slow version, delete one key at a time
_rmdir_from_keys(store, path)
def _rename_from_keys(store: MutableMapping, src_path: str, dst_path: str) -> None:
# assume path already normalized
src_prefix = _path_to_prefix(src_path)
dst_prefix = _path_to_prefix(dst_path)
for key in list(store.keys()):
if key.startswith(src_prefix):
new_key = dst_prefix + key.lstrip(src_prefix)
store[new_key] = store.pop(key)
def rename(store, src_path: Path, dst_path: Path):
"""Rename all items under the given path. If `store` provides a `rename` method,
this will be called, otherwise will fall back to implementation via the
`MutableMapping` interface."""
src_path = normalize_storage_path(src_path)
dst_path = normalize_storage_path(dst_path)
if hasattr(store, 'rename'):
# pass through
store.rename(src_path, dst_path)
else:
# slow version, delete one key at a time
_rename_from_keys(store, src_path, dst_path)
def _listdir_from_keys(store: MutableMapping, path: Optional[str] = None) -> List[str]:
# assume path already normalized
prefix = _path_to_prefix(path)
children = set()
for key in list(store.keys()):
if key.startswith(prefix) and len(key) > len(prefix):
suffix = key[len(prefix):]
child = suffix.split('/')[0]
children.add(child)
return sorted(children)
def listdir(store, path: Path = None):
"""Obtain a directory listing for the given path. If `store` provides a `listdir`
method, this will be called, otherwise will fall back to implementation via the
`MutableMapping` interface."""
path = normalize_storage_path(path)
if hasattr(store, 'listdir'):
# pass through
return store.listdir(path)
else:
# slow version, iterate through all keys
return _listdir_from_keys(store, path)
def getsize(store, path: Path = None) -> int:
"""Compute size of stored items for a given path. If `store` provides a `getsize`
method, this will be called, otherwise will return -1."""
path = normalize_storage_path(path)
if hasattr(store, 'getsize'):
# pass through
return store.getsize(path)
elif isinstance(store, dict):
# compute from size of values
if path in store:
v = store[path]
size = buffer_size(v)
else:
members = listdir(store, path)
prefix = _path_to_prefix(path)
size = 0
for k in members:
try:
v = store[prefix + k]
except KeyError:
pass
else:
try:
size += buffer_size(v)
except TypeError:
return -1
return size
else:
return -1
def _require_parent_group(
path: Optional[str],
store: MutableMapping,
chunk_store: Optional[MutableMapping],
overwrite: bool,
):
# assume path is normalized
if path:
segments = path.split('/')
for i in range(len(segments)):
p = '/'.join(segments[:i])
if contains_array(store, p):
_init_group_metadata(store, path=p, chunk_store=chunk_store,
overwrite=overwrite)
elif not contains_group(store, p):
_init_group_metadata(store, path=p, chunk_store=chunk_store)
def init_array(
store: MutableMapping,
shape: Tuple[int, ...],
chunks: Union[bool, int, Tuple[int, ...]] = True,
dtype=None,
compressor="default",
fill_value=None,
order: str = "C",
overwrite: bool = False,
path: Path = None,
chunk_store: MutableMapping = None,
filters=None,
object_codec=None,
):
"""Initialize an array store with the given configuration. Note that this is a low-level
function and there should be no need to call this directly from user code.
Parameters
----------
store : MutableMapping
A mapping that supports string keys and bytes-like values.
shape : int or tuple of ints
Array shape.
chunks : bool, int or tuple of ints, optional
Chunk shape. If True, will be guessed from `shape` and `dtype`. If
False, will be set to `shape`, i.e., single chunk for the whole array.
dtype : string or dtype, optional
NumPy dtype.
compressor : Codec, optional
Primary compressor.
fill_value : object
Default value to use for uninitialized portions of the array.
order : {'C', 'F'}, optional
Memory layout to be used within each chunk.
overwrite : bool, optional
If True, erase all data in `store` prior to initialisation.
path : string, bytes, optional
Path under which array is stored.
chunk_store : MutableMapping, optional
Separate storage for chunks. If not provided, `store` will be used
for storage of both chunks and metadata.
filters : sequence, optional
Sequence of filters to use to encode chunk data prior to compression.
object_codec : Codec, optional
A codec to encode object arrays, only needed if dtype=object.
Examples
--------
Initialize an array store::
>>> from zarr.storage import init_array
>>> store = dict()
>>> init_array(store, shape=(10000, 10000), chunks=(1000, 1000))
>>> sorted(store.keys())
['.zarray']
Array metadata is stored as JSON::
>>> print(store['.zarray'].decode())
{
"chunks": [
1000,
1000
],
"compressor": {
"blocksize": 0,
"clevel": 5,
"cname": "lz4",
"id": "blosc",
"shuffle": 1
},
"dtype": "<f8",
"fill_value": null,
"filters": null,
"order": "C",
"shape": [
10000,
10000
],
"zarr_format": 2
}
Initialize an array using a storage path::
>>> store = dict()
>>> init_array(store, shape=100000000, chunks=1000000, dtype='i1', path='foo')
>>> sorted(store.keys())
['.zgroup', 'foo/.zarray']
>>> print(store['foo/.zarray'].decode())
{
"chunks": [
1000000
],
"compressor": {
"blocksize": 0,
"clevel": 5,
"cname": "lz4",
"id": "blosc",
"shuffle": 1
},
"dtype": "|i1",
"fill_value": null,
"filters": null,
"order": "C",
"shape": [
100000000
],
"zarr_format": 2
}
Notes
-----
The initialisation process involves normalising all array metadata, encoding
as JSON and storing under the '.zarray' key.
"""
# normalize path
path = normalize_storage_path(path)
# ensure parent group initialized
_require_parent_group(path, store=store, chunk_store=chunk_store, overwrite=overwrite)
_init_array_metadata(store, shape=shape, chunks=chunks, dtype=dtype,
compressor=compressor, fill_value=fill_value,
order=order, overwrite=overwrite, path=path,
chunk_store=chunk_store, filters=filters,
object_codec=object_codec)
def _init_array_metadata(
store,
shape,
chunks=None,
dtype=None,
compressor="default",
fill_value=None,
order="C",
overwrite=False,
path: Optional[str] = None,
chunk_store=None,
filters=None,
object_codec=None,
):
# guard conditions
if overwrite:
# attempt to delete any pre-existing items in store
rmdir(store, path)
if chunk_store is not None:
rmdir(chunk_store, path)
elif contains_array(store, path):
raise ContainsArrayError(path)
elif contains_group(store, path):
raise ContainsGroupError(path)
# normalize metadata
dtype, object_codec = normalize_dtype(dtype, object_codec)
shape = normalize_shape(shape) + dtype.shape
dtype = dtype.base
chunks = normalize_chunks(chunks, shape, dtype.itemsize)
order = normalize_order(order)
fill_value = normalize_fill_value(fill_value, dtype)
# compressor prep
if shape == ():
# no point in compressing a 0-dimensional array, only a single value
compressor = None
elif compressor == 'none':
# compatibility
compressor = None
elif compressor == 'default':
compressor = default_compressor
# obtain compressor config
compressor_config = None
if compressor:
try:
compressor_config = compressor.get_config()
except AttributeError as e:
raise BadCompressorError(compressor) from e
# obtain filters config
if filters:
filters_config = [f.get_config() for f in filters]
else:
filters_config = []
# deal with object encoding
if dtype == object:
if object_codec is None:
if not filters:
# there are no filters so we can be sure there is no object codec
raise ValueError('missing object_codec for object array')
else:
# one of the filters may be an object codec, issue a warning rather
# than raise an error to maintain backwards-compatibility
warnings.warn('missing object_codec for object array; this will raise a '
'ValueError in version 3.0', FutureWarning)
else:
filters_config.insert(0, object_codec.get_config())
elif object_codec is not None:
warnings.warn('an object_codec is only needed for object arrays')
# use null to indicate no filters
if not filters_config:
filters_config = None # type: ignore
# initialize metadata
meta = dict(shape=shape, chunks=chunks, dtype=dtype,
compressor=compressor_config, fill_value=fill_value,
order=order, filters=filters_config)
key = _path_to_prefix(path) + array_meta_key
store[key] = encode_array_metadata(meta)
# backwards compatibility
init_store = init_array
def init_group(
store: MutableMapping,
overwrite: bool = False,
path: Path = None,
chunk_store: MutableMapping = None,
):
"""Initialize a group store. Note that this is a low-level function and there should be no
need to call this directly from user code.
Parameters
----------
store : MutableMapping
A mapping that supports string keys and byte sequence values.
overwrite : bool, optional
If True, erase all data in `store` prior to initialisation.
path : string, optional
Path under which array is stored.
chunk_store : MutableMapping, optional
Separate storage for chunks. If not provided, `store` will be used
for storage of both chunks and metadata.
"""
# normalize path
path = normalize_storage_path(path)
# ensure parent group initialized
_require_parent_group(path, store=store, chunk_store=chunk_store,
overwrite=overwrite)
# initialise metadata
_init_group_metadata(store=store, overwrite=overwrite, path=path,
chunk_store=chunk_store)
def _init_group_metadata(
store: MutableMapping,
overwrite: Optional[bool] = False,
path: Optional[str] = None,
chunk_store: MutableMapping = None,
):
# guard conditions
if overwrite:
# attempt to delete any pre-existing items in store
rmdir(store, path)
if chunk_store is not None:
rmdir(chunk_store, path)
elif contains_array(store, path):
raise ContainsArrayError(path)
elif contains_group(store, path):
raise ContainsGroupError(path)
# initialize metadata
# N.B., currently no metadata properties are needed, however there may
# be in future
meta = dict() # type: ignore
key = _path_to_prefix(path) + group_meta_key
store[key] = encode_group_metadata(meta)
def _dict_store_keys(d: Dict, prefix="", cls=dict):
for k in d.keys():
v = d[k]
if isinstance(v, cls):
for sk in _dict_store_keys(v, prefix + k + '/', cls):
yield sk
else:
yield prefix + k
class MemoryStore(MutableMapping):
"""Store class that uses a hierarchy of :class:`dict` objects, thus all data
will be held in main memory.
Examples
--------
This is the default class used when creating a group. E.g.::
>>> import zarr
>>> g = zarr.group()
>>> type(g.store)
<class 'zarr.storage.MemoryStore'>
Note that the default class when creating an array is the built-in
:class:`dict` class, i.e.::
>>> z = zarr.zeros(100)
>>> type(z.store)
<class 'dict'>
Notes
-----
Safe to write in multiple threads.
"""
def __init__(self, root=None, cls=dict):
if root is None:
self.root = cls()
else:
self.root = root
self.cls = cls
self.write_mutex = Lock()
def __getstate__(self):
return self.root, self.cls
def __setstate__(self, state):
root, cls = state
self.__init__(root=root, cls=cls)
def _get_parent(self, item: str):
parent = self.root
# split the item
segments = item.split('/')
# find the parent container
for k in segments[:-1]:
parent = parent[k]
if not isinstance(parent, self.cls):
raise KeyError(item)
return parent, segments[-1]
def _require_parent(self, item):
parent = self.root
# split the item
segments = item.split('/')
# require the parent container
for k in segments[:-1]:
try:
parent = parent[k]
except KeyError:
parent[k] = self.cls()
parent = parent[k]
else:
if not isinstance(parent, self.cls):
raise KeyError(item)
return parent, segments[-1]
def __getitem__(self, item: str):
parent, key = self._get_parent(item)
try:
value = parent[key]
except KeyError:
raise KeyError(item)
else:
if isinstance(value, self.cls):
raise KeyError(item)
else:
return value
def __setitem__(self, item: str, value):
with self.write_mutex:
parent, key = self._require_parent(item)
value = ensure_bytes(value)
parent[key] = value
def __delitem__(self, item: str):
with self.write_mutex:
parent, key = self._get_parent(item)
try:
del parent[key]
except KeyError:
raise KeyError(item)
def __contains__(self, item: str): # type: ignore[override]
try:
parent, key = self._get_parent(item)
value = parent[key]
except KeyError:
return False
else:
return not isinstance(value, self.cls)
def __eq__(self, other):
return (
isinstance(other, MemoryStore) and
self.root == other.root and
self.cls == other.cls
)
def keys(self):
for k in _dict_store_keys(self.root, cls=self.cls):
yield k
def __iter__(self):
return self.keys()
def __len__(self) -> int:
return sum(1 for _ in self.keys())
def listdir(self, path: Path = None) -> List[str]:
path = normalize_storage_path(path)
if path:
try:
parent, key = self._get_parent(path)
value = parent[key]
except KeyError:
return []
else:
value = self.root
if isinstance(value, self.cls):
return sorted(value.keys())
else:
return []
def rename(self, src_path: Path, dst_path: Path):
src_path = normalize_storage_path(src_path)
dst_path = normalize_storage_path(dst_path)
src_parent, src_key = self._get_parent(src_path)
dst_parent, dst_key = self._require_parent(dst_path)
dst_parent[dst_key] = src_parent.pop(src_key)
def rmdir(self, path: Path = None):
path = normalize_storage_path(path)
if path:
try:
parent, key = self._get_parent(path)
value = parent[key]
except KeyError:
return
else:
if isinstance(value, self.cls):
del parent[key]
else:
# clear out root
self.root = self.cls()
def getsize(self, path: Path = None):
path = normalize_storage_path(path)
# obtain value to return size of
value = None
if path:
try:
parent, key = self._get_parent(path)
value = parent[key]
except KeyError:
pass
else:
value = self.root
# obtain size of value
if value is None:
return 0
elif isinstance(value, self.cls):
# total size for directory
size = 0
for v in value.values():
if not isinstance(v, self.cls):
size += buffer_size(v)
return size
else:
return buffer_size(value)
def clear(self):
with self.write_mutex:
self.root.clear()
class DictStore(MemoryStore):
def __init__(self, *args, **kwargs):
warnings.warn("DictStore has been renamed to MemoryStore in 2.4.0 and "
"will be removed in the future. Please use MemoryStore.",
DeprecationWarning,
stacklevel=2)
super().__init__(*args, **kwargs)
class DirectoryStore(MutableMapping):
"""Storage class using directories and files on a standard file system.
Parameters
----------
path : string
Location of directory to use as the root of the storage hierarchy.
normalize_keys : bool, optional
If True, all store keys will be normalized to use lower case characters
(e.g. 'foo' and 'FOO' will be treated as equivalent). This can be
useful to avoid potential discrepancies between case-senstive and
case-insensitive file system. Default value is False.
Examples
--------
Store a single array::
>>> import zarr
>>> store = zarr.DirectoryStore('data/array.zarr')
>>> z = zarr.zeros((10, 10), chunks=(5, 5), store=store, overwrite=True)
>>> z[...] = 42
Each chunk of the array is stored as a separate file on the file system,
i.e.::
>>> import os
>>> sorted(os.listdir('data/array.zarr'))
['.zarray', '0.0', '0.1', '1.0', '1.1']
Store a group::
>>> store = zarr.DirectoryStore('data/group.zarr')
>>> root = zarr.group(store=store, overwrite=True)
>>> foo = root.create_group('foo')
>>> bar = foo.zeros('bar', shape=(10, 10), chunks=(5, 5))
>>> bar[...] = 42
When storing a group, levels in the group hierarchy will correspond to
directories on the file system, i.e.::
>>> sorted(os.listdir('data/group.zarr'))
['.zgroup', 'foo']
>>> sorted(os.listdir('data/group.zarr/foo'))
['.zgroup', 'bar']
>>> sorted(os.listdir('data/group.zarr/foo/bar'))
['.zarray', '0.0', '0.1', '1.0', '1.1']
Notes
-----
Atomic writes are used, which means that data are first written to a
temporary file, then moved into place when the write is successfully
completed. Files are only held open while they are being read or written and are
closed immediately afterwards, so there is no need to manually close any files.
Safe to write in multiple threads or processes.
"""
def __init__(self, path, normalize_keys=False):
# guard conditions
path = os.path.abspath(path)
if os.path.exists(path) and not os.path.isdir(path):
raise FSPathExistNotDir(path)
self.path = path
self.normalize_keys = normalize_keys
def _normalize_key(self, key):
return key.lower() if self.normalize_keys else key
def _fromfile(self, fn):
""" Read data from a file
Parameters
----------
fn : str
Filepath to open and read from.
Notes
-----
Subclasses should overload this method to specify any custom
file reading logic.
"""
with open(fn, 'rb') as f:
return f.read()
def _tofile(self, a, fn):
""" Write data to a file
Parameters
----------
a : array-like
Data to write into the file.
fn : str
Filepath to open and write to.
Notes
-----
Subclasses should overload this method to specify any custom
file writing logic.
"""
with open(fn, mode='wb') as f:
f.write(a)
def __getitem__(self, key):
key = self._normalize_key(key)
filepath = os.path.join(self.path, key)
if os.path.isfile(filepath):
return self._fromfile(filepath)
else:
raise KeyError(key)
def __setitem__(self, key, value):
key = self._normalize_key(key)
# coerce to flat, contiguous array (ideally without copying)
value = ensure_contiguous_ndarray(value)
# destination path for key
file_path = os.path.join(self.path, key)
# ensure there is no directory in the way
if os.path.isdir(file_path):
shutil.rmtree(file_path)
# ensure containing directory exists
dir_path, file_name = os.path.split(file_path)
if os.path.isfile(dir_path):
raise KeyError(key)
if not os.path.exists(dir_path):
try:
os.makedirs(dir_path)
except OSError as e:
if e.errno != errno.EEXIST:
raise KeyError(key)
# write to temporary file
# note we're not using tempfile.NamedTemporaryFile to avoid restrictive file permissions
temp_name = file_name + '.' + uuid.uuid4().hex + '.partial'
temp_path = os.path.join(dir_path, temp_name)
try:
self._tofile(value, temp_path)
# move temporary file into place
os.replace(temp_path, file_path)
finally:
# clean up if temp file still exists for whatever reason
if os.path.exists(temp_path): # pragma: no cover
os.remove(temp_path)
def __delitem__(self, key):
key = self._normalize_key(key)
path = os.path.join(self.path, key)
if os.path.isfile(path):
os.remove(path)
elif os.path.isdir(path):
# include support for deleting directories, even though strictly
# speaking these do not exist as keys in the store
shutil.rmtree(path)
else:
raise KeyError(key)
def __contains__(self, key):
key = self._normalize_key(key)
file_path = os.path.join(self.path, key)
return os.path.isfile(file_path)
def __eq__(self, other):
return (
isinstance(other, DirectoryStore) and
self.path == other.path
)
def keys(self):
if os.path.exists(self.path):
yield from self._keys_fast(self.path)
@staticmethod
def _keys_fast(path, walker=os.walk):
"""
Faster logic on platform where the separator is `/` and using
`os.walk()` to decrease the number of stats.call.
"""
it = iter(walker(path))
d0, dirnames, filenames = next(it)
if d0.endswith('/'):
root_len = len(d0)
else:
root_len = len(d0)+1
for f in filenames:
yield f
for dirpath, _, filenames in it:
for f in filenames:
yield dirpath[root_len:].replace('\\', '/')+'/'+f
def __iter__(self):
return self.keys()
def __len__(self):
return sum(1 for _ in self.keys())
def dir_path(self, path=None):
store_path = normalize_storage_path(path)
dir_path = self.path
if store_path:
dir_path = os.path.join(dir_path, store_path)
return dir_path
def listdir(self, path=None):
dir_path = self.dir_path(path)
if os.path.isdir(dir_path):
return sorted(os.listdir(dir_path))
else:
return []
def rename(self, src_path, dst_path):
store_src_path = normalize_storage_path(src_path)
store_dst_path = normalize_storage_path(dst_path)
dir_path = self.path
src_path = os.path.join(dir_path, store_src_path)
dst_path = os.path.join(dir_path, store_dst_path)
os.renames(src_path, dst_path)
def rmdir(self, path=None):
store_path = normalize_storage_path(path)
dir_path = self.path
if store_path:
dir_path = os.path.join(dir_path, store_path)
if os.path.isdir(dir_path):
shutil.rmtree(dir_path)
def getsize(self, path=None):
store_path = normalize_storage_path(path)
fs_path = self.path
if store_path:
fs_path = os.path.join(fs_path, store_path)
if os.path.isfile(fs_path):
return os.path.getsize(fs_path)
elif os.path.isdir(fs_path):
size = 0
for child in scandir(fs_path):
if child.is_file():
size += child.stat().st_size
return size
else:
return 0
def clear(self):
shutil.rmtree(self.path)
def atexit_rmtree(path,
isdir=os.path.isdir,
rmtree=shutil.rmtree): # pragma: no cover
"""Ensure directory removal at interpreter exit."""
if isdir(path):
rmtree(path)
# noinspection PyShadowingNames
def atexit_rmglob(path,
glob=glob.glob,
isdir=os.path.isdir,
isfile=os.path.isfile,
remove=os.remove,
rmtree=shutil.rmtree): # pragma: no cover
"""Ensure removal of multiple files at interpreter exit."""
for p in glob(path):
if isfile(p):
remove(p)
elif isdir(p):
rmtree(p)
class FSStore(MutableMapping):