TheHassanSaud commited on
Commit
35ea8a0
·
1 Parent(s): bb6f167

Upload folder using huggingface_hub (part 4)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +48 -0
  2. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/METADATA +257 -0
  3. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/RECORD +61 -0
  4. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/WHEEL +4 -0
  5. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/licenses/LICENSE +29 -0
  6. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/__init__.py +0 -0
  7. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/arrow.py +322 -0
  8. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/asyn_wrapper.py +124 -0
  9. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/cache_mapper.py +75 -0
  10. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/cache_metadata.py +217 -0
  11. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/cached.py +1040 -0
  12. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/chained.py +23 -0
  13. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/dask.py +152 -0
  14. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/data.py +71 -0
  15. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/dbfs.py +497 -0
  16. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/dirfs.py +426 -0
  17. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/ftp.py +442 -0
  18. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/gist.py +241 -0
  19. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/git.py +114 -0
  20. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/github.py +333 -0
  21. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/http.py +902 -0
  22. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/http_sync.py +937 -0
  23. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/jupyter.py +129 -0
  24. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/libarchive.py +213 -0
  25. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/local.py +517 -0
  26. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/memory.py +393 -0
  27. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/reference.py +1339 -0
  28. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/sftp.py +187 -0
  29. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/smb.py +416 -0
  30. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/tar.py +139 -0
  31. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/webhdfs.py +503 -0
  32. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/zip.py +183 -0
  33. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/json.py +112 -0
  34. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/mapping.py +251 -0
  35. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/parquet.py +572 -0
  36. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/registry.py +337 -0
  37. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/spec.py +2342 -0
  38. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/__init__.py +290 -0
  39. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/common.py +175 -0
  40. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/copy.py +557 -0
  41. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/get.py +587 -0
  42. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/mv.py +57 -0
  43. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/open.py +11 -0
  44. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/pipe.py +11 -0
  45. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/put.py +591 -0
  46. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/transaction.py +90 -0
  47. pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/utils.py +757 -0
  48. pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_C.cpython-311-x86_64-linux-gnu.so +3 -0
  49. pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/__init__.py +39 -0
  50. pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/__pycache__/__init__.cpython-311.pyc +0 -0
.gitattributes CHANGED
@@ -528,3 +528,51 @@ pace_revision_1/.venv-pace/lib/python3.11/site-packages/fontTools/misc/bezierToo
528
  pace_revision_1/.venv-pace/lib/python3.11/site-packages/fontTools/pens/momentsPen.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
529
  pace_revision_1/.venv-pace/lib/python3.11/site-packages/fontTools/qu2cu/qu2cu.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
530
  pace_revision_1/.venv-pace/lib/python3.11/site-packages/fontTools/varLib/iup.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
528
  pace_revision_1/.venv-pace/lib/python3.11/site-packages/fontTools/pens/momentsPen.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
529
  pace_revision_1/.venv-pace/lib/python3.11/site-packages/fontTools/qu2cu/qu2cu.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
530
  pace_revision_1/.venv-pace/lib/python3.11/site-packages/fontTools/varLib/iup.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
531
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_C.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
532
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_conv.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
533
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_errors.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
534
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_npystrings.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
535
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_objects.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
536
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_proxy.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
537
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_selector.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
538
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/defs.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
539
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
540
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5a.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
541
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5ac.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
542
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5d.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
543
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5ds.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
544
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5f.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
545
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5fd.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
546
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5g.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
547
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5i.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
548
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5l.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
549
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5o.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
550
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5p.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
551
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5pl.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
552
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5r.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
553
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5s.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
554
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5t.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
555
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5z.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
556
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/utils.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
557
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libaec-187855bc.so.0.1.3 filter=lfs diff=lfs merge=lfs -text
558
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libhdf5-7d060e2f.so.310.5.1 filter=lfs diff=lfs merge=lfs -text
559
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libhdf5_hl-0ce065ed.so.310.0.6 filter=lfs diff=lfs merge=lfs -text
560
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/kiwisolver/_cext.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
561
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/_cm_listed.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
562
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/_mathtext.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
563
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/axis.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
564
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/backend_bases.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
565
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/cbook.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
566
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/collections.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
567
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/colors.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
568
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/figure.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
569
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/patches.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
570
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/pyplot.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
571
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/ticker.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
572
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/transforms.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
573
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/widgets.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
574
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/_c_internal_utils.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
575
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/_image.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
576
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/_path.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
577
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/_qhull.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
578
+ pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/_tri.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/METADATA ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: fsspec
3
+ Version: 2026.7.0
4
+ Summary: File-system specification
5
+ Project-URL: Changelog, https://filesystem-spec.readthedocs.io/en/latest/changelog.html
6
+ Project-URL: Documentation, https://filesystem-spec.readthedocs.io/en/latest/
7
+ Project-URL: Homepage, https://github.com/fsspec/filesystem_spec
8
+ Maintainer-email: Martin Durant <mdurant@anaconda.com>
9
+ License-Expression: BSD-3-Clause
10
+ License-File: LICENSE
11
+ Keywords: file
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Requires-Python: >=3.10
21
+ Provides-Extra: abfs
22
+ Requires-Dist: adlfs; extra == 'abfs'
23
+ Provides-Extra: adl
24
+ Requires-Dist: adlfs; extra == 'adl'
25
+ Provides-Extra: arrow
26
+ Requires-Dist: pyarrow>=1; extra == 'arrow'
27
+ Provides-Extra: dask
28
+ Requires-Dist: dask; extra == 'dask'
29
+ Requires-Dist: distributed; extra == 'dask'
30
+ Provides-Extra: dev
31
+ Requires-Dist: pre-commit; extra == 'dev'
32
+ Requires-Dist: ruff>=0.5; extra == 'dev'
33
+ Provides-Extra: doc
34
+ Requires-Dist: numpydoc; extra == 'doc'
35
+ Requires-Dist: sphinx; extra == 'doc'
36
+ Requires-Dist: sphinx-design; extra == 'doc'
37
+ Requires-Dist: sphinx-rtd-theme; extra == 'doc'
38
+ Requires-Dist: yarl; extra == 'doc'
39
+ Provides-Extra: dropbox
40
+ Requires-Dist: dropbox; extra == 'dropbox'
41
+ Requires-Dist: dropboxdrivefs; extra == 'dropbox'
42
+ Requires-Dist: requests; extra == 'dropbox'
43
+ Provides-Extra: entrypoints
44
+ Provides-Extra: full
45
+ Requires-Dist: adlfs; extra == 'full'
46
+ Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'full'
47
+ Requires-Dist: dask; extra == 'full'
48
+ Requires-Dist: distributed; extra == 'full'
49
+ Requires-Dist: dropbox; extra == 'full'
50
+ Requires-Dist: dropboxdrivefs; extra == 'full'
51
+ Requires-Dist: fusepy; extra == 'full'
52
+ Requires-Dist: gcsfs>=2026.4.0; extra == 'full'
53
+ Requires-Dist: libarchive-c; extra == 'full'
54
+ Requires-Dist: ocifs; extra == 'full'
55
+ Requires-Dist: panel; extra == 'full'
56
+ Requires-Dist: paramiko; extra == 'full'
57
+ Requires-Dist: pyarrow>=1; extra == 'full'
58
+ Requires-Dist: pygit2; extra == 'full'
59
+ Requires-Dist: requests; extra == 'full'
60
+ Requires-Dist: s3fs>=2026.6.0; extra == 'full'
61
+ Requires-Dist: smbprotocol; extra == 'full'
62
+ Requires-Dist: tqdm; extra == 'full'
63
+ Provides-Extra: fuse
64
+ Requires-Dist: fusepy; extra == 'fuse'
65
+ Provides-Extra: gcs
66
+ Requires-Dist: gcsfs>=2026.4.0; extra == 'gcs'
67
+ Provides-Extra: git
68
+ Requires-Dist: pygit2; extra == 'git'
69
+ Provides-Extra: github
70
+ Requires-Dist: requests; extra == 'github'
71
+ Provides-Extra: gs
72
+ Requires-Dist: gcsfs>=2026.4.0; extra == 'gs'
73
+ Provides-Extra: gui
74
+ Requires-Dist: panel; extra == 'gui'
75
+ Provides-Extra: hdfs
76
+ Requires-Dist: pyarrow>=1; extra == 'hdfs'
77
+ Provides-Extra: http
78
+ Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'http'
79
+ Provides-Extra: libarchive
80
+ Requires-Dist: libarchive-c; extra == 'libarchive'
81
+ Provides-Extra: oci
82
+ Requires-Dist: ocifs; extra == 'oci'
83
+ Provides-Extra: s3
84
+ Requires-Dist: s3fs>=2026.6.0; extra == 's3'
85
+ Provides-Extra: sftp
86
+ Requires-Dist: paramiko; extra == 'sftp'
87
+ Provides-Extra: smb
88
+ Requires-Dist: smbprotocol; extra == 'smb'
89
+ Provides-Extra: ssh
90
+ Requires-Dist: paramiko; extra == 'ssh'
91
+ Provides-Extra: test
92
+ Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test'
93
+ Requires-Dist: numpy; extra == 'test'
94
+ Requires-Dist: pytest; extra == 'test'
95
+ Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test'
96
+ Requires-Dist: pytest-benchmark; extra == 'test'
97
+ Requires-Dist: pytest-cov; extra == 'test'
98
+ Requires-Dist: pytest-mock; extra == 'test'
99
+ Requires-Dist: pytest-recording; extra == 'test'
100
+ Requires-Dist: pytest-rerunfailures; extra == 'test'
101
+ Requires-Dist: requests; extra == 'test'
102
+ Provides-Extra: test-downstream
103
+ Requires-Dist: aiobotocore<3.0.0,>=2.5.4; extra == 'test-downstream'
104
+ Requires-Dist: dask[dataframe,test]; extra == 'test-downstream'
105
+ Requires-Dist: moto[server]<5,>4; extra == 'test-downstream'
106
+ Requires-Dist: pytest-timeout; extra == 'test-downstream'
107
+ Requires-Dist: xarray; extra == 'test-downstream'
108
+ Provides-Extra: test-full
109
+ Requires-Dist: adlfs; extra == 'test-full'
110
+ Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test-full'
111
+ Requires-Dist: backports-zstd; (python_version < '3.14') and extra == 'test-full'
112
+ Requires-Dist: cloudpickle; extra == 'test-full'
113
+ Requires-Dist: dask; extra == 'test-full'
114
+ Requires-Dist: distributed; extra == 'test-full'
115
+ Requires-Dist: dropbox; extra == 'test-full'
116
+ Requires-Dist: dropboxdrivefs; extra == 'test-full'
117
+ Requires-Dist: fastparquet; extra == 'test-full'
118
+ Requires-Dist: fusepy; extra == 'test-full'
119
+ Requires-Dist: gcsfs>=2026.4.0; extra == 'test-full'
120
+ Requires-Dist: jinja2; extra == 'test-full'
121
+ Requires-Dist: kerchunk; extra == 'test-full'
122
+ Requires-Dist: libarchive-c; extra == 'test-full'
123
+ Requires-Dist: lz4; extra == 'test-full'
124
+ Requires-Dist: notebook; extra == 'test-full'
125
+ Requires-Dist: numpy; extra == 'test-full'
126
+ Requires-Dist: ocifs; extra == 'test-full'
127
+ Requires-Dist: pandas<3.0.0; extra == 'test-full'
128
+ Requires-Dist: panel; extra == 'test-full'
129
+ Requires-Dist: paramiko; extra == 'test-full'
130
+ Requires-Dist: pyarrow>=1; extra == 'test-full'
131
+ Requires-Dist: pyftpdlib; extra == 'test-full'
132
+ Requires-Dist: pygit2; extra == 'test-full'
133
+ Requires-Dist: pytest; extra == 'test-full'
134
+ Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test-full'
135
+ Requires-Dist: pytest-benchmark; extra == 'test-full'
136
+ Requires-Dist: pytest-cov; extra == 'test-full'
137
+ Requires-Dist: pytest-mock; extra == 'test-full'
138
+ Requires-Dist: pytest-recording; extra == 'test-full'
139
+ Requires-Dist: pytest-rerunfailures; extra == 'test-full'
140
+ Requires-Dist: python-snappy; extra == 'test-full'
141
+ Requires-Dist: requests; extra == 'test-full'
142
+ Requires-Dist: s3fs>=2026.6.0; extra == 'test-full'
143
+ Requires-Dist: smbprotocol; extra == 'test-full'
144
+ Requires-Dist: tqdm; extra == 'test-full'
145
+ Requires-Dist: urllib3; extra == 'test-full'
146
+ Requires-Dist: zarr<3.2.0; extra == 'test-full'
147
+ Requires-Dist: zstandard; (python_version < '3.14') and extra == 'test-full'
148
+ Provides-Extra: tqdm
149
+ Requires-Dist: tqdm; extra == 'tqdm'
150
+ Description-Content-Type: text/markdown
151
+
152
+ # filesystem_spec
153
+
154
+ [![PyPI version](https://badge.fury.io/py/fsspec.svg)](https://pypi.python.org/pypi/fsspec/)
155
+ [![Anaconda-Server Badge](https://anaconda.org/conda-forge/fsspec/badges/version.svg)](https://anaconda.org/conda-forge/fsspec)
156
+ ![Build](https://github.com/fsspec/filesystem_spec/workflows/CI/badge.svg)
157
+ [![Docs](https://readthedocs.org/projects/filesystem-spec/badge/?version=latest)](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest)
158
+
159
+ A specification for pythonic filesystems.
160
+
161
+ ## Install
162
+
163
+ ```bash
164
+ pip install fsspec
165
+ ```
166
+
167
+ would install the base fsspec. Various optionally supported features might require specification of custom
168
+ extra require, e.g. `pip install fsspec[ssh]` will install dependencies for `ssh` backends support.
169
+ Use `pip install fsspec[full]` for installation of all known extra dependencies.
170
+
171
+ Up-to-date package also provided through conda-forge distribution:
172
+
173
+ ```bash
174
+ conda install -c conda-forge fsspec
175
+ ```
176
+
177
+
178
+ ## Purpose
179
+
180
+ To produce a template or specification for a file-system interface, that specific implementations should follow,
181
+ so that applications making use of them can rely on a common behaviour and not have to worry about the specific
182
+ internal implementation decisions with any given backend. Many such implementations are included in this package,
183
+ or in sister projects such as `s3fs` and `gcsfs`.
184
+
185
+ In addition, if this is well-designed, then additional functionality, such as a key-value store or FUSE
186
+ mounting of the file-system implementation may be available for all implementations "for free".
187
+
188
+ ## Documentation
189
+
190
+ Please refer to [RTD](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest)
191
+
192
+ ## Develop
193
+
194
+ fsspec uses GitHub Actions for CI. Environment files can be found
195
+ in the "ci/" directory. Note that the main environment is called "py38",
196
+ but it is expected that the version of python installed be adjustable at
197
+ CI runtime. For local use, pick a version suitable for you.
198
+
199
+ ```bash
200
+ # For a new environment (mamba / conda).
201
+ mamba create -n fsspec -c conda-forge python=3.10 -y
202
+ conda activate fsspec
203
+
204
+ # Standard dev install with docs and tests.
205
+ pip install -e ".[dev,doc,test]"
206
+
207
+ # Full tests except for downstream
208
+ pip install s3fs
209
+ pip uninstall s3fs
210
+ pip install -e .[dev,doc,test_full]
211
+ pip install s3fs --no-deps
212
+ pytest -v
213
+
214
+ # Downstream tests.
215
+ sh install_s3fs.sh
216
+ # Windows powershell.
217
+ install_s3fs.sh
218
+ ```
219
+
220
+ ### Testing
221
+
222
+ Tests can be run in the dev environment, if activated, via ``pytest fsspec``.
223
+
224
+ The full fsspec suite requires a system-level docker, docker-compose, and fuse
225
+ installation. If only making changes to one backend implementation, it is
226
+ not generally necessary to run all tests locally.
227
+
228
+ It is expected that contributors ensure that any change to fsspec does not
229
+ cause issues or regressions for either other fsspec-related packages such
230
+ as gcsfs and s3fs, nor for downstream users of fsspec. The "downstream" CI
231
+ run and corresponding environment file run a set of tests from the dask
232
+ test suite, and very minimal tests against pandas and zarr from the
233
+ test_downstream.py module in this repo.
234
+
235
+ ### Code Formatting
236
+
237
+ fsspec uses [Black](https://black.readthedocs.io/en/stable) to ensure
238
+ a consistent code format throughout the project.
239
+ Run ``black fsspec`` from the root of the filesystem_spec repository to
240
+ auto-format your code. Additionally, many editors have plugins that will apply
241
+ ``black`` as you edit files. ``black`` is included in the ``tox`` environments.
242
+
243
+ Optionally, you may wish to setup [pre-commit hooks](https://pre-commit.com) to
244
+ automatically run ``black`` when you make a git commit.
245
+ Run ``pre-commit install --install-hooks`` from the root of the
246
+ filesystem_spec repository to setup pre-commit hooks. ``black`` will now be run
247
+ before you commit, reformatting any changed files. You can format without
248
+ committing via ``pre-commit run`` or skip these checks with ``git commit
249
+ --no-verify``.
250
+
251
+ ## Support
252
+
253
+ Work on this repository is supported in part by:
254
+
255
+ "Anaconda, Inc. - Advancing AI through open source."
256
+
257
+ <a href="https://anaconda.com/"><img src="https://camo.githubusercontent.com/b8555ef2222598ed37ce38ac86955febbd25de7619931bb7dd3c58432181d3b6/68747470733a2f2f626565776172652e6f72672f636f6d6d756e6974792f6d656d626572732f616e61636f6e64612f616e61636f6e64612d6c617267652e706e67" alt="anaconda logo" width="40%"/></a>
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/RECORD ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fsspec-2026.7.0.dist-info/METADATA,sha256=iLFldYXeFOO7gqpSeKqVlbMKpMp06tBz2JUGFcgICZ0,10561
2
+ fsspec-2026.7.0.dist-info/RECORD,,
3
+ fsspec-2026.7.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
4
+ fsspec-2026.7.0.dist-info/licenses/LICENSE,sha256=LcNUls5TpzB5FcAIqESq1T53K0mzTN0ARFBnaRQH7JQ,1513
5
+ fsspec/__init__.py,sha256=xFcoHBD17fc5KamKUQAIA0rePGjLqIN1WBAd9NAoAi8,2111
6
+ fsspec/_version.py,sha256=XYrsnKX7E2XNoSiwqs7ALMtioidXl8y8KSliz3pL7S0,526
7
+ fsspec/archive.py,sha256=vM6t_lgV6lBWbBYwpm3S4ofBQFQxUPr5KkDQrrQcQro,2411
8
+ fsspec/asyn.py,sha256=V1Kig3HVzgWwZ-VtUYhys3QfdmiWRLG7EcP1E1PwM6M,39105
9
+ fsspec/caching.py,sha256=Glmc9tDtS8Ctp44sd7mJURJYq7sHkH_yD480q6IgbxE,34777
10
+ fsspec/callbacks.py,sha256=BDIwLzK6rr_0V5ch557fSzsivCElpdqhXr5dZ9Te-EE,9210
11
+ fsspec/compression.py,sha256=3v_Fe39gzRRWfaeXpzNjAGPqgTzmETYRCo3qHVqD3po,5132
12
+ fsspec/config.py,sha256=mHKzAgjXa_LwqtO_VoTJJ568VqwYkbK3gUp4J6JZJp4,4238
13
+ fsspec/conftest.py,sha256=uWfm_Qs5alPRxOhRpDfQ0-1jqSJ54pni4y96IxOREXM,3446
14
+ fsspec/core.py,sha256=EapTTO4bGR9G12rC90FiaBRemMhqo0ypx3ZqXj1zVuk,24189
15
+ fsspec/dircache.py,sha256=YzogWJrhEastHU7vWz-cJiJ7sdtLXFXhEpInGKd4EcM,2717
16
+ fsspec/exceptions.py,sha256=pauSLDMxzTJMOjvX1WEUK0cMyFkrFxpWJsyFywav7A8,331
17
+ fsspec/fuse.py,sha256=Q-3NOOyLqBfYa4Db5E19z_ZY36zzYHtIs1mOUasItBQ,10177
18
+ fsspec/generic.py,sha256=-LIADa9qRN79bfa3Hl9m3HaN6rlU2GNivawLNmybqxE,13752
19
+ fsspec/gui.py,sha256=CQ7QsrTpaDlWSLNOpwNoJc7khOcYXIZxmrAJN9bHWQU,14002
20
+ fsspec/implementations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
21
+ fsspec/implementations/arrow.py,sha256=HSXhExZ3HKNkWEm6m36h2jrbVilt3u8MvJI60u1_6fU,9236
22
+ fsspec/implementations/asyn_wrapper.py,sha256=3lfJkGs6D_AwRBdxTSYlL-RCVdaXBZ9Itys2P5o5Si0,3738
23
+ fsspec/implementations/cache_mapper.py,sha256=W4wlxyPxZbSp9ItJ0pYRVBMh6bw9eFypgP6kUYuuiI4,2421
24
+ fsspec/implementations/cache_metadata.py,sha256=EPhQV27lgPlYREYprDET1vcMed15pVNMit-Ta1ljoyE,7942
25
+ fsspec/implementations/cached.py,sha256=A_QyiukZzVznBWSZgMXSLd6h6K7k-ueroqnsoVY4bZg,37134
26
+ fsspec/implementations/chained.py,sha256=iGivpNaHUFjB_ea0-HAPhcmm6CL8qnDf270PSj7JwuE,680
27
+ fsspec/implementations/dask.py,sha256=CXZbJzIVOhKV8ILcxuy3bTvcacCueAbyQxmvAkbPkrk,4466
28
+ fsspec/implementations/data.py,sha256=9tMcy1fyX1auvzFX2aANPK9CfPoarnxTCDLhX12usvs,2131
29
+ fsspec/implementations/dbfs.py,sha256=yHuLUGNmQd5pUCt9vpXleQNpjOpIZZwVZA08YauQU4U,16249
30
+ fsspec/implementations/dirfs.py,sha256=KaIHW18i4-eNqdv7NR9qXEvoobQ88trGCNrqb4XW9ew,13449
31
+ fsspec/implementations/ftp.py,sha256=S_y5XOv_QhBiYBw430qzFB5MfS9AzxNBOs3f87XehC0,13539
32
+ fsspec/implementations/gist.py,sha256=Y6jTDrE-wuTwvpPyAQDuuOMBGxlajafKWoB1_yX6jdY,8528
33
+ fsspec/implementations/git.py,sha256=qBDWMz5LNllPqVjr5jf_1FuNha4P5lyQI3IlhYg-wUE,3731
34
+ fsspec/implementations/github.py,sha256=aCsZL8UvXZgdkcB1RUs3DdLeNrjLKcFsFYeQFDWbBFo,11653
35
+ fsspec/implementations/http.py,sha256=1uWwxllOjPe8mQD54IrCYQJHU1YaAXh_cDmXBk-AoQ8,30894
36
+ fsspec/implementations/http_sync.py,sha256=UmBqd938ebwVjYgVtzg-ysG3ZoGhIJw0wFtQAfxV3Aw,30332
37
+ fsspec/implementations/jupyter.py,sha256=q1PlQ66AAswGFyr8MFKWyobaV2YekMWRtqENBDQtD28,4002
38
+ fsspec/implementations/libarchive.py,sha256=SpIA1F-zf7kb2-VYUVuhMrXTBOhBxUXKgEW1RaAdDoA,7098
39
+ fsspec/implementations/local.py,sha256=jpvvSYj8RaocLB8YuHjGlWOTMJAJNTnUBj9D_Zn32BA,17216
40
+ fsspec/implementations/memory.py,sha256=fXUYjKF1xr4_9FX26vDCazEhmFbE7Om4xUufIOQe2vA,14088
41
+ fsspec/implementations/reference.py,sha256=YKLzPBF6bLpOnHY9iM0MR5JLGRi5CB6x1cWIgMb6Ahg,49974
42
+ fsspec/implementations/sftp.py,sha256=v7t-LpD4hEycHnw1kbepyoNgrhClshXQXitFuY4mBWE,5951
43
+ fsspec/implementations/smb.py,sha256=5fhu8h06nOLBPh2c48aT7WBRqh9cEcbIwtyu06wTjec,15236
44
+ fsspec/implementations/tar.py,sha256=adO9r_Badc4ucfApmK-mrvbv1re0_qoxwBjgnSMIrh0,4601
45
+ fsspec/implementations/webhdfs.py,sha256=osF2m0nhDil6sbMzYW_4DZzhxF4ygtb59XDiybd9Fyg,17589
46
+ fsspec/implementations/zip.py,sha256=GPDJh4UtUNJmaqijUQ0eiEZIGpwusQjkIcbhsrmLSi0,6263
47
+ fsspec/json.py,sha256=4EBZ-xOmRiyxmIqPIwxmDImosRQ7io7qBM2xjJPsEE4,3768
48
+ fsspec/mapping.py,sha256=m2ndB_gtRBXYmNJg0Ie1-BVR75TFleHmIQBzC-yWhjU,8343
49
+ fsspec/parquet.py,sha256=0SzfswUTc2k5nAj7xZNYPPyvUkFNXznFRXXtBRhr-iE,20506
50
+ fsspec/registry.py,sha256=KeDNL9HOyHX_D4D4qQGAI-Y3DQhiLeUC1VK2I81NZaE,12344
51
+ fsspec/spec.py,sha256=3LTaRdAhOTIPCetwPCS9HC6MR1VlcdfLVBh4mWFrXns,79674
52
+ fsspec/tests/abstract/__init__.py,sha256=V0-8FqQPfHlHZ3xomJ0hyWl6t1QvqsDnQFJYHeSTlEw,10197
53
+ fsspec/tests/abstract/common.py,sha256=1GQwNo5AONzAnzZj0fWgn8NJPLXALehbsuGxS3FzWVU,4973
54
+ fsspec/tests/abstract/copy.py,sha256=gU5-d97U3RSde35Vp4RxPY4rWwL744HiSrJ8IBOp9-8,19967
55
+ fsspec/tests/abstract/get.py,sha256=vNR4HztvTR7Cj56AMo7_tx7TeYz1Jgr_2Wb8Lv-UiBY,20755
56
+ fsspec/tests/abstract/mv.py,sha256=k8eUEBIrRrGMsBY5OOaDXdGnQUKGwDIfQyduB6YD3Ns,1982
57
+ fsspec/tests/abstract/open.py,sha256=Fi2PBPYLbRqysF8cFm0rwnB41kMdQVYjq8cGyDXp3BU,329
58
+ fsspec/tests/abstract/pipe.py,sha256=LFzIrLCB5GLXf9rzFKJmE8AdG7LQ_h4bJo70r8FLPqM,402
59
+ fsspec/tests/abstract/put.py,sha256=7aih17OKB_IZZh1Mkq1eBDIjobhtMQmI8x-Pw-S_aZk,21201
60
+ fsspec/transaction.py,sha256=xliRG6U2Zf3khG4xcw9WiB-yAoqJSHEGK_VjHOdtgo0,2398
61
+ fsspec/utils.py,sha256=T6x7JS-qHGdZ6hMPrT1tH6_41lHFw88g3WxgNIItYPc,24114
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2018, Martin Durant
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ * Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ * Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ * Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/__init__.py ADDED
File without changes
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/arrow.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import errno
2
+ import io
3
+ import os
4
+ import secrets
5
+ import shutil
6
+ from contextlib import suppress
7
+ from functools import cached_property, wraps
8
+ from urllib.parse import parse_qs
9
+
10
+ from fsspec.spec import AbstractFileSystem
11
+ from fsspec.utils import (
12
+ get_package_version_without_import,
13
+ infer_storage_options,
14
+ mirror_from,
15
+ tokenize,
16
+ )
17
+
18
+
19
+ def wrap_exceptions(func):
20
+ @wraps(func)
21
+ def wrapper(*args, **kwargs):
22
+ try:
23
+ return func(*args, **kwargs)
24
+ except OSError as exception:
25
+ if not exception.args:
26
+ raise
27
+
28
+ message, *args = exception.args
29
+ if isinstance(message, str) and "does not exist" in message:
30
+ raise FileNotFoundError(errno.ENOENT, message) from exception
31
+ else:
32
+ raise
33
+
34
+ return wrapper
35
+
36
+
37
+ PYARROW_VERSION = None
38
+ _EMPTY_ROOT_MARKER_FILESYSTEMS = {"gcs", "s3"}
39
+
40
+
41
+ class ArrowFSWrapper(AbstractFileSystem):
42
+ """FSSpec-compatible wrapper of pyarrow.fs.FileSystem.
43
+
44
+ Parameters
45
+ ----------
46
+ fs : pyarrow.fs.FileSystem
47
+
48
+ """
49
+
50
+ root_marker = "/"
51
+
52
+ def __init__(self, fs, **kwargs):
53
+ global PYARROW_VERSION
54
+ PYARROW_VERSION = get_package_version_without_import("pyarrow")
55
+ self.fs = fs
56
+ if fs.type_name in _EMPTY_ROOT_MARKER_FILESYSTEMS:
57
+ self.root_marker = ""
58
+ super().__init__(**kwargs)
59
+
60
+ @property
61
+ def protocol(self):
62
+ return self.fs.type_name
63
+
64
+ @cached_property
65
+ def fsid(self):
66
+ return "hdfs_" + tokenize(self.fs.host, self.fs.port)
67
+
68
+ def _parent(self, path):
69
+ if self.root_marker:
70
+ return super()._parent(path)
71
+
72
+ path = self._strip_protocol(path).lstrip("/")
73
+ return path.rsplit("/", 1)[0] if "/" in path else ""
74
+
75
+ @classmethod
76
+ def _strip_protocol(cls, path):
77
+ ops = infer_storage_options(path)
78
+ path = ops["path"]
79
+ if path.startswith("//"):
80
+ # special case for "hdfs://path" (without the triple slash)
81
+ path = path[1:]
82
+ return path
83
+
84
+ def ls(self, path, detail=False, **kwargs):
85
+ path = self._strip_protocol(path)
86
+ from pyarrow.fs import FileSelector
87
+
88
+ try:
89
+ entries = [
90
+ self._make_entry(entry)
91
+ for entry in self.fs.get_file_info(FileSelector(path))
92
+ ]
93
+ except (FileNotFoundError, NotADirectoryError):
94
+ entries = [self.info(path, **kwargs)]
95
+ if detail:
96
+ return entries
97
+ else:
98
+ return [entry["name"] for entry in entries]
99
+
100
+ def info(self, path, **kwargs):
101
+ path = self._strip_protocol(path)
102
+ [info] = self.fs.get_file_info([path])
103
+ return self._make_entry(info)
104
+
105
+ def exists(self, path):
106
+ path = self._strip_protocol(path)
107
+ try:
108
+ self.info(path)
109
+ except FileNotFoundError:
110
+ return False
111
+ else:
112
+ return True
113
+
114
+ def _make_entry(self, info):
115
+ from pyarrow.fs import FileType
116
+
117
+ if info.type is FileType.Directory:
118
+ kind = "directory"
119
+ elif info.type is FileType.File:
120
+ kind = "file"
121
+ elif info.type is FileType.NotFound:
122
+ raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), info.path)
123
+ else:
124
+ kind = "other"
125
+
126
+ return {
127
+ "name": info.path,
128
+ "size": info.size,
129
+ "type": kind,
130
+ "mtime": info.mtime,
131
+ }
132
+
133
+ @wrap_exceptions
134
+ def cp_file(self, path1, path2, **kwargs):
135
+ path1 = self._strip_protocol(path1).rstrip("/")
136
+ path2 = self._strip_protocol(path2).rstrip("/")
137
+
138
+ with self._open(path1, "rb") as lstream:
139
+ tmp_fname = f"{path2}.tmp.{secrets.token_hex(6)}"
140
+ try:
141
+ with self.open(tmp_fname, "wb") as rstream:
142
+ shutil.copyfileobj(lstream, rstream)
143
+ self.fs.move(tmp_fname, path2)
144
+ except BaseException:
145
+ with suppress(FileNotFoundError):
146
+ self.fs.delete_file(tmp_fname)
147
+ raise
148
+
149
+ @wrap_exceptions
150
+ def mv(self, path1, path2, **kwargs):
151
+ path1 = self._strip_protocol(path1).rstrip("/")
152
+ path2 = self._strip_protocol(path2).rstrip("/")
153
+ self.fs.move(path1, path2)
154
+
155
+ @wrap_exceptions
156
+ def rm_file(self, path):
157
+ path = self._strip_protocol(path)
158
+ self.fs.delete_file(path)
159
+
160
+ @wrap_exceptions
161
+ def rm(self, path, recursive=False, maxdepth=None):
162
+ path = self._strip_protocol(path).rstrip("/")
163
+ if self.isdir(path):
164
+ if recursive:
165
+ self.fs.delete_dir(path)
166
+ else:
167
+ raise ValueError("Can't delete directories without recursive=False")
168
+ else:
169
+ self.fs.delete_file(path)
170
+
171
+ @wrap_exceptions
172
+ def _open(self, path, mode="rb", block_size=None, seekable=True, **kwargs):
173
+ if mode == "rb":
174
+ if seekable:
175
+ method = self.fs.open_input_file
176
+ else:
177
+ method = self.fs.open_input_stream
178
+ elif mode == "wb":
179
+ method = self.fs.open_output_stream
180
+ elif mode == "ab":
181
+ method = self.fs.open_append_stream
182
+ else:
183
+ raise ValueError(f"unsupported mode for Arrow filesystem: {mode!r}")
184
+
185
+ _kwargs = {}
186
+ if mode != "rb" or not seekable:
187
+ if int(PYARROW_VERSION.split(".")[0]) >= 4:
188
+ # disable compression auto-detection
189
+ _kwargs["compression"] = None
190
+ stream = method(path, **_kwargs)
191
+
192
+ return ArrowFile(self, stream, path, mode, block_size, **kwargs)
193
+
194
+ @wrap_exceptions
195
+ def mkdir(self, path, create_parents=True, **kwargs):
196
+ path = self._strip_protocol(path)
197
+ if create_parents:
198
+ self.makedirs(path, exist_ok=True)
199
+ else:
200
+ self.fs.create_dir(path, recursive=False)
201
+
202
+ @wrap_exceptions
203
+ def makedirs(self, path, exist_ok=False):
204
+ path = self._strip_protocol(path)
205
+ self.fs.create_dir(path, recursive=True)
206
+
207
+ @wrap_exceptions
208
+ def rmdir(self, path):
209
+ path = self._strip_protocol(path)
210
+ self.fs.delete_dir(path)
211
+
212
+ @wrap_exceptions
213
+ def modified(self, path):
214
+ path = self._strip_protocol(path)
215
+ return self.fs.get_file_info(path).mtime
216
+
217
+ def cat_file(self, path, start=None, end=None, **kwargs):
218
+ kwargs.setdefault("seekable", start not in [None, 0])
219
+ return super().cat_file(path, start, end, **kwargs)
220
+
221
+ def get_file(self, rpath, lpath, **kwargs):
222
+ kwargs.setdefault("seekable", False)
223
+ super().get_file(rpath, lpath, **kwargs)
224
+
225
+
226
+ @mirror_from(
227
+ "stream",
228
+ [
229
+ "read",
230
+ "seek",
231
+ "tell",
232
+ "write",
233
+ "readable",
234
+ "writable",
235
+ "close",
236
+ "seekable",
237
+ ],
238
+ )
239
+ class ArrowFile(io.IOBase):
240
+ def __init__(self, fs, stream, path, mode, block_size=None, **kwargs):
241
+ self.path = path
242
+ self.mode = mode
243
+
244
+ self.fs = fs
245
+ self.stream = stream
246
+
247
+ self.blocksize = self.block_size = block_size
248
+ self.kwargs = kwargs
249
+
250
+ def __enter__(self):
251
+ return self
252
+
253
+ @property
254
+ def size(self):
255
+ if self.stream.seekable():
256
+ return self.stream.size()
257
+ return None
258
+
259
+ def __exit__(self, *args):
260
+ return self.close()
261
+
262
+
263
+ class HadoopFileSystem(ArrowFSWrapper):
264
+ """A wrapper on top of the pyarrow.fs.HadoopFileSystem
265
+ to connect it's interface with fsspec"""
266
+
267
+ protocol = "hdfs"
268
+
269
+ def __init__(
270
+ self,
271
+ host="default",
272
+ port=0,
273
+ user=None,
274
+ kerb_ticket=None,
275
+ replication=3,
276
+ extra_conf=None,
277
+ **kwargs,
278
+ ):
279
+ """
280
+
281
+ Parameters
282
+ ----------
283
+ host: str
284
+ Hostname, IP or "default" to try to read from Hadoop config
285
+ port: int
286
+ Port to connect on, or default from Hadoop config if 0
287
+ user: str or None
288
+ If given, connect as this username
289
+ kerb_ticket: str or None
290
+ If given, use this ticket for authentication
291
+ replication: int
292
+ set replication factor of file for write operations. default value is 3.
293
+ extra_conf: None or dict
294
+ Passed on to HadoopFileSystem
295
+ """
296
+ from pyarrow.fs import HadoopFileSystem
297
+
298
+ fs = HadoopFileSystem(
299
+ host=host,
300
+ port=port,
301
+ user=user,
302
+ kerb_ticket=kerb_ticket,
303
+ replication=replication,
304
+ extra_conf=extra_conf,
305
+ )
306
+ super().__init__(fs=fs, **kwargs)
307
+
308
+ @staticmethod
309
+ def _get_kwargs_from_urls(path):
310
+ ops = infer_storage_options(path)
311
+ out = {}
312
+ if ops.get("host", None):
313
+ out["host"] = ops["host"]
314
+ if ops.get("username", None):
315
+ out["user"] = ops["username"]
316
+ if ops.get("port", None):
317
+ out["port"] = ops["port"]
318
+ if ops.get("url_query", None):
319
+ queries = parse_qs(ops["url_query"])
320
+ if queries.get("replication", None):
321
+ out["replication"] = int(queries["replication"][0])
322
+ return out
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/asyn_wrapper.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import functools
3
+ import inspect
4
+
5
+ import fsspec
6
+ from fsspec.asyn import AsyncFileSystem, running_async
7
+
8
+ from .chained import ChainedFileSystem
9
+
10
+
11
+ def async_wrapper(func, obj=None, semaphore=None):
12
+ """
13
+ Wraps a synchronous function to make it awaitable.
14
+
15
+ Parameters
16
+ ----------
17
+ func : callable
18
+ The synchronous function to wrap.
19
+ obj : object, optional
20
+ The instance to bind the function to, if applicable.
21
+ semaphore : asyncio.Semaphore, optional
22
+ A semaphore to limit concurrent calls.
23
+
24
+ Returns
25
+ -------
26
+ coroutine
27
+ An awaitable version of the function.
28
+ """
29
+
30
+ @functools.wraps(func)
31
+ async def wrapper(*args, **kwargs):
32
+ if semaphore:
33
+ async with semaphore:
34
+ return await asyncio.to_thread(func, *args, **kwargs)
35
+ return await asyncio.to_thread(func, *args, **kwargs)
36
+
37
+ return wrapper
38
+
39
+
40
+ class AsyncFileSystemWrapper(AsyncFileSystem, ChainedFileSystem):
41
+ """
42
+ A wrapper class to convert a synchronous filesystem into an asynchronous one.
43
+
44
+ This class takes an existing synchronous filesystem implementation and wraps all
45
+ its methods to provide an asynchronous interface.
46
+
47
+ Parameters
48
+ ----------
49
+ sync_fs : AbstractFileSystem
50
+ The synchronous filesystem instance to wrap.
51
+ """
52
+
53
+ protocol = "asyncwrapper", "async_wrapper"
54
+ cachable = False
55
+
56
+ def __init__(
57
+ self,
58
+ fs=None,
59
+ asynchronous=None,
60
+ target_protocol=None,
61
+ target_options=None,
62
+ semaphore=None,
63
+ max_concurrent_tasks=None,
64
+ **kwargs,
65
+ ):
66
+ if asynchronous is None:
67
+ asynchronous = running_async()
68
+ super().__init__(asynchronous=asynchronous, **kwargs)
69
+ if fs is not None:
70
+ self.sync_fs = fs
71
+ else:
72
+ self.sync_fs = fsspec.filesystem(target_protocol, **target_options)
73
+ self.protocol = self.sync_fs.protocol
74
+ self.semaphore = semaphore
75
+ self._wrap_all_sync_methods()
76
+
77
+ @property
78
+ def fsid(self):
79
+ return f"async_{self.sync_fs.fsid}"
80
+
81
+ def _wrap_all_sync_methods(self):
82
+ """
83
+ Wrap all synchronous methods of the underlying filesystem with asynchronous versions.
84
+ """
85
+ excluded_methods = {"open"}
86
+ for method_name in dir(self.sync_fs):
87
+ if method_name.startswith("_") or method_name in excluded_methods:
88
+ continue
89
+
90
+ attr = inspect.getattr_static(self.sync_fs, method_name)
91
+ if isinstance(attr, property):
92
+ continue
93
+
94
+ method = getattr(self.sync_fs, method_name)
95
+ if callable(method) and not inspect.iscoroutinefunction(method):
96
+ async_method = async_wrapper(method, obj=self, semaphore=self.semaphore)
97
+ setattr(self, f"_{method_name}", async_method)
98
+
99
+ @classmethod
100
+ def wrap_class(cls, sync_fs_class):
101
+ """
102
+ Create a new class that can be used to instantiate an AsyncFileSystemWrapper
103
+ with lazy instantiation of the underlying synchronous filesystem.
104
+
105
+ Parameters
106
+ ----------
107
+ sync_fs_class : type
108
+ The class of the synchronous filesystem to wrap.
109
+
110
+ Returns
111
+ -------
112
+ type
113
+ A new class that wraps the provided synchronous filesystem class.
114
+ """
115
+
116
+ class GeneratedAsyncFileSystemWrapper(cls):
117
+ def __init__(self, *args, **kwargs):
118
+ sync_fs = sync_fs_class(*args, **kwargs)
119
+ super().__init__(sync_fs)
120
+
121
+ GeneratedAsyncFileSystemWrapper.__name__ = (
122
+ f"Async{sync_fs_class.__name__}Wrapper"
123
+ )
124
+ return GeneratedAsyncFileSystemWrapper
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/cache_mapper.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import abc
4
+ import hashlib
5
+
6
+ from fsspec.implementations.local import make_path_posix
7
+
8
+
9
+ class AbstractCacheMapper(abc.ABC):
10
+ """Abstract super-class for mappers from remote URLs to local cached
11
+ basenames.
12
+ """
13
+
14
+ @abc.abstractmethod
15
+ def __call__(self, path: str) -> str: ...
16
+
17
+ def __eq__(self, other: object) -> bool:
18
+ # Identity only depends on class. When derived classes have attributes
19
+ # they will need to be included.
20
+ return isinstance(other, type(self))
21
+
22
+ def __hash__(self) -> int:
23
+ # Identity only depends on class. When derived classes have attributes
24
+ # they will need to be included.
25
+ return hash(type(self))
26
+
27
+
28
+ class BasenameCacheMapper(AbstractCacheMapper):
29
+ """Cache mapper that uses the basename of the remote URL and a fixed number
30
+ of directory levels above this.
31
+
32
+ The default is zero directory levels, meaning different paths with the same
33
+ basename will have the same cached basename.
34
+ """
35
+
36
+ def __init__(self, directory_levels: int = 0):
37
+ if directory_levels < 0:
38
+ raise ValueError(
39
+ "BasenameCacheMapper requires zero or positive directory_levels"
40
+ )
41
+ self.directory_levels = directory_levels
42
+
43
+ # Separator for directories when encoded as strings.
44
+ self._separator = "_@_"
45
+
46
+ def __call__(self, path: str) -> str:
47
+ path = make_path_posix(path)
48
+ prefix, *bits = path.rsplit("/", self.directory_levels + 1)
49
+ if bits:
50
+ return self._separator.join(bits)
51
+ else:
52
+ return prefix # No separator found, simple filename
53
+
54
+ def __eq__(self, other: object) -> bool:
55
+ return super().__eq__(other) and self.directory_levels == other.directory_levels
56
+
57
+ def __hash__(self) -> int:
58
+ return super().__hash__() ^ hash(self.directory_levels)
59
+
60
+
61
+ class HashCacheMapper(AbstractCacheMapper):
62
+ """Cache mapper that uses a hash of the remote URL."""
63
+
64
+ def __call__(self, path: str) -> str:
65
+ return hashlib.sha256(path.encode()).hexdigest()
66
+
67
+
68
+ def create_cache_mapper(same_names: bool) -> AbstractCacheMapper:
69
+ """Factory method to create cache mapper for backward compatibility with
70
+ ``CachingFileSystem`` constructor using ``same_names`` kwarg.
71
+ """
72
+ if same_names:
73
+ return BasenameCacheMapper()
74
+ else:
75
+ return HashCacheMapper()
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/cache_metadata.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import time
5
+ from typing import TYPE_CHECKING
6
+
7
+ from fsspec.utils import atomic_write
8
+
9
+ try:
10
+ import ujson as json
11
+ except ImportError:
12
+ if not TYPE_CHECKING:
13
+ import json
14
+
15
+ if TYPE_CHECKING:
16
+ from collections.abc import Iterator
17
+ from typing import Any, Literal, TypeAlias
18
+
19
+ from .cached import CachingFileSystem
20
+
21
+ Detail: TypeAlias = dict[str, Any]
22
+
23
+
24
+ class CacheMetadata:
25
+ """Cache metadata.
26
+
27
+ All reading and writing of cache metadata is performed by this class,
28
+ accessing the cached files and blocks is not.
29
+
30
+ Metadata is stored in a single file per storage directory in JSON format.
31
+ For backward compatibility. No longer supports pickle.
32
+ """
33
+
34
+ def __init__(self, storage: list[str]):
35
+ """
36
+
37
+ Parameters
38
+ ----------
39
+ storage: list[str]
40
+ Directories containing cached files, must be at least one. Metadata
41
+ is stored in the last of these directories by convention.
42
+ """
43
+ if not storage:
44
+ raise ValueError("CacheMetadata expects at least one storage location")
45
+
46
+ self._storage = storage
47
+ self.cached_files: list[Detail] = [{}]
48
+
49
+ def _load(self, fn: str) -> Detail:
50
+ """Low-level function to load metadata from specific file"""
51
+ with open(fn, "r") as f:
52
+ loaded = json.load(f)
53
+ for c in loaded.values():
54
+ if isinstance(c.get("blocks"), list):
55
+ c["blocks"] = set(c["blocks"])
56
+ return loaded
57
+
58
+ def _save(self, metadata_to_save: Detail, fn: str) -> None:
59
+ """Low-level function to save metadata to specific file"""
60
+ with atomic_write(fn, mode="w") as f:
61
+ json.dump(metadata_to_save, f)
62
+
63
+ def _scan_locations(
64
+ self, writable_only: bool = False
65
+ ) -> Iterator[tuple[str, str, bool]]:
66
+ """Yield locations (filenames) where metadata is stored, and whether
67
+ writable or not.
68
+
69
+ Parameters
70
+ ----------
71
+ writable: bool
72
+ Set to True to only yield writable locations.
73
+
74
+ Returns
75
+ -------
76
+ Yields (str, str, bool)
77
+ """
78
+ n = len(self._storage)
79
+ for i, storage in enumerate(self._storage):
80
+ writable = i == n - 1
81
+ if writable_only and not writable:
82
+ continue
83
+ yield os.path.join(storage, "cache"), storage, writable
84
+
85
+ def check_file(
86
+ self, path: str, cfs: CachingFileSystem | None
87
+ ) -> Literal[False] | tuple[Detail, str]:
88
+ """If path is in cache return its details, otherwise return ``False``.
89
+
90
+ If the optional CachingFileSystem is specified then it is used to
91
+ perform extra checks to reject possible matches, such as if they are
92
+ too old.
93
+ """
94
+ for (fn, base, _), cache in zip(self._scan_locations(), self.cached_files):
95
+ if path not in cache:
96
+ continue
97
+ detail = cache[path].copy()
98
+
99
+ if cfs is not None:
100
+ if cfs.check_files and detail["uid"] != cfs.fs.ukey(path):
101
+ # Wrong file as determined by hash of file properties
102
+ continue
103
+ if cfs.expiry and time.time() - detail["time"] > cfs.expiry:
104
+ # Cached file has expired
105
+ continue
106
+
107
+ fn = os.path.join(base, detail["fn"])
108
+ if os.path.exists(fn):
109
+ return detail, fn
110
+ return False
111
+
112
+ def clear_expired(self, expiry_time: int) -> tuple[list[str], bool]:
113
+ """Remove expired metadata from the cache.
114
+
115
+ Returns names of files corresponding to expired metadata and a boolean
116
+ flag indicating whether the writable cache is empty. Caller is
117
+ responsible for deleting the expired files.
118
+ """
119
+ expired_files = []
120
+ for path, detail in self.cached_files[-1].copy().items():
121
+ if time.time() - detail["time"] > expiry_time:
122
+ fn = detail.get("fn", "")
123
+ if not fn:
124
+ raise RuntimeError(
125
+ f"Cache metadata does not contain 'fn' for {path}"
126
+ )
127
+ fn = os.path.join(self._storage[-1], fn)
128
+ expired_files.append(fn)
129
+ self.cached_files[-1].pop(path)
130
+
131
+ if self.cached_files[-1]:
132
+ cache_path = os.path.join(self._storage[-1], "cache")
133
+ self._save(self.cached_files[-1], cache_path)
134
+
135
+ writable_cache_empty = not self.cached_files[-1]
136
+ return expired_files, writable_cache_empty
137
+
138
+ def load(self) -> None:
139
+ """Load all metadata from disk and store in ``self.cached_files``"""
140
+ cached_files = []
141
+ for fn, _, _ in self._scan_locations():
142
+ if os.path.exists(fn):
143
+ # TODO: consolidate blocks here
144
+ cached_files.append(self._load(fn))
145
+ else:
146
+ cached_files.append({})
147
+ self.cached_files = cached_files or [{}]
148
+
149
+ def on_close_cached_file(self, f: Any, path: str) -> None:
150
+ """Perform side-effect actions on closing a cached file.
151
+
152
+ The actual closing of the file is the responsibility of the caller.
153
+ """
154
+ # File must be writable, so in self.cached_files[-1]
155
+ c = self.cached_files[-1][path]
156
+ if c["blocks"] is not True and len(c["blocks"]) * f.blocksize >= f.size:
157
+ c["blocks"] = True
158
+
159
+ def pop_file(self, path: str) -> str | None:
160
+ """Remove metadata of cached file.
161
+
162
+ If path is in the cache, return the filename of the cached file,
163
+ otherwise return ``None``. Caller is responsible for deleting the
164
+ cached file.
165
+ """
166
+ details = self.check_file(path, None)
167
+ if not details:
168
+ return None
169
+ _, fn = details
170
+ if fn.startswith(self._storage[-1]):
171
+ self.cached_files[-1].pop(path)
172
+ self.save()
173
+ else:
174
+ raise PermissionError(
175
+ "Can only delete cached file in last, writable cache location"
176
+ )
177
+ return fn
178
+
179
+ def save(self) -> None:
180
+ """Save metadata to disk"""
181
+ for (fn, _, writable), cache in zip(self._scan_locations(), self.cached_files):
182
+ if not writable:
183
+ continue
184
+
185
+ if os.path.exists(fn):
186
+ cached_files = self._load(fn)
187
+ for k, c in cached_files.items():
188
+ if k in cache:
189
+ if c["blocks"] is True or cache[k]["blocks"] is True:
190
+ c["blocks"] = True
191
+ else:
192
+ # self.cached_files[*][*]["blocks"] must continue to
193
+ # point to the same set object so that updates
194
+ # performed by MMapCache are propagated back to
195
+ # self.cached_files.
196
+ blocks = cache[k]["blocks"]
197
+ blocks.update(c["blocks"])
198
+ c["blocks"] = blocks
199
+ c["time"] = max(c["time"], cache[k]["time"])
200
+ c["uid"] = cache[k]["uid"]
201
+
202
+ # Files can be added to cache after it was written once
203
+ for k, c in cache.items():
204
+ if k not in cached_files:
205
+ cached_files[k] = c
206
+ else:
207
+ cached_files = cache
208
+ cache = {k: v.copy() for k, v in cached_files.items()}
209
+ for c in cache.values():
210
+ if isinstance(c["blocks"], set):
211
+ c["blocks"] = list(c["blocks"])
212
+ self._save(cache, fn)
213
+ self.cached_files[-1] = cached_files
214
+
215
+ def update_file(self, path: str, detail: Detail) -> None:
216
+ """Update metadata for specific file in memory, do not save"""
217
+ self.cached_files[-1][path] = detail
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/cached.py ADDED
@@ -0,0 +1,1040 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import logging
5
+ import os
6
+ import tempfile
7
+ import time
8
+ import weakref
9
+ from collections.abc import Callable
10
+ from shutil import rmtree
11
+ from typing import TYPE_CHECKING, Any, ClassVar
12
+
13
+ from fsspec import filesystem
14
+ from fsspec.callbacks import DEFAULT_CALLBACK
15
+ from fsspec.compression import compr
16
+ from fsspec.core import BaseCache, MMapCache
17
+ from fsspec.exceptions import BlocksizeMismatchError
18
+ from fsspec.implementations.cache_mapper import create_cache_mapper
19
+ from fsspec.implementations.cache_metadata import CacheMetadata
20
+ from fsspec.implementations.chained import ChainedFileSystem
21
+ from fsspec.implementations.local import LocalFileSystem
22
+ from fsspec.spec import AbstractBufferedFile
23
+ from fsspec.transaction import Transaction
24
+ from fsspec.utils import infer_compression
25
+
26
+ if TYPE_CHECKING:
27
+ from fsspec.implementations.cache_mapper import AbstractCacheMapper
28
+
29
+ logger = logging.getLogger("fsspec.cached")
30
+
31
+
32
+ class WriteCachedTransaction(Transaction):
33
+ def complete(self, commit=True):
34
+ rpaths = [f.path for f in self.files]
35
+ lpaths = [f.fn for f in self.files]
36
+ if commit:
37
+ self.fs.put(lpaths, rpaths)
38
+ self.files.clear()
39
+ self.fs._intrans = False
40
+ self.fs._transaction = None
41
+ self.fs = None # break cycle
42
+
43
+
44
+ class CachingFileSystem(ChainedFileSystem):
45
+ """Locally caching filesystem, layer over any other FS
46
+
47
+ This class implements chunk-wise local storage of remote files, for quick
48
+ access after the initial download. The files are stored in a given
49
+ directory with hashes of URLs for the filenames. If no directory is given,
50
+ a temporary one is used, which should be cleaned up by the OS after the
51
+ process ends. The files themselves are sparse (as implemented in
52
+ :class:`~fsspec.caching.MMapCache`), so only the data which is accessed
53
+ takes up space.
54
+
55
+ Restrictions:
56
+
57
+ - the block-size must be the same for each access of a given file, unless
58
+ all blocks of the file have already been read
59
+ - caching can only be applied to file-systems which produce files
60
+ derived from fsspec.spec.AbstractBufferedFile ; LocalFileSystem is also
61
+ allowed, for testing
62
+ """
63
+
64
+ protocol: ClassVar[str | tuple[str, ...]] = ("blockcache", "cached")
65
+ _strip_tokenize_options = ("fo",)
66
+
67
+ def __init__(
68
+ self,
69
+ target_protocol=None,
70
+ cache_storage="TMP",
71
+ cache_check=10,
72
+ check_files=False,
73
+ expiry_time=604800,
74
+ target_options=None,
75
+ fs=None,
76
+ same_names: bool | None = None,
77
+ compression=None,
78
+ cache_mapper: AbstractCacheMapper | None = None,
79
+ cache_storage_mode=None,
80
+ **kwargs,
81
+ ):
82
+ """
83
+
84
+ Parameters
85
+ ----------
86
+ target_protocol: str (optional)
87
+ Target filesystem protocol. Provide either this or ``fs``.
88
+ cache_storage: str or list(str)
89
+ Location to store files. If "TMP", this is a temporary directory,
90
+ and will be cleaned up by the OS when this process ends (or later).
91
+ If a list, each location will be tried in the order given, but
92
+ only the last will be considered writable.
93
+ cache_check: int
94
+ Number of seconds between reload of cache metadata
95
+ check_files: bool
96
+ Whether to explicitly see if the UID of the remote file matches
97
+ the stored one before using. Warning: some file systems such as
98
+ HTTP cannot reliably give a unique hash of the contents of some
99
+ path, so be sure to set this option to False.
100
+ expiry_time: int
101
+ The time in seconds after which a local copy is considered useless.
102
+ Set to falsy to prevent expiry. The default is equivalent to one
103
+ week.
104
+ target_options: dict or None
105
+ Passed to the instantiation of the FS, if fs is None.
106
+ fs: filesystem instance
107
+ The target filesystem to run against. Provide this or ``protocol``.
108
+ same_names: bool (optional)
109
+ By default, target URLs are hashed using a ``HashCacheMapper`` so
110
+ that files from different backends with the same basename do not
111
+ conflict. If this argument is ``true``, a ``BasenameCacheMapper``
112
+ is used instead. Other cache mapper options are available by using
113
+ the ``cache_mapper`` keyword argument. Only one of this and
114
+ ``cache_mapper`` should be specified.
115
+ compression: str (optional)
116
+ To decompress on download. Can be 'infer' (guess from the URL name),
117
+ one of the entries in ``fsspec.compression.compr``, or None for no
118
+ decompression.
119
+ cache_mapper: AbstractCacheMapper (optional)
120
+ The object use to map from original filenames to cached filenames.
121
+ Only one of this and ``same_names`` should be specified.
122
+ cache_storage_mode: int (optional)
123
+ Permission mode used when creating the cache storage directory,
124
+ e.g. ``0o700``. The default of ``None`` leaves the directory at
125
+ the system default (governed by the umask), which is the existing
126
+ behaviour. Pass an octal mode such as ``0o700`` to keep the cache
127
+ directory, and so the cached data files within it, readable by the
128
+ owner only.
129
+ """
130
+ super().__init__(**kwargs)
131
+ if fs is None and target_protocol is None:
132
+ raise ValueError(
133
+ "Please provide filesystem instance(fs) or target_protocol"
134
+ )
135
+ if not (fs is None) ^ (target_protocol is None):
136
+ raise ValueError(
137
+ "Both filesystems (fs) and target_protocol may not be both given."
138
+ )
139
+ if cache_storage == "TMP":
140
+ tempdir = tempfile.mkdtemp()
141
+ storage = [tempdir]
142
+ weakref.finalize(self, self._remove_tempdir, tempdir)
143
+ else:
144
+ if isinstance(cache_storage, str):
145
+ storage = [cache_storage]
146
+ else:
147
+ storage = cache_storage
148
+ self.cache_storage_mode = cache_storage_mode
149
+ self._makedirs(storage[-1])
150
+ self.storage = storage
151
+ self.kwargs = target_options or {}
152
+ self.cache_check = cache_check
153
+ self.check_files = check_files
154
+ self.expiry = expiry_time
155
+ self.compression = compression
156
+
157
+ # Size of cache in bytes. If None then the size is unknown and will be
158
+ # recalculated the next time cache_size() is called. On writes to the
159
+ # cache this is reset to None.
160
+ self._cache_size = None
161
+
162
+ if same_names is not None and cache_mapper is not None:
163
+ raise ValueError(
164
+ "Cannot specify both same_names and cache_mapper in "
165
+ "CachingFileSystem.__init__"
166
+ )
167
+ if cache_mapper is not None:
168
+ self._mapper = cache_mapper
169
+ else:
170
+ self._mapper = create_cache_mapper(
171
+ same_names if same_names is not None else False
172
+ )
173
+
174
+ self.target_protocol = (
175
+ target_protocol
176
+ if isinstance(target_protocol, str)
177
+ else (fs.protocol if isinstance(fs.protocol, str) else fs.protocol[0])
178
+ )
179
+ self._metadata = CacheMetadata(self.storage)
180
+ self.load_cache()
181
+ self.fs = fs if fs is not None else filesystem(target_protocol, **self.kwargs)
182
+
183
+ def _strip_protocol(path):
184
+ # acts as a method, since each instance has a difference target
185
+ return self.fs._strip_protocol(type(self)._strip_protocol(path))
186
+
187
+ self._strip_protocol: Callable = _strip_protocol
188
+
189
+ @staticmethod
190
+ def _remove_tempdir(tempdir):
191
+ try:
192
+ rmtree(tempdir)
193
+ except Exception:
194
+ pass
195
+
196
+ def _makedirs(self, path):
197
+ if self.cache_storage_mode is None:
198
+ os.makedirs(path, exist_ok=True)
199
+ else:
200
+ os.makedirs(path, exist_ok=True, mode=self.cache_storage_mode)
201
+
202
+ def _mkcache(self):
203
+ self._makedirs(self.storage[-1])
204
+
205
+ def cache_size(self):
206
+ """Return size of cache in bytes.
207
+
208
+ If more than one cache directory is in use, only the size of the last
209
+ one (the writable cache directory) is returned.
210
+ """
211
+ if self._cache_size is None:
212
+ cache_dir = self.storage[-1]
213
+ self._cache_size = filesystem("file").du(cache_dir, withdirs=True)
214
+ return self._cache_size
215
+
216
+ def load_cache(self):
217
+ """Read set of stored blocks from file"""
218
+ self._metadata.load()
219
+ self._mkcache()
220
+ self.last_cache = time.time()
221
+
222
+ def save_cache(self):
223
+ """Save set of stored blocks from file"""
224
+ self._mkcache()
225
+ self._metadata.save()
226
+ self.last_cache = time.time()
227
+ self._cache_size = None
228
+
229
+ def _check_cache(self):
230
+ """Reload caches if time elapsed or any disappeared"""
231
+ self._mkcache()
232
+ if not self.cache_check:
233
+ # explicitly told not to bother checking
234
+ return
235
+ timecond = time.time() - self.last_cache > self.cache_check
236
+ existcond = all(os.path.exists(storage) for storage in self.storage)
237
+ if timecond or not existcond:
238
+ self.load_cache()
239
+
240
+ def _check_file(self, path):
241
+ """Is path in cache and still valid"""
242
+ path = self._strip_protocol(path)
243
+ self._check_cache()
244
+ return self._metadata.check_file(path, self)
245
+
246
+ def clear_cache(self):
247
+ """Remove all files and metadata from the cache
248
+
249
+ In the case of multiple cache locations, this clears only the last one,
250
+ which is assumed to be the read/write one.
251
+ """
252
+ rmtree(self.storage[-1])
253
+ self.load_cache()
254
+ self._cache_size = None
255
+
256
+ def clear_expired_cache(self, expiry_time=None):
257
+ """Remove all expired files and metadata from the cache
258
+
259
+ In the case of multiple cache locations, this clears only the last one,
260
+ which is assumed to be the read/write one.
261
+
262
+ Parameters
263
+ ----------
264
+ expiry_time: int
265
+ The time in seconds after which a local copy is considered useless.
266
+ If not defined the default is equivalent to the attribute from the
267
+ file caching instantiation.
268
+ """
269
+
270
+ if not expiry_time:
271
+ expiry_time = self.expiry
272
+
273
+ self._check_cache()
274
+
275
+ expired_files, writable_cache_empty = self._metadata.clear_expired(expiry_time)
276
+ for fn in expired_files:
277
+ if os.path.exists(fn):
278
+ os.remove(fn)
279
+
280
+ if writable_cache_empty:
281
+ rmtree(self.storage[-1])
282
+ self.load_cache()
283
+
284
+ self._cache_size = None
285
+
286
+ def pop_from_cache(self, path):
287
+ """Remove cached version of given file
288
+
289
+ Deletes local copy of the given (remote) path. If it is found in a cache
290
+ location which is not the last, it is assumed to be read-only, and
291
+ raises PermissionError
292
+ """
293
+ path = self._strip_protocol(path)
294
+ fn = self._metadata.pop_file(path)
295
+ if fn is not None:
296
+ os.remove(fn)
297
+ self._cache_size = None
298
+
299
+ def _open(
300
+ self,
301
+ path,
302
+ mode="rb",
303
+ block_size=None,
304
+ autocommit=True,
305
+ cache_options=None,
306
+ **kwargs,
307
+ ):
308
+ """Wrap the target _open
309
+
310
+ If the whole file exists in the cache, just open it locally and
311
+ return that.
312
+
313
+ Otherwise, open the file on the target FS, and make it have a mmap
314
+ cache pointing to the location which we determine, in our cache.
315
+ The ``blocks`` instance is shared, so as the mmap cache instance
316
+ updates, so does the entry in our ``cached_files`` attribute.
317
+ We monkey-patch this file, so that when it closes, we call
318
+ ``close_and_update`` to save the state of the blocks.
319
+ """
320
+ path = self._strip_protocol(path)
321
+
322
+ path = self.fs._strip_protocol(path)
323
+ if "r" not in mode:
324
+ return self.fs._open(
325
+ path,
326
+ mode=mode,
327
+ block_size=block_size,
328
+ autocommit=autocommit,
329
+ cache_options=cache_options,
330
+ **kwargs,
331
+ )
332
+ detail = self._check_file(path)
333
+ if detail:
334
+ # file is in cache
335
+ detail, fn = detail
336
+ hash, blocks = detail["fn"], detail["blocks"]
337
+ if blocks is True:
338
+ # stored file is complete
339
+ logger.debug("Opening local copy of %s", path)
340
+ return open(fn, mode)
341
+ # TODO: action where partial file exists in read-only cache
342
+ logger.debug("Opening partially cached copy of %s", path)
343
+ else:
344
+ hash = self._mapper(path)
345
+ fn = os.path.join(self.storage[-1], hash)
346
+ blocks = set()
347
+ detail = {
348
+ "original": path,
349
+ "fn": hash,
350
+ "blocks": blocks,
351
+ "time": time.time(),
352
+ "uid": self.fs.ukey(path),
353
+ }
354
+ self._metadata.update_file(path, detail)
355
+ logger.debug("Creating local sparse file for %s", path)
356
+
357
+ # explicitly submitting the size to the open call will avoid extra
358
+ # operations when opening. This is particularly relevant
359
+ # for any file that is read over a network, e.g. S3.
360
+ size = detail.get("size")
361
+
362
+ # call target filesystems open
363
+ self._mkcache()
364
+ f = self.fs._open(
365
+ path,
366
+ mode=mode,
367
+ block_size=block_size,
368
+ autocommit=autocommit,
369
+ cache_options=cache_options,
370
+ cache_type="none",
371
+ size=size,
372
+ **kwargs,
373
+ )
374
+
375
+ # set size if not already set
376
+ if size is None:
377
+ detail["size"] = f.size
378
+ self._metadata.update_file(path, detail)
379
+
380
+ if self.compression:
381
+ comp = (
382
+ infer_compression(path)
383
+ if self.compression == "infer"
384
+ else self.compression
385
+ )
386
+ f = compr[comp](f, mode="rb")
387
+ if "blocksize" in detail:
388
+ if detail["blocksize"] != f.blocksize:
389
+ raise BlocksizeMismatchError(
390
+ f"Cached file must be reopened with same block"
391
+ f" size as original (old: {detail['blocksize']},"
392
+ f" new {f.blocksize})"
393
+ )
394
+ else:
395
+ detail["blocksize"] = f.blocksize
396
+
397
+ def _fetch_ranges(ranges):
398
+ return self.fs.cat_ranges(
399
+ [path] * len(ranges),
400
+ [r[0] for r in ranges],
401
+ [r[1] for r in ranges],
402
+ **kwargs,
403
+ )
404
+
405
+ multi_fetcher = None if self.compression else _fetch_ranges
406
+ f.cache = MMapCache(
407
+ f.blocksize, f._fetch_range, f.size, fn, blocks, multi_fetcher=multi_fetcher
408
+ )
409
+ close = f.close
410
+ f.close = lambda: self.close_and_update(f, close)
411
+ self.save_cache()
412
+ return f
413
+
414
+ def _parent(self, path):
415
+ return self.fs._parent(path)
416
+
417
+ def hash_name(self, path: str, *args: Any) -> str:
418
+ # Kept for backward compatibility with downstream libraries.
419
+ # Ignores extra arguments, previously same_name boolean.
420
+ return self._mapper(path)
421
+
422
+ def close_and_update(self, f, close):
423
+ """Called when a file is closing, so store the set of blocks"""
424
+ if f.closed:
425
+ return
426
+ path = self._strip_protocol(f.path)
427
+ self._metadata.on_close_cached_file(f, path)
428
+ try:
429
+ logger.debug("going to save")
430
+ self.save_cache()
431
+ logger.debug("saved")
432
+ except OSError:
433
+ logger.debug("Cache saving failed while closing file")
434
+ except NameError:
435
+ logger.debug("Cache save failed due to interpreter shutdown")
436
+ close()
437
+ f.closed = True
438
+
439
+ def ls(self, path, detail=True, **kwargs):
440
+ return self.fs.ls(path, detail, **kwargs)
441
+
442
+ def __getattribute__(self, item):
443
+ if item in {
444
+ "load_cache",
445
+ "_get_cached_file_before_open",
446
+ "_open",
447
+ "save_cache",
448
+ "close_and_update",
449
+ "__init__",
450
+ "__getattribute__",
451
+ "__reduce__",
452
+ "_make_local_details",
453
+ "open",
454
+ "cat",
455
+ "cat_file",
456
+ "_cat_file",
457
+ "cat_ranges",
458
+ "_cat_ranges",
459
+ "get",
460
+ "read_block",
461
+ "tail",
462
+ "head",
463
+ "info",
464
+ "ls",
465
+ "exists",
466
+ "isfile",
467
+ "isdir",
468
+ "_check_file",
469
+ "_check_cache",
470
+ "_makedirs",
471
+ "_mkcache",
472
+ "clear_cache",
473
+ "clear_expired_cache",
474
+ "pop_from_cache",
475
+ "local_file",
476
+ "_paths_from_path",
477
+ "get_mapper",
478
+ "open_many",
479
+ "commit_many",
480
+ "hash_name",
481
+ "__hash__",
482
+ "__eq__",
483
+ "to_json",
484
+ "to_dict",
485
+ "cache_size",
486
+ "pipe_file",
487
+ "pipe",
488
+ "start_transaction",
489
+ "end_transaction",
490
+ }:
491
+ # all the methods defined in this class. Note `open` here, since
492
+ # it calls `_open`, but is actually in superclass
493
+ if hasattr(type(self), item):
494
+ return lambda *args, **kw: getattr(type(self), item).__get__(self)(
495
+ *args, **kw
496
+ )
497
+ # method is in the whitelist but not defined on this subclass;
498
+ # fall through to delegate to the wrapped filesystem below
499
+ if item in ["__reduce_ex__"]:
500
+ raise AttributeError
501
+ if item in ["transaction"]:
502
+ # property
503
+ return type(self).transaction.__get__(self)
504
+ if item in {"_cache", "transaction_type", "protocol"}:
505
+ # class attributes
506
+ return getattr(type(self), item)
507
+ if item == "__class__":
508
+ return type(self)
509
+ d = object.__getattribute__(self, "__dict__")
510
+ fs = d.get("fs", None) # fs is not immediately defined
511
+ if item in d:
512
+ return d[item]
513
+ elif fs is not None:
514
+ if item in fs.__dict__:
515
+ # attribute of instance
516
+ return fs.__dict__[item]
517
+ # attributed belonging to the target filesystem
518
+ cls = type(fs)
519
+ m = getattr(cls, item)
520
+ if (inspect.isfunction(m) or inspect.isdatadescriptor(m)) and (
521
+ not hasattr(m, "__self__") or m.__self__ is None
522
+ ):
523
+ # instance method
524
+ return m.__get__(fs, cls)
525
+ return m # class method or attribute
526
+ else:
527
+ # attributes of the superclass, while target is being set up
528
+ return super().__getattribute__(item)
529
+
530
+ def __eq__(self, other):
531
+ """Test for equality."""
532
+ if self is other:
533
+ return True
534
+ if not isinstance(other, type(self)):
535
+ return False
536
+ return (
537
+ self.storage == other.storage
538
+ and self.kwargs == other.kwargs
539
+ and self.cache_check == other.cache_check
540
+ and self.check_files == other.check_files
541
+ and self.expiry == other.expiry
542
+ and self.compression == other.compression
543
+ and self._mapper == other._mapper
544
+ and self.target_protocol == other.target_protocol
545
+ )
546
+
547
+ def __hash__(self):
548
+ """Calculate hash."""
549
+ return (
550
+ hash(tuple(self.storage))
551
+ ^ hash(str(self.kwargs))
552
+ ^ hash(self.cache_check)
553
+ ^ hash(self.check_files)
554
+ ^ hash(self.expiry)
555
+ ^ hash(self.compression)
556
+ ^ hash(self._mapper)
557
+ ^ hash(self.target_protocol)
558
+ )
559
+
560
+
561
+ class WholeFileCacheFileSystem(CachingFileSystem):
562
+ """Caches whole remote files on first access
563
+
564
+ This class is intended as a layer over any other file system, and
565
+ will make a local copy of each file accessed, so that all subsequent
566
+ reads are local. This is similar to ``CachingFileSystem``, but without
567
+ the block-wise functionality and so can work even when sparse files
568
+ are not allowed. See its docstring for definition of the init
569
+ arguments.
570
+
571
+ The class still needs access to the remote store for listing files,
572
+ and may refresh cached files.
573
+ """
574
+
575
+ protocol = "filecache"
576
+ local_file = True
577
+
578
+ def open_many(self, open_files, **kwargs):
579
+ paths = [of.path for of in open_files]
580
+ if "r" in open_files.mode:
581
+ self._mkcache()
582
+ else:
583
+ return [
584
+ LocalTempFile(
585
+ self.fs,
586
+ path,
587
+ mode=open_files.mode,
588
+ fn=os.path.join(self.storage[-1], self._mapper(path)),
589
+ **kwargs,
590
+ )
591
+ for path in paths
592
+ ]
593
+
594
+ if self.compression:
595
+ raise NotImplementedError
596
+ details = [self._check_file(sp) for sp in paths]
597
+ downpath = [p for p, d in zip(paths, details) if not d]
598
+ downfn0 = [
599
+ os.path.join(self.storage[-1], self._mapper(p))
600
+ for p, d in zip(paths, details)
601
+ ] # keep these path names for opening later
602
+ downfn = [fn for fn, d in zip(downfn0, details) if not d]
603
+ if downpath:
604
+ # skip if all files are already cached and up to date
605
+ self.fs.get(downpath, downfn)
606
+
607
+ # update metadata - only happens when downloads are successful
608
+ newdetail = [
609
+ {
610
+ "original": path,
611
+ "fn": self._mapper(path),
612
+ "blocks": True,
613
+ "time": time.time(),
614
+ "uid": self.fs.ukey(path),
615
+ }
616
+ for path in downpath
617
+ ]
618
+ for path, detail in zip(downpath, newdetail):
619
+ self._metadata.update_file(path, detail)
620
+ self.save_cache()
621
+
622
+ def firstpart(fn):
623
+ # helper to adapt both whole-file and simple-cache
624
+ return fn[1] if isinstance(fn, tuple) else fn
625
+
626
+ return [
627
+ open(firstpart(fn0) if fn0 else fn1, mode=open_files.mode)
628
+ for fn0, fn1 in zip(details, downfn0)
629
+ ]
630
+
631
+ def commit_many(self, open_files):
632
+ self.fs.put([f.fn for f in open_files], [f.path for f in open_files])
633
+ [f.close() for f in open_files]
634
+ for f in open_files:
635
+ # in case autocommit is off, and so close did not already delete
636
+ try:
637
+ os.remove(f.name)
638
+ except FileNotFoundError:
639
+ pass
640
+ self._cache_size = None
641
+
642
+ def _make_local_details(self, path):
643
+ hash = self._mapper(path)
644
+ fn = os.path.join(self.storage[-1], hash)
645
+ detail = {
646
+ "original": path,
647
+ "fn": hash,
648
+ "blocks": True,
649
+ "time": time.time(),
650
+ "uid": self.fs.ukey(path),
651
+ }
652
+ self._metadata.update_file(path, detail)
653
+ logger.debug("Copying %s to local cache", path)
654
+ return fn
655
+
656
+ def cat(
657
+ self,
658
+ path,
659
+ recursive=False,
660
+ on_error="raise",
661
+ callback=DEFAULT_CALLBACK,
662
+ **kwargs,
663
+ ):
664
+ paths = self.expand_path(
665
+ path, recursive=recursive, maxdepth=kwargs.get("maxdepth")
666
+ )
667
+ getpaths = []
668
+ storepaths = []
669
+ fns = []
670
+ out = {}
671
+ for p in paths.copy():
672
+ try:
673
+ detail = self._check_file(p)
674
+ if not detail:
675
+ fn = self._make_local_details(p)
676
+ getpaths.append(p)
677
+ storepaths.append(fn)
678
+ else:
679
+ detail, fn = detail if isinstance(detail, tuple) else (None, detail)
680
+ fns.append(fn)
681
+ except Exception as e:
682
+ if on_error == "raise":
683
+ raise
684
+ if on_error == "return":
685
+ out[p] = e
686
+ paths.remove(p)
687
+
688
+ if getpaths:
689
+ self.fs.get(getpaths, storepaths)
690
+ self.save_cache()
691
+
692
+ callback.set_size(len(paths))
693
+ for p, fn in zip(paths, fns):
694
+ with open(fn, "rb") as f:
695
+ out[p] = f.read()
696
+ callback.relative_update(1)
697
+ if isinstance(path, str) and len(paths) == 1 and recursive is False:
698
+ out = out[paths[0]]
699
+ return out
700
+
701
+ def _get_cached_file_before_open(self, path, **kwargs):
702
+ fn = self._make_local_details(path)
703
+ # call target filesystems open
704
+ self._mkcache()
705
+ if self.compression:
706
+ with self.fs._open(path, mode="rb", **kwargs) as f, open(fn, "wb") as f2:
707
+ if isinstance(f, AbstractBufferedFile):
708
+ # want no type of caching if just downloading whole thing
709
+ f.cache = BaseCache(0, f.cache.fetcher, f.size)
710
+ comp = (
711
+ infer_compression(path)
712
+ if self.compression == "infer"
713
+ else self.compression
714
+ )
715
+ f = compr[comp](f, mode="rb")
716
+ data = True
717
+ while data:
718
+ block = getattr(f, "blocksize", 5 * 2**20)
719
+ data = f.read(block)
720
+ f2.write(data)
721
+ else:
722
+ self.fs.get_file(path, fn)
723
+ self.save_cache()
724
+
725
+ def _open(self, path, mode="rb", **kwargs):
726
+ path = self._strip_protocol(path)
727
+ # For read (or append), (try) download from remote
728
+ if "r" in mode or "a" in mode:
729
+ if not self._check_file(path):
730
+ if self.fs.exists(path):
731
+ self._get_cached_file_before_open(path, **kwargs)
732
+ elif "r" in mode:
733
+ raise FileNotFoundError(path)
734
+
735
+ detail, fn = self._check_file(path)
736
+ _, blocks = detail["fn"], detail["blocks"]
737
+ if blocks is True:
738
+ logger.debug("Opening local copy of %s", path)
739
+ else:
740
+ raise ValueError(
741
+ f"Attempt to open partially cached file {path}"
742
+ f" as a wholly cached file"
743
+ )
744
+
745
+ # Just reading does not need special file handling
746
+ if "r" in mode and "+" not in mode:
747
+ # In order to support downstream filesystems to be able to
748
+ # infer the compression from the original filename, like
749
+ # the `TarFileSystem`, let's extend the `io.BufferedReader`
750
+ # fileobject protocol by adding a dedicated attribute
751
+ # `original`.
752
+ f = open(fn, mode)
753
+ f.original = detail.get("original")
754
+ return f
755
+
756
+ hash = self._mapper(path)
757
+ fn = os.path.join(self.storage[-1], hash)
758
+ user_specified_kwargs = {
759
+ k: v
760
+ for k, v in kwargs.items()
761
+ # those kwargs were added by open(), we don't want them
762
+ if k not in ["autocommit", "block_size", "cache_options"]
763
+ }
764
+ return LocalTempFile(self, path, mode=mode, fn=fn, **user_specified_kwargs)
765
+
766
+ async def _cat_file(self, path, start=None, end=None, **kwargs):
767
+ logger.debug("async cat_file %s", path)
768
+ path = self._strip_protocol(path)
769
+ sha = self._mapper(path)
770
+ fn = self._check_file(path)
771
+
772
+ if not fn:
773
+ fn = os.path.join(self.storage[-1], sha)
774
+ await self.fs._get_file(path, fn, **kwargs)
775
+
776
+ with open(fn, "rb") as f: # noqa ASYNC230
777
+ if start:
778
+ f.seek(start)
779
+ size = -1 if end is None else end - f.tell()
780
+ return f.read(size)
781
+
782
+ async def _cat_ranges(
783
+ self, paths, starts, ends, max_gap=None, on_error="return", **kwargs
784
+ ):
785
+ logger.debug("async cat ranges %s", paths)
786
+ lpaths = []
787
+ rset = set()
788
+ download = []
789
+ rpaths = []
790
+ for p in paths:
791
+ fn = self._check_file(p)
792
+ if fn is None and p not in rset:
793
+ sha = self._mapper(p)
794
+ fn = os.path.join(self.storage[-1], sha)
795
+ download.append(fn)
796
+ rset.add(p)
797
+ rpaths.append(p)
798
+ lpaths.append(fn)
799
+ if download:
800
+ await self.fs._get(rpaths, download, on_error=on_error)
801
+
802
+ return LocalFileSystem().cat_ranges(
803
+ lpaths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs
804
+ )
805
+
806
+
807
+ class SimpleCacheFileSystem(WholeFileCacheFileSystem):
808
+ """Caches whole remote files on first access
809
+
810
+ This class is intended as a layer over any other file system, and
811
+ will make a local copy of each file accessed, so that all subsequent
812
+ reads are local. This implementation only copies whole files, and
813
+ does not keep any metadata about the download time or file details.
814
+ It is therefore safer to use in multi-threaded/concurrent situations.
815
+
816
+ This is the only of the caching filesystems that supports write: you will
817
+ be given a real local open file, and upon close and commit, it will be
818
+ uploaded to the target filesystem; the writability or the target URL is
819
+ not checked until that time.
820
+
821
+ """
822
+
823
+ protocol = "simplecache"
824
+ local_file = True
825
+ transaction_type = WriteCachedTransaction
826
+
827
+ def __init__(self, **kwargs):
828
+ kw = kwargs.copy()
829
+ for key in ["cache_check", "expiry_time", "check_files"]:
830
+ kw[key] = False
831
+ super().__init__(**kw)
832
+ for storage in self.storage:
833
+ if not os.path.exists(storage):
834
+ self._makedirs(storage)
835
+
836
+ def _check_file(self, path):
837
+ self._check_cache()
838
+ sha = self._mapper(path)
839
+ for storage in self.storage:
840
+ fn = os.path.join(storage, sha)
841
+ if os.path.exists(fn):
842
+ return fn
843
+
844
+ def save_cache(self):
845
+ pass
846
+
847
+ def load_cache(self):
848
+ pass
849
+
850
+ def pipe_file(self, path, value=None, **kwargs):
851
+ if self._intrans:
852
+ with self.open(path, "wb") as f:
853
+ f.write(value)
854
+ else:
855
+ super().pipe_file(path, value)
856
+
857
+ def ls(self, path, detail=True, **kwargs):
858
+ path = self._strip_protocol(path)
859
+ details = []
860
+ try:
861
+ details = self.fs.ls(
862
+ path, detail=True, **kwargs
863
+ ).copy() # don't edit original!
864
+ except FileNotFoundError as e:
865
+ ex = e
866
+ else:
867
+ ex = None
868
+ if self._intrans:
869
+ path1 = path.rstrip("/") + "/"
870
+ for f in self.transaction.files:
871
+ if f.path == path:
872
+ details.append(
873
+ {"name": path, "size": f.size or f.tell(), "type": "file"}
874
+ )
875
+ elif f.path.startswith(path1):
876
+ if f.path.count("/") == path1.count("/"):
877
+ details.append(
878
+ {"name": f.path, "size": f.size or f.tell(), "type": "file"}
879
+ )
880
+ else:
881
+ dname = "/".join(f.path.split("/")[: path1.count("/") + 1])
882
+ details.append({"name": dname, "size": 0, "type": "directory"})
883
+ if ex is not None and not details:
884
+ raise ex
885
+ if detail:
886
+ return details
887
+ return sorted(_["name"] for _ in details)
888
+
889
+ def info(self, path, **kwargs):
890
+ path = self._strip_protocol(path)
891
+ if self._intrans:
892
+ f = [_ for _ in self.transaction.files if _.path == path]
893
+ if f:
894
+ size = os.path.getsize(f[0].fn) if f[0].closed else f[0].tell()
895
+ return {"name": path, "size": size, "type": "file"}
896
+ f = any(_.path.startswith(path + "/") for _ in self.transaction.files)
897
+ if f:
898
+ return {"name": path, "size": 0, "type": "directory"}
899
+ return self.fs.info(path, **kwargs)
900
+
901
+ def pipe(self, path, value=None, **kwargs):
902
+ if isinstance(path, str):
903
+ self.pipe_file(self._strip_protocol(path), value, **kwargs)
904
+ elif isinstance(path, dict):
905
+ for k, v in path.items():
906
+ self.pipe_file(self._strip_protocol(k), v, **kwargs)
907
+ else:
908
+ raise ValueError("path must be str or dict")
909
+
910
+ def cat_ranges(
911
+ self, paths, starts, ends, max_gap=None, on_error="return", **kwargs
912
+ ):
913
+ logger.debug("cat ranges %s", paths)
914
+ lpaths = [self._check_file(p) for p in paths]
915
+ rpaths = [p for l, p in zip(lpaths, paths) if l is False]
916
+ lpaths = [l for l, p in zip(lpaths, paths) if l is False]
917
+ self.fs.get(rpaths, lpaths)
918
+ paths = [self._check_file(p) for p in paths]
919
+ return LocalFileSystem().cat_ranges(
920
+ paths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs
921
+ )
922
+
923
+ def _get_cached_file_before_open(self, path, **kwargs):
924
+ sha = self._mapper(path)
925
+ fn = os.path.join(self.storage[-1], sha)
926
+ logger.debug("Copying %s to local cache", path)
927
+
928
+ self._mkcache()
929
+ self._cache_size = None
930
+
931
+ if self.compression:
932
+ with self.fs._open(path, mode="rb", **kwargs) as f, open(fn, "wb") as f2:
933
+ if isinstance(f, AbstractBufferedFile):
934
+ # want no type of caching if just downloading whole thing
935
+ f.cache = BaseCache(0, f.cache.fetcher, f.size)
936
+ comp = (
937
+ infer_compression(path)
938
+ if self.compression == "infer"
939
+ else self.compression
940
+ )
941
+ f = compr[comp](f, mode="rb")
942
+ data = True
943
+ while data:
944
+ block = getattr(f, "blocksize", 5 * 2**20)
945
+ data = f.read(block)
946
+ f2.write(data)
947
+ else:
948
+ self.fs.get_file(path, fn)
949
+
950
+ def _open(self, path, mode="rb", **kwargs):
951
+ path = self._strip_protocol(path)
952
+ sha = self._mapper(path)
953
+
954
+ # For read (or append), (try) download from remote
955
+ if "r" in mode or "a" in mode:
956
+ if not self._check_file(path):
957
+ # append does not require an existing file but read does
958
+ if self.fs.exists(path):
959
+ self._get_cached_file_before_open(path, **kwargs)
960
+ elif "r" in mode:
961
+ raise FileNotFoundError(path)
962
+
963
+ fn = self._check_file(path)
964
+ # Just reading does not need special file handling
965
+ if "r" in mode and "+" not in mode:
966
+ return open(fn, mode)
967
+
968
+ fn = os.path.join(self.storage[-1], sha)
969
+ user_specified_kwargs = {
970
+ k: v
971
+ for k, v in kwargs.items()
972
+ if k not in ["autocommit", "block_size", "cache_options"]
973
+ } # those were added by open()
974
+ return LocalTempFile(
975
+ self,
976
+ path,
977
+ mode=mode,
978
+ autocommit=not self._intrans,
979
+ fn=fn,
980
+ **user_specified_kwargs,
981
+ )
982
+
983
+
984
+ class LocalTempFile:
985
+ """A temporary local file, which will be uploaded on commit"""
986
+
987
+ def __init__(self, fs, path, fn, mode="wb", autocommit=True, seek=0, **kwargs):
988
+ self.fn = fn
989
+ self.fh = open(fn, mode)
990
+ self.mode = mode
991
+ if seek:
992
+ self.fh.seek(seek)
993
+ self.path = path
994
+ self.size = None
995
+ self.fs = fs
996
+ self.closed = False
997
+ self.autocommit = autocommit
998
+ self.kwargs = kwargs
999
+
1000
+ def __reduce__(self):
1001
+ # always open in r+b to allow continuing writing at a location
1002
+ return (
1003
+ LocalTempFile,
1004
+ (self.fs, self.path, self.fn, "r+b", self.autocommit, self.tell()),
1005
+ )
1006
+
1007
+ def __enter__(self):
1008
+ return self.fh
1009
+
1010
+ def __exit__(self, exc_type, exc_val, exc_tb):
1011
+ self.close()
1012
+
1013
+ def close(self):
1014
+ # self.size = self.fh.tell()
1015
+ if self.closed:
1016
+ return
1017
+ self.fh.close()
1018
+ self.closed = True
1019
+ if self.autocommit:
1020
+ self.commit()
1021
+
1022
+ def discard(self):
1023
+ self.fh.close()
1024
+ os.remove(self.fn)
1025
+
1026
+ def commit(self):
1027
+ # calling put() with list arguments avoids path expansion and additional operations
1028
+ # like isdir()
1029
+ self.fs.put([self.fn], [self.path], **self.kwargs)
1030
+ # we do not delete the local copy, it's still in the cache.
1031
+
1032
+ @property
1033
+ def name(self):
1034
+ return self.fn
1035
+
1036
+ def __repr__(self) -> str:
1037
+ return f"LocalTempFile: {self.path}"
1038
+
1039
+ def __getattr__(self, item):
1040
+ return getattr(self.fh, item)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/chained.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import ClassVar
2
+
3
+ from fsspec import AbstractFileSystem
4
+
5
+ __all__ = ("ChainedFileSystem",)
6
+
7
+
8
+ class ChainedFileSystem(AbstractFileSystem):
9
+ """Chained filesystem base class.
10
+
11
+ A chained filesystem is designed to be layered over another FS.
12
+ This is useful to implement things like caching.
13
+
14
+ This base class does very little on its own, but is used as a marker
15
+ that the class is designed for chaining.
16
+
17
+ Right now this is only used in `url_to_fs` to provide the path argument
18
+ (`fo`) to the chained filesystem from the underlying filesystem.
19
+
20
+ Additional functionality may be added in the future.
21
+ """
22
+
23
+ protocol: ClassVar[str] = "chained"
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/dask.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dask
2
+ from distributed.client import Client, _get_global_client
3
+ from distributed.worker import Worker
4
+
5
+ from fsspec import filesystem
6
+ from fsspec.spec import AbstractBufferedFile, AbstractFileSystem
7
+ from fsspec.utils import infer_storage_options
8
+
9
+
10
+ def _get_client(client):
11
+ if client is None:
12
+ return _get_global_client()
13
+ elif isinstance(client, Client):
14
+ return client
15
+ else:
16
+ # e.g., connection string
17
+ return Client(client)
18
+
19
+
20
+ def _in_worker():
21
+ return bool(Worker._instances)
22
+
23
+
24
+ class DaskWorkerFileSystem(AbstractFileSystem):
25
+ """View files accessible to a worker as any other remote file-system
26
+
27
+ When instances are run on the worker, uses the real filesystem. When
28
+ run on the client, they call the worker to provide information or data.
29
+
30
+ **Warning** this implementation is experimental, and read-only for now.
31
+ """
32
+
33
+ def __init__(
34
+ self, target_protocol=None, target_options=None, fs=None, client=None, **kwargs
35
+ ):
36
+ super().__init__(**kwargs)
37
+ if not (fs is None) ^ (target_protocol is None):
38
+ raise ValueError(
39
+ "Please provide one of filesystem instance (fs) or"
40
+ " target_protocol, not both"
41
+ )
42
+ self.target_protocol = target_protocol
43
+ self.target_options = target_options
44
+ self.worker = None
45
+ self.client = client
46
+ self.fs = fs
47
+ self._determine_worker()
48
+
49
+ @staticmethod
50
+ def _get_kwargs_from_urls(path):
51
+ so = infer_storage_options(path)
52
+ if "host" in so and "port" in so:
53
+ return {"client": f"{so['host']}:{so['port']}"}
54
+ else:
55
+ return {}
56
+
57
+ def _determine_worker(self):
58
+ if _in_worker():
59
+ self.worker = True
60
+ if self.fs is None:
61
+ self.fs = filesystem(
62
+ self.target_protocol, **(self.target_options or {})
63
+ )
64
+ else:
65
+ self.worker = False
66
+ self.client = _get_client(self.client)
67
+ self.rfs = dask.delayed(self)
68
+
69
+ def mkdir(self, *args, **kwargs):
70
+ if self.worker:
71
+ self.fs.mkdir(*args, **kwargs)
72
+ else:
73
+ self.rfs.mkdir(*args, **kwargs).compute()
74
+
75
+ def rm(self, *args, **kwargs):
76
+ if self.worker:
77
+ self.fs.rm(*args, **kwargs)
78
+ else:
79
+ self.rfs.rm(*args, **kwargs).compute()
80
+
81
+ def copy(self, *args, **kwargs):
82
+ if self.worker:
83
+ self.fs.copy(*args, **kwargs)
84
+ else:
85
+ self.rfs.copy(*args, **kwargs).compute()
86
+
87
+ def mv(self, *args, **kwargs):
88
+ if self.worker:
89
+ self.fs.mv(*args, **kwargs)
90
+ else:
91
+ self.rfs.mv(*args, **kwargs).compute()
92
+
93
+ def ls(self, *args, **kwargs):
94
+ if self.worker:
95
+ return self.fs.ls(*args, **kwargs)
96
+ else:
97
+ return self.rfs.ls(*args, **kwargs).compute()
98
+
99
+ def _open(
100
+ self,
101
+ path,
102
+ mode="rb",
103
+ block_size=None,
104
+ autocommit=True,
105
+ cache_options=None,
106
+ **kwargs,
107
+ ):
108
+ if self.worker:
109
+ return self.fs._open(
110
+ path,
111
+ mode=mode,
112
+ block_size=block_size,
113
+ autocommit=autocommit,
114
+ cache_options=cache_options,
115
+ **kwargs,
116
+ )
117
+ else:
118
+ return DaskFile(
119
+ fs=self,
120
+ path=path,
121
+ mode=mode,
122
+ block_size=block_size,
123
+ autocommit=autocommit,
124
+ cache_options=cache_options,
125
+ **kwargs,
126
+ )
127
+
128
+ def fetch_range(self, path, mode, start, end):
129
+ if self.worker:
130
+ with self._open(path, mode) as f:
131
+ f.seek(start)
132
+ return f.read(end - start)
133
+ else:
134
+ return self.rfs.fetch_range(path, mode, start, end).compute()
135
+
136
+
137
+ class DaskFile(AbstractBufferedFile):
138
+ def __init__(self, mode="rb", **kwargs):
139
+ if mode != "rb":
140
+ raise ValueError('Remote dask files can only be opened in "rb" mode')
141
+ super().__init__(**kwargs)
142
+
143
+ def _upload_chunk(self, final=False):
144
+ pass
145
+
146
+ def _initiate_upload(self):
147
+ """Create remote file/upload"""
148
+ pass
149
+
150
+ def _fetch_range(self, start, end):
151
+ """Get the specified set of bytes from remote"""
152
+ return self.fs.fetch_range(self.path, self.mode, start, end)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/data.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import io
3
+ from urllib.parse import unquote
4
+
5
+ from fsspec import AbstractFileSystem
6
+ from fsspec.utils import stringify_path
7
+
8
+
9
+ class DataFileSystem(AbstractFileSystem):
10
+ """A handy decoder for data-URLs
11
+
12
+ Example
13
+ -------
14
+ >>> with fsspec.open("data:,Hello%2C%20World%21") as f:
15
+ ... print(f.read())
16
+ b"Hello, World!"
17
+
18
+ See https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs
19
+ """
20
+
21
+ protocol = "data"
22
+
23
+ def __init__(self, **kwargs):
24
+ """No parameters for this filesystem"""
25
+ super().__init__(**kwargs)
26
+
27
+ @classmethod
28
+ def _strip_protocol(cls, path):
29
+ if isinstance(path, list):
30
+ return [cls._strip_protocol(p) for p in path]
31
+ path = stringify_path(path)
32
+ if path.startswith("data://"):
33
+ path = path[7:]
34
+ elif path.startswith("data:"):
35
+ path = path[5:]
36
+ # Do NOT strip trailing slashes, as they may be meaningful base64 characters
37
+ # or percent-encoded data content
38
+ return path
39
+
40
+ def cat_file(self, path, start=None, end=None, **kwargs):
41
+ pref, data = path.split(",", 1)
42
+ if pref.endswith("base64"):
43
+ return base64.b64decode(data)[start:end]
44
+ return unquote(data).encode()[start:end]
45
+
46
+ def info(self, path, **kwargs):
47
+ pref, name = path.split(",", 1)
48
+ data = self.cat_file(path)
49
+ mime = pref.split(":", 1)[1].split(";", 1)[0]
50
+ return {"name": name, "size": len(data), "type": "file", "mimetype": mime}
51
+
52
+ def _open(
53
+ self,
54
+ path,
55
+ mode="rb",
56
+ block_size=None,
57
+ autocommit=True,
58
+ cache_options=None,
59
+ **kwargs,
60
+ ):
61
+ if "r" not in mode:
62
+ raise ValueError("Read only filesystem")
63
+ return io.BytesIO(self.cat_file(path))
64
+
65
+ @staticmethod
66
+ def encode(data: bytes, mime: str | None = None):
67
+ """Format the given data into data-URL syntax
68
+
69
+ This version always base64 encodes, even when the data is ascii/url-safe.
70
+ """
71
+ return f"data:{mime or ''};base64,{base64.b64encode(data).decode()}"
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/dbfs.py ADDED
@@ -0,0 +1,497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import urllib
5
+
6
+ import requests
7
+ from requests.adapters import HTTPAdapter, Retry
8
+ from typing_extensions import override
9
+
10
+ from fsspec import AbstractFileSystem
11
+ from fsspec.spec import AbstractBufferedFile
12
+
13
+
14
+ class DatabricksException(Exception):
15
+ """
16
+ Helper class for exceptions raised in this module.
17
+ """
18
+
19
+ def __init__(self, error_code, message, details=None):
20
+ """Create a new DatabricksException"""
21
+ super().__init__(message)
22
+
23
+ self.error_code = error_code
24
+ self.message = message
25
+ self.details = details
26
+
27
+
28
+ class DatabricksFileSystem(AbstractFileSystem):
29
+ """
30
+ Get access to the Databricks filesystem implementation over HTTP.
31
+ Can be used inside and outside of a databricks cluster.
32
+ """
33
+
34
+ def __init__(self, instance, token, **kwargs):
35
+ """
36
+ Create a new DatabricksFileSystem.
37
+
38
+ Parameters
39
+ ----------
40
+ instance: str
41
+ The instance URL of the databricks cluster.
42
+ For example for an Azure databricks cluster, this
43
+ has the form adb-<some-number>.<two digits>.azuredatabricks.net.
44
+ token: str
45
+ Your personal token. Find out more
46
+ here: https://docs.databricks.com/dev-tools/api/latest/authentication.html
47
+ """
48
+ self.instance = instance
49
+ self.token = token
50
+ self.session = requests.Session()
51
+ self.retries = Retry(
52
+ total=10,
53
+ backoff_factor=0.05,
54
+ status_forcelist=[408, 429, 500, 502, 503, 504],
55
+ )
56
+
57
+ self.session.mount("https://", HTTPAdapter(max_retries=self.retries))
58
+ self.session.headers.update({"Authorization": f"Bearer {self.token}"})
59
+
60
+ super().__init__(**kwargs)
61
+
62
+ @override
63
+ def _ls_from_cache(self, path) -> list[dict[str, str | int]] | None:
64
+ """Check cache for listing
65
+
66
+ Returns listing, if found (may be empty list for a directory that
67
+ exists but contains nothing), None if not in cache.
68
+ """
69
+ self.dircache.pop(path.rstrip("/"), None)
70
+
71
+ parent = self._parent(path)
72
+ if parent in self.dircache:
73
+ for entry in self.dircache[parent]:
74
+ if entry["name"] == path.rstrip("/"):
75
+ if entry["type"] != "directory":
76
+ return [entry]
77
+ return []
78
+ raise FileNotFoundError(path)
79
+
80
+ def ls(self, path, detail=True, **kwargs):
81
+ """
82
+ List the contents of the given path.
83
+
84
+ Parameters
85
+ ----------
86
+ path: str
87
+ Absolute path
88
+ detail: bool
89
+ Return not only the list of filenames,
90
+ but also additional information on file sizes
91
+ and types.
92
+ """
93
+ try:
94
+ out = self._ls_from_cache(path)
95
+ except FileNotFoundError:
96
+ # This happens if the `path`'s parent was cached, but `path` is not
97
+ # there. This suggests that `path` is new since the parent was
98
+ # cached. Attempt to invalidate parent's cache before continuing.
99
+ self.dircache.pop(self._parent(path), None)
100
+ out = None
101
+
102
+ if not out:
103
+ try:
104
+ r = self._send_to_api(
105
+ method="get", endpoint="list", json={"path": path}
106
+ )
107
+ except DatabricksException as e:
108
+ if e.error_code == "RESOURCE_DOES_NOT_EXIST":
109
+ raise FileNotFoundError(e.message) from e
110
+
111
+ raise
112
+ files = r.get("files", [])
113
+ out = [
114
+ {
115
+ "name": o["path"],
116
+ "type": "directory" if o["is_dir"] else "file",
117
+ "size": o["file_size"],
118
+ }
119
+ for o in files
120
+ ]
121
+ self.dircache[path] = out
122
+
123
+ if detail:
124
+ return out
125
+ return [o["name"] for o in out]
126
+
127
+ def makedirs(self, path, exist_ok=True):
128
+ """
129
+ Create a given absolute path and all of its parents.
130
+
131
+ Parameters
132
+ ----------
133
+ path: str
134
+ Absolute path to create
135
+ exist_ok: bool
136
+ If false, checks if the folder
137
+ exists before creating it (and raises an
138
+ Exception if this is the case)
139
+ """
140
+ if not exist_ok:
141
+ try:
142
+ # If the following succeeds, the path is already present
143
+ self._send_to_api(
144
+ method="get", endpoint="get-status", json={"path": path}
145
+ )
146
+ raise FileExistsError(f"Path {path} already exists")
147
+ except DatabricksException as e:
148
+ if e.error_code == "RESOURCE_DOES_NOT_EXIST":
149
+ pass
150
+
151
+ try:
152
+ self._send_to_api(method="post", endpoint="mkdirs", json={"path": path})
153
+ except DatabricksException as e:
154
+ if e.error_code == "RESOURCE_ALREADY_EXISTS":
155
+ raise FileExistsError(e.message) from e
156
+
157
+ raise
158
+ self.invalidate_cache(self._parent(path))
159
+
160
+ def mkdir(self, path, create_parents=True, **kwargs):
161
+ """
162
+ Create a given absolute path and all of its parents.
163
+
164
+ Parameters
165
+ ----------
166
+ path: str
167
+ Absolute path to create
168
+ create_parents: bool
169
+ Whether to create all parents or not.
170
+ "False" is not implemented so far.
171
+ """
172
+ if not create_parents:
173
+ raise NotImplementedError
174
+
175
+ self.mkdirs(path, **kwargs)
176
+
177
+ def rm(self, path, recursive=False, **kwargs):
178
+ """
179
+ Remove the file or folder at the given absolute path.
180
+
181
+ Parameters
182
+ ----------
183
+ path: str
184
+ Absolute path what to remove
185
+ recursive: bool
186
+ Recursively delete all files in a folder.
187
+ """
188
+ try:
189
+ self._send_to_api(
190
+ method="post",
191
+ endpoint="delete",
192
+ json={"path": path, "recursive": recursive},
193
+ )
194
+ except DatabricksException as e:
195
+ # This is not really an exception, it just means
196
+ # not everything was deleted so far
197
+ if e.error_code == "PARTIAL_DELETE":
198
+ self.rm(path=path, recursive=recursive)
199
+ elif e.error_code == "IO_ERROR":
200
+ # Using the same exception as the os module would use here
201
+ raise OSError(e.message) from e
202
+
203
+ raise
204
+ self.invalidate_cache(self._parent(path))
205
+
206
+ def mv(
207
+ self, source_path, destination_path, recursive=False, maxdepth=None, **kwargs
208
+ ):
209
+ """
210
+ Move a source to a destination path.
211
+
212
+ A note from the original [databricks API manual]
213
+ (https://docs.databricks.com/dev-tools/api/latest/dbfs.html#move).
214
+
215
+ When moving a large number of files the API call will time out after
216
+ approximately 60s, potentially resulting in partially moved data.
217
+ Therefore, for operations that move more than 10k files, we strongly
218
+ discourage using the DBFS REST API.
219
+
220
+ Parameters
221
+ ----------
222
+ source_path: str
223
+ From where to move (absolute path)
224
+ destination_path: str
225
+ To where to move (absolute path)
226
+ recursive: bool
227
+ Not implemented to far.
228
+ maxdepth:
229
+ Not implemented to far.
230
+ """
231
+ if recursive:
232
+ raise NotImplementedError
233
+ if maxdepth:
234
+ raise NotImplementedError
235
+
236
+ try:
237
+ self._send_to_api(
238
+ method="post",
239
+ endpoint="move",
240
+ json={"source_path": source_path, "destination_path": destination_path},
241
+ )
242
+ except DatabricksException as e:
243
+ if e.error_code == "RESOURCE_DOES_NOT_EXIST":
244
+ raise FileNotFoundError(e.message) from e
245
+ elif e.error_code == "RESOURCE_ALREADY_EXISTS":
246
+ raise FileExistsError(e.message) from e
247
+
248
+ raise
249
+ self.invalidate_cache(self._parent(source_path))
250
+ self.invalidate_cache(self._parent(destination_path))
251
+
252
+ def _open(self, path, mode="rb", block_size="default", **kwargs):
253
+ """
254
+ Overwrite the base class method to make sure to create a DBFile.
255
+ All arguments are copied from the base method.
256
+
257
+ Only the default blocksize is allowed.
258
+ """
259
+ return DatabricksFile(self, path, mode=mode, block_size=block_size, **kwargs)
260
+
261
+ def _send_to_api(self, method, endpoint, json):
262
+ """
263
+ Send the given json to the DBFS API
264
+ using a get or post request (specified by the argument `method`).
265
+
266
+ Parameters
267
+ ----------
268
+ method: str
269
+ Which http method to use for communication; "get" or "post".
270
+ endpoint: str
271
+ Where to send the request to (last part of the API URL)
272
+ json: dict
273
+ Dictionary of information to send
274
+ """
275
+ if method == "post":
276
+ session_call = self.session.post
277
+ elif method == "get":
278
+ session_call = self.session.get
279
+ else:
280
+ raise ValueError(f"Do not understand method {method}")
281
+
282
+ url = urllib.parse.urljoin(f"https://{self.instance}/api/2.0/dbfs/", endpoint)
283
+
284
+ r = session_call(url, json=json)
285
+
286
+ # The DBFS API will return a json, also in case of an exception.
287
+ # We want to preserve this information as good as possible.
288
+ try:
289
+ r.raise_for_status()
290
+ except requests.HTTPError as e:
291
+ # try to extract json error message
292
+ # if that fails, fall back to the original exception
293
+ try:
294
+ exception_json = e.response.json()
295
+ except Exception:
296
+ raise e from None
297
+
298
+ raise DatabricksException(**exception_json) from e
299
+
300
+ return r.json()
301
+
302
+ def _create_handle(self, path, overwrite=True):
303
+ """
304
+ Internal function to create a handle, which can be used to
305
+ write blocks of a file to DBFS.
306
+ A handle has a unique identifier which needs to be passed
307
+ whenever written during this transaction.
308
+ The handle is active for 10 minutes - after that a new
309
+ write transaction needs to be created.
310
+ Make sure to close the handle after you are finished.
311
+
312
+ Parameters
313
+ ----------
314
+ path: str
315
+ Absolute path for this file.
316
+ overwrite: bool
317
+ If a file already exist at this location, either overwrite
318
+ it or raise an exception.
319
+ """
320
+ try:
321
+ r = self._send_to_api(
322
+ method="post",
323
+ endpoint="create",
324
+ json={"path": path, "overwrite": overwrite},
325
+ )
326
+ return r["handle"]
327
+ except DatabricksException as e:
328
+ if e.error_code == "RESOURCE_ALREADY_EXISTS":
329
+ raise FileExistsError(e.message) from e
330
+
331
+ raise
332
+
333
+ def _close_handle(self, handle):
334
+ """
335
+ Close a handle, which was opened by :func:`_create_handle`.
336
+
337
+ Parameters
338
+ ----------
339
+ handle: str
340
+ Which handle to close.
341
+ """
342
+ try:
343
+ self._send_to_api(method="post", endpoint="close", json={"handle": handle})
344
+ except DatabricksException as e:
345
+ if e.error_code == "RESOURCE_DOES_NOT_EXIST":
346
+ raise FileNotFoundError(e.message) from e
347
+
348
+ raise
349
+
350
+ def _add_data(self, handle, data):
351
+ """
352
+ Upload data to an already opened file handle
353
+ (opened by :func:`_create_handle`).
354
+ The maximal allowed data size is 1MB after
355
+ conversion to base64.
356
+ Remember to close the handle when you are finished.
357
+
358
+ Parameters
359
+ ----------
360
+ handle: str
361
+ Which handle to upload data to.
362
+ data: bytes
363
+ Block of data to add to the handle.
364
+ """
365
+ data = base64.b64encode(data).decode()
366
+ try:
367
+ self._send_to_api(
368
+ method="post",
369
+ endpoint="add-block",
370
+ json={"handle": handle, "data": data},
371
+ )
372
+ except DatabricksException as e:
373
+ if e.error_code == "RESOURCE_DOES_NOT_EXIST":
374
+ raise FileNotFoundError(e.message) from e
375
+ elif e.error_code == "MAX_BLOCK_SIZE_EXCEEDED":
376
+ raise ValueError(e.message) from e
377
+
378
+ raise
379
+
380
+ def _get_data(self, path, start, end):
381
+ """
382
+ Download data in bytes from a given absolute path in a block
383
+ from [start, start+length].
384
+ The maximum number of allowed bytes to read is 1MB.
385
+
386
+ Parameters
387
+ ----------
388
+ path: str
389
+ Absolute path to download data from
390
+ start: int
391
+ Start position of the block
392
+ end: int
393
+ End position of the block
394
+ """
395
+ try:
396
+ r = self._send_to_api(
397
+ method="get",
398
+ endpoint="read",
399
+ json={"path": path, "offset": start, "length": end - start},
400
+ )
401
+ return base64.b64decode(r["data"])
402
+ except DatabricksException as e:
403
+ if e.error_code == "RESOURCE_DOES_NOT_EXIST":
404
+ raise FileNotFoundError(e.message) from e
405
+ elif e.error_code in ["INVALID_PARAMETER_VALUE", "MAX_READ_SIZE_EXCEEDED"]:
406
+ raise ValueError(e.message) from e
407
+
408
+ raise
409
+
410
+ def invalidate_cache(self, path=None):
411
+ if path is None:
412
+ self.dircache.clear()
413
+ else:
414
+ self.dircache.pop(path, None)
415
+ super().invalidate_cache(path)
416
+
417
+
418
+ class DatabricksFile(AbstractBufferedFile):
419
+ """
420
+ Helper class for files referenced in the DatabricksFileSystem.
421
+ """
422
+
423
+ DEFAULT_BLOCK_SIZE = 1 * 2**20 # only allowed block size
424
+
425
+ def __init__(
426
+ self,
427
+ fs,
428
+ path,
429
+ mode="rb",
430
+ block_size="default",
431
+ autocommit=True,
432
+ cache_type="readahead",
433
+ cache_options=None,
434
+ **kwargs,
435
+ ):
436
+ """
437
+ Create a new instance of the DatabricksFile.
438
+
439
+ The blocksize needs to be the default one.
440
+ """
441
+ if block_size is None or block_size == "default":
442
+ block_size = self.DEFAULT_BLOCK_SIZE
443
+
444
+ if block_size != self.DEFAULT_BLOCK_SIZE:
445
+ raise ValueError(
446
+ f"Only the default block size is allowed, not {block_size}"
447
+ )
448
+
449
+ super().__init__(
450
+ fs,
451
+ path,
452
+ mode=mode,
453
+ block_size=block_size,
454
+ autocommit=autocommit,
455
+ cache_type=cache_type,
456
+ cache_options=cache_options or {},
457
+ **kwargs,
458
+ )
459
+
460
+ def _initiate_upload(self):
461
+ """Internal function to start a file upload"""
462
+ self.handle = self.fs._create_handle(self.path)
463
+
464
+ def _upload_chunk(self, final=False):
465
+ """Internal function to add a chunk of data to a started upload"""
466
+ self.buffer.seek(0)
467
+ data = self.buffer.getvalue()
468
+
469
+ data_chunks = [
470
+ data[start:end] for start, end in self._to_sized_blocks(len(data))
471
+ ]
472
+
473
+ for data_chunk in data_chunks:
474
+ self.fs._add_data(handle=self.handle, data=data_chunk)
475
+
476
+ if final:
477
+ self.fs._close_handle(handle=self.handle)
478
+ return True
479
+
480
+ def _fetch_range(self, start, end):
481
+ """Internal function to download a block of data"""
482
+ return_buffer = b""
483
+ length = end - start
484
+ for chunk_start, chunk_end in self._to_sized_blocks(length, start):
485
+ return_buffer += self.fs._get_data(
486
+ path=self.path, start=chunk_start, end=chunk_end
487
+ )
488
+
489
+ return return_buffer
490
+
491
+ def _to_sized_blocks(self, length, start=0):
492
+ """Helper function to split a range from 0 to total_length into blocksizes"""
493
+ end = start + length
494
+ for data_chunk in range(start, end, self.blocksize):
495
+ data_start = data_chunk
496
+ data_end = min(end, data_chunk + self.blocksize)
497
+ yield data_start, data_end
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/dirfs.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .. import filesystem
2
+ from ..asyn import AsyncFileSystem
3
+ from .chained import ChainedFileSystem
4
+ from .local import LocalFileSystem
5
+
6
+
7
+ def _escapes_root(path):
8
+ """Whether a relative path would resolve above its root via ".." segments."""
9
+ depth = 0
10
+ for part in path.split("/"):
11
+ if part == "..":
12
+ depth -= 1
13
+ if depth < 0:
14
+ return True
15
+ elif part and part != ".":
16
+ depth += 1
17
+ return False
18
+
19
+
20
+ class DirFileSystem(AsyncFileSystem, ChainedFileSystem):
21
+ """Directory prefix filesystem
22
+
23
+ The DirFileSystem is a filesystem-wrapper. It assumes every path it is dealing with
24
+ is relative to the `path`. After performing the necessary paths operation it
25
+ delegates everything to the wrapped filesystem.
26
+ """
27
+
28
+ protocol = "dir"
29
+
30
+ def __init__(
31
+ self,
32
+ path=None,
33
+ fs=None,
34
+ fo=None,
35
+ target_protocol=None,
36
+ target_options=None,
37
+ **storage_options,
38
+ ):
39
+ """
40
+ Parameters
41
+ ----------
42
+ path: str
43
+ Path to the directory.
44
+ fs: AbstractFileSystem
45
+ An instantiated filesystem to wrap.
46
+ target_protocol, target_options:
47
+ if fs is none, construct it from these
48
+ fo: str
49
+ Alternate for path; do not provide both
50
+ """
51
+ super().__init__(**storage_options)
52
+ if fs is None:
53
+ fs = filesystem(protocol=target_protocol, **(target_options or {}))
54
+ path = path or fo
55
+
56
+ if self.asynchronous and not fs.async_impl:
57
+ raise ValueError("can't use asynchronous with non-async fs")
58
+
59
+ if fs.async_impl and self.asynchronous != fs.asynchronous:
60
+ raise ValueError("both dirfs and fs should be in the same sync/async mode")
61
+
62
+ self.path = fs._strip_protocol(path)
63
+ self.fs = fs
64
+
65
+ def _join(self, path):
66
+ if isinstance(path, str):
67
+ if not self.path:
68
+ return path
69
+ if not path:
70
+ return self.path
71
+ path = self._strip_protocol(path)
72
+ # ".." only navigates above the root on filesystems that resolve it
73
+ # against a real directory tree; on object stores it is a literal
74
+ # path part, so only guard the local case here.
75
+ if isinstance(self.fs, LocalFileSystem) and _escapes_root(path):
76
+ raise ValueError(
77
+ f"path {path!r} escapes the {self.path!r} root of the filesystem"
78
+ )
79
+ return self.fs.sep.join((self.path, path))
80
+ if isinstance(path, dict):
81
+ return {self._join(_path): value for _path, value in path.items()}
82
+ return [self._join(_path) for _path in path]
83
+
84
+ def _relpath(self, path):
85
+ if isinstance(path, str):
86
+ if not self.path:
87
+ return path
88
+ # We need to account for S3FileSystem returning paths that do not
89
+ # start with a '/'
90
+ if path == self.path or (
91
+ self.path.startswith(self.fs.sep) and path == self.path[1:]
92
+ ):
93
+ return ""
94
+ prefix = self.path + self.fs.sep
95
+ if self.path.startswith(self.fs.sep) and not path.startswith(self.fs.sep):
96
+ prefix = prefix[1:]
97
+ assert path.startswith(prefix)
98
+ return path[len(prefix) :]
99
+ return [self._relpath(_path) for _path in path]
100
+
101
+ # Wrappers below
102
+
103
+ @property
104
+ def sep(self):
105
+ return self.fs.sep
106
+
107
+ async def set_session(self, *args, **kwargs):
108
+ return await self.fs.set_session(*args, **kwargs)
109
+
110
+ async def _rm_file(self, path, **kwargs):
111
+ return await self.fs._rm_file(self._join(path), **kwargs)
112
+
113
+ def rm_file(self, path, **kwargs):
114
+ return self.fs.rm_file(self._join(path), **kwargs)
115
+
116
+ async def _rm(self, path, *args, **kwargs):
117
+ return await self.fs._rm(self._join(path), *args, **kwargs)
118
+
119
+ def rm(self, path, *args, **kwargs):
120
+ return self.fs.rm(self._join(path), *args, **kwargs)
121
+
122
+ def delete(self, path, recursive=False, maxdepth=None):
123
+ return self.fs.delete(self._join(path), recursive=recursive, maxdepth=maxdepth)
124
+
125
+ async def _cp_file(self, path1, path2, **kwargs):
126
+ return await self.fs._cp_file(self._join(path1), self._join(path2), **kwargs)
127
+
128
+ def cp_file(self, path1, path2, **kwargs):
129
+ return self.fs.cp_file(self._join(path1), self._join(path2), **kwargs)
130
+
131
+ async def _copy(
132
+ self,
133
+ path1,
134
+ path2,
135
+ *args,
136
+ **kwargs,
137
+ ):
138
+ return await self.fs._copy(
139
+ self._join(path1),
140
+ self._join(path2),
141
+ *args,
142
+ **kwargs,
143
+ )
144
+
145
+ def copy(self, path1, path2, *args, **kwargs):
146
+ return self.fs.copy(
147
+ self._join(path1),
148
+ self._join(path2),
149
+ *args,
150
+ **kwargs,
151
+ )
152
+
153
+ async def _pipe(self, path, *args, **kwargs):
154
+ return await self.fs._pipe(self._join(path), *args, **kwargs)
155
+
156
+ def pipe(self, path, *args, **kwargs):
157
+ return self.fs.pipe(self._join(path), *args, **kwargs)
158
+
159
+ async def _pipe_file(self, path, *args, **kwargs):
160
+ return await self.fs._pipe_file(self._join(path), *args, **kwargs)
161
+
162
+ def pipe_file(self, path, *args, **kwargs):
163
+ return self.fs.pipe_file(self._join(path), *args, **kwargs)
164
+
165
+ def write_text(
166
+ self, path, value, encoding=None, errors=None, newline=None, **kwargs
167
+ ):
168
+ return self.fs.write_text(
169
+ self._join(path),
170
+ value,
171
+ encoding=encoding,
172
+ errors=errors,
173
+ newline=newline,
174
+ **kwargs,
175
+ )
176
+
177
+ async def _cat_file(self, path, *args, **kwargs):
178
+ return await self.fs._cat_file(self._join(path), *args, **kwargs)
179
+
180
+ def cat_file(self, path, *args, **kwargs):
181
+ return self.fs.cat_file(self._join(path), *args, **kwargs)
182
+
183
+ async def _cat(self, path, *args, **kwargs):
184
+ ret = await self.fs._cat(
185
+ self._join(path),
186
+ *args,
187
+ **kwargs,
188
+ )
189
+
190
+ if isinstance(ret, dict):
191
+ return {self._relpath(key): value for key, value in ret.items()}
192
+
193
+ return ret
194
+
195
+ def cat(self, path, *args, **kwargs):
196
+ ret = self.fs.cat(
197
+ self._join(path),
198
+ *args,
199
+ **kwargs,
200
+ )
201
+
202
+ if isinstance(ret, dict):
203
+ return {self._relpath(key): value for key, value in ret.items()}
204
+
205
+ return ret
206
+
207
+ async def _put_file(self, lpath, rpath, **kwargs):
208
+ return await self.fs._put_file(lpath, self._join(rpath), **kwargs)
209
+
210
+ def put_file(self, lpath, rpath, **kwargs):
211
+ return self.fs.put_file(lpath, self._join(rpath), **kwargs)
212
+
213
+ async def _put(
214
+ self,
215
+ lpath,
216
+ rpath,
217
+ *args,
218
+ **kwargs,
219
+ ):
220
+ return await self.fs._put(
221
+ lpath,
222
+ self._join(rpath),
223
+ *args,
224
+ **kwargs,
225
+ )
226
+
227
+ def put(self, lpath, rpath, *args, **kwargs):
228
+ return self.fs.put(
229
+ lpath,
230
+ self._join(rpath),
231
+ *args,
232
+ **kwargs,
233
+ )
234
+
235
+ async def _get_file(self, rpath, lpath, **kwargs):
236
+ return await self.fs._get_file(self._join(rpath), lpath, **kwargs)
237
+
238
+ def get_file(self, rpath, lpath, **kwargs):
239
+ return self.fs.get_file(self._join(rpath), lpath, **kwargs)
240
+
241
+ async def _get(self, rpath, *args, **kwargs):
242
+ return await self.fs._get(self._join(rpath), *args, **kwargs)
243
+
244
+ def get(self, rpath, *args, **kwargs):
245
+ return self.fs.get(self._join(rpath), *args, **kwargs)
246
+
247
+ async def _isfile(self, path):
248
+ return await self.fs._isfile(self._join(path))
249
+
250
+ def isfile(self, path):
251
+ return self.fs.isfile(self._join(path))
252
+
253
+ async def _isdir(self, path):
254
+ return await self.fs._isdir(self._join(path))
255
+
256
+ def isdir(self, path):
257
+ return self.fs.isdir(self._join(path))
258
+
259
+ async def _size(self, path):
260
+ return await self.fs._size(self._join(path))
261
+
262
+ def size(self, path):
263
+ return self.fs.size(self._join(path))
264
+
265
+ async def _exists(self, path):
266
+ return await self.fs._exists(self._join(path))
267
+
268
+ def exists(self, path):
269
+ return self.fs.exists(self._join(path))
270
+
271
+ async def _info(self, path, **kwargs):
272
+ info = await self.fs._info(self._join(path), **kwargs)
273
+ info = info.copy()
274
+ info["name"] = self._relpath(info["name"])
275
+ return info
276
+
277
+ def info(self, path, **kwargs):
278
+ info = self.fs.info(self._join(path), **kwargs)
279
+ info = info.copy()
280
+ info["name"] = self._relpath(info["name"])
281
+ return info
282
+
283
+ async def _ls(self, path, detail=True, **kwargs):
284
+ ret = (await self.fs._ls(self._join(path), detail=detail, **kwargs)).copy()
285
+ if detail:
286
+ out = []
287
+ for entry in ret:
288
+ entry = entry.copy()
289
+ entry["name"] = self._relpath(entry["name"])
290
+ out.append(entry)
291
+ return out
292
+
293
+ return self._relpath(ret)
294
+
295
+ def ls(self, path, detail=True, **kwargs):
296
+ ret = self.fs.ls(self._join(path), detail=detail, **kwargs).copy()
297
+ if detail:
298
+ out = []
299
+ for entry in ret:
300
+ entry = entry.copy()
301
+ entry["name"] = self._relpath(entry["name"])
302
+ out.append(entry)
303
+ return out
304
+
305
+ return self._relpath(ret)
306
+
307
+ async def _walk(self, path, *args, **kwargs):
308
+ async for root, dirs, files in self.fs._walk(self._join(path), *args, **kwargs):
309
+ yield self._relpath(root), dirs, files
310
+
311
+ def walk(self, path, *args, **kwargs):
312
+ for root, dirs, files in self.fs.walk(self._join(path), *args, **kwargs):
313
+ yield self._relpath(root), dirs, files
314
+
315
+ async def _glob(self, path, **kwargs):
316
+ detail = kwargs.get("detail", False)
317
+ ret = await self.fs._glob(self._join(path), **kwargs)
318
+ if detail:
319
+ return {self._relpath(path): info for path, info in ret.items()}
320
+ return self._relpath(ret)
321
+
322
+ def glob(self, path, **kwargs):
323
+ detail = kwargs.get("detail", False)
324
+ ret = self.fs.glob(self._join(path), **kwargs)
325
+ if detail:
326
+ return {self._relpath(path): info for path, info in ret.items()}
327
+ return self._relpath(ret)
328
+
329
+ async def _du(self, path, *args, **kwargs):
330
+ total = kwargs.get("total", True)
331
+ ret = await self.fs._du(self._join(path), *args, **kwargs)
332
+ if total:
333
+ return ret
334
+
335
+ return {self._relpath(path): size for path, size in ret.items()}
336
+
337
+ def du(self, path, *args, **kwargs):
338
+ total = kwargs.get("total", True)
339
+ ret = self.fs.du(self._join(path), *args, **kwargs)
340
+ if total:
341
+ return ret
342
+
343
+ return {self._relpath(path): size for path, size in ret.items()}
344
+
345
+ async def _find(self, path, *args, **kwargs):
346
+ detail = kwargs.get("detail", False)
347
+ ret = await self.fs._find(self._join(path), *args, **kwargs)
348
+ if detail:
349
+ return {self._relpath(path): info for path, info in ret.items()}
350
+ return self._relpath(ret)
351
+
352
+ def find(self, path, *args, **kwargs):
353
+ detail = kwargs.get("detail", False)
354
+ ret = self.fs.find(self._join(path), *args, **kwargs)
355
+ if detail:
356
+ return {self._relpath(path): info for path, info in ret.items()}
357
+ return self._relpath(ret)
358
+
359
+ async def _expand_path(self, path, *args, **kwargs):
360
+ return self._relpath(
361
+ await self.fs._expand_path(self._join(path), *args, **kwargs)
362
+ )
363
+
364
+ def expand_path(self, path, *args, **kwargs):
365
+ return self._relpath(self.fs.expand_path(self._join(path), *args, **kwargs))
366
+
367
+ async def _mkdir(self, path, *args, **kwargs):
368
+ return await self.fs._mkdir(self._join(path), *args, **kwargs)
369
+
370
+ def mkdir(self, path, *args, **kwargs):
371
+ return self.fs.mkdir(self._join(path), *args, **kwargs)
372
+
373
+ async def _makedirs(self, path, *args, **kwargs):
374
+ return await self.fs._makedirs(self._join(path), *args, **kwargs)
375
+
376
+ def makedirs(self, path, *args, **kwargs):
377
+ return self.fs.makedirs(self._join(path), *args, **kwargs)
378
+
379
+ def rmdir(self, path):
380
+ return self.fs.rmdir(self._join(path))
381
+
382
+ def mv(self, path1, path2, **kwargs):
383
+ return self.fs.mv(
384
+ self._join(path1),
385
+ self._join(path2),
386
+ **kwargs,
387
+ )
388
+
389
+ def touch(self, path, **kwargs):
390
+ return self.fs.touch(self._join(path), **kwargs)
391
+
392
+ def created(self, path):
393
+ return self.fs.created(self._join(path))
394
+
395
+ def modified(self, path):
396
+ return self.fs.modified(self._join(path))
397
+
398
+ def sign(self, path, *args, **kwargs):
399
+ return self.fs.sign(self._join(path), *args, **kwargs)
400
+
401
+ def __repr__(self):
402
+ return f"{self.__class__.__qualname__}(path='{self.path}', fs={self.fs})"
403
+
404
+ def open(
405
+ self,
406
+ path,
407
+ *args,
408
+ **kwargs,
409
+ ):
410
+ return self.fs.open(
411
+ self._join(path),
412
+ *args,
413
+ **kwargs,
414
+ )
415
+
416
+ async def open_async(
417
+ self,
418
+ path,
419
+ *args,
420
+ **kwargs,
421
+ ):
422
+ return await self.fs.open_async(
423
+ self._join(path),
424
+ *args,
425
+ **kwargs,
426
+ )
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/ftp.py ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import ssl
3
+ import uuid
4
+ from ftplib import FTP, FTP_TLS, Error, error_perm
5
+ from typing import Any
6
+
7
+ from ..spec import AbstractBufferedFile, AbstractFileSystem
8
+ from ..utils import infer_storage_options, isfilelike
9
+
10
+ SECURITY_PROTOCOL_MAP = {
11
+ "tls": ssl.PROTOCOL_TLS,
12
+ "sslv23": ssl.PROTOCOL_SSLv23,
13
+ }
14
+ for protocol in ["TLSv1", "TLSv1_1", "TLSv1_2"]:
15
+ if hasattr(ssl, f"PROTOCOL_{protocol}"):
16
+ SECURITY_PROTOCOL_MAP[protocol.lower()] = getattr(ssl, f"PROTOCOL_{protocol}")
17
+
18
+
19
+ class ImplicitFTPTLS(FTP_TLS):
20
+ """
21
+ FTP_TLS subclass that automatically wraps sockets in SSL
22
+ to support implicit FTPS.
23
+ """
24
+
25
+ def __init__(self, *args, **kwargs):
26
+ super().__init__(*args, **kwargs)
27
+ self._sock = None
28
+
29
+ @property
30
+ def sock(self):
31
+ """Return the socket."""
32
+ return self._sock
33
+
34
+ @sock.setter
35
+ def sock(self, value):
36
+ """When modifying the socket, ensure that it is ssl wrapped."""
37
+ if value is not None and not isinstance(value, ssl.SSLSocket):
38
+ value = self.context.wrap_socket(value)
39
+ self._sock = value
40
+
41
+
42
+ class FTPFileSystem(AbstractFileSystem):
43
+ """A filesystem over classic FTP"""
44
+
45
+ root_marker = "/"
46
+ cachable = False
47
+ protocol = "ftp"
48
+
49
+ def __init__(
50
+ self,
51
+ host,
52
+ port=21,
53
+ username=None,
54
+ password=None,
55
+ acct=None,
56
+ block_size=None,
57
+ tempdir=None,
58
+ timeout=30,
59
+ encoding="utf-8",
60
+ tls=False,
61
+ **kwargs,
62
+ ):
63
+ """
64
+ You can use _get_kwargs_from_urls to get some kwargs from
65
+ a reasonable FTP url.
66
+
67
+ Authentication will be anonymous if username/password are not
68
+ given.
69
+
70
+ Parameters
71
+ ----------
72
+ host: str
73
+ The remote server name/ip to connect to
74
+ port: int
75
+ Port to connect with
76
+ username: str or None
77
+ If authenticating, the user's identifier
78
+ password: str of None
79
+ User's password on the server, if using
80
+ acct: str or None
81
+ Some servers also need an "account" string for auth
82
+ block_size: int or None
83
+ If given, the read-ahead or write buffer size.
84
+ tempdir: str
85
+ Directory on remote to put temporary files when in a transaction
86
+ timeout: int
87
+ Timeout of the ftp connection in seconds
88
+ encoding: str
89
+ Encoding to use for directories and filenames in FTP connection
90
+ tls: bool or str
91
+ Enable FTP-TLS for secure connections:
92
+ - False: Plain FTP (default)
93
+ - True: Explicit TLS (FTPS with AUTH TLS command)
94
+ - "tls": Auto-negotiate highest protocol
95
+ - "tlsv1": TLS v1.0
96
+ - "tlsv1_1": TLS v1.1
97
+ - "tlsv1_2": TLS v1.2
98
+ """
99
+ super().__init__(**kwargs)
100
+ self.host = host
101
+ self.port = port
102
+ self.tempdir = tempdir or "/tmp"
103
+ self.cred = username or "", password or "", acct or ""
104
+ self.timeout = timeout
105
+ self.encoding = encoding
106
+ if block_size is not None:
107
+ self.blocksize = block_size
108
+ else:
109
+ self.blocksize = 2**16
110
+ self.tls = tls
111
+ self._connect()
112
+ if isinstance(self.tls, bool) and self.tls:
113
+ self.ftp.prot_p()
114
+
115
+ def _connect(self):
116
+ security = None
117
+ if self.tls:
118
+ if isinstance(self.tls, str):
119
+ ftp_cls = ImplicitFTPTLS
120
+ security = SECURITY_PROTOCOL_MAP.get(
121
+ self.tls,
122
+ f"Not supported {self.tls} protocol",
123
+ )
124
+ if isinstance(security, str):
125
+ raise ValueError(security)
126
+ else:
127
+ ftp_cls = FTP_TLS
128
+ else:
129
+ ftp_cls = FTP
130
+ self.ftp = ftp_cls(timeout=self.timeout, encoding=self.encoding)
131
+ if security:
132
+ self.ftp.ssl_version = security
133
+ self.ftp.connect(self.host, self.port)
134
+ self.ftp.login(*self.cred)
135
+
136
+ @classmethod
137
+ def _strip_protocol(cls, path):
138
+ return "/" + infer_storage_options(path)["path"].lstrip("/").rstrip("/")
139
+
140
+ @staticmethod
141
+ def _get_kwargs_from_urls(urlpath):
142
+ out = infer_storage_options(urlpath)
143
+ out.pop("path", None)
144
+ out.pop("protocol", None)
145
+ return out
146
+
147
+ def ls(self, path, detail=True, **kwargs):
148
+ path = self._strip_protocol(path)
149
+ out = []
150
+ if path not in self.dircache:
151
+ try:
152
+ try:
153
+ out = [
154
+ (fn, details)
155
+ for (fn, details) in self.ftp.mlsd(path)
156
+ if fn not in [".", ".."]
157
+ and details["type"] not in ["pdir", "cdir"]
158
+ ]
159
+ except error_perm:
160
+ out = _mlsd2(self.ftp, path) # Not platform independent
161
+ for fn, details in out:
162
+ details["name"] = "/".join(
163
+ ["" if path == "/" else path, fn.lstrip("/")]
164
+ )
165
+ if details["type"] == "file":
166
+ details["size"] = int(details["size"])
167
+ else:
168
+ details["size"] = 0
169
+ if details["type"] == "dir":
170
+ details["type"] = "directory"
171
+ self.dircache[path] = out
172
+ except Error:
173
+ try:
174
+ info = self.info(path)
175
+ if info["type"] == "file":
176
+ out = [(path, info)]
177
+ except (Error, IndexError) as exc:
178
+ raise FileNotFoundError(path) from exc
179
+ files = self.dircache.get(path, out)
180
+ if not detail:
181
+ return sorted([fn for fn, details in files])
182
+ return [details for fn, details in files]
183
+
184
+ def info(self, path, **kwargs):
185
+ # implement with direct method
186
+ path = self._strip_protocol(path)
187
+ if path == "/":
188
+ # special case, since this dir has no real entry
189
+ return {"name": "/", "size": 0, "type": "directory"}
190
+ files = self.ls(self._parent(path).lstrip("/"), True)
191
+ try:
192
+ out = next(f for f in files if f["name"] == path)
193
+ except StopIteration as exc:
194
+ raise FileNotFoundError(path) from exc
195
+ return out
196
+
197
+ def get_file(self, rpath, lpath, **kwargs):
198
+ if self.isdir(rpath):
199
+ if not os.path.exists(lpath):
200
+ os.mkdir(lpath)
201
+ return
202
+ if isfilelike(lpath):
203
+ outfile = lpath
204
+ else:
205
+ outfile = open(lpath, "wb")
206
+
207
+ def cb(x):
208
+ outfile.write(x)
209
+
210
+ self.ftp.retrbinary(
211
+ f"RETR {rpath}",
212
+ blocksize=self.blocksize,
213
+ callback=cb,
214
+ )
215
+ if not isfilelike(lpath):
216
+ outfile.close()
217
+
218
+ def cat_file(self, path, start=None, end=None, **kwargs):
219
+ if end is not None:
220
+ return super().cat_file(path, start, end, **kwargs)
221
+ out = []
222
+
223
+ def cb(x):
224
+ out.append(x)
225
+
226
+ try:
227
+ self.ftp.retrbinary(
228
+ f"RETR {path}",
229
+ blocksize=self.blocksize,
230
+ rest=start,
231
+ callback=cb,
232
+ )
233
+ except (Error, error_perm) as orig_exc:
234
+ raise FileNotFoundError(path) from orig_exc
235
+ return b"".join(out)
236
+
237
+ def _open(
238
+ self,
239
+ path,
240
+ mode="rb",
241
+ block_size=None,
242
+ cache_options=None,
243
+ autocommit=True,
244
+ **kwargs,
245
+ ):
246
+ path = self._strip_protocol(path)
247
+ block_size = block_size or self.blocksize
248
+ return FTPFile(
249
+ self,
250
+ path,
251
+ mode=mode,
252
+ block_size=block_size,
253
+ tempdir=self.tempdir,
254
+ autocommit=autocommit,
255
+ cache_options=cache_options,
256
+ )
257
+
258
+ def _rm(self, path):
259
+ path = self._strip_protocol(path)
260
+ self.ftp.delete(path)
261
+ self.invalidate_cache(self._parent(path))
262
+
263
+ def rm(self, path, recursive=False, maxdepth=None):
264
+ paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
265
+ for p in reversed(paths):
266
+ if self.isfile(p):
267
+ self.rm_file(p)
268
+ else:
269
+ self.rmdir(p)
270
+
271
+ def mkdir(self, path: str, create_parents: bool = True, **kwargs: Any) -> None:
272
+ path = self._strip_protocol(path)
273
+ parent = self._parent(path)
274
+ if parent != self.root_marker and not self.exists(parent) and create_parents:
275
+ self.mkdir(parent, create_parents=create_parents)
276
+
277
+ self.ftp.mkd(path)
278
+ self.invalidate_cache(self._parent(path))
279
+
280
+ def makedirs(self, path: str, exist_ok: bool = False) -> None:
281
+ path = self._strip_protocol(path)
282
+ if self.exists(path):
283
+ # NB: "/" does not "exist" as it has no directory entry
284
+ if not exist_ok:
285
+ raise FileExistsError(f"{path} exists without `exist_ok`")
286
+ # exists_ok=True -> no-op
287
+ else:
288
+ self.mkdir(path, create_parents=True)
289
+
290
+ def rmdir(self, path):
291
+ path = self._strip_protocol(path)
292
+ self.ftp.rmd(path)
293
+ self.invalidate_cache(self._parent(path))
294
+
295
+ def mv(self, path1, path2, **kwargs):
296
+ path1 = self._strip_protocol(path1)
297
+ path2 = self._strip_protocol(path2)
298
+ self.ftp.rename(path1, path2)
299
+ self.invalidate_cache(self._parent(path1))
300
+ self.invalidate_cache(self._parent(path2))
301
+
302
+ def __del__(self):
303
+ self.ftp.close()
304
+
305
+ def invalidate_cache(self, path=None):
306
+ if path is None:
307
+ self.dircache.clear()
308
+ else:
309
+ self.dircache.pop(path, None)
310
+ super().invalidate_cache(path)
311
+
312
+
313
+ class TransferDone(Exception):
314
+ """Internal exception to break out of transfer"""
315
+
316
+ pass
317
+
318
+
319
+ class FTPFile(AbstractBufferedFile):
320
+ """Interact with a remote FTP file with read/write buffering"""
321
+
322
+ def __init__(
323
+ self,
324
+ fs,
325
+ path,
326
+ mode="rb",
327
+ block_size="default",
328
+ autocommit=True,
329
+ cache_type="readahead",
330
+ cache_options=None,
331
+ **kwargs,
332
+ ):
333
+ super().__init__(
334
+ fs,
335
+ path,
336
+ mode=mode,
337
+ block_size=block_size,
338
+ autocommit=autocommit,
339
+ cache_type=cache_type,
340
+ cache_options=cache_options,
341
+ **kwargs,
342
+ )
343
+ if not autocommit:
344
+ self.target = self.path
345
+ self.path = "/".join([kwargs["tempdir"], str(uuid.uuid4())])
346
+
347
+ def commit(self):
348
+ self.fs.mv(self.path, self.target)
349
+
350
+ def discard(self):
351
+ self.fs.rm(self.path)
352
+
353
+ def _fetch_range(self, start, end):
354
+ """Get bytes between given byte limits
355
+
356
+ Implemented by raising an exception in the fetch callback when the
357
+ number of bytes received reaches the requested amount.
358
+
359
+ Will fail if the server does not respect the REST command on
360
+ retrieve requests.
361
+ """
362
+ out = []
363
+ total = [0]
364
+
365
+ def callback(x):
366
+ total[0] += len(x)
367
+ if total[0] > end - start:
368
+ out.append(x[: (end - start) - total[0]])
369
+ if end < self.size:
370
+ raise TransferDone
371
+ else:
372
+ out.append(x)
373
+
374
+ if total[0] == end - start and end < self.size:
375
+ raise TransferDone
376
+
377
+ try:
378
+ self.fs.ftp.retrbinary(
379
+ f"RETR {self.path}",
380
+ blocksize=self.blocksize,
381
+ rest=start,
382
+ callback=callback,
383
+ )
384
+ except TransferDone:
385
+ try:
386
+ # stop transfer, we got enough bytes for this block
387
+ self.fs.ftp.abort()
388
+ self.fs.ftp.getmultiline()
389
+ except Error:
390
+ self.fs._connect()
391
+
392
+ return b"".join(out)
393
+
394
+ def _upload_chunk(self, final=False):
395
+ self.buffer.seek(0)
396
+ self.fs.ftp.storbinary(
397
+ f"STOR {self.path}", self.buffer, blocksize=self.blocksize, rest=self.offset
398
+ )
399
+ return True
400
+
401
+
402
+ def _mlsd2(ftp, path="."):
403
+ """
404
+ Fall back to using `dir` instead of `mlsd` if not supported.
405
+
406
+ This parses a Linux style `ls -l` response to `dir`, but the response may
407
+ be platform dependent.
408
+
409
+ Parameters
410
+ ----------
411
+ ftp: ftplib.FTP
412
+ path: str
413
+ Expects to be given path, but defaults to ".".
414
+ """
415
+ lines = []
416
+ minfo = []
417
+ ftp.dir(path, lines.append)
418
+ for line in lines:
419
+ split_line = line.split(maxsplit=8)
420
+ if len(split_line) < 9:
421
+ continue
422
+ name = split_line[8]
423
+ unix_mode = split_line[0]
424
+ if unix_mode[0] == "l" and " -> " in name:
425
+ # Symbolic link: "<name> -> <target>"; keep only the link name.
426
+ name = name.split(" -> ", 1)[0]
427
+ this = (
428
+ name,
429
+ {
430
+ "modify": " ".join(split_line[5:8]),
431
+ "unix.owner": split_line[2],
432
+ "unix.group": split_line[3],
433
+ "unix.mode": unix_mode,
434
+ "size": split_line[4],
435
+ },
436
+ )
437
+ if this[1]["unix.mode"][0] == "d":
438
+ this[1]["type"] = "dir"
439
+ else:
440
+ this[1]["type"] = "file"
441
+ minfo.append(this)
442
+ return minfo
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/gist.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+
3
+ from ..spec import AbstractFileSystem
4
+ from ..utils import infer_storage_options
5
+ from .memory import MemoryFile
6
+
7
+
8
+ class GistFileSystem(AbstractFileSystem):
9
+ """
10
+ Interface to files in a single GitHub Gist.
11
+
12
+ Provides read-only access to a gist's files. Gists do not contain
13
+ subdirectories, so file listing is straightforward.
14
+
15
+ Parameters
16
+ ----------
17
+ gist_id: str
18
+ The ID of the gist you want to access (the long hex value from the URL).
19
+ filenames: list[str] (optional)
20
+ If provided, only make a file system representing these files, and do not fetch
21
+ the list of all files for this gist.
22
+ sha: str (optional)
23
+ If provided, fetch a particular revision of the gist. If omitted,
24
+ the latest revision is used.
25
+ username: str (optional)
26
+ GitHub username for authentication.
27
+ token: str (optional)
28
+ GitHub personal access token (required if username is given), or.
29
+ timeout: (float, float) or float, optional
30
+ Connect and read timeouts for requests (default 60s each).
31
+ kwargs: dict
32
+ Stored on `self.request_kw` and passed to `requests.get` when fetching Gist
33
+ metadata or reading ("opening") a file.
34
+ """
35
+
36
+ protocol = "gist"
37
+ gist_url = "https://api.github.com/gists/{gist_id}"
38
+ gist_rev_url = "https://api.github.com/gists/{gist_id}/{sha}"
39
+
40
+ def __init__(
41
+ self,
42
+ gist_id,
43
+ filenames=None,
44
+ sha=None,
45
+ username=None,
46
+ token=None,
47
+ timeout=None,
48
+ **kwargs,
49
+ ):
50
+ super().__init__()
51
+ self.gist_id = gist_id
52
+ self.filenames = filenames
53
+ self.sha = sha # revision of the gist (optional)
54
+ if username is not None and token is None:
55
+ raise ValueError("User auth requires a token")
56
+ self.username = username
57
+ self.token = token
58
+ self.request_kw = kwargs
59
+ # Default timeouts to 60s connect/read if none provided
60
+ self.timeout = timeout if timeout is not None else (60, 60)
61
+
62
+ # We use a single-level "directory" cache, because a gist is essentially flat
63
+ self.dircache[""] = self._fetch_file_list()
64
+
65
+ @property
66
+ def kw(self):
67
+ """Auth parameters passed to 'requests' if we have username/token."""
68
+ kw = {
69
+ "headers": {
70
+ "Accept": "application/vnd.github+json",
71
+ "X-GitHub-Api-Version": "2022-11-28",
72
+ }
73
+ }
74
+ kw.update(self.request_kw)
75
+ if self.username and self.token:
76
+ kw["auth"] = (self.username, self.token)
77
+ elif self.token:
78
+ kw["headers"]["Authorization"] = f"Bearer {self.token}"
79
+ return kw
80
+
81
+ def _fetch_gist_metadata(self):
82
+ """
83
+ Fetch the JSON metadata for this gist (possibly for a specific revision).
84
+ """
85
+ if self.sha:
86
+ url = self.gist_rev_url.format(gist_id=self.gist_id, sha=self.sha)
87
+ else:
88
+ url = self.gist_url.format(gist_id=self.gist_id)
89
+
90
+ r = requests.get(url, timeout=self.timeout, **self.kw)
91
+ if r.status_code == 404:
92
+ raise FileNotFoundError(
93
+ f"Gist not found: {self.gist_id}@{self.sha or 'latest'}"
94
+ )
95
+ r.raise_for_status()
96
+ return r.json()
97
+
98
+ def _fetch_file_list(self):
99
+ """
100
+ Returns a list of dicts describing each file in the gist. These get stored
101
+ in self.dircache[""].
102
+ """
103
+ meta = self._fetch_gist_metadata()
104
+ if self.filenames:
105
+ available_files = meta.get("files", {})
106
+ files = {}
107
+ for fn in self.filenames:
108
+ if fn not in available_files:
109
+ raise FileNotFoundError(fn)
110
+ files[fn] = available_files[fn]
111
+ else:
112
+ files = meta.get("files", {})
113
+
114
+ out = []
115
+ for fname, finfo in files.items():
116
+ if finfo is None:
117
+ # Occasionally GitHub returns a file entry with null if it was deleted
118
+ continue
119
+ # Build a directory entry
120
+ out.append(
121
+ {
122
+ "name": fname, # file's name
123
+ "type": "file", # gists have no subdirectories
124
+ "size": finfo.get("size", 0), # file size in bytes
125
+ "raw_url": finfo.get("raw_url"),
126
+ }
127
+ )
128
+ return out
129
+
130
+ @classmethod
131
+ def _strip_protocol(cls, path):
132
+ """
133
+ Remove 'gist://' from the path, if present.
134
+ """
135
+ # The default infer_storage_options can handle gist://username:token@id/file
136
+ # or gist://id/file, but let's ensure we handle a normal usage too.
137
+ # We'll just strip the protocol prefix if it exists.
138
+ path = infer_storage_options(path).get("path", path)
139
+ return path.lstrip("/")
140
+
141
+ @staticmethod
142
+ def _get_kwargs_from_urls(path):
143
+ """
144
+ Parse 'gist://' style URLs into GistFileSystem constructor kwargs.
145
+ For example:
146
+ gist://:TOKEN@<gist_id>/file.txt
147
+ gist://username:TOKEN@<gist_id>/file.txt
148
+ """
149
+ so = infer_storage_options(path)
150
+ out = {}
151
+ if "username" in so and so["username"]:
152
+ out["username"] = so["username"]
153
+ if "password" in so and so["password"]:
154
+ out["token"] = so["password"]
155
+ if "host" in so and so["host"]:
156
+ # We interpret 'host' as the gist ID
157
+ out["gist_id"] = so["host"]
158
+
159
+ # Extract SHA and filename from path
160
+ if "path" in so and so["path"]:
161
+ path_parts = so["path"].rsplit("/", 2)[-2:]
162
+ if len(path_parts) == 2:
163
+ if path_parts[0]: # SHA present
164
+ out["sha"] = path_parts[0]
165
+ if path_parts[1]: # filename also present
166
+ out["filenames"] = [path_parts[1]]
167
+
168
+ return out
169
+
170
+ def ls(self, path="", detail=False, **kwargs):
171
+ """
172
+ List files in the gist. Gists are single-level, so any 'path' is basically
173
+ the filename, or empty for all files.
174
+
175
+ Parameters
176
+ ----------
177
+ path : str, optional
178
+ The filename to list. If empty, returns all files in the gist.
179
+ detail : bool, default False
180
+ If True, return a list of dicts; if False, return a list of filenames.
181
+ """
182
+ path = self._strip_protocol(path or "")
183
+ # If path is empty, return all
184
+ if path == "":
185
+ results = self.dircache[""]
186
+ else:
187
+ # We want just the single file with this name
188
+ all_files = self.dircache[""]
189
+ results = [f for f in all_files if f["name"] == path]
190
+ if not results:
191
+ raise FileNotFoundError(path)
192
+ if detail:
193
+ return results
194
+ else:
195
+ return sorted(f["name"] for f in results)
196
+
197
+ def _open(self, path, mode="rb", block_size=None, **kwargs):
198
+ """
199
+ Read a single file from the gist.
200
+ """
201
+ if mode != "rb":
202
+ raise NotImplementedError("GitHub Gist FS is read-only (no write).")
203
+
204
+ path = self._strip_protocol(path)
205
+ # Find the file entry in our dircache
206
+ matches = [f for f in self.dircache[""] if f["name"] == path]
207
+ if not matches:
208
+ raise FileNotFoundError(path)
209
+ finfo = matches[0]
210
+
211
+ raw_url = finfo.get("raw_url")
212
+ if not raw_url:
213
+ raise FileNotFoundError(f"No raw_url for file: {path}")
214
+
215
+ r = requests.get(raw_url, timeout=self.timeout, **self.kw)
216
+ if r.status_code == 404:
217
+ raise FileNotFoundError(path)
218
+ r.raise_for_status()
219
+ return MemoryFile(path, None, r.content)
220
+
221
+ def cat(self, path, recursive=False, on_error="raise", **kwargs):
222
+ """
223
+ Return {path: contents} for the given file or files. If 'recursive' is True,
224
+ and path is empty, returns all files in the gist.
225
+ """
226
+ paths = self.expand_path(path, recursive=recursive)
227
+ out = {}
228
+ for p in paths:
229
+ try:
230
+ with self.open(p, "rb") as f:
231
+ out[p] = f.read()
232
+ except FileNotFoundError as e:
233
+ if on_error == "raise":
234
+ raise e
235
+ elif on_error == "omit":
236
+ pass # skip
237
+ else:
238
+ out[p] = e
239
+ if len(paths) == 1 and paths[0] == path:
240
+ return out[path]
241
+ return out
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/git.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import pygit2
4
+
5
+ from fsspec.spec import AbstractFileSystem
6
+
7
+ from .memory import MemoryFile
8
+
9
+
10
+ class GitFileSystem(AbstractFileSystem):
11
+ """Browse the files of a local git repo at any hash/tag/branch
12
+
13
+ (experimental backend)
14
+ """
15
+
16
+ root_marker = ""
17
+ cachable = True
18
+
19
+ def __init__(self, path=None, fo=None, ref=None, **kwargs):
20
+ """
21
+
22
+ Parameters
23
+ ----------
24
+ path: str (optional)
25
+ Local location of the repo (uses current directory if not given).
26
+ May be deprecated in favour of ``fo``. When used with a higher
27
+ level function such as fsspec.open(), may be of the form
28
+ "git://[path-to-repo[:]][ref@]path/to/file" (but the actual
29
+ file path should not contain "@" or ":").
30
+ fo: str (optional)
31
+ Same as ``path``, but passed as part of a chained URL. This one
32
+ takes precedence if both are given.
33
+ ref: str (optional)
34
+ Reference to work with, could be a hash, tag or branch name. Defaults
35
+ to current working tree. Note that ``ls`` and ``open`` also take hash,
36
+ so this becomes the default for those operations
37
+ kwargs
38
+ """
39
+ super().__init__(**kwargs)
40
+ self.repo = pygit2.Repository(fo or path or os.getcwd())
41
+ self.ref = ref or "master"
42
+
43
+ @classmethod
44
+ def _strip_protocol(cls, path):
45
+ path = super()._strip_protocol(path).lstrip("/")
46
+ if ":" in path:
47
+ path = path.split(":", 1)[1]
48
+ if "@" in path:
49
+ path = path.split("@", 1)[1]
50
+ return path.lstrip("/")
51
+
52
+ def _path_to_object(self, path, ref):
53
+ comm, ref = self.repo.resolve_refish(ref or self.ref)
54
+ parts = path.split("/")
55
+ tree = comm.tree
56
+ for part in parts:
57
+ if part and isinstance(tree, pygit2.Tree):
58
+ if part not in tree:
59
+ raise FileNotFoundError(path)
60
+ tree = tree[part]
61
+ return tree
62
+
63
+ @staticmethod
64
+ def _get_kwargs_from_urls(path):
65
+ path = path.removeprefix("git://")
66
+ out = {}
67
+ if ":" in path:
68
+ out["path"], path = path.split(":", 1)
69
+ if "@" in path:
70
+ out["ref"], path = path.split("@", 1)
71
+ return out
72
+
73
+ @staticmethod
74
+ def _object_to_info(obj, path=None):
75
+ # obj.name and obj.filemode are None for the root tree!
76
+ is_dir = isinstance(obj, pygit2.Tree)
77
+ return {
78
+ "type": "directory" if is_dir else "file",
79
+ "name": (
80
+ "/".join([path, obj.name or ""]).lstrip("/") if path else obj.name
81
+ ),
82
+ "hex": str(obj.id),
83
+ "mode": "100644" if obj.filemode is None else f"{obj.filemode:o}",
84
+ "size": 0 if is_dir else obj.size,
85
+ }
86
+
87
+ def ls(self, path, detail=True, ref=None, **kwargs):
88
+ tree = self._path_to_object(self._strip_protocol(path), ref)
89
+ return [
90
+ GitFileSystem._object_to_info(obj, path)
91
+ if detail
92
+ else GitFileSystem._object_to_info(obj, path)["name"]
93
+ for obj in (tree if isinstance(tree, pygit2.Tree) else [tree])
94
+ ]
95
+
96
+ def info(self, path, ref=None, **kwargs):
97
+ tree = self._path_to_object(self._strip_protocol(path), ref)
98
+ return GitFileSystem._object_to_info(tree, path)
99
+
100
+ def ukey(self, path, ref=None):
101
+ return self.info(path, ref=ref)["hex"]
102
+
103
+ def _open(
104
+ self,
105
+ path,
106
+ mode="rb",
107
+ block_size=None,
108
+ autocommit=True,
109
+ cache_options=None,
110
+ ref=None,
111
+ **kwargs,
112
+ ):
113
+ obj = self._path_to_object(path, ref or self.ref)
114
+ return MemoryFile(data=obj.data)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/github.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import re
3
+
4
+ import requests
5
+
6
+ from ..spec import AbstractFileSystem
7
+ from ..utils import infer_storage_options
8
+ from .memory import MemoryFile
9
+
10
+
11
+ class GithubFileSystem(AbstractFileSystem):
12
+ """Interface to files in github
13
+
14
+ An instance of this class provides the files residing within a remote github
15
+ repository. You may specify a point in the repos history, by SHA, branch
16
+ or tag (default is current master).
17
+
18
+ For files less than 1 MB in size, file content is returned directly in a
19
+ MemoryFile. For larger files, or for files tracked by git-lfs, file content
20
+ is returned as an HTTPFile wrapping the ``download_url`` provided by the
21
+ GitHub API.
22
+
23
+ When using fsspec.open, allows URIs of the form:
24
+
25
+ - "github://path/file", in which case you must specify org, repo and
26
+ may specify sha in the extra args
27
+ - 'github://org:repo@/precip/catalog.yml', where the org and repo are
28
+ part of the URI
29
+ - 'github://org:repo@sha/precip/catalog.yml', where the sha is also included
30
+
31
+ ``sha`` can be the full or abbreviated hex of the commit you want to fetch
32
+ from, or a branch or tag name (so long as it doesn't contain special characters
33
+ like "/", "?", which would have to be HTTP-encoded).
34
+
35
+ For authorised access, you must provide username and token, which can be made
36
+ at https://github.com/settings/tokens
37
+ """
38
+
39
+ url = "https://api.github.com/repos/{org}/{repo}/git/trees/{sha}"
40
+ content_url = "https://api.github.com/repos/{org}/{repo}/contents/{path}?ref={sha}"
41
+ protocol = "github"
42
+ timeout = (60, 60) # connect, read timeouts
43
+
44
+ def __init__(
45
+ self, org, repo, sha=None, username=None, token=None, timeout=None, **kwargs
46
+ ):
47
+ super().__init__(**kwargs)
48
+ self.org = org
49
+ self.repo = repo
50
+ if (username is None) ^ (token is None):
51
+ raise ValueError("Auth required both username and token")
52
+ self.username = username
53
+ self.token = token
54
+ if timeout is not None:
55
+ self.timeout = timeout
56
+ if sha is None:
57
+ # look up default branch (not necessarily "master")
58
+ u = "https://api.github.com/repos/{org}/{repo}"
59
+ r = requests.get(
60
+ u.format(org=org, repo=repo), timeout=self.timeout, **self.kw
61
+ )
62
+ r.raise_for_status()
63
+ sha = r.json()["default_branch"]
64
+
65
+ self.root = sha
66
+ self.ls("")
67
+ try:
68
+ from .http import HTTPFileSystem
69
+
70
+ self.http_fs = HTTPFileSystem(**kwargs)
71
+ except ImportError:
72
+ self.http_fs = None
73
+
74
+ @property
75
+ def kw(self):
76
+ if self.username:
77
+ return {"auth": (self.username, self.token)}
78
+ return {}
79
+
80
+ @classmethod
81
+ def repos(cls, org_or_user, is_org=True):
82
+ """List repo names for given org or user
83
+
84
+ This may become the top level of the FS
85
+
86
+ Parameters
87
+ ----------
88
+ org_or_user: str
89
+ Name of the github org or user to query
90
+ is_org: bool (default True)
91
+ Whether the name is an organisation (True) or user (False)
92
+
93
+ Returns
94
+ -------
95
+ List of string
96
+ """
97
+ r = requests.get(
98
+ f"https://api.github.com/{['users', 'orgs'][is_org]}/{org_or_user}/repos",
99
+ timeout=cls.timeout,
100
+ )
101
+ r.raise_for_status()
102
+ return [repo["name"] for repo in r.json()]
103
+
104
+ @property
105
+ def tags(self):
106
+ """Names of tags in the repo"""
107
+ r = requests.get(
108
+ f"https://api.github.com/repos/{self.org}/{self.repo}/tags",
109
+ timeout=self.timeout,
110
+ **self.kw,
111
+ )
112
+ r.raise_for_status()
113
+ return [t["name"] for t in r.json()]
114
+
115
+ @property
116
+ def branches(self):
117
+ """Names of branches in the repo"""
118
+ r = requests.get(
119
+ f"https://api.github.com/repos/{self.org}/{self.repo}/branches",
120
+ timeout=self.timeout,
121
+ **self.kw,
122
+ )
123
+ r.raise_for_status()
124
+ return [t["name"] for t in r.json()]
125
+
126
+ @property
127
+ def refs(self):
128
+ """Named references, tags and branches"""
129
+ return {"tags": self.tags, "branches": self.branches}
130
+
131
+ def ls(self, path, detail=False, sha=None, _sha=None, **kwargs):
132
+ """List files at given path
133
+
134
+ Parameters
135
+ ----------
136
+ path: str
137
+ Location to list, relative to repo root
138
+ detail: bool
139
+ If True, returns list of dicts, one per file; if False, returns
140
+ list of full filenames only
141
+ sha: str (optional)
142
+ List at the given point in the repo history, branch or tag name or commit
143
+ SHA
144
+ _sha: str (optional)
145
+ List this specific tree object (used internally to descend into trees)
146
+ """
147
+ path = self._strip_protocol(path)
148
+ if path == "":
149
+ _sha = sha or self.root
150
+ if _sha is None:
151
+ parts = path.rstrip("/").split("/")
152
+ so_far = ""
153
+ _sha = sha or self.root
154
+ for part in parts:
155
+ out = self.ls(so_far, True, sha=sha, _sha=_sha)
156
+ so_far += "/" + part if so_far else part
157
+ out = [o for o in out if o["name"] == so_far]
158
+ if not out:
159
+ raise FileNotFoundError(path)
160
+ out = out[0]
161
+ if out["type"] == "file":
162
+ if detail:
163
+ return [out]
164
+ else:
165
+ return path
166
+ _sha = out["sha"]
167
+ if path not in self.dircache or sha not in [self.root, None]:
168
+ r = requests.get(
169
+ self.url.format(org=self.org, repo=self.repo, sha=_sha),
170
+ timeout=self.timeout,
171
+ **self.kw,
172
+ )
173
+ if r.status_code == 404:
174
+ raise FileNotFoundError(path)
175
+ r.raise_for_status()
176
+ types = {"blob": "file", "tree": "directory"}
177
+ out = [
178
+ {
179
+ "name": path + "/" + f["path"] if path else f["path"],
180
+ "mode": f["mode"],
181
+ "type": types[f["type"]],
182
+ "size": f.get("size", 0),
183
+ "sha": f["sha"],
184
+ }
185
+ for f in r.json()["tree"]
186
+ if f["type"] in types
187
+ ]
188
+ if sha in [self.root, None]:
189
+ self.dircache[path] = out
190
+ else:
191
+ out = self.dircache[path]
192
+ if detail:
193
+ return out
194
+ else:
195
+ return sorted([f["name"] for f in out])
196
+
197
+ def invalidate_cache(self, path=None):
198
+ self.dircache.clear()
199
+
200
+ @classmethod
201
+ def _strip_protocol(cls, path):
202
+ opts = infer_storage_options(path)
203
+ if "username" not in opts:
204
+ return super()._strip_protocol(path)
205
+ return opts["path"].lstrip("/")
206
+
207
+ @staticmethod
208
+ def _get_kwargs_from_urls(path):
209
+ opts = infer_storage_options(path)
210
+ if "username" not in opts:
211
+ return {}
212
+ out = {"org": opts["username"], "repo": opts["password"]}
213
+ if opts["host"]:
214
+ out["sha"] = opts["host"]
215
+ return out
216
+
217
+ def _open(
218
+ self,
219
+ path,
220
+ mode="rb",
221
+ block_size=None,
222
+ cache_options=None,
223
+ sha=None,
224
+ **kwargs,
225
+ ):
226
+ if mode != "rb":
227
+ raise NotImplementedError
228
+
229
+ # construct a url to hit the GitHub API's repo contents API
230
+ url = self.content_url.format(
231
+ org=self.org, repo=self.repo, path=path, sha=sha or self.root
232
+ )
233
+
234
+ # make a request to this API, and parse the response as JSON
235
+ r = requests.get(url, timeout=self.timeout, **self.kw)
236
+ if r.status_code == 404:
237
+ raise FileNotFoundError(path)
238
+ r.raise_for_status()
239
+ content_json = r.json()
240
+
241
+ # if the response's content key is not empty, try to parse it as base64
242
+ if content_json["content"]:
243
+ content = base64.b64decode(content_json["content"])
244
+
245
+ # as long as the content does not start with the string
246
+ # "version https://git-lfs.github.com/"
247
+ # then it is probably not a git-lfs pointer and we can just return
248
+ # the content directly
249
+ if not content.startswith(b"version https://git-lfs.github.com/"):
250
+ return MemoryFile(None, None, content)
251
+
252
+ # we land here if the content was not present in the first response
253
+ # (regular file over 1MB or git-lfs tracked file)
254
+ # in this case, we get let the HTTPFileSystem handle the download
255
+ if self.http_fs is None:
256
+ raise ImportError(
257
+ "Please install fsspec[http] to access github files >1 MB "
258
+ "or git-lfs tracked files."
259
+ )
260
+ return self.http_fs.open(
261
+ content_json["download_url"],
262
+ mode=mode,
263
+ block_size=block_size,
264
+ cache_options=cache_options,
265
+ **kwargs,
266
+ )
267
+
268
+ def rm(self, path, recursive=False, maxdepth=None, message=None):
269
+ path = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
270
+ for p in reversed(path):
271
+ self.rm_file(p, message=message)
272
+
273
+ def rm_file(self, path, message=None, **kwargs):
274
+ """
275
+ Remove a file from a specified branch using a given commit message.
276
+
277
+ Since Github DELETE operation requires a branch name, and we can't reliably
278
+ determine whether the provided SHA refers to a branch, tag, or commit, we
279
+ assume it's a branch. If it's not, the user will encounter an error when
280
+ attempting to retrieve the file SHA or delete the file.
281
+
282
+ Parameters
283
+ ----------
284
+ path: str
285
+ The file's location relative to the repository root.
286
+ message: str, optional
287
+ The commit message for the deletion.
288
+ """
289
+
290
+ if not self.username:
291
+ raise ValueError("Authentication required")
292
+
293
+ path = self._strip_protocol(path)
294
+
295
+ # Attempt to get SHA from cache or Github API
296
+ sha = self._get_sha_from_cache(path)
297
+ if not sha:
298
+ url = self.content_url.format(
299
+ org=self.org, repo=self.repo, path=path.lstrip("/"), sha=self.root
300
+ )
301
+ r = requests.get(url, timeout=self.timeout, **self.kw)
302
+ if r.status_code == 404:
303
+ raise FileNotFoundError(path)
304
+ r.raise_for_status()
305
+ sha = r.json()["sha"]
306
+
307
+ # Delete the file
308
+ delete_url = self.content_url.format(
309
+ org=self.org, repo=self.repo, path=path, sha=self.root
310
+ )
311
+ branch = self.root
312
+ data = {
313
+ "message": message or f"Delete {path}",
314
+ "sha": sha,
315
+ **({"branch": branch} if branch else {}),
316
+ }
317
+
318
+ r = requests.delete(delete_url, json=data, timeout=self.timeout, **self.kw)
319
+ error_message = r.json().get("message", "")
320
+ if re.search(r"Branch .+ not found", error_message):
321
+ error = "Remove only works when the filesystem is initialised from a branch or default (None)"
322
+ raise ValueError(error)
323
+ r.raise_for_status()
324
+
325
+ self.invalidate_cache(path)
326
+
327
+ def _get_sha_from_cache(self, path):
328
+ for entries in self.dircache.values():
329
+ for entry in entries:
330
+ entry_path = entry.get("name")
331
+ if entry_path and entry_path == path and "sha" in entry:
332
+ return entry["sha"]
333
+ return None
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/http.py ADDED
@@ -0,0 +1,902 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import io
3
+ import logging
4
+ import re
5
+ import weakref
6
+ from copy import copy
7
+ from urllib.parse import urlparse
8
+
9
+ import aiohttp
10
+ import yarl
11
+
12
+ from fsspec.asyn import AbstractAsyncStreamedFile, AsyncFileSystem, sync, sync_wrapper
13
+ from fsspec.callbacks import DEFAULT_CALLBACK
14
+ from fsspec.exceptions import FSTimeoutError
15
+ from fsspec.spec import AbstractBufferedFile
16
+ from fsspec.utils import (
17
+ DEFAULT_BLOCK_SIZE,
18
+ glob_translate,
19
+ isfilelike,
20
+ nullcontext,
21
+ tokenize,
22
+ )
23
+
24
+ from ..caching import AllBytes
25
+
26
+ # https://stackoverflow.com/a/15926317/3821154
27
+ ex = re.compile(r"""<(a|A)\s+(?:[^>]*?\s+)?(href|HREF)=["'](?P<url>[^"']+)""")
28
+ ex2 = re.compile(r"""(?P<url>http[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""")
29
+ logger = logging.getLogger("fsspec.http")
30
+
31
+
32
+ async def get_client(**kwargs):
33
+ return aiohttp.ClientSession(**kwargs)
34
+
35
+
36
+ class HTTPFileSystem(AsyncFileSystem):
37
+ """
38
+ Simple File-System for fetching data via HTTP(S)
39
+
40
+ ``ls()`` is implemented by loading the parent page and doing a regex
41
+ match on the result. If simple_link=True, anything of the form
42
+ "http(s)://server.com/stuff?thing=other"; otherwise only links within
43
+ HTML href tags will be used.
44
+
45
+ URLs are passed unfiltered to aiohttp, so all addresses are accessible. Where URLs are
46
+ supplied by a user, the calling application may wish to filter to prevent scanning.
47
+ """
48
+
49
+ protocol = ("http", "https")
50
+ sep = "/"
51
+
52
+ def __init__(
53
+ self,
54
+ simple_links=True,
55
+ block_size=None,
56
+ same_scheme=True,
57
+ size_policy=None,
58
+ cache_type="bytes",
59
+ cache_options=None,
60
+ asynchronous=False,
61
+ loop=None,
62
+ client_kwargs=None,
63
+ get_client=get_client,
64
+ encoded=False,
65
+ **storage_options,
66
+ ):
67
+ """
68
+ NB: if this is called async, you must await set_client
69
+
70
+ Parameters
71
+ ----------
72
+ block_size: int
73
+ Blocks to read bytes; if 0, will default to raw requests file-like
74
+ objects instead of HTTPFile instances
75
+ simple_links: bool
76
+ If True, will consider both HTML <a> tags and anything that looks
77
+ like a URL; if False, will consider only the former.
78
+ same_scheme: True
79
+ When doing ls/glob, if this is True, only consider paths that have
80
+ http/https matching the input URLs.
81
+ size_policy: this argument is deprecated
82
+ client_kwargs: dict
83
+ Passed to aiohttp.ClientSession, see
84
+ https://docs.aiohttp.org/en/stable/client_reference.html
85
+ For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}``
86
+ get_client: Callable[..., aiohttp.ClientSession]
87
+ A callable, which takes keyword arguments and constructs
88
+ an aiohttp.ClientSession. Its state will be managed by
89
+ the HTTPFileSystem class.
90
+ storage_options: key-value
91
+ Any other parameters passed on to requests
92
+ cache_type, cache_options: defaults used in open()
93
+ """
94
+ super().__init__(self, asynchronous=asynchronous, loop=loop, **storage_options)
95
+ self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE
96
+ self.simple_links = simple_links
97
+ self.same_schema = same_scheme
98
+ self.cache_type = cache_type
99
+ self.cache_options = cache_options
100
+ self.client_kwargs = client_kwargs or {}
101
+ self.get_client = get_client
102
+ self.encoded = encoded
103
+ self.kwargs = storage_options
104
+ self._session = None
105
+
106
+ # Clean caching-related parameters from `storage_options`
107
+ # before propagating them as `request_options` through `self.kwargs`.
108
+ # TODO: Maybe rename `self.kwargs` to `self.request_options` to make
109
+ # it clearer.
110
+ request_options = copy(storage_options)
111
+ self.use_listings_cache = request_options.pop("use_listings_cache", False)
112
+ request_options.pop("listings_expiry_time", None)
113
+ request_options.pop("max_paths", None)
114
+ request_options.pop("skip_instance_cache", None)
115
+ self.kwargs = request_options
116
+
117
+ @property
118
+ def fsid(self):
119
+ return "http"
120
+
121
+ def encode_url(self, url):
122
+ return yarl.URL(url, encoded=self.encoded)
123
+
124
+ @staticmethod
125
+ def close_session(loop, session):
126
+ if loop is not None and loop.is_running():
127
+ try:
128
+ sync(loop, session.close, timeout=0.1)
129
+ return
130
+ except (TimeoutError, FSTimeoutError, NotImplementedError):
131
+ pass
132
+ connector = getattr(session, "_connector", None)
133
+ if connector is not None:
134
+ # close after loop is dead
135
+ connector._close()
136
+
137
+ async def set_session(self):
138
+ if self._session is None:
139
+ self._session = await self.get_client(loop=self.loop, **self.client_kwargs)
140
+ if not self.asynchronous:
141
+ weakref.finalize(self, self.close_session, self.loop, self._session)
142
+ return self._session
143
+
144
+ @classmethod
145
+ def _strip_protocol(cls, path):
146
+ """For HTTP, we always want to keep the full URL"""
147
+ return path
148
+
149
+ @classmethod
150
+ def _parent(cls, path):
151
+ # override, since _strip_protocol is different for URLs
152
+ par = super()._parent(path)
153
+ if len(par) > 7: # "http://..."
154
+ return par
155
+ return ""
156
+
157
+ async def _ls_real(self, url, detail=True, **kwargs):
158
+ # ignoring URL-encoded arguments
159
+ kw = self.kwargs.copy()
160
+ kw.update(kwargs)
161
+ logger.debug(url)
162
+ session = await self.set_session()
163
+ async with session.get(self.encode_url(url), **self.kwargs) as r:
164
+ self._raise_not_found_for_status(r, url)
165
+
166
+ if "Content-Type" in r.headers:
167
+ mimetype = r.headers["Content-Type"].partition(";")[0]
168
+ else:
169
+ mimetype = None
170
+
171
+ if mimetype in ("text/html", None):
172
+ try:
173
+ text = await r.text(errors="ignore")
174
+ if self.simple_links:
175
+ links = ex2.findall(text) + [u[2] for u in ex.findall(text)]
176
+ else:
177
+ links = [u[2] for u in ex.findall(text)]
178
+ except UnicodeDecodeError:
179
+ links = [] # binary, not HTML
180
+ else:
181
+ links = []
182
+
183
+ out = set()
184
+ parts = urlparse(url)
185
+ for l in links:
186
+ if isinstance(l, tuple):
187
+ l = l[1]
188
+ if l.startswith("/") and len(l) > 1:
189
+ # absolute URL on this server
190
+ l = f"{parts.scheme}://{parts.netloc}{l}"
191
+ if l.startswith("http"):
192
+ if self.same_schema and l.startswith(url.rstrip("/") + "/"):
193
+ out.add(l)
194
+ elif l.replace("https", "http").startswith(
195
+ url.replace("https", "http").rstrip("/") + "/"
196
+ ):
197
+ # allowed to cross http <-> https
198
+ out.add(l)
199
+ else:
200
+ if l not in ["..", "../"]:
201
+ # Ignore FTP-like "parent"
202
+ out.add("/".join([url.rstrip("/"), l.lstrip("/")]))
203
+ if not out and url.endswith("/"):
204
+ out = await self._ls_real(url.rstrip("/"), detail=False)
205
+ if detail:
206
+ return [
207
+ {
208
+ "name": u,
209
+ "size": None,
210
+ "type": "directory" if u.endswith("/") else "file",
211
+ }
212
+ for u in out
213
+ ]
214
+ else:
215
+ return sorted(out)
216
+
217
+ async def _ls(self, url, detail=True, **kwargs):
218
+ if self.use_listings_cache and url in self.dircache:
219
+ out = self.dircache[url]
220
+ else:
221
+ out = await self._ls_real(url, detail=detail, **kwargs)
222
+ self.dircache[url] = out
223
+ return out
224
+
225
+ ls = sync_wrapper(_ls)
226
+
227
+ def _raise_not_found_for_status(self, response, url):
228
+ """
229
+ Raises FileNotFoundError for 404s, otherwise uses raise_for_status.
230
+ """
231
+ if response.status == 404:
232
+ raise FileNotFoundError(url)
233
+ response.raise_for_status()
234
+
235
+ async def _cat_file(self, url, start=None, end=None, **kwargs):
236
+ kw = self.kwargs.copy()
237
+ kw.update(kwargs)
238
+ logger.debug(url)
239
+
240
+ if start is not None or end is not None:
241
+ if start == end:
242
+ return b""
243
+ headers = kw.pop("headers", {}).copy()
244
+
245
+ headers["Range"] = await self._process_limits(url, start, end)
246
+ kw["headers"] = headers
247
+ session = await self.set_session()
248
+ async with session.get(self.encode_url(url), **kw) as r:
249
+ out = await r.read()
250
+ self._raise_not_found_for_status(r, url)
251
+ return out
252
+
253
+ async def _get_file(
254
+ self, rpath, lpath, chunk_size=5 * 2**20, callback=DEFAULT_CALLBACK, **kwargs
255
+ ):
256
+ kw = self.kwargs.copy()
257
+ kw.update(kwargs)
258
+ logger.debug(rpath)
259
+ session = await self.set_session()
260
+ async with session.get(self.encode_url(rpath), **kw) as r:
261
+ try:
262
+ size = int(r.headers["content-length"])
263
+ except (ValueError, KeyError):
264
+ size = None
265
+
266
+ callback.set_size(size)
267
+ self._raise_not_found_for_status(r, rpath)
268
+ if isfilelike(lpath):
269
+ outfile = lpath
270
+ else:
271
+ outfile = open(lpath, "wb") # noqa: ASYNC230
272
+
273
+ try:
274
+ chunk = True
275
+ while chunk:
276
+ chunk = await r.content.read(chunk_size)
277
+ outfile.write(chunk)
278
+ callback.relative_update(len(chunk))
279
+ finally:
280
+ if not isfilelike(lpath):
281
+ outfile.close()
282
+
283
+ async def _put_file(
284
+ self,
285
+ lpath,
286
+ rpath,
287
+ chunk_size=5 * 2**20,
288
+ callback=DEFAULT_CALLBACK,
289
+ method="post",
290
+ mode="overwrite",
291
+ **kwargs,
292
+ ):
293
+ if mode != "overwrite":
294
+ raise NotImplementedError("Exclusive write")
295
+
296
+ async def gen_chunks():
297
+ # Support passing arbitrary file-like objects
298
+ # and use them instead of streams.
299
+ if isinstance(lpath, io.IOBase):
300
+ context = nullcontext(lpath)
301
+ use_seek = False # might not support seeking
302
+ else:
303
+ context = open(lpath, "rb") # noqa: ASYNC230
304
+ use_seek = True
305
+
306
+ with context as f:
307
+ if use_seek:
308
+ callback.set_size(f.seek(0, 2))
309
+ f.seek(0)
310
+ else:
311
+ callback.set_size(getattr(f, "size", None))
312
+
313
+ chunk = f.read(chunk_size)
314
+ while chunk:
315
+ yield chunk
316
+ callback.relative_update(len(chunk))
317
+ chunk = f.read(chunk_size)
318
+
319
+ kw = self.kwargs.copy()
320
+ kw.update(kwargs)
321
+ session = await self.set_session()
322
+
323
+ method = method.lower()
324
+ if method not in ("post", "put"):
325
+ raise ValueError(
326
+ f"method has to be either 'post' or 'put', not: {method!r}"
327
+ )
328
+
329
+ meth = getattr(session, method)
330
+ async with meth(self.encode_url(rpath), data=gen_chunks(), **kw) as resp:
331
+ self._raise_not_found_for_status(resp, rpath)
332
+
333
+ async def _exists(self, path, strict=False, **kwargs):
334
+ kw = self.kwargs.copy()
335
+ kw.update(kwargs)
336
+ try:
337
+ logger.debug(path)
338
+ session = await self.set_session()
339
+ r = await session.get(self.encode_url(path), **kw)
340
+ async with r:
341
+ if strict:
342
+ self._raise_not_found_for_status(r, path)
343
+ return r.status < 400
344
+ except FileNotFoundError:
345
+ return False
346
+ except aiohttp.ClientError:
347
+ if strict:
348
+ raise
349
+ return False
350
+
351
+ async def _isfile(self, path, **kwargs):
352
+ return await self._exists(path, **kwargs)
353
+
354
+ def _open(
355
+ self,
356
+ path,
357
+ mode="rb",
358
+ block_size=None,
359
+ autocommit=None, # XXX: This differs from the base class.
360
+ cache_type=None,
361
+ cache_options=None,
362
+ size=None,
363
+ **kwargs,
364
+ ):
365
+ """Make a file-like object
366
+
367
+ Parameters
368
+ ----------
369
+ path: str
370
+ Full URL with protocol
371
+ mode: string
372
+ must be "rb"
373
+ block_size: int or None
374
+ Bytes to download in one request; use instance value if None. If
375
+ zero, will return a streaming Requests file-like instance.
376
+ kwargs: key-value
377
+ Any other parameters, passed to requests calls
378
+ """
379
+ if mode != "rb":
380
+ raise NotImplementedError
381
+ block_size = block_size if block_size is not None else self.block_size
382
+ kw = self.kwargs.copy()
383
+ kw["asynchronous"] = self.asynchronous
384
+ kw.update(kwargs)
385
+ info = {}
386
+ size = size or info.update(self.info(path, **kwargs)) or info["size"]
387
+ session = sync(self.loop, self.set_session)
388
+ if block_size and size and info.get("partial", True):
389
+ return HTTPFile(
390
+ self,
391
+ path,
392
+ session=session,
393
+ block_size=block_size,
394
+ mode=mode,
395
+ size=size,
396
+ cache_type=cache_type or self.cache_type,
397
+ cache_options=cache_options or self.cache_options,
398
+ loop=self.loop,
399
+ **kw,
400
+ )
401
+ else:
402
+ return HTTPStreamFile(
403
+ self,
404
+ path,
405
+ mode=mode,
406
+ loop=self.loop,
407
+ session=session,
408
+ **kw,
409
+ )
410
+
411
+ async def open_async(self, path, mode="rb", size=None, **kwargs):
412
+ session = await self.set_session()
413
+ if size is None:
414
+ try:
415
+ size = (await self._info(path, **kwargs))["size"]
416
+ except FileNotFoundError:
417
+ pass
418
+ return AsyncStreamFile(
419
+ self,
420
+ path,
421
+ loop=self.loop,
422
+ session=session,
423
+ size=size,
424
+ **kwargs,
425
+ )
426
+
427
+ def ukey(self, url):
428
+ """Unique identifier; assume HTTP files are static, unchanging"""
429
+ return tokenize(url, self.kwargs, self.protocol)
430
+
431
+ async def _info(self, url, **kwargs):
432
+ """Get info of URL
433
+
434
+ Tries to access location via HEAD, and then GET methods, but does
435
+ not fetch the data.
436
+
437
+ It is possible that the server does not supply any size information, in
438
+ which case size will be given as None (and certain operations on the
439
+ corresponding file will not work).
440
+ """
441
+ info = {}
442
+ session = await self.set_session()
443
+
444
+ for policy in ["head", "get"]:
445
+ try:
446
+ info.update(
447
+ await _file_info(
448
+ self.encode_url(url),
449
+ size_policy=policy,
450
+ session=session,
451
+ **self.kwargs,
452
+ **kwargs,
453
+ )
454
+ )
455
+ if info.get("size") is not None:
456
+ break
457
+ except Exception as exc:
458
+ if policy == "get":
459
+ # If get failed, then raise a FileNotFoundError
460
+ raise FileNotFoundError(url) from exc
461
+ logger.debug("", exc_info=exc)
462
+
463
+ return {"name": url, "size": None, **info, "type": "file"}
464
+
465
+ async def _glob(self, path, maxdepth=None, **kwargs):
466
+ """
467
+ Find files by glob-matching.
468
+
469
+ This implementation is idntical to the one in AbstractFileSystem,
470
+ but "?" is not considered as a character for globbing, because it is
471
+ so common in URLs, often identifying the "query" part.
472
+ """
473
+ if maxdepth is not None and maxdepth < 1:
474
+ raise ValueError("maxdepth must be at least 1")
475
+ import re
476
+
477
+ ends_with_slash = path.endswith("/") # _strip_protocol strips trailing slash
478
+ path = self._strip_protocol(path)
479
+ append_slash_to_dirname = ends_with_slash or path.endswith(("/**", "/*"))
480
+ idx_star = path.find("*") if path.find("*") >= 0 else len(path)
481
+ idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
482
+
483
+ min_idx = min(idx_star, idx_brace)
484
+
485
+ detail = kwargs.pop("detail", False)
486
+
487
+ if not has_magic(path):
488
+ if await self._exists(path, **kwargs):
489
+ if not detail:
490
+ return [path]
491
+ else:
492
+ return {path: await self._info(path, **kwargs)}
493
+ else:
494
+ if not detail:
495
+ return [] # glob of non-existent returns empty
496
+ else:
497
+ return {}
498
+ elif "/" in path[:min_idx]:
499
+ min_idx = path[:min_idx].rindex("/")
500
+ root = path[: min_idx + 1]
501
+ depth = path[min_idx + 1 :].count("/") + 1
502
+ else:
503
+ root = ""
504
+ depth = path[min_idx + 1 :].count("/") + 1
505
+
506
+ if "**" in path:
507
+ if maxdepth is not None:
508
+ idx_double_stars = path.find("**")
509
+ depth_double_stars = path[idx_double_stars:].count("/") + 1
510
+ depth = depth - depth_double_stars + maxdepth
511
+ else:
512
+ depth = None
513
+
514
+ allpaths = await self._find(
515
+ root, maxdepth=depth, withdirs=True, detail=True, **kwargs
516
+ )
517
+
518
+ pattern = glob_translate(path + ("/" if ends_with_slash else ""))
519
+ pattern = re.compile(pattern)
520
+
521
+ out = {
522
+ (
523
+ p.rstrip("/")
524
+ if not append_slash_to_dirname
525
+ and info["type"] == "directory"
526
+ and p.endswith("/")
527
+ else p
528
+ ): info
529
+ for p, info in sorted(allpaths.items())
530
+ if pattern.match(p.rstrip("/"))
531
+ }
532
+
533
+ if detail:
534
+ return out
535
+ else:
536
+ return list(out)
537
+
538
+ async def _isdir(self, path):
539
+ # override, since all URLs are (also) files
540
+ try:
541
+ return bool(await self._ls(path))
542
+ except (FileNotFoundError, ValueError):
543
+ return False
544
+
545
+ async def _pipe_file(self, path, value, mode="overwrite", **kwargs):
546
+ """
547
+ Write bytes to a remote file over HTTP.
548
+
549
+ Parameters
550
+ ----------
551
+ path : str
552
+ Target URL where the data should be written
553
+ value : bytes
554
+ Data to be written
555
+ mode : str
556
+ How to write to the file - 'overwrite' or 'append'
557
+ **kwargs : dict
558
+ Additional parameters to pass to the HTTP request
559
+ """
560
+ url = self._strip_protocol(path)
561
+ headers = kwargs.pop("headers", {})
562
+ headers["Content-Length"] = str(len(value))
563
+
564
+ session = await self.set_session()
565
+
566
+ async with session.put(
567
+ self.encode_url(url), data=value, headers=headers, **kwargs
568
+ ) as r:
569
+ r.raise_for_status()
570
+
571
+
572
+ class HTTPFile(AbstractBufferedFile):
573
+ """
574
+ A file-like object pointing to a remote HTTP(S) resource
575
+
576
+ Supports only reading, with read-ahead of a predetermined block-size.
577
+
578
+ In the case that the server does not supply the filesize, only reading of
579
+ the complete file in one go is supported.
580
+
581
+ Parameters
582
+ ----------
583
+ url: str
584
+ Full URL of the remote resource, including the protocol
585
+ session: aiohttp.ClientSession or None
586
+ All calls will be made within this session, to avoid restarting
587
+ connections where the server allows this
588
+ block_size: int or None
589
+ The amount of read-ahead to do, in bytes. Default is 5MB, or the value
590
+ configured for the FileSystem creating this file
591
+ size: None or int
592
+ If given, this is the size of the file in bytes, and we don't attempt
593
+ to call the server to find the value.
594
+ kwargs: all other key-values are passed to requests calls.
595
+ """
596
+
597
+ def __init__(
598
+ self,
599
+ fs,
600
+ url,
601
+ session=None,
602
+ block_size=None,
603
+ mode="rb",
604
+ cache_type="bytes",
605
+ cache_options=None,
606
+ size=None,
607
+ loop=None,
608
+ asynchronous=False,
609
+ **kwargs,
610
+ ):
611
+ if mode != "rb":
612
+ raise NotImplementedError("File mode not supported")
613
+ self.asynchronous = asynchronous
614
+ self.loop = loop
615
+ self.url = url
616
+ self.session = session
617
+ self.details = {"name": url, "size": size, "type": "file"}
618
+ super().__init__(
619
+ fs=fs,
620
+ path=url,
621
+ mode=mode,
622
+ block_size=block_size,
623
+ cache_type=cache_type,
624
+ cache_options=cache_options,
625
+ **kwargs,
626
+ )
627
+
628
+ def read(self, length=-1):
629
+ """Read bytes from file
630
+
631
+ Parameters
632
+ ----------
633
+ length: int
634
+ Read up to this many bytes. If negative, read all content to end of
635
+ file. If the server has not supplied the filesize, attempting to
636
+ read only part of the data will raise a ValueError.
637
+ """
638
+ if (
639
+ (length < 0 and self.loc == 0) # explicit read all
640
+ # but not when the size is known and fits into a block anyways
641
+ and not (self.size is not None and self.size <= self.blocksize)
642
+ ):
643
+ self._fetch_all()
644
+ if self.size is None:
645
+ if length < 0:
646
+ self._fetch_all()
647
+ else:
648
+ length = min(self.size - self.loc, length)
649
+ return super().read(length)
650
+
651
+ async def async_fetch_all(self):
652
+ """Read whole file in one shot, without caching
653
+
654
+ This is only called when position is still at zero,
655
+ and read() is called without a byte-count.
656
+ """
657
+ logger.debug(f"Fetch all for {self}")
658
+ if not isinstance(self.cache, AllBytes):
659
+ r = await self.session.get(self.fs.encode_url(self.url), **self.kwargs)
660
+ async with r:
661
+ r.raise_for_status()
662
+ out = await r.read()
663
+ self.cache = AllBytes(
664
+ size=len(out), fetcher=None, blocksize=None, data=out
665
+ )
666
+ self.size = len(out)
667
+
668
+ _fetch_all = sync_wrapper(async_fetch_all)
669
+
670
+ def _parse_content_range(self, headers):
671
+ """Parse the Content-Range header"""
672
+ s = headers.get("Content-Range", "")
673
+ m = re.match(r"bytes (\d+-\d+|\*)/(\d+|\*)", s)
674
+ if not m:
675
+ return None, None, None
676
+
677
+ if m[1] == "*":
678
+ start = end = None
679
+ else:
680
+ start, end = [int(x) for x in m[1].split("-")]
681
+ total = None if m[2] == "*" else int(m[2])
682
+ return start, end, total
683
+
684
+ async def async_fetch_range(self, start, end):
685
+ """Download a block of data
686
+
687
+ The expectation is that the server returns only the requested bytes,
688
+ with HTTP code 206. If this is not the case, we first check the headers,
689
+ and then stream the output - if the data size is bigger than we
690
+ requested, an exception is raised.
691
+ """
692
+ logger.debug(f"Fetch range for {self}: {start}-{end}")
693
+ kwargs = self.kwargs.copy()
694
+ headers = kwargs.pop("headers", {}).copy()
695
+ headers["Range"] = f"bytes={start}-{end - 1}"
696
+ logger.debug(f"{self.url} : {headers['Range']}")
697
+ r = await self.session.get(
698
+ self.fs.encode_url(self.url), headers=headers, **kwargs
699
+ )
700
+ async with r:
701
+ if r.status == 416:
702
+ # range request outside file
703
+ return b""
704
+ r.raise_for_status()
705
+
706
+ # If the server has handled the range request, it should reply
707
+ # with status 206 (partial content). But we'll guess that a suitable
708
+ # Content-Range header or a Content-Length no more than the
709
+ # requested range also mean we have got the desired range.
710
+ response_is_range = (
711
+ r.status == 206
712
+ or self._parse_content_range(r.headers)[0] == start
713
+ or int(r.headers.get("Content-Length", end + 1)) <= end - start
714
+ )
715
+
716
+ if response_is_range:
717
+ # partial content, as expected
718
+ out = await r.read()
719
+ elif start > 0:
720
+ raise ValueError(
721
+ "The HTTP server doesn't appear to support range requests. "
722
+ "Only reading this file from the beginning is supported. "
723
+ "Open with block_size=0 for a streaming file interface."
724
+ )
725
+ else:
726
+ # Response is not a range, but we want the start of the file,
727
+ # so we can read the required amount anyway.
728
+ cl = 0
729
+ out = []
730
+ while True:
731
+ chunk = await r.content.read(2**20)
732
+ # data size unknown, let's read until we have enough
733
+ if chunk:
734
+ out.append(chunk)
735
+ cl += len(chunk)
736
+ if cl > end - start:
737
+ break
738
+ else:
739
+ break
740
+ out = b"".join(out)[: end - start]
741
+ return out
742
+
743
+ _fetch_range = sync_wrapper(async_fetch_range)
744
+
745
+
746
+ magic_check = re.compile("([*[])")
747
+
748
+
749
+ def has_magic(s):
750
+ match = magic_check.search(s)
751
+ return match is not None
752
+
753
+
754
+ class HTTPStreamFile(AbstractBufferedFile):
755
+ def __init__(self, fs, url, mode="rb", loop=None, session=None, **kwargs):
756
+ self.asynchronous = kwargs.pop("asynchronous", False)
757
+ self.url = url
758
+ self.loop = loop
759
+ self.session = session
760
+ if mode != "rb":
761
+ raise ValueError
762
+ self.details = {"name": url, "size": None}
763
+ super().__init__(fs=fs, path=url, mode=mode, cache_type="none", **kwargs)
764
+
765
+ async def cor():
766
+ r = await self.session.get(self.fs.encode_url(url), **kwargs).__aenter__()
767
+ self.fs._raise_not_found_for_status(r, url)
768
+ return r
769
+
770
+ self.r = sync(self.loop, cor)
771
+ self.loop = fs.loop
772
+
773
+ def seek(self, loc, whence=0):
774
+ if loc == 0 and whence == 1:
775
+ return
776
+ if loc == self.loc and whence == 0:
777
+ return
778
+ raise ValueError("Cannot seek streaming HTTP file")
779
+
780
+ async def _read(self, num=-1):
781
+ out = await self.r.content.read(num)
782
+ self.loc += len(out)
783
+ return out
784
+
785
+ read = sync_wrapper(_read)
786
+
787
+ async def _close(self):
788
+ self.r.close()
789
+
790
+ def close(self):
791
+ asyncio.run_coroutine_threadsafe(self._close(), self.loop)
792
+ super().close()
793
+
794
+
795
+ class AsyncStreamFile(AbstractAsyncStreamedFile):
796
+ def __init__(
797
+ self, fs, url, mode="rb", loop=None, session=None, size=None, **kwargs
798
+ ):
799
+ self.url = url
800
+ self.session = session
801
+ self.r = None
802
+ if mode != "rb":
803
+ raise ValueError
804
+ self.details = {"name": url, "size": None}
805
+ self.kwargs = kwargs
806
+ super().__init__(fs=fs, path=url, mode=mode, cache_type="none")
807
+ self.size = size
808
+
809
+ async def read(self, num=-1):
810
+ if self.r is None:
811
+ r = await self.session.get(
812
+ self.fs.encode_url(self.url), **self.kwargs
813
+ ).__aenter__()
814
+ self.fs._raise_not_found_for_status(r, self.url)
815
+ self.r = r
816
+ out = await self.r.content.read(num)
817
+ self.loc += len(out)
818
+ return out
819
+
820
+ async def close(self):
821
+ if self.r is not None:
822
+ self.r.close()
823
+ self.r = None
824
+ await super().close()
825
+
826
+
827
+ async def get_range(session, url, start, end, file=None, **kwargs):
828
+ # explicit get a range when we know it must be safe
829
+ kwargs = kwargs.copy()
830
+ headers = kwargs.pop("headers", {}).copy()
831
+ headers["Range"] = f"bytes={start}-{end - 1}"
832
+ r = await session.get(url, headers=headers, **kwargs)
833
+ r.raise_for_status()
834
+ async with r:
835
+ out = await r.read()
836
+ if file:
837
+ with open(file, "r+b") as f: # noqa: ASYNC230
838
+ f.seek(start)
839
+ f.write(out)
840
+ else:
841
+ return out
842
+
843
+
844
+ async def _file_info(url, session, size_policy="head", **kwargs):
845
+ """Call HEAD on the server to get details about the file (size/checksum etc.)
846
+
847
+ Default operation is to explicitly allow redirects and use encoding
848
+ 'identity' (no compression) to get the true size of the target.
849
+ """
850
+ logger.debug("Retrieve file size for %s", url)
851
+ kwargs = kwargs.copy()
852
+ ar = kwargs.pop("allow_redirects", True)
853
+ head = kwargs.get("headers", {}).copy()
854
+ head["Accept-Encoding"] = "identity"
855
+ kwargs["headers"] = head
856
+
857
+ info = {}
858
+ if size_policy == "head":
859
+ r = await session.head(url, allow_redirects=ar, **kwargs)
860
+ elif size_policy == "get":
861
+ r = await session.get(url, allow_redirects=ar, **kwargs)
862
+ else:
863
+ raise TypeError(f'size_policy must be "head" or "get", got {size_policy}')
864
+ async with r:
865
+ r.raise_for_status()
866
+
867
+ if "Content-Length" in r.headers:
868
+ # Some servers may choose to ignore Accept-Encoding and return
869
+ # compressed content, in which case the returned size is unreliable.
870
+ if "Content-Encoding" not in r.headers or r.headers["Content-Encoding"] in [
871
+ "identity",
872
+ "",
873
+ ]:
874
+ info["size"] = int(r.headers["Content-Length"])
875
+ elif "Content-Range" in r.headers:
876
+ info["size"] = int(r.headers["Content-Range"].split("/")[1])
877
+
878
+ if "Content-Type" in r.headers:
879
+ info["mimetype"] = r.headers["Content-Type"].partition(";")[0]
880
+
881
+ if r.headers.get("Accept-Ranges") == "none":
882
+ # Some servers may explicitly discourage partial content requests, but
883
+ # the lack of "Accept-Ranges" does not always indicate they would fail
884
+ info["partial"] = False
885
+
886
+ info["url"] = str(r.url)
887
+
888
+ for checksum_field in ["ETag", "Content-MD5", "Digest", "Last-Modified"]:
889
+ if r.headers.get(checksum_field):
890
+ info[checksum_field] = r.headers[checksum_field]
891
+
892
+ return info
893
+
894
+
895
+ async def _file_size(url, session=None, *args, **kwargs):
896
+ if session is None:
897
+ session = await get_client()
898
+ info = await _file_info(url, session=session, *args, **kwargs)
899
+ return info.get("size")
900
+
901
+
902
+ file_size = sync_wrapper(_file_size)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/http_sync.py ADDED
@@ -0,0 +1,937 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This file is largely copied from http.py"""
2
+
3
+ import io
4
+ import logging
5
+ import re
6
+ import urllib.error
7
+ import urllib.parse
8
+ from copy import copy
9
+ from json import dumps, loads
10
+ from urllib.parse import urlparse
11
+
12
+ try:
13
+ import yarl
14
+ except (ImportError, ModuleNotFoundError, OSError):
15
+ yarl = False
16
+
17
+ from fsspec.callbacks import _DEFAULT_CALLBACK
18
+ from fsspec.registry import register_implementation
19
+ from fsspec.spec import AbstractBufferedFile, AbstractFileSystem
20
+ from fsspec.utils import DEFAULT_BLOCK_SIZE, isfilelike, nullcontext, tokenize
21
+
22
+ from ..caching import AllBytes
23
+
24
+ # https://stackoverflow.com/a/15926317/3821154
25
+ ex = re.compile(r"""<(a|A)\s+(?:[^>]*?\s+)?(href|HREF)=["'](?P<url>[^"']+)""")
26
+ ex2 = re.compile(r"""(?P<url>http[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""")
27
+ logger = logging.getLogger("fsspec.http")
28
+
29
+
30
+ class JsHttpException(urllib.error.HTTPError): ...
31
+
32
+
33
+ class StreamIO(io.BytesIO):
34
+ # fake class, so you can set attributes on it
35
+ # will eventually actually stream
36
+ ...
37
+
38
+
39
+ class ResponseProxy:
40
+ """Looks like a requests response"""
41
+
42
+ def __init__(self, req, stream=False):
43
+ self.request = req
44
+ self.stream = stream
45
+ self._data = None
46
+ self._headers = None
47
+
48
+ @property
49
+ def raw(self):
50
+ if self._data is None:
51
+ b = self.request.response.to_bytes()
52
+ if self.stream:
53
+ self._data = StreamIO(b)
54
+ else:
55
+ self._data = b
56
+ return self._data
57
+
58
+ def close(self):
59
+ if hasattr(self, "_data"):
60
+ del self._data
61
+
62
+ @property
63
+ def headers(self):
64
+ if self._headers is None:
65
+ self._headers = dict(
66
+ [
67
+ _.split(": ")
68
+ for _ in self.request.getAllResponseHeaders().strip().split("\r\n")
69
+ ]
70
+ )
71
+ return self._headers
72
+
73
+ @property
74
+ def status_code(self):
75
+ return int(self.request.status)
76
+
77
+ def raise_for_status(self):
78
+ if not self.ok:
79
+ raise JsHttpException(
80
+ self.url, self.status_code, self.reason, self.headers, None
81
+ )
82
+
83
+ def iter_content(self, chunksize, *_, **__):
84
+ while True:
85
+ out = self.raw.read(chunksize)
86
+ if out:
87
+ yield out
88
+ else:
89
+ break
90
+
91
+ @property
92
+ def reason(self):
93
+ return self.request.statusText
94
+
95
+ @property
96
+ def ok(self):
97
+ return self.status_code < 400
98
+
99
+ @property
100
+ def url(self):
101
+ return self.request.response.responseURL
102
+
103
+ @property
104
+ def text(self):
105
+ # TODO: encoding from headers
106
+ return self.content.decode()
107
+
108
+ @property
109
+ def content(self):
110
+ self.stream = False
111
+ return self.raw
112
+
113
+ def json(self):
114
+ return loads(self.text)
115
+
116
+
117
+ class RequestsSessionShim:
118
+ def __init__(self):
119
+ self.headers = {}
120
+
121
+ def request(
122
+ self,
123
+ method,
124
+ url,
125
+ params=None,
126
+ data=None,
127
+ headers=None,
128
+ cookies=None,
129
+ files=None,
130
+ auth=None,
131
+ timeout=None,
132
+ allow_redirects=None,
133
+ proxies=None,
134
+ hooks=None,
135
+ stream=None,
136
+ verify=None,
137
+ cert=None,
138
+ json=None,
139
+ ):
140
+ from js import Blob, XMLHttpRequest
141
+
142
+ logger.debug("JS request: %s %s", method, url)
143
+
144
+ if cert or verify or proxies or files or cookies or hooks:
145
+ raise NotImplementedError
146
+ if data and json:
147
+ raise ValueError("Use json= or data=, not both")
148
+ req = XMLHttpRequest.new()
149
+ extra = auth if auth else ()
150
+ if params:
151
+ url = f"{url}?{urllib.parse.urlencode(params)}"
152
+ req.open(method, url, False, *extra)
153
+ if timeout:
154
+ req.timeout = timeout
155
+ if headers:
156
+ for k, v in headers.items():
157
+ req.setRequestHeader(k, v)
158
+
159
+ req.setRequestHeader("Accept", "application/octet-stream")
160
+ req.responseType = "arraybuffer"
161
+ if json:
162
+ blob = Blob.new([dumps(data)], {type: "application/json"})
163
+ req.send(blob)
164
+ elif data:
165
+ if isinstance(data, io.IOBase):
166
+ data = data.read()
167
+ blob = Blob.new([data], {type: "application/octet-stream"})
168
+ req.send(blob)
169
+ else:
170
+ req.send(None)
171
+ return ResponseProxy(req, stream=stream)
172
+
173
+ def get(self, url, **kwargs):
174
+ return self.request("GET", url, **kwargs)
175
+
176
+ def head(self, url, **kwargs):
177
+ return self.request("HEAD", url, **kwargs)
178
+
179
+ def post(self, url, **kwargs):
180
+ return self.request("POST}", url, **kwargs)
181
+
182
+ def put(self, url, **kwargs):
183
+ return self.request("PUT", url, **kwargs)
184
+
185
+ def patch(self, url, **kwargs):
186
+ return self.request("PATCH", url, **kwargs)
187
+
188
+ def delete(self, url, **kwargs):
189
+ return self.request("DELETE", url, **kwargs)
190
+
191
+
192
+ class HTTPFileSystem(AbstractFileSystem):
193
+ """
194
+ Simple File-System for fetching data via HTTP(S)
195
+
196
+ This is the BLOCKING version of the normal HTTPFileSystem. It uses
197
+ requests in normal python and the JS runtime in pyodide.
198
+
199
+ ***This implementation is extremely experimental, do not use unless
200
+ you are testing pyodide/pyscript integration***
201
+ """
202
+
203
+ protocol = ("http", "https", "sync-http", "sync-https")
204
+ sep = "/"
205
+
206
+ def __init__(
207
+ self,
208
+ simple_links=True,
209
+ block_size=None,
210
+ same_scheme=True,
211
+ cache_type="readahead",
212
+ cache_options=None,
213
+ client_kwargs=None,
214
+ encoded=False,
215
+ **storage_options,
216
+ ):
217
+ """
218
+
219
+ Parameters
220
+ ----------
221
+ block_size: int
222
+ Blocks to read bytes; if 0, will default to raw requests file-like
223
+ objects instead of HTTPFile instances
224
+ simple_links: bool
225
+ If True, will consider both HTML <a> tags and anything that looks
226
+ like a URL; if False, will consider only the former.
227
+ same_scheme: True
228
+ When doing ls/glob, if this is True, only consider paths that have
229
+ http/https matching the input URLs.
230
+ size_policy: this argument is deprecated
231
+ client_kwargs: dict
232
+ Passed to aiohttp.ClientSession, see
233
+ https://docs.aiohttp.org/en/stable/client_reference.html
234
+ For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}``
235
+ storage_options: key-value
236
+ Any other parameters passed on to requests
237
+ cache_type, cache_options: defaults used in open
238
+ """
239
+ super().__init__(self, **storage_options)
240
+ self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE
241
+ self.simple_links = simple_links
242
+ self.same_schema = same_scheme
243
+ self.cache_type = cache_type
244
+ self.cache_options = cache_options
245
+ self.client_kwargs = client_kwargs or {}
246
+ self.encoded = encoded
247
+ self.kwargs = storage_options
248
+
249
+ try:
250
+ import js # noqa: F401
251
+
252
+ logger.debug("Starting JS session")
253
+ self.session = RequestsSessionShim()
254
+ self.js = True
255
+ except Exception as e:
256
+ import requests
257
+
258
+ logger.debug("Starting cpython session because of: %s", e)
259
+ self.session = requests.Session(**(client_kwargs or {}))
260
+ self.js = False
261
+
262
+ request_options = copy(storage_options)
263
+ self.use_listings_cache = request_options.pop("use_listings_cache", False)
264
+ request_options.pop("listings_expiry_time", None)
265
+ request_options.pop("max_paths", None)
266
+ request_options.pop("skip_instance_cache", None)
267
+ self.kwargs = request_options
268
+
269
+ @property
270
+ def fsid(self):
271
+ return "sync-http"
272
+
273
+ def encode_url(self, url):
274
+ if yarl:
275
+ return yarl.URL(url, encoded=self.encoded)
276
+ return url
277
+
278
+ @classmethod
279
+ def _strip_protocol(cls, path: str) -> str:
280
+ """For HTTP, we always want to keep the full URL"""
281
+ path = path.replace("sync-http://", "http://").replace(
282
+ "sync-https://", "https://"
283
+ )
284
+ return path
285
+
286
+ @classmethod
287
+ def _parent(cls, path):
288
+ # override, since _strip_protocol is different for URLs
289
+ par = super()._parent(path)
290
+ if len(par) > 7: # "http://..."
291
+ return par
292
+ return ""
293
+
294
+ def _ls_real(self, url, detail=True, **kwargs):
295
+ # ignoring URL-encoded arguments
296
+ kw = self.kwargs.copy()
297
+ kw.update(kwargs)
298
+ logger.debug(url)
299
+ r = self.session.get(self.encode_url(url), **self.kwargs)
300
+ self._raise_not_found_for_status(r, url)
301
+ text = r.text
302
+ if self.simple_links:
303
+ links = ex2.findall(text) + [u[2] for u in ex.findall(text)]
304
+ else:
305
+ links = [u[2] for u in ex.findall(text)]
306
+ out = set()
307
+ parts = urlparse(url)
308
+ for l in links:
309
+ if isinstance(l, tuple):
310
+ l = l[1]
311
+ if l.startswith("/") and len(l) > 1:
312
+ # absolute URL on this server
313
+ l = parts.scheme + "://" + parts.netloc + l
314
+ if l.startswith("http"):
315
+ if self.same_schema and l.startswith(url.rstrip("/") + "/"):
316
+ out.add(l)
317
+ elif l.replace("https", "http").startswith(
318
+ url.replace("https", "http").rstrip("/") + "/"
319
+ ):
320
+ # allowed to cross http <-> https
321
+ out.add(l)
322
+ else:
323
+ if l not in ["..", "../"]:
324
+ # Ignore FTP-like "parent"
325
+ out.add("/".join([url.rstrip("/"), l.lstrip("/")]))
326
+ if not out and url.endswith("/"):
327
+ out = self._ls_real(url.rstrip("/"), detail=False)
328
+ if detail:
329
+ return [
330
+ {
331
+ "name": u,
332
+ "size": None,
333
+ "type": "directory" if u.endswith("/") else "file",
334
+ }
335
+ for u in out
336
+ ]
337
+ else:
338
+ return sorted(out)
339
+
340
+ def ls(self, url, detail=True, **kwargs):
341
+ if self.use_listings_cache and url in self.dircache:
342
+ out = self.dircache[url]
343
+ else:
344
+ out = self._ls_real(url, detail=detail, **kwargs)
345
+ self.dircache[url] = out
346
+ return out
347
+
348
+ def _raise_not_found_for_status(self, response, url):
349
+ """
350
+ Raises FileNotFoundError for 404s, otherwise uses raise_for_status.
351
+ """
352
+ if response.status_code == 404:
353
+ raise FileNotFoundError(url)
354
+ response.raise_for_status()
355
+
356
+ def cat_file(self, url, start=None, end=None, **kwargs):
357
+ kw = self.kwargs.copy()
358
+ kw.update(kwargs)
359
+ logger.debug(url)
360
+
361
+ if start is not None or end is not None:
362
+ if start == end:
363
+ return b""
364
+ headers = kw.pop("headers", {}).copy()
365
+
366
+ headers["Range"] = self._process_limits(url, start, end)
367
+ kw["headers"] = headers
368
+ r = self.session.get(self.encode_url(url), **kw)
369
+ self._raise_not_found_for_status(r, url)
370
+ return r.content
371
+
372
+ def get_file(
373
+ self, rpath, lpath, chunk_size=5 * 2**20, callback=_DEFAULT_CALLBACK, **kwargs
374
+ ):
375
+ kw = self.kwargs.copy()
376
+ kw.update(kwargs)
377
+ logger.debug(rpath)
378
+ r = self.session.get(self.encode_url(rpath), **kw)
379
+ try:
380
+ size = int(
381
+ r.headers.get("content-length", None)
382
+ or r.headers.get("Content-Length", None)
383
+ )
384
+ except (ValueError, KeyError, TypeError):
385
+ size = None
386
+
387
+ callback.set_size(size)
388
+ self._raise_not_found_for_status(r, rpath)
389
+ if not isfilelike(lpath):
390
+ lpath = open(lpath, "wb")
391
+ for chunk in r.iter_content(chunk_size, decode_unicode=False):
392
+ lpath.write(chunk)
393
+ callback.relative_update(len(chunk))
394
+
395
+ def put_file(
396
+ self,
397
+ lpath,
398
+ rpath,
399
+ chunk_size=5 * 2**20,
400
+ callback=_DEFAULT_CALLBACK,
401
+ method="post",
402
+ **kwargs,
403
+ ):
404
+ def gen_chunks():
405
+ # Support passing arbitrary file-like objects
406
+ # and use them instead of streams.
407
+ if isinstance(lpath, io.IOBase):
408
+ context = nullcontext(lpath)
409
+ use_seek = False # might not support seeking
410
+ else:
411
+ context = open(lpath, "rb")
412
+ use_seek = True
413
+
414
+ with context as f:
415
+ if use_seek:
416
+ callback.set_size(f.seek(0, 2))
417
+ f.seek(0)
418
+ else:
419
+ callback.set_size(getattr(f, "size", None))
420
+
421
+ chunk = f.read(chunk_size)
422
+ while chunk:
423
+ yield chunk
424
+ callback.relative_update(len(chunk))
425
+ chunk = f.read(chunk_size)
426
+
427
+ kw = self.kwargs.copy()
428
+ kw.update(kwargs)
429
+
430
+ method = method.lower()
431
+ if method not in ("post", "put"):
432
+ raise ValueError(
433
+ f"method has to be either 'post' or 'put', not: {method!r}"
434
+ )
435
+
436
+ meth = getattr(self.session, method)
437
+ resp = meth(rpath, data=gen_chunks(), **kw)
438
+ self._raise_not_found_for_status(resp, rpath)
439
+
440
+ def _process_limits(self, url, start, end):
441
+ """Helper for "Range"-based _cat_file"""
442
+ size = None
443
+ suff = False
444
+ if start is not None and start < 0:
445
+ # if start is negative and end None, end is the "suffix length"
446
+ if end is None:
447
+ end = -start
448
+ start = ""
449
+ suff = True
450
+ else:
451
+ size = size or self.info(url)["size"]
452
+ start = size + start
453
+ elif start is None:
454
+ start = 0
455
+ if not suff:
456
+ if end is not None and end < 0:
457
+ if start is not None:
458
+ size = size or self.info(url)["size"]
459
+ end = size + end
460
+ elif end is None:
461
+ end = ""
462
+ if isinstance(end, int):
463
+ end -= 1 # bytes range is inclusive
464
+ return f"bytes={start}-{end}"
465
+
466
+ def exists(self, path, strict=False, **kwargs):
467
+ kw = self.kwargs.copy()
468
+ kw.update(kwargs)
469
+ try:
470
+ logger.debug(path)
471
+ r = self.session.get(self.encode_url(path), **kw)
472
+ if strict:
473
+ self._raise_not_found_for_status(r, path)
474
+ return r.status_code < 400
475
+ except FileNotFoundError:
476
+ return False
477
+ except Exception:
478
+ if strict:
479
+ raise
480
+ return False
481
+
482
+ def isfile(self, path, **kwargs):
483
+ return self.exists(path, **kwargs)
484
+
485
+ def _open(
486
+ self,
487
+ path,
488
+ mode="rb",
489
+ block_size=None,
490
+ autocommit=None, # XXX: This differs from the base class.
491
+ cache_type=None,
492
+ cache_options=None,
493
+ size=None,
494
+ **kwargs,
495
+ ):
496
+ """Make a file-like object
497
+
498
+ Parameters
499
+ ----------
500
+ path: str
501
+ Full URL with protocol
502
+ mode: string
503
+ must be "rb"
504
+ block_size: int or None
505
+ Bytes to download in one request; use instance value if None. If
506
+ zero, will return a streaming Requests file-like instance.
507
+ kwargs: key-value
508
+ Any other parameters, passed to requests calls
509
+ """
510
+ if mode != "rb":
511
+ raise NotImplementedError
512
+ block_size = block_size if block_size is not None else self.block_size
513
+ kw = self.kwargs.copy()
514
+ kw.update(kwargs)
515
+ size = size or self.info(path, **kwargs)["size"]
516
+ if block_size and size:
517
+ return HTTPFile(
518
+ self,
519
+ path,
520
+ session=self.session,
521
+ block_size=block_size,
522
+ mode=mode,
523
+ size=size,
524
+ cache_type=cache_type or self.cache_type,
525
+ cache_options=cache_options or self.cache_options,
526
+ **kw,
527
+ )
528
+ else:
529
+ return HTTPStreamFile(
530
+ self,
531
+ path,
532
+ mode=mode,
533
+ session=self.session,
534
+ **kw,
535
+ )
536
+
537
+ def ukey(self, url):
538
+ """Unique identifier; assume HTTP files are static, unchanging"""
539
+ return tokenize(url, self.kwargs, self.protocol)
540
+
541
+ def info(self, url, **kwargs):
542
+ """Get info of URL
543
+
544
+ Tries to access location via HEAD, and then GET methods, but does
545
+ not fetch the data.
546
+
547
+ It is possible that the server does not supply any size information, in
548
+ which case size will be given as None (and certain operations on the
549
+ corresponding file will not work).
550
+ """
551
+ info = {}
552
+ for policy in ["head", "get"]:
553
+ try:
554
+ info.update(
555
+ _file_info(
556
+ self.encode_url(url),
557
+ size_policy=policy,
558
+ session=self.session,
559
+ **self.kwargs,
560
+ **kwargs,
561
+ )
562
+ )
563
+ if info.get("size") is not None:
564
+ break
565
+ except Exception as exc:
566
+ if policy == "get":
567
+ # If get failed, then raise a FileNotFoundError
568
+ raise FileNotFoundError(url) from exc
569
+ logger.debug(str(exc))
570
+
571
+ return {"name": url, "size": None, **info, "type": "file"}
572
+
573
+ def glob(self, path, maxdepth=None, **kwargs):
574
+ """
575
+ Find files by glob-matching.
576
+
577
+ This implementation is idntical to the one in AbstractFileSystem,
578
+ but "?" is not considered as a character for globbing, because it is
579
+ so common in URLs, often identifying the "query" part.
580
+ """
581
+ import re
582
+
583
+ ends = path.endswith("/")
584
+ path = self._strip_protocol(path)
585
+ indstar = path.find("*") if path.find("*") >= 0 else len(path)
586
+ indbrace = path.find("[") if path.find("[") >= 0 else len(path)
587
+
588
+ ind = min(indstar, indbrace)
589
+
590
+ detail = kwargs.pop("detail", False)
591
+
592
+ if not has_magic(path):
593
+ root = path
594
+ depth = 1
595
+ if ends:
596
+ path += "/*"
597
+ elif self.exists(path):
598
+ if not detail:
599
+ return [path]
600
+ else:
601
+ return {path: self.info(path)}
602
+ else:
603
+ if not detail:
604
+ return [] # glob of non-existent returns empty
605
+ else:
606
+ return {}
607
+ elif "/" in path[:ind]:
608
+ ind2 = path[:ind].rindex("/")
609
+ root = path[: ind2 + 1]
610
+ depth = None if "**" in path else path[ind2 + 1 :].count("/") + 1
611
+ else:
612
+ root = ""
613
+ depth = None if "**" in path else path[ind + 1 :].count("/") + 1
614
+
615
+ allpaths = self.find(
616
+ root, maxdepth=maxdepth or depth, withdirs=True, detail=True, **kwargs
617
+ )
618
+ # Escape characters special to python regex, leaving our supported
619
+ # special characters in place.
620
+ # See https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html
621
+ # for shell globbing details.
622
+ pattern = (
623
+ "^"
624
+ + (
625
+ path.replace("\\", r"\\")
626
+ .replace(".", r"\.")
627
+ .replace("+", r"\+")
628
+ .replace("//", "/")
629
+ .replace("(", r"\(")
630
+ .replace(")", r"\)")
631
+ .replace("|", r"\|")
632
+ .replace("^", r"\^")
633
+ .replace("$", r"\$")
634
+ .replace("{", r"\{")
635
+ .replace("}", r"\}")
636
+ .rstrip("/")
637
+ )
638
+ + "$"
639
+ )
640
+ pattern = re.sub("[*]{2}", "=PLACEHOLDER=", pattern)
641
+ pattern = re.sub("[*]", "[^/]*", pattern)
642
+ pattern = re.compile(pattern.replace("=PLACEHOLDER=", ".*"))
643
+ out = {
644
+ p: allpaths[p]
645
+ for p in sorted(allpaths)
646
+ if pattern.match(p.replace("//", "/").rstrip("/"))
647
+ }
648
+ if detail:
649
+ return out
650
+ else:
651
+ return list(out)
652
+
653
+ def isdir(self, path):
654
+ # override, since all URLs are (also) files
655
+ try:
656
+ return bool(self.ls(path))
657
+ except (FileNotFoundError, ValueError):
658
+ return False
659
+
660
+
661
+ class HTTPFile(AbstractBufferedFile):
662
+ """
663
+ A file-like object pointing to a remove HTTP(S) resource
664
+
665
+ Supports only reading, with read-ahead of a predermined block-size.
666
+
667
+ In the case that the server does not supply the filesize, only reading of
668
+ the complete file in one go is supported.
669
+
670
+ Parameters
671
+ ----------
672
+ url: str
673
+ Full URL of the remote resource, including the protocol
674
+ session: requests.Session or None
675
+ All calls will be made within this session, to avoid restarting
676
+ connections where the server allows this
677
+ block_size: int or None
678
+ The amount of read-ahead to do, in bytes. Default is 5MB, or the value
679
+ configured for the FileSystem creating this file
680
+ size: None or int
681
+ If given, this is the size of the file in bytes, and we don't attempt
682
+ to call the server to find the value.
683
+ kwargs: all other key-values are passed to requests calls.
684
+ """
685
+
686
+ def __init__(
687
+ self,
688
+ fs,
689
+ url,
690
+ session=None,
691
+ block_size=None,
692
+ mode="rb",
693
+ cache_type="bytes",
694
+ cache_options=None,
695
+ size=None,
696
+ **kwargs,
697
+ ):
698
+ if mode != "rb":
699
+ raise NotImplementedError("File mode not supported")
700
+ self.url = url
701
+ self.session = session
702
+ self.details = {"name": url, "size": size, "type": "file"}
703
+ super().__init__(
704
+ fs=fs,
705
+ path=url,
706
+ mode=mode,
707
+ block_size=block_size,
708
+ cache_type=cache_type,
709
+ cache_options=cache_options,
710
+ **kwargs,
711
+ )
712
+
713
+ def read(self, length=-1):
714
+ """Read bytes from file
715
+
716
+ Parameters
717
+ ----------
718
+ length: int
719
+ Read up to this many bytes. If negative, read all content to end of
720
+ file. If the server has not supplied the filesize, attempting to
721
+ read only part of the data will raise a ValueError.
722
+ """
723
+ if (
724
+ (length < 0 and self.loc == 0) # explicit read all
725
+ # but not when the size is known and fits into a block anyways
726
+ and not (self.size is not None and self.size <= self.blocksize)
727
+ ):
728
+ self._fetch_all()
729
+ if self.size is None:
730
+ if length < 0:
731
+ self._fetch_all()
732
+ else:
733
+ length = min(self.size - self.loc, length)
734
+ return super().read(length)
735
+
736
+ def _fetch_all(self):
737
+ """Read whole file in one shot, without caching
738
+
739
+ This is only called when position is still at zero,
740
+ and read() is called without a byte-count.
741
+ """
742
+ logger.debug(f"Fetch all for {self}")
743
+ if not isinstance(self.cache, AllBytes):
744
+ r = self.session.get(self.fs.encode_url(self.url), **self.kwargs)
745
+ r.raise_for_status()
746
+ out = r.content
747
+ self.cache = AllBytes(size=len(out), fetcher=None, blocksize=None, data=out)
748
+ self.size = len(out)
749
+
750
+ def _parse_content_range(self, headers):
751
+ """Parse the Content-Range header"""
752
+ s = headers.get("Content-Range", "")
753
+ m = re.match(r"bytes (\d+-\d+|\*)/(\d+|\*)", s)
754
+ if not m:
755
+ return None, None, None
756
+
757
+ if m[1] == "*":
758
+ start = end = None
759
+ else:
760
+ start, end = [int(x) for x in m[1].split("-")]
761
+ total = None if m[2] == "*" else int(m[2])
762
+ return start, end, total
763
+
764
+ def _fetch_range(self, start, end):
765
+ """Download a block of data
766
+
767
+ The expectation is that the server returns only the requested bytes,
768
+ with HTTP code 206. If this is not the case, we first check the headers,
769
+ and then stream the output - if the data size is bigger than we
770
+ requested, an exception is raised.
771
+ """
772
+ logger.debug(f"Fetch range for {self}: {start}-{end}")
773
+ kwargs = self.kwargs.copy()
774
+ headers = kwargs.pop("headers", {}).copy()
775
+ headers["Range"] = f"bytes={start}-{end - 1}"
776
+ logger.debug("%s : %s", self.url, headers["Range"])
777
+ r = self.session.get(self.fs.encode_url(self.url), headers=headers, **kwargs)
778
+ if r.status_code == 416:
779
+ # range request outside file
780
+ return b""
781
+ r.raise_for_status()
782
+
783
+ # If the server has handled the range request, it should reply
784
+ # with status 206 (partial content). But we'll guess that a suitable
785
+ # Content-Range header or a Content-Length no more than the
786
+ # requested range also mean we have got the desired range.
787
+ cl = r.headers.get("Content-Length", r.headers.get("content-length", end + 1))
788
+ response_is_range = (
789
+ r.status_code == 206
790
+ or self._parse_content_range(r.headers)[0] == start
791
+ or int(cl) <= end - start
792
+ )
793
+
794
+ if response_is_range:
795
+ # partial content, as expected
796
+ out = r.content
797
+ elif start > 0:
798
+ raise ValueError(
799
+ "The HTTP server doesn't appear to support range requests. "
800
+ "Only reading this file from the beginning is supported. "
801
+ "Open with block_size=0 for a streaming file interface."
802
+ )
803
+ else:
804
+ # Response is not a range, but we want the start of the file,
805
+ # so we can read the required amount anyway.
806
+ cl = 0
807
+ out = []
808
+ for chunk in r.iter_content(2**20, False):
809
+ out.append(chunk)
810
+ cl += len(chunk)
811
+ out = b"".join(out)[: end - start]
812
+ return out
813
+
814
+
815
+ magic_check = re.compile("([*[])")
816
+
817
+
818
+ def has_magic(s):
819
+ match = magic_check.search(s)
820
+ return match is not None
821
+
822
+
823
+ class HTTPStreamFile(AbstractBufferedFile):
824
+ def __init__(self, fs, url, mode="rb", session=None, **kwargs):
825
+ self.url = url
826
+ self.session = session
827
+ if mode != "rb":
828
+ raise ValueError
829
+ self.details = {"name": url, "size": None}
830
+ super().__init__(fs=fs, path=url, mode=mode, cache_type="readahead", **kwargs)
831
+
832
+ r = self.session.get(self.fs.encode_url(url), stream=True, **kwargs)
833
+ self.fs._raise_not_found_for_status(r, url)
834
+ self.it = r.iter_content(1024, False)
835
+ self.leftover = b""
836
+
837
+ self.r = r
838
+
839
+ def seek(self, *args, **kwargs):
840
+ raise ValueError("Cannot seek streaming HTTP file")
841
+
842
+ def read(self, num=-1):
843
+ bufs = [self.leftover]
844
+ leng = len(self.leftover)
845
+ while leng < num or num < 0:
846
+ try:
847
+ out = self.it.__next__()
848
+ except StopIteration:
849
+ break
850
+ if out:
851
+ bufs.append(out)
852
+ else:
853
+ break
854
+ leng += len(out)
855
+ out = b"".join(bufs)
856
+ if num >= 0:
857
+ self.leftover = out[num:]
858
+ out = out[:num]
859
+ else:
860
+ self.leftover = b""
861
+ self.loc += len(out)
862
+ return out
863
+
864
+ def close(self):
865
+ self.r.close()
866
+ self.closed = True
867
+
868
+
869
+ def get_range(session, url, start, end, **kwargs):
870
+ # explicit get a range when we know it must be safe
871
+ kwargs = kwargs.copy()
872
+ headers = kwargs.pop("headers", {}).copy()
873
+ headers["Range"] = f"bytes={start}-{end - 1}"
874
+ r = session.get(url, headers=headers, **kwargs)
875
+ r.raise_for_status()
876
+ return r.content
877
+
878
+
879
+ def _file_info(url, session, size_policy="head", **kwargs):
880
+ """Call HEAD on the server to get details about the file (size/checksum etc.)
881
+
882
+ Default operation is to explicitly allow redirects and use encoding
883
+ 'identity' (no compression) to get the true size of the target.
884
+ """
885
+ logger.debug("Retrieve file size for %s", url)
886
+ kwargs = kwargs.copy()
887
+ ar = kwargs.pop("allow_redirects", True)
888
+ head = kwargs.get("headers", {}).copy()
889
+ # TODO: not allowed in JS
890
+ # head["Accept-Encoding"] = "identity"
891
+ kwargs["headers"] = head
892
+
893
+ info = {}
894
+ if size_policy == "head":
895
+ r = session.head(url, allow_redirects=ar, **kwargs)
896
+ elif size_policy == "get":
897
+ r = session.get(url, allow_redirects=ar, **kwargs)
898
+ else:
899
+ raise TypeError(f'size_policy must be "head" or "get", got {size_policy}')
900
+ r.raise_for_status()
901
+
902
+ # TODO:
903
+ # recognise lack of 'Accept-Ranges',
904
+ # or 'Accept-Ranges': 'none' (not 'bytes')
905
+ # to mean streaming only, no random access => return None
906
+ if "Content-Length" in r.headers:
907
+ info["size"] = int(r.headers["Content-Length"])
908
+ elif "Content-Range" in r.headers:
909
+ info["size"] = int(r.headers["Content-Range"].split("/")[1])
910
+ elif "content-length" in r.headers:
911
+ info["size"] = int(r.headers["content-length"])
912
+ elif "content-range" in r.headers:
913
+ info["size"] = int(r.headers["content-range"].split("/")[1])
914
+
915
+ for checksum_field in ["ETag", "Content-MD5", "Digest"]:
916
+ if r.headers.get(checksum_field):
917
+ info[checksum_field] = r.headers[checksum_field]
918
+
919
+ return info
920
+
921
+
922
+ # importing this is enough to register it
923
+ def register():
924
+ register_implementation("http", HTTPFileSystem, clobber=True)
925
+ register_implementation("https", HTTPFileSystem, clobber=True)
926
+ register_implementation("sync-http", HTTPFileSystem, clobber=True)
927
+ register_implementation("sync-https", HTTPFileSystem, clobber=True)
928
+
929
+
930
+ register()
931
+
932
+
933
+ def unregister():
934
+ from fsspec.implementations.http import HTTPFileSystem
935
+
936
+ register_implementation("http", HTTPFileSystem, clobber=True)
937
+ register_implementation("https", HTTPFileSystem, clobber=True)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/jupyter.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import io
3
+ import re
4
+
5
+ import requests
6
+
7
+ import fsspec
8
+
9
+
10
+ class JupyterFileSystem(fsspec.AbstractFileSystem):
11
+ """View of the files as seen by a Jupyter server (notebook or lab)"""
12
+
13
+ protocol = ("jupyter", "jlab")
14
+
15
+ def __init__(self, url, tok=None, **kwargs):
16
+ """
17
+
18
+ Parameters
19
+ ----------
20
+ url : str
21
+ Base URL of the server, like "http://127.0.0.1:8888". May include
22
+ token in the string, which is given by the process when starting up
23
+ tok : str
24
+ If the token is obtained separately, can be given here
25
+ kwargs
26
+ """
27
+ if "?" in url:
28
+ if tok is None:
29
+ try:
30
+ tok = re.findall("token=([a-z0-9]+)", url)[0]
31
+ except IndexError as e:
32
+ raise ValueError("Could not determine token") from e
33
+ url = url.split("?", 1)[0]
34
+ self.url = url.rstrip("/") + "/api/contents"
35
+ self.session = requests.Session()
36
+ if tok:
37
+ self.session.headers["Authorization"] = f"token {tok}"
38
+
39
+ super().__init__(**kwargs)
40
+
41
+ def ls(self, path, detail=True, **kwargs):
42
+ path = self._strip_protocol(path)
43
+ r = self.session.get(f"{self.url}/{path}")
44
+ if r.status_code == 404:
45
+ raise FileNotFoundError(path)
46
+ r.raise_for_status()
47
+ out = r.json()
48
+
49
+ if out["type"] == "directory":
50
+ out = out["content"]
51
+ else:
52
+ out = [out]
53
+ for o in out:
54
+ o["name"] = o.pop("path")
55
+ o.pop("content")
56
+ if o["type"] == "notebook":
57
+ o["type"] = "file"
58
+ if detail:
59
+ return out
60
+ return [o["name"] for o in out]
61
+
62
+ def cat_file(self, path, start=None, end=None, **kwargs):
63
+ path = self._strip_protocol(path)
64
+ r = self.session.get(f"{self.url}/{path}")
65
+ if r.status_code == 404:
66
+ raise FileNotFoundError(path)
67
+ r.raise_for_status()
68
+ out = r.json()
69
+ if out["format"] == "text":
70
+ # data should be binary
71
+ b = out["content"].encode()
72
+ else:
73
+ b = base64.b64decode(out["content"])
74
+ return b[start:end]
75
+
76
+ def pipe_file(self, path, value, **_):
77
+ path = self._strip_protocol(path)
78
+ json = {
79
+ "name": path.rsplit("/", 1)[-1],
80
+ "path": path,
81
+ "size": len(value),
82
+ "content": base64.b64encode(value).decode(),
83
+ "format": "base64",
84
+ "type": "file",
85
+ }
86
+ self.session.put(f"{self.url}/{path}", json=json)
87
+
88
+ def mkdir(self, path, create_parents=True, **kwargs):
89
+ path = self._strip_protocol(path)
90
+ if create_parents and "/" in path:
91
+ self.mkdir(path.rsplit("/", 1)[0], True)
92
+ json = {
93
+ "name": path.rsplit("/", 1)[-1],
94
+ "path": path,
95
+ "size": None,
96
+ "content": None,
97
+ "type": "directory",
98
+ }
99
+ self.session.put(f"{self.url}/{path}", json=json)
100
+
101
+ def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs):
102
+ if path1 == path2:
103
+ return
104
+ self.session.patch(f"{self.url}/{path1}", json={"path": path2})
105
+
106
+ def _rm(self, path):
107
+ path = self._strip_protocol(path)
108
+ self.session.delete(f"{self.url}/{path}")
109
+
110
+ def _open(self, path, mode="rb", **kwargs):
111
+ path = self._strip_protocol(path)
112
+ if mode == "rb":
113
+ data = self.cat_file(path)
114
+ return io.BytesIO(data)
115
+ else:
116
+ return SimpleFileWriter(self, path, mode="wb")
117
+
118
+
119
+ class SimpleFileWriter(fsspec.spec.AbstractBufferedFile):
120
+ def _upload_chunk(self, final=False):
121
+ """Never uploads a chunk until file is done
122
+
123
+ Not suitable for large files
124
+ """
125
+ if final is False:
126
+ return False
127
+ self.buffer.seek(0)
128
+ data = self.buffer.read()
129
+ self.fs.pipe_file(self.path, data)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/libarchive.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import contextmanager
2
+ from ctypes import (
3
+ CFUNCTYPE,
4
+ POINTER,
5
+ c_int,
6
+ c_longlong,
7
+ c_void_p,
8
+ cast,
9
+ create_string_buffer,
10
+ )
11
+
12
+ import libarchive
13
+ import libarchive.ffi as ffi
14
+
15
+ from fsspec import open_files
16
+ from fsspec.archive import AbstractArchiveFileSystem
17
+ from fsspec.implementations.memory import MemoryFile
18
+ from fsspec.utils import DEFAULT_BLOCK_SIZE
19
+
20
+ # Libarchive requires seekable files or memory only for certain archive
21
+ # types. However, since we read the directory first to cache the contents
22
+ # and also allow random access to any file, the file-like object needs
23
+ # to be seekable no matter what.
24
+
25
+ # Seek call-backs (not provided in the libarchive python wrapper)
26
+ SEEK_CALLBACK = CFUNCTYPE(c_longlong, c_int, c_void_p, c_longlong, c_int)
27
+ read_set_seek_callback = ffi.ffi(
28
+ "read_set_seek_callback", [ffi.c_archive_p, SEEK_CALLBACK], c_int, ffi.check_int
29
+ )
30
+ new_api = hasattr(ffi, "NO_OPEN_CB")
31
+
32
+
33
+ @contextmanager
34
+ def custom_reader(file, format_name="all", filter_name="all", block_size=ffi.page_size):
35
+ """Read an archive from a seekable file-like object.
36
+
37
+ The `file` object must support the standard `readinto` and 'seek' methods.
38
+ """
39
+ buf = create_string_buffer(block_size)
40
+ buf_p = cast(buf, c_void_p)
41
+
42
+ def read_func(archive_p, context, ptrptr):
43
+ # readinto the buffer, returns number of bytes read
44
+ length = file.readinto(buf)
45
+ # write the address of the buffer into the pointer
46
+ ptrptr = cast(ptrptr, POINTER(c_void_p))
47
+ ptrptr[0] = buf_p
48
+ # tell libarchive how much data was written into the buffer
49
+ return length
50
+
51
+ def seek_func(archive_p, context, offset, whence):
52
+ file.seek(offset, whence)
53
+ # tell libarchvie the current position
54
+ return file.tell()
55
+
56
+ read_cb = ffi.READ_CALLBACK(read_func)
57
+ seek_cb = SEEK_CALLBACK(seek_func)
58
+
59
+ if new_api:
60
+ open_cb = ffi.NO_OPEN_CB
61
+ close_cb = ffi.NO_CLOSE_CB
62
+ else:
63
+ open_cb = libarchive.read.OPEN_CALLBACK(ffi.VOID_CB)
64
+ close_cb = libarchive.read.CLOSE_CALLBACK(ffi.VOID_CB)
65
+
66
+ with libarchive.read.new_archive_read(format_name, filter_name) as archive_p:
67
+ read_set_seek_callback(archive_p, seek_cb)
68
+ ffi.read_open(archive_p, None, open_cb, read_cb, close_cb)
69
+ yield libarchive.read.ArchiveRead(archive_p)
70
+
71
+
72
+ class LibArchiveFileSystem(AbstractArchiveFileSystem):
73
+ """Compressed archives as a file-system (read-only)
74
+
75
+ Supports the following formats:
76
+ tar, pax , cpio, ISO9660, zip, mtree, shar, ar, raw, xar, lha/lzh, rar
77
+ Microsoft CAB, 7-Zip, WARC
78
+
79
+ See the libarchive documentation for further restrictions.
80
+ https://www.libarchive.org/
81
+
82
+ Keeps file object open while instance lives. It only works in seekable
83
+ file-like objects. In case the filesystem does not support this kind of
84
+ file object, it is recommended to cache locally.
85
+
86
+ This class is pickleable, but not necessarily thread-safe (depends on the
87
+ platform). See libarchive documentation for details.
88
+ """
89
+
90
+ root_marker = ""
91
+ protocol = "libarchive"
92
+ cachable = False
93
+
94
+ def __init__(
95
+ self,
96
+ fo="",
97
+ mode="r",
98
+ target_protocol=None,
99
+ target_options=None,
100
+ block_size=DEFAULT_BLOCK_SIZE,
101
+ **kwargs,
102
+ ):
103
+ """
104
+ Parameters
105
+ ----------
106
+ fo: str or file-like
107
+ Contains ZIP, and must exist. If a str, will fetch file using
108
+ :meth:`~fsspec.open_files`, which must return one file exactly.
109
+ mode: str
110
+ Currently, only 'r' accepted
111
+ target_protocol: str (optional)
112
+ If ``fo`` is a string, this value can be used to override the
113
+ FS protocol inferred from a URL
114
+ target_options: dict (optional)
115
+ Kwargs passed when instantiating the target FS, if ``fo`` is
116
+ a string.
117
+ """
118
+ super().__init__(self, **kwargs)
119
+ if mode != "r":
120
+ raise ValueError("Only read from archive files accepted")
121
+ if isinstance(fo, str):
122
+ files = open_files(fo, protocol=target_protocol, **(target_options or {}))
123
+ if len(files) != 1:
124
+ raise ValueError(
125
+ f'Path "{fo}" did not resolve to exactly one file: "{files}"'
126
+ )
127
+ fo = files[0]
128
+ self.of = fo
129
+ self.fo = fo.__enter__() # the whole instance is a context
130
+ self.block_size = block_size
131
+ self.dir_cache = None
132
+
133
+ @contextmanager
134
+ def _open_archive(self):
135
+ self.fo.seek(0)
136
+ with custom_reader(self.fo, block_size=self.block_size) as arc:
137
+ yield arc
138
+
139
+ @classmethod
140
+ def _strip_protocol(cls, path):
141
+ # file paths are always relative to the archive root
142
+ return super()._strip_protocol(path).lstrip("/")
143
+
144
+ def _get_dirs(self):
145
+ fields = {
146
+ "name": "pathname",
147
+ "size": "size",
148
+ "created": "ctime",
149
+ "mode": "mode",
150
+ "uid": "uid",
151
+ "gid": "gid",
152
+ "mtime": "mtime",
153
+ }
154
+
155
+ if self.dir_cache is not None:
156
+ return
157
+
158
+ self.dir_cache = {}
159
+ list_names = []
160
+ with self._open_archive() as arc:
161
+ for entry in arc:
162
+ if not entry.isdir and not entry.isfile:
163
+ # Skip symbolic links, fifo entries, etc.
164
+ continue
165
+ self.dir_cache.update(
166
+ {
167
+ dirname: {"name": dirname, "size": 0, "type": "directory"}
168
+ for dirname in self._all_dirnames(set(entry.name))
169
+ }
170
+ )
171
+ f = {key: getattr(entry, fields[key]) for key in fields}
172
+ f["type"] = "directory" if entry.isdir else "file"
173
+ list_names.append(entry.name)
174
+
175
+ self.dir_cache[f["name"]] = f
176
+ # libarchive does not seem to return an entry for the directories (at least
177
+ # not in all formats), so get the directories names from the files names
178
+ self.dir_cache.update(
179
+ {
180
+ dirname: {"name": dirname, "size": 0, "type": "directory"}
181
+ for dirname in self._all_dirnames(list_names)
182
+ }
183
+ )
184
+
185
+ def _open(
186
+ self,
187
+ path,
188
+ mode="rb",
189
+ block_size=None,
190
+ autocommit=True,
191
+ cache_options=None,
192
+ **kwargs,
193
+ ):
194
+ path = self._strip_protocol(path)
195
+ if mode != "rb":
196
+ raise NotImplementedError
197
+
198
+ data = b""
199
+ with self._open_archive() as arc:
200
+ for entry in arc:
201
+ if entry.pathname != path:
202
+ continue
203
+
204
+ if entry.size == 0:
205
+ # empty file, so there are no blocks
206
+ break
207
+
208
+ for block in entry.get_blocks(entry.size):
209
+ data = block
210
+ break
211
+ else:
212
+ raise ValueError
213
+ return MemoryFile(fs=self, path=path, data=data)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/local.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import io
3
+ import logging
4
+ import os
5
+ import os.path as osp
6
+ import shutil
7
+ import stat
8
+ import tempfile
9
+ from functools import lru_cache
10
+
11
+ from fsspec import AbstractFileSystem
12
+ from fsspec.compression import compr
13
+ from fsspec.core import get_compression
14
+ from fsspec.utils import isfilelike, stringify_path
15
+
16
+ logger = logging.getLogger("fsspec.local")
17
+
18
+
19
+ class LocalFileSystem(AbstractFileSystem):
20
+ """Interface to files on local storage
21
+
22
+ Parameters
23
+ ----------
24
+ auto_mkdir: bool
25
+ Whether, when opening a file, the directory containing it should
26
+ be created (if it doesn't already exist). This is assumed by pyarrow
27
+ code.
28
+ """
29
+
30
+ root_marker = "/"
31
+ protocol = "file", "local"
32
+ local_file = True
33
+
34
+ def __init__(self, auto_mkdir=False, **kwargs):
35
+ super().__init__(**kwargs)
36
+ self.auto_mkdir = auto_mkdir
37
+
38
+ @property
39
+ def fsid(self):
40
+ return "local"
41
+
42
+ def mkdir(self, path, create_parents=True, **kwargs):
43
+ path = self._strip_protocol(path)
44
+ if self.exists(path):
45
+ raise FileExistsError(path)
46
+ if create_parents:
47
+ self.makedirs(path, exist_ok=True)
48
+ else:
49
+ os.mkdir(path, **kwargs)
50
+
51
+ def makedirs(self, path, exist_ok=False):
52
+ path = self._strip_protocol(path)
53
+ os.makedirs(path, exist_ok=exist_ok)
54
+
55
+ def rmdir(self, path):
56
+ path = self._strip_protocol(path)
57
+ os.rmdir(path)
58
+
59
+ def ls(self, path, detail=False, **kwargs):
60
+ path = self._strip_protocol(path)
61
+ path_info = self.info(path)
62
+ infos = []
63
+ if path_info["type"] == "directory":
64
+ with os.scandir(path) as it:
65
+ for f in it:
66
+ try:
67
+ # Only get the info if requested since it is a bit expensive (the stat call inside)
68
+ # The strip_protocol is also used in info() and calls make_path_posix to always return posix paths
69
+ info = self.info(f) if detail else self._strip_protocol(f.path)
70
+ infos.append(info)
71
+ except FileNotFoundError:
72
+ pass
73
+ else:
74
+ infos = [path_info] if detail else [path_info["name"]]
75
+
76
+ return infos
77
+
78
+ def info(self, path, **kwargs):
79
+ if isinstance(path, os.DirEntry):
80
+ # scandir DirEntry
81
+ out = path.stat(follow_symlinks=False)
82
+ link = path.is_symlink()
83
+ if path.is_dir(follow_symlinks=False):
84
+ t = "directory"
85
+ elif path.is_file(follow_symlinks=False):
86
+ t = "file"
87
+ else:
88
+ t = "other"
89
+
90
+ size = out.st_size
91
+ if link:
92
+ try:
93
+ out2 = path.stat(follow_symlinks=True)
94
+ size = out2.st_size
95
+ except OSError:
96
+ size = 0
97
+ path = self._strip_protocol(path.path)
98
+ else:
99
+ # str or path-like
100
+ path = self._strip_protocol(path)
101
+ out = os.stat(path, follow_symlinks=False)
102
+ link = stat.S_ISLNK(out.st_mode)
103
+ if link:
104
+ out = os.stat(path, follow_symlinks=True)
105
+ size = out.st_size
106
+ if stat.S_ISDIR(out.st_mode):
107
+ t = "directory"
108
+ elif stat.S_ISREG(out.st_mode):
109
+ t = "file"
110
+ else:
111
+ t = "other"
112
+
113
+ # Check for the 'st_birthtime' attribute, which is not always present; fallback to st_ctime
114
+ created_time = getattr(out, "st_birthtime", out.st_ctime)
115
+
116
+ result = {
117
+ "name": path,
118
+ "size": size,
119
+ "type": t,
120
+ "created": created_time,
121
+ "islink": link,
122
+ }
123
+ for field in ["mode", "uid", "gid", "mtime", "ino", "nlink"]:
124
+ result[field] = getattr(out, f"st_{field}")
125
+ if link:
126
+ result["destination"] = os.readlink(path)
127
+ return result
128
+
129
+ def lexists(self, path, **kwargs):
130
+ return osp.lexists(path)
131
+
132
+ def cp_file(self, path1, path2, **kwargs):
133
+ path1 = self._strip_protocol(path1)
134
+ path2 = self._strip_protocol(path2)
135
+ if self.auto_mkdir:
136
+ self.makedirs(self._parent(path2), exist_ok=True)
137
+ if self.isfile(path1):
138
+ shutil.copyfile(path1, path2)
139
+ elif self.isdir(path1):
140
+ self.mkdirs(path2, exist_ok=True)
141
+ else:
142
+ raise FileNotFoundError(path1)
143
+
144
+ def isfile(self, path):
145
+ path = self._strip_protocol(path)
146
+ return os.path.isfile(path)
147
+
148
+ def isdir(self, path):
149
+ path = self._strip_protocol(path)
150
+ return os.path.isdir(path)
151
+
152
+ def get_file(self, path1, path2, callback=None, **kwargs):
153
+ if isfilelike(path2):
154
+ with open(path1, "rb") as f:
155
+ shutil.copyfileobj(f, path2)
156
+ else:
157
+ return self.cp_file(path1, path2, **kwargs)
158
+
159
+ def put_file(self, path1, path2, callback=None, **kwargs):
160
+ return self.cp_file(path1, path2, **kwargs)
161
+
162
+ def mv(self, path1, path2, recursive: bool = True, **kwargs):
163
+ """Move files/directories
164
+ For the specific case of local, all ops on directories are recursive and
165
+ the recursive= kwarg is ignored.
166
+ """
167
+ path1 = self._strip_protocol(path1)
168
+ path2 = self._strip_protocol(path2)
169
+
170
+ if self.auto_mkdir:
171
+ self.makedirs(self._parent(path2), exist_ok=True)
172
+
173
+ shutil.move(path1, path2)
174
+
175
+ def link(self, src, dst, **kwargs):
176
+ src = self._strip_protocol(src)
177
+ dst = self._strip_protocol(dst)
178
+ os.link(src, dst, **kwargs)
179
+
180
+ def symlink(self, src, dst, **kwargs):
181
+ src = self._strip_protocol(src)
182
+ dst = self._strip_protocol(dst)
183
+ os.symlink(src, dst, **kwargs)
184
+
185
+ def islink(self, path) -> bool:
186
+ return os.path.islink(self._strip_protocol(path))
187
+
188
+ def rm_file(self, path):
189
+ os.remove(self._strip_protocol(path))
190
+
191
+ def rm(self, path, recursive=False, maxdepth=None):
192
+ if not isinstance(path, list):
193
+ path = [path]
194
+
195
+ for p in path:
196
+ p = self._strip_protocol(p)
197
+ if self.isdir(p) and not self.islink(p):
198
+ if not recursive:
199
+ raise ValueError("Cannot delete directory, set recursive=True")
200
+ if osp.abspath(p) == os.getcwd():
201
+ raise ValueError("Cannot delete current working directory")
202
+ shutil.rmtree(p)
203
+ else:
204
+ os.remove(p)
205
+
206
+ def unstrip_protocol(self, name):
207
+ protocol = self.protocol if isinstance(self.protocol, str) else self.protocol[0]
208
+ name = self._strip_protocol(name) # normalise for local/win/...
209
+ return f"{protocol}://{name}"
210
+
211
+ def _open(self, path, mode="rb", block_size=None, **kwargs):
212
+ path = self._strip_protocol(path)
213
+ if self.auto_mkdir and ("w" in mode or "x" in mode or "a" in mode):
214
+ self.makedirs(self._parent(path), exist_ok=True)
215
+ return LocalFileOpener(path, mode, fs=self, **kwargs)
216
+
217
+ def touch(self, path, truncate=True, **kwargs):
218
+ path = self._strip_protocol(path)
219
+ if self.auto_mkdir:
220
+ self.makedirs(self._parent(path), exist_ok=True)
221
+ if self.exists(path):
222
+ os.utime(path, None)
223
+ else:
224
+ open(path, "a").close()
225
+ if truncate:
226
+ os.truncate(path, 0)
227
+
228
+ def created(self, path):
229
+ info = self.info(path=path)
230
+ return datetime.datetime.fromtimestamp(
231
+ info["created"], tz=datetime.timezone.utc
232
+ )
233
+
234
+ def modified(self, path):
235
+ info = self.info(path=path)
236
+ return datetime.datetime.fromtimestamp(info["mtime"], tz=datetime.timezone.utc)
237
+
238
+ @classmethod
239
+ def _parent(cls, path):
240
+ path = cls._strip_protocol(path)
241
+ if os.sep == "/":
242
+ # posix native
243
+ return path.rsplit("/", 1)[0] or "/"
244
+ else:
245
+ # NT
246
+ path_ = path.rsplit("/", 1)[0]
247
+ if len(path_) <= 3:
248
+ if path_[1:2] == ":":
249
+ # nt root (something like c:/)
250
+ return path_[0] + ":/"
251
+ # More cases may be required here
252
+ return path_
253
+
254
+ @classmethod
255
+ def _strip_protocol(cls, path):
256
+ path = stringify_path(path)
257
+ protos = (cls.protocol,) if isinstance(cls.protocol, str) else cls.protocol
258
+ prefixes = (protocol + sep for protocol in protos for sep in ("://", ":"))
259
+ for prefix in prefixes:
260
+ if path.startswith(prefix):
261
+ path = path.removeprefix(prefix)
262
+ break
263
+
264
+ path = make_path_posix(path)
265
+ if os.sep != "/":
266
+ # This code-path is a stripped down version of
267
+ # > drive, path = ntpath.splitdrive(path)
268
+ if path[1:2] == ":":
269
+ # Absolute drive-letter path, e.g. X:\Windows
270
+ # Relative path with drive, e.g. X:Windows
271
+ drive, path = path[:2], path[2:]
272
+ elif path[:2] == "//":
273
+ # UNC drives, e.g. \\server\share or \\?\UNC\server\share
274
+ # Device drives, e.g. \\.\device or \\?\device
275
+ if (index1 := path.find("/", 2)) == -1 or (
276
+ index2 := path.find("/", index1 + 1)
277
+ ) == -1:
278
+ drive, path = path, ""
279
+ else:
280
+ drive, path = path[:index2], path[index2:]
281
+ else:
282
+ # Relative path, e.g. Windows
283
+ drive = ""
284
+
285
+ path = path.rstrip("/") or cls.root_marker
286
+ return drive + path
287
+
288
+ else:
289
+ return path.rstrip("/") or cls.root_marker
290
+
291
+ def _isfilestore(self):
292
+ # Inheriting from DaskFileSystem makes this False (S3, etc. were)
293
+ # the original motivation. But we are a posix-like file system.
294
+ # See https://github.com/dask/dask/issues/5526
295
+ return True
296
+
297
+ def chmod(self, path, mode):
298
+ path = stringify_path(path)
299
+ return os.chmod(path, mode)
300
+
301
+
302
+ def make_path_posix(path):
303
+ """Make path generic and absolute for current OS"""
304
+ if not isinstance(path, str):
305
+ if isinstance(path, (list, set, tuple)):
306
+ return type(path)(make_path_posix(p) for p in path)
307
+ else:
308
+ path = stringify_path(path)
309
+ if not isinstance(path, str):
310
+ raise TypeError(f"could not convert {path!r} to string")
311
+ if os.sep == "/":
312
+ # Native posix
313
+ if path.startswith("/"):
314
+ # most common fast case for posix
315
+ return path
316
+ elif path.startswith("~"):
317
+ return osp.expanduser(path)
318
+ elif path.startswith("./"):
319
+ path = path[2:]
320
+ elif path == ".":
321
+ path = ""
322
+ return f"{os.getcwd()}/{path}"
323
+ else:
324
+ # NT handling
325
+ if path[0:1] == "/" and path[2:3] == ":":
326
+ # path is like "/c:/local/path"
327
+ path = path[1:]
328
+ if path[1:2] == ":":
329
+ # windows full path like "C:\\local\\path"
330
+ if len(path) <= 3:
331
+ # nt root (something like c:/)
332
+ return path[0] + ":/"
333
+ path = path.replace("\\", "/")
334
+ return path
335
+ elif path[0:1] == "~":
336
+ return make_path_posix(osp.expanduser(path))
337
+ elif path.startswith(("\\\\", "//")):
338
+ # windows UNC/DFS-style paths
339
+ return "//" + path[2:].replace("\\", "/")
340
+ elif path.startswith(("\\", "/")):
341
+ # windows relative path with root
342
+ path = path.replace("\\", "/")
343
+ return f"{osp.splitdrive(os.getcwd())[0]}{path}"
344
+ else:
345
+ path = path.replace("\\", "/")
346
+ if path.startswith("./"):
347
+ path = path[2:]
348
+ elif path == ".":
349
+ path = ""
350
+ return f"{make_path_posix(os.getcwd())}/{path}"
351
+
352
+
353
+ def trailing_sep(path):
354
+ """Return True if the path ends with a path separator.
355
+
356
+ A forward slash is always considered a path separator, even on Operating
357
+ Systems that normally use a backslash.
358
+ """
359
+ # TODO: if all incoming paths were posix-compliant then separator would
360
+ # always be a forward slash, simplifying this function.
361
+ # See https://github.com/fsspec/filesystem_spec/pull/1250
362
+ return path.endswith(os.sep) or (os.altsep is not None and path.endswith(os.altsep))
363
+
364
+
365
+ @lru_cache(maxsize=1)
366
+ def get_umask(mask: int = 0o666) -> int:
367
+ """Get the current umask.
368
+
369
+ Follows https://stackoverflow.com/a/44130549 to get the umask.
370
+ Temporarily sets the umask to the given value, and then resets it to the
371
+ original value.
372
+ """
373
+ value = os.umask(mask)
374
+ os.umask(value)
375
+ return value
376
+
377
+
378
+ class LocalFileOpener(io.IOBase):
379
+ def __init__(
380
+ self, path, mode, autocommit=True, fs=None, compression=None, **kwargs
381
+ ):
382
+ logger.debug("open file: %s", path)
383
+ self.path = path
384
+ self.mode = mode
385
+ self.fs = fs
386
+ self.f = None
387
+ self.autocommit = autocommit
388
+ self.compression = get_compression(path, compression)
389
+ self.blocksize = io.DEFAULT_BUFFER_SIZE
390
+ self._open()
391
+
392
+ def _open(self):
393
+ if self.f is None or self.f.closed:
394
+ if self.autocommit or "w" not in self.mode:
395
+ self.f = open(self.path, mode=self.mode)
396
+ if self.compression:
397
+ compress = compr[self.compression]
398
+ self.f = compress(self.f, mode=self.mode)
399
+ else:
400
+ # TODO: check if path is writable?
401
+ i, name = tempfile.mkstemp()
402
+ os.close(i) # we want normal open and normal buffered file
403
+ self.temp = name
404
+ self.f = open(name, mode=self.mode)
405
+ if "w" not in self.mode:
406
+ self.size = self.f.seek(0, 2)
407
+ self.f.seek(0)
408
+ self.f.size = self.size
409
+
410
+ def _fetch_range(self, start, end):
411
+ # probably only used by cached FS
412
+ if "r" not in self.mode:
413
+ raise ValueError
414
+ self._open()
415
+ self.f.seek(start)
416
+ return self.f.read(end - start)
417
+
418
+ def __setstate__(self, state):
419
+ self.f = None
420
+ loc = state.pop("loc", None)
421
+ self.__dict__.update(state)
422
+ if "r" in state["mode"]:
423
+ self.f = None
424
+ self._open()
425
+ self.f.seek(loc)
426
+
427
+ def __getstate__(self):
428
+ d = self.__dict__.copy()
429
+ d.pop("f")
430
+ if "r" in self.mode:
431
+ d["loc"] = self.f.tell()
432
+ else:
433
+ if not self.f.closed:
434
+ raise ValueError("Cannot serialise open write-mode local file")
435
+ return d
436
+
437
+ def commit(self):
438
+ if self.autocommit:
439
+ raise RuntimeError("Can only commit if not already set to autocommit")
440
+ try:
441
+ shutil.move(self.temp, self.path)
442
+ except PermissionError as e:
443
+ # shutil.move raises PermissionError if os.rename
444
+ # and the default copy2 fallback with shutil.copystats fail.
445
+ # The file should be there nonetheless, but without copied permissions.
446
+ # If it doesn't exist, there was no permission to create the file.
447
+ if not os.path.exists(self.path):
448
+ raise e
449
+ else:
450
+ # If PermissionError is not raised, permissions can be set.
451
+ try:
452
+ mask = 0o666
453
+ os.chmod(self.path, mask & ~get_umask(mask))
454
+ except RuntimeError:
455
+ pass
456
+
457
+ def discard(self):
458
+ if self.autocommit:
459
+ raise RuntimeError("Cannot discard if set to autocommit")
460
+ os.remove(self.temp)
461
+
462
+ def readable(self) -> bool:
463
+ return True
464
+
465
+ def writable(self) -> bool:
466
+ return "r" not in self.mode
467
+
468
+ def read(self, *args, **kwargs):
469
+ return self.f.read(*args, **kwargs)
470
+
471
+ def write(self, *args, **kwargs):
472
+ return self.f.write(*args, **kwargs)
473
+
474
+ def tell(self, *args, **kwargs):
475
+ return self.f.tell(*args, **kwargs)
476
+
477
+ def seek(self, *args, **kwargs):
478
+ return self.f.seek(*args, **kwargs)
479
+
480
+ def seekable(self, *args, **kwargs):
481
+ return self.f.seekable(*args, **kwargs)
482
+
483
+ def readline(self, *args, **kwargs):
484
+ return self.f.readline(*args, **kwargs)
485
+
486
+ def readlines(self, *args, **kwargs):
487
+ return self.f.readlines(*args, **kwargs)
488
+
489
+ def close(self):
490
+ return self.f.close()
491
+
492
+ def truncate(self, size=None) -> int:
493
+ return self.f.truncate(size)
494
+
495
+ @property
496
+ def closed(self):
497
+ return self.f.closed
498
+
499
+ def fileno(self):
500
+ return self.raw.fileno()
501
+
502
+ def flush(self) -> None:
503
+ self.f.flush()
504
+
505
+ def __iter__(self):
506
+ return self.f.__iter__()
507
+
508
+ def __getattr__(self, item):
509
+ return getattr(self.f, item)
510
+
511
+ def __enter__(self):
512
+ self._incontext = True
513
+ return self
514
+
515
+ def __exit__(self, exc_type, exc_value, traceback):
516
+ self._incontext = False
517
+ self.f.__exit__(exc_type, exc_value, traceback)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/memory.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from datetime import datetime, timezone
5
+ from errno import ENOTEMPTY
6
+ from io import BytesIO
7
+ from pathlib import PurePath, PureWindowsPath
8
+ from typing import Any, ClassVar
9
+
10
+ from fsspec import AbstractFileSystem
11
+ from fsspec.implementations.local import LocalFileSystem
12
+ from fsspec.utils import stringify_path
13
+
14
+ logger = logging.getLogger("fsspec.memoryfs")
15
+
16
+
17
+ class MemoryFileSystem(AbstractFileSystem):
18
+ """A filesystem based on a dict of BytesIO objects
19
+
20
+ This is a global filesystem so instances of this class all point to the same
21
+ in memory filesystem.
22
+ """
23
+
24
+ store: ClassVar[dict[str, Any]] = {} # global, do not overwrite!
25
+ pseudo_dirs = [""] # global, do not overwrite!
26
+ protocol = "memory"
27
+ root_marker = "/"
28
+
29
+ @classmethod
30
+ def _strip_protocol(cls, path):
31
+ if isinstance(path, PurePath):
32
+ if isinstance(path, PureWindowsPath):
33
+ return LocalFileSystem._strip_protocol(path)
34
+ else:
35
+ path = stringify_path(path)
36
+
37
+ path = path.removeprefix("memory://")
38
+ if "::" in path or "://" in path:
39
+ return path.rstrip("/")
40
+ path = path.lstrip("/").rstrip("/")
41
+ return "/" + path if path else ""
42
+
43
+ def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
44
+ # The base implementation calls ls() once per directory, and each ls()
45
+ # scans the whole (global) store, giving O(n_dirs * n_entries) behaviour
46
+ # for a tree. Since the store is a flat mapping of every path, the same
47
+ # result can be produced with a single pass over it.
48
+ if maxdepth is not None and maxdepth < 1:
49
+ raise ValueError("maxdepth must be at least 1")
50
+ path = self._strip_protocol(path)
51
+ if path in self.store:
52
+ # path is itself a file
53
+ if not detail:
54
+ return [path]
55
+ filelike = self.store[path]
56
+ return {
57
+ path: {
58
+ "name": path,
59
+ "size": filelike.size,
60
+ "type": "file",
61
+ "created": filelike.created.timestamp(),
62
+ }
63
+ }
64
+
65
+ # Uniform prefix so that the search root "" (the filesystem root) and a
66
+ # nested path are handled the same way; rel depth is rel.count("/") + 1.
67
+ prefix = path + "/" if path else "/"
68
+ out = {}
69
+ dirs = {}
70
+
71
+ def add_ancestor_dirs(name):
72
+ # Register every directory implied between ``path`` and ``name`` that
73
+ # is within maxdepth, mirroring how walk() surfaces implied dirs.
74
+ idx = name.rfind("/")
75
+ while idx > len(path):
76
+ parent = name[:idx]
77
+ if parent in dirs:
78
+ break
79
+ rel = parent[len(prefix) :]
80
+ if maxdepth is None or rel.count("/") + 1 <= maxdepth:
81
+ dirs[parent] = {"name": parent, "size": 0, "type": "directory"}
82
+ idx = parent.rfind("/")
83
+
84
+ # `store` is shared by every MemoryFileSystem instance, so iterate a
85
+ # snapshot: a concurrent create/delete would otherwise raise
86
+ # "dictionary changed size during iteration". ls() does the same.
87
+ for name, filelike in tuple(self.store.items()):
88
+ if not name.startswith(prefix):
89
+ continue
90
+ rel = name[len(prefix) :]
91
+ if withdirs:
92
+ add_ancestor_dirs(name)
93
+ if maxdepth is not None and rel.count("/") + 1 > maxdepth:
94
+ continue
95
+ out[name] = {
96
+ "name": name,
97
+ "size": filelike.size,
98
+ "type": "file",
99
+ "created": filelike.created.timestamp(),
100
+ }
101
+
102
+ if withdirs:
103
+ # Explicitly-created (possibly empty) directories live in pseudo_dirs.
104
+ for pdir in self.pseudo_dirs:
105
+ if pdir and pdir.startswith(prefix):
106
+ add_ancestor_dirs(pdir + "/")
107
+ out.update(dirs)
108
+ # Mirror the base find(): include the search root itself when it is
109
+ # a directory (needed for posix glob compliance).
110
+ if path != "" and self.isdir(path):
111
+ out[path] = self.info(path)
112
+
113
+ names = sorted(out)
114
+ return {name: out[name] for name in names} if detail else names
115
+
116
+ def ls(self, path, detail=True, **kwargs):
117
+ path = self._strip_protocol(path)
118
+ if path in self.store:
119
+ # there is a key with this exact name
120
+ if not detail:
121
+ return [path]
122
+ return [
123
+ {
124
+ "name": path,
125
+ "size": self.store[path].size,
126
+ "type": "file",
127
+ "created": self.store[path].created.timestamp(),
128
+ }
129
+ ]
130
+ paths = set()
131
+ starter = path + "/"
132
+ out = []
133
+ for p2 in tuple(self.store):
134
+ if p2.startswith(starter):
135
+ if "/" not in p2[len(starter) :]:
136
+ # exact child
137
+ out.append(
138
+ {
139
+ "name": p2,
140
+ "size": self.store[p2].size,
141
+ "type": "file",
142
+ "created": self.store[p2].created.timestamp(),
143
+ }
144
+ )
145
+ elif len(p2) > len(starter):
146
+ # implied child directory
147
+ ppath = starter + p2[len(starter) :].split("/", 1)[0]
148
+ if ppath not in paths:
149
+ out = out or []
150
+ out.append(
151
+ {
152
+ "name": ppath,
153
+ "size": 0,
154
+ "type": "directory",
155
+ }
156
+ )
157
+ paths.add(ppath)
158
+ for p2 in self.pseudo_dirs:
159
+ if p2.startswith(starter):
160
+ if "/" not in p2[len(starter) :]:
161
+ # exact child pdir
162
+ if p2 not in paths:
163
+ out.append({"name": p2, "size": 0, "type": "directory"})
164
+ paths.add(p2)
165
+ else:
166
+ # directory implied by deeper pdir
167
+ ppath = starter + p2[len(starter) :].split("/", 1)[0]
168
+ if ppath not in paths:
169
+ out.append({"name": ppath, "size": 0, "type": "directory"})
170
+ paths.add(ppath)
171
+ if not out:
172
+ if path in self.pseudo_dirs:
173
+ # empty dir
174
+ return []
175
+ raise FileNotFoundError(path)
176
+ if detail:
177
+ return out
178
+ return sorted([f["name"] for f in out])
179
+
180
+ def mkdir(self, path, create_parents=True, **kwargs):
181
+ path = self._strip_protocol(path)
182
+ if path in self.store or path in self.pseudo_dirs:
183
+ raise FileExistsError(path)
184
+ if self._parent(path).strip("/") and self.isfile(self._parent(path)):
185
+ raise NotADirectoryError(self._parent(path))
186
+ if create_parents and self._parent(path).strip("/"):
187
+ try:
188
+ self.mkdir(self._parent(path), create_parents, **kwargs)
189
+ except FileExistsError:
190
+ pass
191
+ if path and path not in self.pseudo_dirs:
192
+ self.pseudo_dirs.append(path)
193
+
194
+ def makedirs(self, path, exist_ok=False):
195
+ try:
196
+ self.mkdir(path, create_parents=True)
197
+ except FileExistsError:
198
+ if not exist_ok:
199
+ raise
200
+
201
+ def pipe_file(self, path, value, mode="overwrite", **kwargs):
202
+ """Set the bytes of given file
203
+
204
+ Avoids copies of the data if possible
205
+ """
206
+ mode = "xb" if mode == "create" else "wb"
207
+ self.open(path, mode=mode, data=value)
208
+
209
+ def rmdir(self, path):
210
+ path = self._strip_protocol(path)
211
+ if path == "":
212
+ # silently avoid deleting FS root
213
+ return
214
+ if path in self.pseudo_dirs:
215
+ if not self.ls(path):
216
+ self.pseudo_dirs.remove(path)
217
+ else:
218
+ raise OSError(ENOTEMPTY, "Directory not empty", path)
219
+ else:
220
+ raise FileNotFoundError(path)
221
+
222
+ def info(self, path, **kwargs):
223
+ logger.debug("info: %s", path)
224
+ path = self._strip_protocol(path)
225
+ if path in self.pseudo_dirs or any(
226
+ p.startswith(path + "/") for p in list(self.store) + self.pseudo_dirs
227
+ ):
228
+ return {
229
+ "name": path,
230
+ "size": 0,
231
+ "type": "directory",
232
+ }
233
+ elif path in self.store:
234
+ filelike = self.store[path]
235
+ return {
236
+ "name": path,
237
+ "size": filelike.size,
238
+ "type": "file",
239
+ "created": getattr(filelike, "created", None),
240
+ }
241
+ else:
242
+ raise FileNotFoundError(path)
243
+
244
+ def _open(
245
+ self,
246
+ path,
247
+ mode="rb",
248
+ block_size=None,
249
+ autocommit=True,
250
+ cache_options=None,
251
+ **kwargs,
252
+ ):
253
+ path = self._strip_protocol(path)
254
+ if "x" in mode and self.exists(path):
255
+ raise FileExistsError
256
+ if path in self.pseudo_dirs:
257
+ raise IsADirectoryError(path)
258
+ parent = path
259
+ while len(parent) > 1:
260
+ parent = self._parent(parent)
261
+ if self.isfile(parent):
262
+ raise FileExistsError(parent)
263
+ if mode in ["rb", "ab", "r+b", "a+b"]:
264
+ if path in self.store:
265
+ f = self.store[path]
266
+ if "a" in mode:
267
+ # position at the end of file
268
+ f.seek(0, 2)
269
+ else:
270
+ # position at the beginning of file
271
+ f.seek(0)
272
+ return f
273
+ elif "a" in mode:
274
+ # append modes create the file if it does not exist, matching
275
+ # builtin open() and LocalFileSystem
276
+ m = MemoryFile(self, path, kwargs.get("data"))
277
+ if not self._intrans:
278
+ m.commit()
279
+ # position at the end of file, like the existing-file path above
280
+ m.seek(0, 2)
281
+ return m
282
+ else:
283
+ raise FileNotFoundError(path)
284
+ elif mode in {"wb", "w+b", "xb", "x+b"}:
285
+ if "x" in mode and self.exists(path):
286
+ raise FileExistsError
287
+ m = MemoryFile(self, path, kwargs.get("data"))
288
+ if not self._intrans:
289
+ m.commit()
290
+ return m
291
+ else:
292
+ name = self.__class__.__name__
293
+ raise ValueError(f"unsupported file mode for {name}: {mode!r}")
294
+
295
+ def cp_file(self, path1, path2, **kwargs):
296
+ path1 = self._strip_protocol(path1)
297
+ path2 = self._strip_protocol(path2)
298
+ if self.isfile(path1):
299
+ self.store[path2] = MemoryFile(
300
+ self, path2, self.store[path1].getvalue()
301
+ ) # implicit copy
302
+ elif self.isdir(path1):
303
+ if path2 not in self.pseudo_dirs:
304
+ self.pseudo_dirs.append(path2)
305
+ else:
306
+ raise FileNotFoundError(path1)
307
+
308
+ def cat_file(self, path, start=None, end=None, **kwargs):
309
+ logger.debug("cat: %s", path)
310
+ path = self._strip_protocol(path)
311
+ try:
312
+ return bytes(self.store[path].getbuffer()[start:end])
313
+ except KeyError as e:
314
+ raise FileNotFoundError(path) from e
315
+
316
+ def _rm(self, path):
317
+ path = self._strip_protocol(path)
318
+ try:
319
+ del self.store[path]
320
+ except KeyError as e:
321
+ raise FileNotFoundError(path) from e
322
+
323
+ def modified(self, path):
324
+ path = self._strip_protocol(path)
325
+ try:
326
+ return self.store[path].modified
327
+ except KeyError as e:
328
+ raise FileNotFoundError(path) from e
329
+
330
+ def created(self, path):
331
+ path = self._strip_protocol(path)
332
+ try:
333
+ return self.store[path].created
334
+ except KeyError as e:
335
+ raise FileNotFoundError(path) from e
336
+
337
+ def isfile(self, path):
338
+ path = self._strip_protocol(path)
339
+ return path in self.store
340
+
341
+ def rm(self, path, recursive=False, maxdepth=None):
342
+ if isinstance(path, str):
343
+ path = self._strip_protocol(path)
344
+ else:
345
+ path = [self._strip_protocol(p) for p in path]
346
+ paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
347
+ for p in reversed(paths):
348
+ if self.isfile(p):
349
+ self.rm_file(p)
350
+ # If the expanded path doesn't exist, it is only because the expanded
351
+ # path was a directory that does not exist in self.pseudo_dirs. This
352
+ # is possible if you directly create files without making the
353
+ # directories first.
354
+ elif not self.exists(p):
355
+ continue
356
+ else:
357
+ self.rmdir(p)
358
+
359
+
360
+ class MemoryFile(BytesIO):
361
+ """A BytesIO which can't close and works as a context manager
362
+
363
+ Can initialise with data. Each path should only be active once at any moment.
364
+
365
+ No need to provide fs, path if auto-committing (default)
366
+ """
367
+
368
+ def __init__(self, fs=None, path=None, data=None):
369
+ logger.debug("open file %s", path)
370
+ self.fs = fs
371
+ self.path = path
372
+ self.created = datetime.now(tz=timezone.utc)
373
+ self.modified = datetime.now(tz=timezone.utc)
374
+ if data:
375
+ super().__init__(data)
376
+ self.seek(0)
377
+
378
+ @property
379
+ def size(self):
380
+ return self.getbuffer().nbytes
381
+
382
+ def __enter__(self):
383
+ return self
384
+
385
+ def close(self):
386
+ pass
387
+
388
+ def discard(self):
389
+ pass
390
+
391
+ def commit(self):
392
+ self.fs.store[self.path] = self
393
+ self.modified = datetime.now(tz=timezone.utc)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/reference.py ADDED
@@ -0,0 +1,1339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import collections
3
+ import io
4
+ import itertools
5
+ import logging
6
+ import math
7
+ import os
8
+ from functools import lru_cache
9
+ from itertools import chain
10
+ from typing import TYPE_CHECKING, Literal
11
+
12
+ import fsspec.core
13
+ from fsspec.spec import AbstractBufferedFile
14
+
15
+ try:
16
+ import ujson as json
17
+ except ImportError:
18
+ if not TYPE_CHECKING:
19
+ import json
20
+
21
+ from fsspec.asyn import AsyncFileSystem
22
+ from fsspec.callbacks import DEFAULT_CALLBACK
23
+ from fsspec.core import filesystem, open, split_protocol
24
+ from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper
25
+ from fsspec.utils import (
26
+ isfilelike,
27
+ merge_offset_ranges,
28
+ other_paths,
29
+ )
30
+
31
+ logger = logging.getLogger("fsspec.reference")
32
+
33
+
34
+ class ReferenceNotReachable(RuntimeError):
35
+ def __init__(self, reference, target, *args):
36
+ super().__init__(*args)
37
+ self.reference = reference
38
+ self.target = target
39
+
40
+ def __str__(self):
41
+ return f'Reference "{self.reference}" failed to fetch target {self.target}'
42
+
43
+
44
+ def _first(d):
45
+ return next(iter(d.values()))
46
+
47
+
48
+ def _prot_in_references(path, references):
49
+ ref = references.get(path)
50
+ if isinstance(ref, (list, tuple)) and isinstance(ref[0], str):
51
+ return split_protocol(ref[0])[0] if ref[0] else ref[0]
52
+
53
+
54
+ def _protocol_groups(paths, references):
55
+ if isinstance(paths, str):
56
+ return {_prot_in_references(paths, references): [paths]}
57
+ out = {}
58
+ for path in paths:
59
+ protocol = _prot_in_references(path, references)
60
+ out.setdefault(protocol, []).append(path)
61
+ return out
62
+
63
+
64
+ class RefsValuesView(collections.abc.ValuesView):
65
+ def __iter__(self):
66
+ for val in self._mapping.zmetadata.values():
67
+ yield json.dumps(val).encode()
68
+ yield from self._mapping._items.values()
69
+ for field in self._mapping.listdir():
70
+ chunk_sizes = self._mapping._get_chunk_sizes(field)
71
+ if len(chunk_sizes) == 0:
72
+ yield self._mapping[field + "/0"]
73
+ continue
74
+ yield from self._mapping._generate_all_records(field)
75
+
76
+
77
+ class RefsItemsView(collections.abc.ItemsView):
78
+ def __iter__(self):
79
+ return zip(self._mapping.keys(), self._mapping.values())
80
+
81
+
82
+ def ravel_multi_index(idx, sizes):
83
+ val = 0
84
+ mult = 1
85
+ for i, s in zip(idx[::-1], sizes[::-1]):
86
+ val += i * mult
87
+ mult *= s
88
+ return val
89
+
90
+
91
+ class LazyReferenceMapper(collections.abc.MutableMapping):
92
+ """This interface can be used to read/write references from Parquet stores.
93
+ It is not intended for other types of references.
94
+ It can be used with Kerchunk's MultiZarrToZarr method to combine
95
+ references into a parquet store.
96
+ Examples of this use-case can be found here:
97
+ https://fsspec.github.io/kerchunk/advanced.html?highlight=parquet#parquet-storage"""
98
+
99
+ # import is class level to prevent numpy dep requirement for fsspec
100
+ @property
101
+ def np(self):
102
+ import numpy as np
103
+
104
+ return np
105
+
106
+ @property
107
+ def pd(self):
108
+ import pandas as pd
109
+
110
+ return pd
111
+
112
+ def __init__(
113
+ self,
114
+ root,
115
+ fs=None,
116
+ out_root=None,
117
+ cache_size=128,
118
+ categorical_threshold=10,
119
+ engine: Literal["fastparquet", "pyarrow"] = "fastparquet",
120
+ ):
121
+ """
122
+
123
+ This instance will be writable, storing changes in memory until full partitions
124
+ are accumulated or .flush() is called.
125
+
126
+ To create an empty lazy store, use .create()
127
+
128
+ Parameters
129
+ ----------
130
+ root : str
131
+ Root of parquet store
132
+ fs : fsspec.AbstractFileSystem
133
+ fsspec filesystem object, default is local filesystem.
134
+ cache_size : int, default=128
135
+ Maximum size of LRU cache, where cache_size*record_size denotes
136
+ the total number of references that can be loaded in memory at once.
137
+ categorical_threshold : int
138
+ Encode urls as pandas.Categorical to reduce memory footprint if the ratio
139
+ of the number of unique urls to total number of refs for each variable
140
+ is greater than or equal to this number. (default 10)
141
+ engine: Literal["fastparquet","pyarrow"]
142
+ Engine choice for reading parquet files. (default is "fastparquet")
143
+ """
144
+
145
+ self.root = root
146
+ self.chunk_sizes = {}
147
+ self.cat_thresh = categorical_threshold
148
+ self.engine = engine
149
+ self.cache_size = cache_size
150
+ self.url = self.root + "/{field}/refs.{record}.parq"
151
+ # TODO: derive fs from `root`
152
+ self.fs = fsspec.filesystem("file") if fs is None else fs
153
+ self.out_root = self.fs.unstrip_protocol(out_root or self.root)
154
+
155
+ from importlib.util import find_spec
156
+
157
+ if self.engine == "pyarrow" and find_spec("pyarrow") is None:
158
+ raise ImportError("engine choice `pyarrow` is not installed.")
159
+
160
+ # Apply `lru_cache` decorator manually per instance.
161
+ # This way `self` reference is not held on class level.
162
+ # WARNING: However, this means that self and its members are not reflected
163
+ # in the cache key, so we expect they won't be mutated once a value is cached.
164
+ self.listdir = lru_cache()(self.listdir)
165
+ self._key_to_record = lru_cache(maxsize=4096)(self._key_to_record)
166
+
167
+ def __getattr__(self, item):
168
+ if item in ("_items", "record_size", "zmetadata"):
169
+ self.setup()
170
+ # avoid possible recursion if setup fails somehow
171
+ return self.__dict__[item]
172
+ raise AttributeError(item)
173
+
174
+ def setup(self):
175
+ self._items = {}
176
+ self._items[".zmetadata"] = self.fs.cat_file(
177
+ "/".join([self.root, ".zmetadata"])
178
+ )
179
+ met = json.loads(self._items[".zmetadata"])
180
+ self.record_size = met["record_size"]
181
+ self.zmetadata = met["metadata"]
182
+
183
+ # Define function to open and decompress refs
184
+ @lru_cache(maxsize=self.cache_size)
185
+ def open_refs(field, record):
186
+ """cached parquet file loader"""
187
+ path = self.url.format(field=field, record=record)
188
+ data = io.BytesIO(self.fs.cat_file(path))
189
+ try:
190
+ df = self.pd.read_parquet(data, engine=self.engine)
191
+ refs = {c: df[c].to_numpy(copy=True) for c in df.columns}
192
+ except OSError:
193
+ refs = None
194
+ return refs
195
+
196
+ self.open_refs = open_refs
197
+
198
+ @staticmethod
199
+ def create(root, storage_options=None, fs=None, record_size=10000, **kwargs):
200
+ """Make empty parquet reference set
201
+
202
+ First deletes the contents of the given directory, if it exists.
203
+
204
+ Parameters
205
+ ----------
206
+ root: str
207
+ Directory to contain the output; will be created
208
+ storage_options: dict | None
209
+ For making the filesystem to use for writing is fs is None
210
+ fs: FileSystem | None
211
+ Filesystem for writing
212
+ record_size: int
213
+ Number of references per parquet file
214
+ kwargs: passed to __init__
215
+
216
+ Returns
217
+ -------
218
+ LazyReferenceMapper instance
219
+ """
220
+ met = {"metadata": {}, "record_size": record_size}
221
+ if fs is None:
222
+ fs, root = fsspec.core.url_to_fs(root, **(storage_options or {}))
223
+ if fs.exists(root):
224
+ fs.rm(root, recursive=True)
225
+ fs.makedirs(root, exist_ok=True)
226
+ fs.pipe("/".join([root, ".zmetadata"]), json.dumps(met).encode())
227
+ return LazyReferenceMapper(root, fs, **kwargs)
228
+
229
+ def listdir(self):
230
+ """List top-level directories"""
231
+ dirs = (p.rsplit("/", 1)[0] for p in self.zmetadata if not p.startswith(".z"))
232
+ return set(dirs)
233
+
234
+ def ls(self, path="", detail=True):
235
+ """Shortcut file listings"""
236
+ path = path.rstrip("/")
237
+ pathdash = path + "/" if path else ""
238
+ dirnames = self.listdir()
239
+ dirs = [
240
+ d
241
+ for d in dirnames
242
+ if d.startswith(pathdash) and "/" not in d.lstrip(pathdash)
243
+ ]
244
+ if dirs:
245
+ others = {
246
+ f
247
+ for f in chain(
248
+ [".zmetadata"],
249
+ (name for name in self.zmetadata),
250
+ (name for name in self._items),
251
+ )
252
+ if f.startswith(pathdash) and "/" not in f.lstrip(pathdash)
253
+ }
254
+ if detail is False:
255
+ others.update(dirs)
256
+ return sorted(others)
257
+ dirinfo = [{"name": name, "type": "directory", "size": 0} for name in dirs]
258
+ fileinfo = [
259
+ {
260
+ "name": name,
261
+ "type": "file",
262
+ "size": len(
263
+ json.dumps(self.zmetadata[name])
264
+ if name in self.zmetadata
265
+ else self._items[name]
266
+ ),
267
+ }
268
+ for name in others
269
+ ]
270
+ return sorted(dirinfo + fileinfo, key=lambda s: s["name"])
271
+ field = path
272
+ others = set(
273
+ [name for name in self.zmetadata if name.startswith(f"{path}/")]
274
+ + [name for name in self._items if name.startswith(f"{path}/")]
275
+ )
276
+ fileinfo = [
277
+ {
278
+ "name": name,
279
+ "type": "file",
280
+ "size": len(
281
+ json.dumps(self.zmetadata[name])
282
+ if name in self.zmetadata
283
+ else self._items[name]
284
+ ),
285
+ }
286
+ for name in others
287
+ ]
288
+ keys = self._keys_in_field(field)
289
+
290
+ if detail is False:
291
+ return list(others) + list(keys)
292
+ recs = self._generate_all_records(field)
293
+ recinfo = [
294
+ {"name": name, "type": "file", "size": rec[-1]}
295
+ for name, rec in zip(keys, recs)
296
+ if rec[0] # filters out path==None, deleted/missing
297
+ ]
298
+ return fileinfo + recinfo
299
+
300
+ def _load_one_key(self, key):
301
+ """Get the reference for one key
302
+
303
+ Returns bytes, one-element list or three-element list.
304
+ """
305
+ if key in self._items:
306
+ return self._items[key]
307
+ elif key in self.zmetadata:
308
+ return json.dumps(self.zmetadata[key]).encode()
309
+ elif "/" not in key or self._is_meta(key):
310
+ raise KeyError(key)
311
+ field, _ = key.rsplit("/", 1)
312
+ record, ri, chunk_size = self._key_to_record(key)
313
+ maybe = self._items.get((field, record), {}).get(ri, False)
314
+ if maybe is None:
315
+ # explicitly deleted
316
+ raise KeyError
317
+ elif maybe:
318
+ return maybe
319
+ elif chunk_size == 0:
320
+ return b""
321
+
322
+ # Chunk keys can be loaded from row group and cached in LRU cache
323
+ try:
324
+ refs = self.open_refs(field, record)
325
+ except (ValueError, TypeError, FileNotFoundError) as exc:
326
+ raise KeyError(key) from exc
327
+ columns = ["path", "offset", "size", "raw"]
328
+ selection = [refs[c][ri] if c in refs else None for c in columns]
329
+ raw = selection[-1]
330
+ if raw is not None:
331
+ return raw
332
+ if selection[0] is None:
333
+ raise KeyError("This reference does not exist or has been deleted")
334
+ if selection[1:3] == [0, 0]:
335
+ # URL only
336
+ return selection[:1]
337
+ # URL, offset, size
338
+ return selection[:3]
339
+
340
+ def _key_to_record(self, key):
341
+ """Details needed to construct a reference for one key"""
342
+ field, chunk = key.rsplit("/", 1)
343
+ chunk_sizes = self._get_chunk_sizes(field)
344
+ if len(chunk_sizes) == 0:
345
+ return 0, 0, 0
346
+ chunk_idx = [int(c) for c in chunk.split(".")]
347
+ chunk_number = ravel_multi_index(chunk_idx, chunk_sizes)
348
+ record = chunk_number // self.record_size
349
+ ri = chunk_number % self.record_size
350
+ return record, ri, len(chunk_sizes)
351
+
352
+ def _get_chunk_sizes(self, field):
353
+ """The number of chunks along each axis for a given field"""
354
+ if field not in self.chunk_sizes:
355
+ zarray = self.zmetadata[f"{field}/.zarray"]
356
+ size_ratio = [
357
+ math.ceil(s / c) for s, c in zip(zarray["shape"], zarray["chunks"])
358
+ ]
359
+ self.chunk_sizes[field] = size_ratio or [1]
360
+ return self.chunk_sizes[field]
361
+
362
+ def _generate_record(self, field, record):
363
+ """The references for a given parquet file of a given field"""
364
+ refs = self.open_refs(field, record)
365
+ it = iter(zip(*refs.values()))
366
+ if len(refs) == 3:
367
+ # All urls
368
+ return (list(t) for t in it)
369
+ elif len(refs) == 1:
370
+ # All raws
371
+ return refs["raw"]
372
+ else:
373
+ # Mix of urls and raws
374
+ return (list(t[:3]) if not t[3] else t[3] for t in it)
375
+
376
+ def _generate_all_records(self, field):
377
+ """Load all the references within a field by iterating over the parquet files"""
378
+ nrec = 1
379
+ for ch in self._get_chunk_sizes(field):
380
+ nrec *= ch
381
+ nrec = math.ceil(nrec / self.record_size)
382
+ for record in range(nrec):
383
+ yield from self._generate_record(field, record)
384
+
385
+ def values(self):
386
+ return RefsValuesView(self)
387
+
388
+ def items(self):
389
+ return RefsItemsView(self)
390
+
391
+ def __hash__(self):
392
+ return id(self)
393
+
394
+ def __getitem__(self, key):
395
+ return self._load_one_key(key)
396
+
397
+ def __setitem__(self, key, value):
398
+ if "/" in key and not self._is_meta(key):
399
+ field, chunk = key.rsplit("/", 1)
400
+ record, i, _ = self._key_to_record(key)
401
+ subdict = self._items.setdefault((field, record), {})
402
+ subdict[i] = value
403
+ if len(subdict) == self.record_size:
404
+ self.write(field, record)
405
+ else:
406
+ # metadata or top-level
407
+ if hasattr(value, "to_bytes"):
408
+ val = value.to_bytes().decode()
409
+ elif isinstance(value, bytes):
410
+ val = value.decode()
411
+ else:
412
+ val = value
413
+ self._items[key] = val
414
+ new_value = json.loads(val)
415
+ self.zmetadata[key] = {**self.zmetadata.get(key, {}), **new_value}
416
+
417
+ @staticmethod
418
+ def _is_meta(key):
419
+ return key.startswith(".z") or "/.z" in key
420
+
421
+ def __delitem__(self, key):
422
+ if key in self._items:
423
+ del self._items[key]
424
+ elif key in self.zmetadata:
425
+ del self.zmetadata[key]
426
+ else:
427
+ if "/" in key and not self._is_meta(key):
428
+ field, _ = key.rsplit("/", 1)
429
+ record, i, _ = self._key_to_record(key)
430
+ subdict = self._items.setdefault((field, record), {})
431
+ subdict[i] = None
432
+ if len(subdict) == self.record_size:
433
+ self.write(field, record)
434
+ else:
435
+ # metadata or top-level
436
+ self._items[key] = None
437
+
438
+ def write(self, field, record, base_url=None, storage_options=None):
439
+ # extra requirements if writing
440
+ import kerchunk.df
441
+ import numpy as np
442
+ import pandas as pd
443
+
444
+ partition = self._items[(field, record)]
445
+ original = False
446
+ if len(partition) < self.record_size:
447
+ try:
448
+ original = self.open_refs(field, record)
449
+ except OSError:
450
+ pass
451
+
452
+ if original:
453
+ paths = original["path"]
454
+ offsets = original["offset"]
455
+ sizes = original["size"]
456
+ raws = original["raw"]
457
+ else:
458
+ paths = np.full(self.record_size, np.nan, dtype="O")
459
+ offsets = np.zeros(self.record_size, dtype="int64")
460
+ sizes = np.zeros(self.record_size, dtype="int64")
461
+ raws = np.full(self.record_size, np.nan, dtype="O")
462
+ for j, data in partition.items():
463
+ if isinstance(data, list):
464
+ if (
465
+ str(paths.dtype) == "category"
466
+ and data[0] not in paths.dtype.categories
467
+ ):
468
+ paths = paths.add_categories(data[0])
469
+ paths[j] = data[0]
470
+ if len(data) > 1:
471
+ offsets[j] = data[1]
472
+ sizes[j] = data[2]
473
+ elif data is None:
474
+ # delete
475
+ paths[j] = None
476
+ offsets[j] = 0
477
+ sizes[j] = 0
478
+ raws[j] = None
479
+ else:
480
+ # this is the only call into kerchunk, could remove
481
+ raws[j] = kerchunk.df._proc_raw(data)
482
+ # TODO: only save needed columns
483
+ df = pd.DataFrame(
484
+ {
485
+ "path": paths,
486
+ "offset": offsets,
487
+ "size": sizes,
488
+ "raw": raws,
489
+ },
490
+ copy=False,
491
+ )
492
+ if df.path.count() / (df.path.nunique() or 1) > self.cat_thresh:
493
+ df["path"] = df["path"].astype("category")
494
+ object_encoding = {"raw": "bytes", "path": "utf8"}
495
+ has_nulls = ["path", "raw"]
496
+
497
+ fn = f"{base_url or self.out_root}/{field}/refs.{record}.parq"
498
+ self.fs.mkdirs(f"{base_url or self.out_root}/{field}", exist_ok=True)
499
+
500
+ if self.engine == "pyarrow":
501
+ df_backend_kwargs = {"write_statistics": False}
502
+ elif self.engine == "fastparquet":
503
+ df_backend_kwargs = {
504
+ "stats": False,
505
+ "object_encoding": object_encoding,
506
+ "has_nulls": has_nulls,
507
+ }
508
+ else:
509
+ raise NotImplementedError(f"{self.engine} not supported")
510
+ df.to_parquet(
511
+ fn,
512
+ engine=self.engine,
513
+ storage_options=storage_options
514
+ or getattr(self.fs, "storage_options", None),
515
+ compression="zstd",
516
+ index=False,
517
+ **df_backend_kwargs,
518
+ )
519
+
520
+ partition.clear()
521
+ self._items.pop((field, record))
522
+
523
+ def flush(self, base_url=None, storage_options=None):
524
+ """Output any modified or deleted keys
525
+
526
+ Parameters
527
+ ----------
528
+ base_url: str
529
+ Location of the output
530
+ """
531
+
532
+ # write what we have so far and clear sub chunks
533
+ for thing in list(self._items):
534
+ if isinstance(thing, tuple):
535
+ field, record = thing
536
+ self.write(
537
+ field,
538
+ record,
539
+ base_url=base_url,
540
+ storage_options=storage_options,
541
+ )
542
+
543
+ # gather .zmetadata from self._items and write that too
544
+ for k in list(self._items):
545
+ if k != ".zmetadata" and ".z" in k:
546
+ self.zmetadata[k] = json.loads(self._items.pop(k))
547
+ met = {"metadata": self.zmetadata, "record_size": self.record_size}
548
+ self._items.clear()
549
+ self._items[".zmetadata"] = json.dumps(met).encode()
550
+ self.fs.pipe(
551
+ "/".join([base_url or self.out_root, ".zmetadata"]),
552
+ self._items[".zmetadata"],
553
+ )
554
+
555
+ # TODO: only clear those that we wrote to?
556
+ self.open_refs.cache_clear()
557
+
558
+ def __len__(self):
559
+ # Caveat: This counts expected references, not actual - but is fast
560
+ count = 0
561
+ for field in self.listdir():
562
+ if field.startswith("."):
563
+ count += 1
564
+ else:
565
+ count += math.prod(self._get_chunk_sizes(field))
566
+ count += len(self.zmetadata) # all metadata keys
567
+ # any other files not in reference partitions
568
+ count += sum(1 for _ in self._items if not isinstance(_, tuple))
569
+ return count
570
+
571
+ def __iter__(self):
572
+ # Caveat: returns only existing keys, so the number of these does not
573
+ # match len(self)
574
+ metas = set(self.zmetadata)
575
+ metas.update(self._items)
576
+ for bit in metas:
577
+ if isinstance(bit, str):
578
+ yield bit
579
+ for field in self.listdir():
580
+ for k in self._keys_in_field(field):
581
+ if k in self:
582
+ yield k
583
+
584
+ def __contains__(self, item):
585
+ try:
586
+ self._load_one_key(item)
587
+ return True
588
+ except KeyError:
589
+ return False
590
+
591
+ def _keys_in_field(self, field):
592
+ """List key names in given field
593
+
594
+ Produces strings like "field/x.y" appropriate from the chunking of the array
595
+ """
596
+ chunk_sizes = self._get_chunk_sizes(field)
597
+ if len(chunk_sizes) == 0:
598
+ yield field + "/0"
599
+ return
600
+ inds = itertools.product(*(range(i) for i in chunk_sizes))
601
+ for ind in inds:
602
+ yield field + "/" + ".".join([str(c) for c in ind])
603
+
604
+
605
+ class ReferenceFileSystem(AsyncFileSystem):
606
+ """View byte ranges of some other file as a file system
607
+ Initial version: single file system target, which must support
608
+ async, and must allow start and end args in _cat_file. Later versions
609
+ may allow multiple arbitrary URLs for the targets.
610
+ This FileSystem is read-only. It is designed to be used with async
611
+ targets (for now). We do not get original file details from the target FS.
612
+ Configuration is by passing a dict of references at init, or a URL to
613
+ a JSON file containing the same; this dict
614
+ can also contain concrete data for some set of paths.
615
+ Reference dict format:
616
+ {path0: bytes_data, path1: (target_url, offset, size)}
617
+ https://github.com/fsspec/kerchunk/blob/main/README.md
618
+
619
+ simple_references: if True (default), no jinja interpreting is done,
620
+ which is the safe option.
621
+ """
622
+
623
+ protocol = "reference"
624
+ cachable = False
625
+
626
+ def __init__(
627
+ self,
628
+ fo,
629
+ target=None,
630
+ ref_storage_args=None,
631
+ target_protocol=None,
632
+ target_options=None,
633
+ remote_protocol=None,
634
+ remote_options=None,
635
+ fs=None,
636
+ template_overrides=None,
637
+ simple_templates=True,
638
+ max_gap=64_000,
639
+ max_block=256_000_000,
640
+ cache_size=128,
641
+ **kwargs,
642
+ ):
643
+ """
644
+ Parameters
645
+ ----------
646
+ fo : dict or str
647
+ The set of references to use for this instance, with a structure as above.
648
+ If str referencing a JSON file, will use fsspec.open, in conjunction
649
+ with target_options and target_protocol to open and parse JSON at this
650
+ location. If a directory, then assume references are a set of parquet
651
+ files to be loaded lazily.
652
+ target : str
653
+ For any references having target_url as None, this is the default file
654
+ target to use
655
+ ref_storage_args : dict
656
+ If references is a str, use these kwargs for loading the JSON file.
657
+ Deprecated: use target_options instead.
658
+ target_protocol : str
659
+ Used for loading the reference file, if it is a path. If None, protocol
660
+ will be derived from the given path
661
+ target_options : dict
662
+ Extra FS options for loading the reference file ``fo``, if given as a path
663
+ remote_protocol : str
664
+ The protocol of the filesystem on which the references will be evaluated
665
+ (unless fs is provided). If not given, will be derived from the first
666
+ URL that has a protocol in the templates or in the references, in that
667
+ order.
668
+ remote_options : dict
669
+ kwargs to go with remote_protocol
670
+ fs : AbstractFileSystem | dict(str, (AbstractFileSystem | dict))
671
+ Directly provide a file system(s):
672
+ - a single filesystem instance
673
+ - a dict of protocol:filesystem, where each value is either a filesystem
674
+ instance, or a dict of kwargs that can be used to create in
675
+ instance for the given protocol
676
+
677
+ If this is given, remote_options and remote_protocol are ignored.
678
+ template_overrides : dict
679
+ Swap out any templates in the references file with these - useful for
680
+ testing.
681
+ simple_templates: bool
682
+ Whether templates can be processed with simple replace (True) or if
683
+ jinja is needed (False, much slower). All reference sets produced by
684
+ ``kerchunk`` are simple in this sense, but the spec allows for complex.
685
+ max_gap, max_block: int
686
+ For merging multiple concurrent requests to the same remote file.
687
+ Neighboring byte ranges will only be merged when their
688
+ inter-range gap is <= ``max_gap``. Default is 64KB. Set to 0
689
+ to only merge when it requires no extra bytes. Pass a negative
690
+ number to disable merging, appropriate for local target files.
691
+ Neighboring byte ranges will only be merged when the size of
692
+ the aggregated range is <= ``max_block``. Default is 256MB.
693
+ cache_size : int
694
+ Maximum size of LRU cache, where cache_size*record_size denotes
695
+ the total number of references that can be loaded in memory at once.
696
+ Only used for lazily loaded references.
697
+ kwargs : passed to parent class
698
+ """
699
+ super().__init__(**kwargs)
700
+ self.target = target
701
+ self.template_overrides = template_overrides
702
+ self.simple_templates = simple_templates
703
+ self.templates = {}
704
+ self.fss = {}
705
+ self._dircache = {}
706
+ self.max_gap = max_gap
707
+ self.max_block = max_block
708
+ if isinstance(fo, str):
709
+ dic = dict(
710
+ **(ref_storage_args or target_options or {}), protocol=target_protocol
711
+ )
712
+ ref_fs, fo2 = fsspec.core.url_to_fs(fo, **dic)
713
+ if ".json" not in fo2 and (
714
+ fo.endswith(("parq", "parquet", "/")) or ref_fs.isdir(fo2)
715
+ ):
716
+ # Lazy parquet refs
717
+ logger.info("Open lazy reference dict from URL %s", fo)
718
+ self.references = LazyReferenceMapper(
719
+ fo2,
720
+ fs=ref_fs,
721
+ cache_size=cache_size,
722
+ )
723
+ else:
724
+ # text JSON
725
+ with fsspec.open(fo, "rb", **dic) as f:
726
+ logger.info("Read reference from URL %s", fo)
727
+ text = json.load(f)
728
+ self._process_references(text, template_overrides)
729
+ else:
730
+ # dictionaries
731
+ self._process_references(fo, template_overrides)
732
+ if isinstance(fs, dict):
733
+ self.fss = {
734
+ k: (
735
+ fsspec.filesystem(k.split(":", 1)[0], **opts)
736
+ if isinstance(opts, dict)
737
+ else opts
738
+ )
739
+ for k, opts in fs.items()
740
+ }
741
+ if None not in self.fss:
742
+ self.fss[None] = filesystem("file")
743
+ return
744
+ if fs is not None:
745
+ # single remote FS
746
+ remote_protocol = (
747
+ fs.protocol[0] if isinstance(fs.protocol, tuple) else fs.protocol
748
+ )
749
+ self.fss[remote_protocol] = fs
750
+
751
+ if remote_protocol is None:
752
+ # get single protocol from any templates
753
+ for ref in self.templates.values():
754
+ if callable(ref):
755
+ ref = ref()
756
+ protocol, _ = fsspec.core.split_protocol(ref)
757
+ if protocol and protocol not in self.fss:
758
+ fs = filesystem(protocol, **(remote_options or {}))
759
+ self.fss[protocol] = fs
760
+ if remote_protocol is None:
761
+ # get single protocol from references
762
+ # TODO: warning here, since this can be very expensive?
763
+ for ref in self.references.values():
764
+ if callable(ref):
765
+ ref = ref()
766
+ if isinstance(ref, list) and ref[0]:
767
+ protocol, _ = fsspec.core.split_protocol(ref[0])
768
+ if protocol not in self.fss:
769
+ fs = filesystem(protocol, **(remote_options or {}))
770
+ self.fss[protocol] = fs
771
+ # only use first remote URL
772
+ break
773
+
774
+ if remote_protocol and remote_protocol not in self.fss:
775
+ fs = filesystem(remote_protocol, **(remote_options or {}))
776
+ self.fss[remote_protocol] = fs
777
+
778
+ self.fss[None] = fs or filesystem("file") # default one
779
+ # Wrap any non-async filesystems to ensure async methods are available below
780
+ for k, f in self.fss.items():
781
+ if not f.async_impl:
782
+ self.fss[k] = AsyncFileSystemWrapper(f, asynchronous=self.asynchronous)
783
+ elif self.asynchronous ^ f.asynchronous:
784
+ raise ValueError(
785
+ "Reference-FS's target filesystem must have same value "
786
+ "of asynchronous"
787
+ )
788
+
789
+ def _cat_common(self, path, start=None, end=None):
790
+ path = self._strip_protocol(path)
791
+ logger.debug(f"cat: {path}")
792
+ try:
793
+ part = self.references[path]
794
+ except KeyError as exc:
795
+ raise FileNotFoundError(path) from exc
796
+ if isinstance(part, str):
797
+ part = part.encode()
798
+ if hasattr(part, "to_bytes"):
799
+ part = part.to_bytes()
800
+ if isinstance(part, bytes):
801
+ logger.debug(f"Reference: {path}, type bytes")
802
+ if part.startswith(b"base64:"):
803
+ part = base64.b64decode(part[7:])
804
+ return part, None, None
805
+
806
+ if len(part) == 1:
807
+ logger.debug(f"Reference: {path}, whole file => {part}")
808
+ url = part[0]
809
+ start1, end1 = start, end
810
+ else:
811
+ url, start0, size = part
812
+ logger.debug(f"Reference: {path} => {url}, offset {start0}, size {size}")
813
+ end0 = start0 + size
814
+
815
+ if start is not None:
816
+ if start >= 0:
817
+ start1 = start0 + start
818
+ else:
819
+ start1 = end0 + start
820
+ else:
821
+ start1 = start0
822
+ if end is not None:
823
+ if end >= 0:
824
+ end1 = start0 + end
825
+ else:
826
+ end1 = end0 + end
827
+ else:
828
+ end1 = end0
829
+ if url is None:
830
+ url = self.target
831
+ return url, start1, end1
832
+
833
+ async def _cat_file(self, path, start=None, end=None, **kwargs):
834
+ part_or_url, start0, end0 = self._cat_common(path, start=start, end=end)
835
+ if isinstance(part_or_url, bytes):
836
+ return part_or_url[start:end]
837
+ protocol, _ = split_protocol(part_or_url)
838
+ try:
839
+ return await self.fss[protocol]._cat_file(
840
+ part_or_url, start=start0, end=end0
841
+ )
842
+ except Exception as e:
843
+ raise ReferenceNotReachable(path, part_or_url) from e
844
+
845
+ def cat_file(self, path, start=None, end=None, **kwargs):
846
+ part_or_url, start0, end0 = self._cat_common(path, start=start, end=end)
847
+ if isinstance(part_or_url, bytes):
848
+ return part_or_url[start:end]
849
+ protocol, _ = split_protocol(part_or_url)
850
+ try:
851
+ return self.fss[protocol].cat_file(part_or_url, start=start0, end=end0)
852
+ except Exception as e:
853
+ raise ReferenceNotReachable(path, part_or_url) from e
854
+
855
+ def pipe_file(self, path, value, **_):
856
+ """Temporarily add binary data or reference as a file"""
857
+ self.references[path] = value
858
+
859
+ async def _get_file(self, rpath, lpath, **kwargs):
860
+ if self.isdir(rpath):
861
+ return os.makedirs(lpath, exist_ok=True)
862
+ data = await self._cat_file(rpath)
863
+ with open(lpath, "wb") as f:
864
+ f.write(data)
865
+
866
+ def get_file(self, rpath, lpath, callback=DEFAULT_CALLBACK, **kwargs):
867
+ if self.isdir(rpath):
868
+ return os.makedirs(lpath, exist_ok=True)
869
+ data = self.cat_file(rpath, **kwargs)
870
+ callback.set_size(len(data))
871
+ if isfilelike(lpath):
872
+ lpath.write(data)
873
+ else:
874
+ with open(lpath, "wb") as f:
875
+ f.write(data)
876
+ callback.absolute_update(len(data))
877
+
878
+ def get(self, rpath, lpath, recursive=False, **kwargs):
879
+ if recursive:
880
+ # trigger directory build
881
+ self.ls("")
882
+ rpath = self.expand_path(rpath, recursive=recursive)
883
+ fs = fsspec.filesystem("file", auto_mkdir=True)
884
+ targets = other_paths(rpath, lpath)
885
+ if recursive:
886
+ data = self.cat([r for r in rpath if not self.isdir(r)])
887
+ else:
888
+ data = self.cat(rpath)
889
+ for remote, local in zip(rpath, targets):
890
+ if remote in data:
891
+ fs.pipe_file(local, data[remote])
892
+
893
+ def cat(self, path, recursive=False, on_error="raise", **kwargs):
894
+ if isinstance(path, str) and recursive:
895
+ raise NotImplementedError
896
+ if isinstance(path, list) and (recursive or any("*" in p for p in path)):
897
+ raise NotImplementedError
898
+ # TODO: if references is lazy, pre-fetch all paths in batch before access
899
+ proto_dict = _protocol_groups(path, self.references)
900
+ out = {}
901
+ for proto, paths in proto_dict.items():
902
+ fs = self.fss[proto]
903
+ urls, starts, ends, valid_paths = [], [], [], []
904
+ for p in paths:
905
+ # find references or label not-found. Early exit if any not
906
+ # found and on_error is "raise"
907
+ try:
908
+ u, s, e = self._cat_common(p)
909
+ if not isinstance(u, (bytes, str)):
910
+ # nan/None from parquet
911
+ continue
912
+ except FileNotFoundError as err:
913
+ if on_error == "raise":
914
+ raise
915
+ if on_error != "omit":
916
+ out[p] = err
917
+ else:
918
+ urls.append(u)
919
+ starts.append(s)
920
+ ends.append(e)
921
+ valid_paths.append(p)
922
+
923
+ # process references into form for merging
924
+ urls2 = []
925
+ starts2 = []
926
+ ends2 = []
927
+ paths2 = []
928
+ whole_files = set()
929
+ for u, s, e, p in zip(urls, starts, ends, valid_paths):
930
+ if isinstance(u, bytes):
931
+ # data
932
+ out[p] = u
933
+ elif s is None:
934
+ # whole file - limits are None, None, but no further
935
+ # entries take for this file
936
+ whole_files.add(u)
937
+ urls2.append(u)
938
+ starts2.append(s)
939
+ ends2.append(e)
940
+ paths2.append(p)
941
+ for u, s, e, p in zip(urls, starts, ends, valid_paths):
942
+ # second run to account for files that are to be loaded whole
943
+ if s is not None and u not in whole_files:
944
+ urls2.append(u)
945
+ starts2.append(s)
946
+ ends2.append(e)
947
+ paths2.append(p)
948
+
949
+ # merge and fetch consolidated ranges
950
+ new_paths, new_starts, new_ends = merge_offset_ranges(
951
+ list(urls2),
952
+ list(starts2),
953
+ list(ends2),
954
+ sort=True,
955
+ max_gap=self.max_gap,
956
+ max_block=self.max_block,
957
+ )
958
+ bytes_out = fs.cat_ranges(new_paths, new_starts, new_ends)
959
+
960
+ # unbundle from merged bytes - simple approach
961
+ for u, s, e, p in zip(urls, starts, ends, valid_paths):
962
+ if p in out:
963
+ continue # was bytes, already handled
964
+ for np, ns, ne, b in zip(new_paths, new_starts, new_ends, bytes_out):
965
+ if np == u and (ns is None or ne is None):
966
+ if isinstance(b, Exception):
967
+ out[p] = b
968
+ else:
969
+ out[p] = b[s:e]
970
+ elif np == u and s >= ns and e <= ne:
971
+ if isinstance(b, Exception):
972
+ out[p] = b
973
+ else:
974
+ out[p] = b[s - ns : (e - ne) or None]
975
+
976
+ for k, v in out.copy().items():
977
+ # these were valid references, but fetch failed, so transform exc
978
+ if isinstance(v, Exception) and k in self.references:
979
+ ex = out[k]
980
+ new_ex = ReferenceNotReachable(k, self.references[k])
981
+ new_ex.__cause__ = ex
982
+ if on_error == "raise":
983
+ raise new_ex
984
+ elif on_error != "omit":
985
+ out[k] = new_ex
986
+
987
+ if len(out) == 1 and isinstance(path, str) and "*" not in path:
988
+ return _first(out)
989
+ return out
990
+
991
+ def _process_references(self, references, template_overrides=None):
992
+ vers = references.get("version", None)
993
+ if vers is None:
994
+ self._process_references0(references)
995
+ elif vers == 1:
996
+ self._process_references1(references, template_overrides=template_overrides)
997
+ else:
998
+ raise ValueError(f"Unknown reference spec version: {vers}")
999
+ # TODO: we make dircache by iterating over all entries, but for Spec >= 1,
1000
+ # can replace with programmatic. Is it even needed for mapper interface?
1001
+
1002
+ def _process_references0(self, references):
1003
+ """Make reference dict for Spec Version 0"""
1004
+ if isinstance(references, dict):
1005
+ # do not do this for lazy/parquet backend, which will not make dicts,
1006
+ # but must remain writable in the original object
1007
+ references = {
1008
+ key: json.dumps(val) if isinstance(val, dict) else val
1009
+ for key, val in references.items()
1010
+ }
1011
+ self.references = references
1012
+
1013
+ def _process_references1(self, references, template_overrides=None):
1014
+ if not self.simple_templates or self.templates:
1015
+ import jinja2.sandbox
1016
+ self.references = {}
1017
+ self._process_templates(references.get("templates", {}))
1018
+
1019
+ @lru_cache(1000)
1020
+ def _render_jinja(u):
1021
+ return (
1022
+ jinja2.sandbox.SandboxedEnvironment()
1023
+ .from_string(u)
1024
+ .render(**self.templates)
1025
+ )
1026
+
1027
+ for k, v in references.get("refs", {}).items():
1028
+ if isinstance(v, str):
1029
+ if v.startswith("base64:"):
1030
+ self.references[k] = base64.b64decode(v[7:])
1031
+ self.references[k] = v
1032
+ elif isinstance(v, dict):
1033
+ self.references[k] = json.dumps(v)
1034
+ elif self.templates:
1035
+ u = v[0]
1036
+ if "{{" in u:
1037
+ if self.simple_templates:
1038
+ u = (
1039
+ u.replace("{{", "{")
1040
+ .replace("}}", "}")
1041
+ .format(**self.templates)
1042
+ )
1043
+ else:
1044
+ u = _render_jinja(u)
1045
+ self.references[k] = [u] if len(v) == 1 else [u, v[1], v[2]]
1046
+ else:
1047
+ self.references[k] = v
1048
+ self.references.update(self._process_gen(references.get("gen", [])))
1049
+
1050
+ def _process_templates(self, tmp):
1051
+ self.templates = {}
1052
+ if self.template_overrides is not None:
1053
+ tmp.update(self.template_overrides)
1054
+ for k, v in tmp.items():
1055
+ if "{{" in v:
1056
+ import jinja2.sandbox
1057
+
1058
+ self.templates[k] = (
1059
+ lambda temp=v, **kwargs: jinja2.sandbox.SandboxedEnvironment()
1060
+ .from_string(temp)
1061
+ .render(**kwargs)
1062
+ )
1063
+ else:
1064
+ self.templates[k] = v
1065
+
1066
+ def _process_gen(self, gens):
1067
+ out = {}
1068
+ if self.simple_templates:
1069
+ return out
1070
+ for gen in gens:
1071
+ dimension = {
1072
+ k: (
1073
+ v
1074
+ if isinstance(v, list)
1075
+ else range(v.get("start", 0), v["stop"], v.get("step", 1))
1076
+ )
1077
+ for k, v in gen["dimensions"].items()
1078
+ }
1079
+ products = (
1080
+ dict(zip(dimension.keys(), values))
1081
+ for values in itertools.product(*dimension.values())
1082
+ )
1083
+ for pr in products:
1084
+ import jinja2.sandbox
1085
+
1086
+ key = (
1087
+ jinja2.sandbox.SandboxedEnvironment()
1088
+ .from_string(gen["key"])
1089
+ .render(**pr, **self.templates)
1090
+ )
1091
+ url = (
1092
+ jinja2.sandbox.SandboxedEnvironment()
1093
+ .from_string(gen["url"])
1094
+ .render(**pr, **self.templates)
1095
+ )
1096
+ if ("offset" in gen) and ("length" in gen):
1097
+ offset = int(
1098
+ jinja2.sandbox.SandboxedEnvironment()
1099
+ .from_string(gen["offset"])
1100
+ .render(**pr, **self.templates)
1101
+ )
1102
+ length = int(
1103
+ jinja2.sandbox.SandboxedEnvironment()
1104
+ .from_string(gen["length"])
1105
+ .render(**pr, **self.templates)
1106
+ )
1107
+ out[key] = [url, offset, length]
1108
+ elif ("offset" in gen) ^ ("length" in gen):
1109
+ raise ValueError(
1110
+ "Both 'offset' and 'length' are required for a "
1111
+ "reference generator entry if either is provided."
1112
+ )
1113
+ else:
1114
+ out[key] = [url]
1115
+ return out
1116
+
1117
+ def _dircache_from_items(self):
1118
+ self.dircache = {"": []}
1119
+ it = self.references.items()
1120
+ for path, part in it:
1121
+ if isinstance(part, (bytes, str)) or hasattr(part, "to_bytes"):
1122
+ size = len(part)
1123
+ elif len(part) == 1:
1124
+ size = None
1125
+ else:
1126
+ _, _, size = part
1127
+ par = path.rsplit("/", 1)[0] if "/" in path else ""
1128
+ par0 = par
1129
+ subdirs = [par0]
1130
+ while par0 and par0 not in self.dircache:
1131
+ # collect parent directories
1132
+ par0 = self._parent(par0)
1133
+ subdirs.append(par0)
1134
+
1135
+ subdirs.reverse()
1136
+ for parent, child in zip(subdirs, subdirs[1:]):
1137
+ # register newly discovered directories
1138
+ assert child not in self.dircache
1139
+ assert parent in self.dircache
1140
+ self.dircache[parent].append(
1141
+ {"name": child, "type": "directory", "size": 0}
1142
+ )
1143
+ self.dircache[child] = []
1144
+
1145
+ self.dircache[par].append({"name": path, "type": "file", "size": size})
1146
+
1147
+ def _open(self, path, mode="rb", block_size=None, cache_options=None, **kwargs):
1148
+ part_or_url, start0, end0 = self._cat_common(path)
1149
+ # This logic is kept outside `ReferenceFile` to avoid unnecessary redirection.
1150
+ # That does mean `_cat_common` gets called twice if it eventually reaches `ReferenceFile`.
1151
+ if isinstance(part_or_url, bytes):
1152
+ return io.BytesIO(part_or_url[start0:end0])
1153
+
1154
+ protocol, _ = split_protocol(part_or_url)
1155
+ if start0 is None and end0 is None:
1156
+ return self.fss[protocol]._open(
1157
+ part_or_url,
1158
+ mode,
1159
+ block_size=block_size,
1160
+ cache_options=cache_options,
1161
+ **kwargs,
1162
+ )
1163
+
1164
+ return ReferenceFile(
1165
+ self,
1166
+ path,
1167
+ mode,
1168
+ block_size=block_size,
1169
+ cache_options=cache_options,
1170
+ **kwargs,
1171
+ )
1172
+
1173
+ def ls(self, path, detail=True, **kwargs):
1174
+ logger.debug("list %s", path)
1175
+ path = self._strip_protocol(path)
1176
+ if isinstance(self.references, LazyReferenceMapper):
1177
+ try:
1178
+ return self.references.ls(path, detail)
1179
+ except KeyError:
1180
+ pass
1181
+ raise FileNotFoundError(f"'{path}' is not a known key")
1182
+ if not self.dircache:
1183
+ self._dircache_from_items()
1184
+ out = self._ls_from_cache(path)
1185
+ if out is None:
1186
+ raise FileNotFoundError(path)
1187
+ if detail:
1188
+ return out
1189
+ return [o["name"] for o in out]
1190
+
1191
+ def exists(self, path, **kwargs): # overwrite auto-sync version
1192
+ return self.isdir(path) or self.isfile(path)
1193
+
1194
+ def isdir(self, path): # overwrite auto-sync version
1195
+ if self.dircache:
1196
+ return path in self.dircache
1197
+ elif isinstance(self.references, LazyReferenceMapper):
1198
+ return path in self.references.listdir()
1199
+ else:
1200
+ # this may be faster than building dircache for single calls, but
1201
+ # by looping will be slow for many calls; could cache it?
1202
+ return any(_.startswith(f"{path}/") for _ in self.references)
1203
+
1204
+ def isfile(self, path): # overwrite auto-sync version
1205
+ return path in self.references
1206
+
1207
+ async def _ls(self, path, detail=True, **kwargs): # calls fast sync code
1208
+ return self.ls(path, detail, **kwargs)
1209
+
1210
+ def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
1211
+ if withdirs:
1212
+ return super().find(
1213
+ path, maxdepth=maxdepth, withdirs=withdirs, detail=detail, **kwargs
1214
+ )
1215
+ if path:
1216
+ path = self._strip_protocol(path)
1217
+ r = sorted(k for k in self.references if k.startswith(path))
1218
+ else:
1219
+ r = sorted(self.references)
1220
+ if detail:
1221
+ if not self.dircache:
1222
+ self._dircache_from_items()
1223
+ return {k: self._ls_from_cache(k)[0] for k in r}
1224
+ else:
1225
+ return r
1226
+
1227
+ def info(self, path, **kwargs):
1228
+ out = self.references.get(path)
1229
+ if out is not None:
1230
+ if isinstance(out, (str, bytes)):
1231
+ # decode base64 here
1232
+ return {"name": path, "type": "file", "size": len(out)}
1233
+ elif len(out) > 1:
1234
+ return {"name": path, "type": "file", "size": out[2]}
1235
+ else:
1236
+ out0 = [{"name": path, "type": "file", "size": None}]
1237
+ else:
1238
+ out = self.ls(path, True)
1239
+ out0 = [o for o in out if o["name"] == path]
1240
+ if not out0:
1241
+ return {"name": path, "type": "directory", "size": 0}
1242
+ if out0[0]["size"] is None:
1243
+ # if this is a whole remote file, update size using remote FS
1244
+ prot, _ = split_protocol(self.references[path][0])
1245
+ out0[0]["size"] = self.fss[prot].size(self.references[path][0])
1246
+ return out0[0]
1247
+
1248
+ async def _info(self, path, **kwargs): # calls fast sync code
1249
+ return self.info(path)
1250
+
1251
+ async def _rm_file(self, path, **kwargs):
1252
+ self.references.pop(
1253
+ path, None
1254
+ ) # ignores FileNotFound, just as well for directories
1255
+ self.dircache.clear() # this is a bit heavy handed
1256
+
1257
+ async def _pipe_file(self, path, data, mode="overwrite", **kwargs):
1258
+ if mode == "create" and self.exists(path):
1259
+ raise FileExistsError
1260
+ # can be str or bytes
1261
+ self.references[path] = data
1262
+ self.dircache.clear() # this is a bit heavy handed
1263
+
1264
+ async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs):
1265
+ # puts binary
1266
+ if mode == "create" and self.exists(rpath):
1267
+ raise FileExistsError
1268
+ with open(lpath, "rb") as f:
1269
+ self.references[rpath] = f.read()
1270
+ self.dircache.clear() # this is a bit heavy handed
1271
+
1272
+ def save_json(self, url, **storage_options):
1273
+ """Write modified references into new location"""
1274
+ out = {}
1275
+ for k, v in self.references.items():
1276
+ if isinstance(v, bytes):
1277
+ try:
1278
+ out[k] = v.decode("ascii")
1279
+ except UnicodeDecodeError:
1280
+ out[k] = (b"base64:" + base64.b64encode(v)).decode()
1281
+ else:
1282
+ out[k] = v
1283
+ with fsspec.open(url, "wb", **storage_options) as f:
1284
+ f.write(json.dumps({"version": 1, "refs": out}).encode())
1285
+
1286
+
1287
+ class ReferenceFile(AbstractBufferedFile):
1288
+ def __init__(
1289
+ self,
1290
+ fs,
1291
+ path,
1292
+ mode="rb",
1293
+ block_size="default",
1294
+ autocommit=True,
1295
+ cache_type="readahead",
1296
+ cache_options=None,
1297
+ size=None,
1298
+ **kwargs,
1299
+ ):
1300
+ super().__init__(
1301
+ fs,
1302
+ path,
1303
+ mode=mode,
1304
+ block_size=block_size,
1305
+ autocommit=autocommit,
1306
+ size=size,
1307
+ cache_type=cache_type,
1308
+ cache_options=cache_options,
1309
+ **kwargs,
1310
+ )
1311
+ part_or_url, self.start, self.end = self.fs._cat_common(self.path)
1312
+ protocol, _ = split_protocol(part_or_url)
1313
+ self.src_fs = self.fs.fss[protocol]
1314
+ self.src_path = part_or_url
1315
+ self._f = None
1316
+
1317
+ @property
1318
+ def f(self):
1319
+ if self._f is None or self._f.closed:
1320
+ self._f = self.src_fs._open(
1321
+ self.src_path,
1322
+ mode=self.mode,
1323
+ block_size=self.blocksize,
1324
+ autocommit=self.autocommit,
1325
+ cache_type="none",
1326
+ **self.kwargs,
1327
+ )
1328
+ return self._f
1329
+
1330
+ def close(self):
1331
+ if self._f is not None:
1332
+ self._f.close()
1333
+ return super().close()
1334
+
1335
+ def _fetch_range(self, start, end):
1336
+ start = start + self.start
1337
+ end = min(end + self.start, self.end)
1338
+ self.f.seek(start)
1339
+ return self.f.read(end - start)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/sftp.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import logging
3
+ import os
4
+ import types
5
+ import uuid
6
+ from stat import S_ISDIR, S_ISLNK
7
+
8
+ import paramiko
9
+
10
+ from .. import AbstractFileSystem
11
+ from ..utils import infer_storage_options
12
+
13
+ logger = logging.getLogger("fsspec.sftp")
14
+
15
+
16
+ class SFTPFileSystem(AbstractFileSystem):
17
+ """Files over SFTP/SSH
18
+
19
+ Peer-to-peer filesystem over SSH using paramiko.
20
+
21
+ Note: if using this with the ``open`` or ``open_files``, with full URLs,
22
+ there is no way to tell if a path is relative, so all paths are assumed
23
+ to be absolute.
24
+ """
25
+
26
+ protocol = "sftp", "ssh"
27
+
28
+ def __init__(self, host, **ssh_kwargs):
29
+ """
30
+
31
+ Parameters
32
+ ----------
33
+ host: str
34
+ Hostname or IP as a string
35
+ temppath: str
36
+ Location on the server to put files, when within a transaction
37
+ ssh_kwargs: dict
38
+ Parameters passed on to connection. See details in
39
+ https://docs.paramiko.org/en/3.3/api/client.html#paramiko.client.SSHClient.connect
40
+ May include port, username, password...
41
+ """
42
+ if self._cached:
43
+ return
44
+ super().__init__(**ssh_kwargs)
45
+ self.temppath = ssh_kwargs.pop("temppath", "/tmp") # remote temp directory
46
+ self.host = host
47
+ self.ssh_kwargs = ssh_kwargs
48
+ self._connect()
49
+
50
+ def _connect(self):
51
+ logger.debug("Connecting to SFTP server %s", self.host)
52
+ self.client = paramiko.SSHClient()
53
+ self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
54
+ self.client.connect(self.host, **self.ssh_kwargs)
55
+ self.ftp = self.client.open_sftp()
56
+
57
+ @classmethod
58
+ def _strip_protocol(cls, path):
59
+ return infer_storage_options(path)["path"]
60
+
61
+ @staticmethod
62
+ def _get_kwargs_from_urls(urlpath):
63
+ out = infer_storage_options(urlpath)
64
+ out.pop("path", None)
65
+ out.pop("protocol", None)
66
+ return out
67
+
68
+ def mkdir(self, path, create_parents=True, mode=511):
69
+ path = self._strip_protocol(path)
70
+ logger.debug("Creating folder %s", path)
71
+ if self.exists(path):
72
+ raise FileExistsError(f"File exists: {path}")
73
+
74
+ if create_parents:
75
+ self.makedirs(path)
76
+ else:
77
+ self.ftp.mkdir(path, mode)
78
+
79
+ def makedirs(self, path, exist_ok=False, mode=511):
80
+ if self.exists(path) and not exist_ok:
81
+ raise FileExistsError(f"File exists: {path}")
82
+
83
+ parts = path.split("/")
84
+ new_path = "/" if path[:1] == "/" else ""
85
+
86
+ for part in parts:
87
+ if part:
88
+ new_path = f"{new_path}/{part}" if new_path else part
89
+ if not self.exists(new_path):
90
+ self.ftp.mkdir(new_path, mode)
91
+
92
+ def rmdir(self, path):
93
+ path = self._strip_protocol(path)
94
+ logger.debug("Removing folder %s", path)
95
+ self.ftp.rmdir(path)
96
+
97
+ def info(self, path):
98
+ path = self._strip_protocol(path)
99
+ stat = self._decode_stat(self.ftp.stat(path))
100
+ stat["name"] = path
101
+ return stat
102
+
103
+ @staticmethod
104
+ def _decode_stat(stat, parent_path=None):
105
+ if S_ISDIR(stat.st_mode):
106
+ t = "directory"
107
+ elif S_ISLNK(stat.st_mode):
108
+ t = "link"
109
+ else:
110
+ t = "file"
111
+ out = {
112
+ "name": "",
113
+ "size": stat.st_size,
114
+ "type": t,
115
+ "uid": stat.st_uid,
116
+ "gid": stat.st_gid,
117
+ "time": datetime.datetime.fromtimestamp(
118
+ stat.st_atime, tz=datetime.timezone.utc
119
+ ),
120
+ "mtime": datetime.datetime.fromtimestamp(
121
+ stat.st_mtime, tz=datetime.timezone.utc
122
+ ),
123
+ }
124
+ if parent_path:
125
+ out["name"] = "/".join([parent_path.rstrip("/"), stat.filename])
126
+ return out
127
+
128
+ def ls(self, path, detail=False):
129
+ path = self._strip_protocol(path)
130
+ logger.debug("Listing folder %s", path)
131
+ stats = [self._decode_stat(stat, path) for stat in self.ftp.listdir_iter(path)]
132
+ if detail:
133
+ return stats
134
+ else:
135
+ paths = [stat["name"] for stat in stats]
136
+ return sorted(paths)
137
+
138
+ def put_file(self, lpath, rpath, callback=None, **kwargs):
139
+ self.mkdirs(self._parent(os.fspath(rpath)), exist_ok=True)
140
+ logger.debug("Put file %s into %s", lpath, rpath)
141
+ self.ftp.put(lpath, rpath)
142
+
143
+ def get_file(self, rpath, lpath, **kwargs):
144
+ if self.isdir(rpath):
145
+ os.makedirs(lpath, exist_ok=True)
146
+ else:
147
+ self.ftp.get(self._strip_protocol(rpath), lpath)
148
+
149
+ def _open(self, path, mode="rb", block_size=None, **kwargs):
150
+ """
151
+ block_size: int or None
152
+ If 0, no buffering, if 1, line buffering, if >1, buffer that many
153
+ bytes, if None use default from paramiko.
154
+ """
155
+ logger.debug("Opening file %s", path)
156
+ if kwargs.get("autocommit", True) is False:
157
+ # writes to temporary file, move on commit
158
+ path2 = "/".join([self.temppath, str(uuid.uuid4())])
159
+ f = self.ftp.open(path2, mode, bufsize=block_size if block_size else -1)
160
+ f.temppath = path2
161
+ f.targetpath = path
162
+ f.fs = self
163
+ f.commit = types.MethodType(commit_a_file, f)
164
+ f.discard = types.MethodType(discard_a_file, f)
165
+ else:
166
+ f = self.ftp.open(path, mode, bufsize=block_size if block_size else -1)
167
+ return f
168
+
169
+ def _rm(self, path):
170
+ if self.isdir(path):
171
+ self.ftp.rmdir(path)
172
+ else:
173
+ self.ftp.remove(path)
174
+
175
+ def mv(self, old, new):
176
+ new = self._strip_protocol(new)
177
+ old = self._strip_protocol(old)
178
+ logger.debug("Renaming %s into %s", old, new)
179
+ self.ftp.posix_rename(old, new)
180
+
181
+
182
+ def commit_a_file(self):
183
+ self.fs.mv(self.temppath, self.targetpath)
184
+
185
+
186
+ def discard_a_file(self):
187
+ self.fs._rm(self.temppath)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/smb.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module contains SMBFileSystem class responsible for handling access to
3
+ Windows Samba network shares by using package smbprotocol
4
+ """
5
+
6
+ import datetime
7
+ import re
8
+ import uuid
9
+ from stat import S_ISDIR, S_ISLNK
10
+
11
+ import smbclient
12
+ import smbprotocol.exceptions
13
+
14
+ from .. import AbstractFileSystem
15
+ from ..utils import infer_storage_options
16
+
17
+ # ! pylint: disable=bad-continuation
18
+
19
+
20
+ class SMBFileSystem(AbstractFileSystem):
21
+ """Allow reading and writing to Windows and Samba network shares.
22
+
23
+ When using `fsspec.open()` for getting a file-like object the URI
24
+ should be specified as this format:
25
+ ``smb://workgroup;user:password@server:port/share/folder/file.csv``.
26
+
27
+ Example::
28
+
29
+ >>> import fsspec
30
+ >>> with fsspec.open(
31
+ ... 'smb://myuser:mypassword@myserver.com/' 'share/folder/file.csv'
32
+ ... ) as smbfile:
33
+ ... df = pd.read_csv(smbfile, sep='|', header=None)
34
+
35
+ Note that you need to pass in a valid hostname or IP address for the host
36
+ component of the URL. Do not use the Windows/NetBIOS machine name for the
37
+ host component.
38
+
39
+ The first component of the path in the URL points to the name of the shared
40
+ folder. Subsequent path components will point to the directory/folder/file.
41
+
42
+ The URL components ``workgroup`` , ``user``, ``password`` and ``port`` may be
43
+ optional.
44
+
45
+ .. note::
46
+
47
+ For working this source require `smbprotocol`_ to be installed, e.g.::
48
+
49
+ $ pip install smbprotocol
50
+ # or
51
+ # pip install smbprotocol[kerberos]
52
+
53
+ .. _smbprotocol: https://github.com/jborean93/smbprotocol#requirements
54
+
55
+ Note: if using this with the ``open`` or ``open_files``, with full URLs,
56
+ there is no way to tell if a path is relative, so all paths are assumed
57
+ to be absolute.
58
+ """
59
+
60
+ protocol = "smb"
61
+
62
+ # pylint: disable=too-many-arguments
63
+ def __init__(
64
+ self,
65
+ host,
66
+ port=None,
67
+ username=None,
68
+ password=None,
69
+ timeout=60,
70
+ encrypt=None,
71
+ share_access=None,
72
+ register_session_retries=4,
73
+ register_session_retry_wait=1,
74
+ register_session_retry_factor=10,
75
+ auto_mkdir=False,
76
+ **kwargs,
77
+ ):
78
+ """
79
+ You can use _get_kwargs_from_urls to get some kwargs from
80
+ a reasonable SMB url.
81
+
82
+ Authentication will be anonymous or integrated if username/password are not
83
+ given.
84
+
85
+ Parameters
86
+ ----------
87
+ host: str
88
+ The remote server name/ip to connect to
89
+ port: int or None
90
+ Port to connect with. Usually 445, sometimes 139.
91
+ username: str or None
92
+ Username to connect with. Required if Kerberos auth is not being used.
93
+ password: str or None
94
+ User's password on the server, if using username
95
+ timeout: int
96
+ Connection timeout in seconds
97
+ encrypt: bool
98
+ Whether to force encryption or not, once this has been set to True
99
+ the session cannot be changed back to False.
100
+ share_access: str or None
101
+ Specifies the default access applied to file open operations
102
+ performed with this file system object.
103
+ This affects whether other processes can concurrently open a handle
104
+ to the same file.
105
+
106
+ - None (the default): exclusively locks the file until closed.
107
+ - 'r': Allow other handles to be opened with read access.
108
+ - 'w': Allow other handles to be opened with write access.
109
+ - 'd': Allow other handles to be opened with delete access.
110
+ register_session_retries: int
111
+ Number of retries to register a session with the server. Retries are not performed
112
+ for authentication errors, as they are considered as invalid credentials and not network
113
+ issues. If set to negative value, no register attempts will be performed.
114
+ register_session_retry_wait: int
115
+ Time in seconds to wait between each retry. Number must be non-negative.
116
+ register_session_retry_factor: int
117
+ Base factor for the wait time between each retry. The wait time
118
+ is calculated using exponential function. For factor=1 all wait times
119
+ will be equal to `register_session_retry_wait`. For any number of retries,
120
+ the last wait time will be equal to `register_session_retry_wait` and for retries>1
121
+ the first wait time will be equal to `register_session_retry_wait / factor`.
122
+ Number must be equal to or greater than 1. Optimal factor is 10.
123
+ auto_mkdir: bool
124
+ Whether, when opening a file, the directory containing it should
125
+ be created (if it doesn't already exist). This is assumed by pyarrow
126
+ and zarr-python code.
127
+ """
128
+ super().__init__(**kwargs)
129
+ self.host = host
130
+ self.port = port
131
+ self.username = username
132
+ self.password = password
133
+ self.timeout = timeout
134
+ self.encrypt = encrypt
135
+ self.temppath = kwargs.pop("temppath", "")
136
+ self.share_access = share_access
137
+ self.register_session_retries = register_session_retries
138
+ if register_session_retry_wait < 0:
139
+ raise ValueError(
140
+ "register_session_retry_wait must be a non-negative integer"
141
+ )
142
+ self.register_session_retry_wait = register_session_retry_wait
143
+ if register_session_retry_factor < 1:
144
+ raise ValueError(
145
+ "register_session_retry_factor must be a positive "
146
+ "integer equal to or greater than 1"
147
+ )
148
+ self.register_session_retry_factor = register_session_retry_factor
149
+ self.auto_mkdir = auto_mkdir
150
+ self._connect()
151
+
152
+ @property
153
+ def _port(self):
154
+ return 445 if self.port is None else self.port
155
+
156
+ def _connect(self):
157
+ import time
158
+
159
+ if self.register_session_retries <= -1:
160
+ return
161
+
162
+ retried_errors = []
163
+
164
+ wait_time = self.register_session_retry_wait
165
+ n_waits = (
166
+ self.register_session_retries - 1
167
+ ) # -1 = No wait time after the last retry
168
+ factor = self.register_session_retry_factor
169
+
170
+ # Generate wait times for each retry attempt.
171
+ # Wait times are calculated using exponential function. For factor=1 all wait times
172
+ # will be equal to `wait`. For any number of retries the last wait time will be
173
+ # equal to `wait` and for retries>2 the first wait time will be equal to `wait / factor`.
174
+ wait_times = iter(
175
+ factor ** (n / n_waits - 1) * wait_time for n in range(0, n_waits + 1)
176
+ )
177
+
178
+ for attempt in range(self.register_session_retries + 1):
179
+ try:
180
+ smbclient.register_session(
181
+ self.host,
182
+ username=self.username,
183
+ password=self.password,
184
+ port=self._port,
185
+ encrypt=self.encrypt,
186
+ connection_timeout=self.timeout,
187
+ )
188
+ return
189
+ except (
190
+ smbprotocol.exceptions.SMBAuthenticationError,
191
+ smbprotocol.exceptions.LogonFailure,
192
+ ):
193
+ # These exceptions should not be repeated, as they clearly indicate
194
+ # that the credentials are invalid and not a network issue.
195
+ raise
196
+ except ValueError as exc:
197
+ if re.findall(r"\[Errno -\d+]", str(exc)):
198
+ # This exception is raised by the smbprotocol.transport:Tcp.connect
199
+ # and originates from socket.gaierror (OSError). These exceptions might
200
+ # be raised due to network instability. We will retry to connect.
201
+ retried_errors.append(exc)
202
+ else:
203
+ # All another ValueError exceptions should be raised, as they are not
204
+ # related to network issues.
205
+ raise
206
+ except Exception as exc:
207
+ # Save the exception and retry to connect. This except might be dropped
208
+ # in the future, once all exceptions suited for retry are identified.
209
+ retried_errors.append(exc)
210
+
211
+ if attempt < self.register_session_retries:
212
+ time.sleep(next(wait_times))
213
+
214
+ # Raise last exception to inform user about the connection issues.
215
+ # Note: Should we use ExceptionGroup to raise all exceptions?
216
+ raise retried_errors[-1]
217
+
218
+ @classmethod
219
+ def _strip_protocol(cls, path):
220
+ return infer_storage_options(path)["path"]
221
+
222
+ @staticmethod
223
+ def _get_kwargs_from_urls(path):
224
+ # smb://workgroup;user:password@host:port/share/folder/file.csv
225
+ out = infer_storage_options(path)
226
+ out.pop("path", None)
227
+ out.pop("protocol", None)
228
+ return out
229
+
230
+ def mkdir(self, path, create_parents=True, **kwargs):
231
+ wpath = _as_unc_path(self.host, path)
232
+ if create_parents:
233
+ smbclient.makedirs(wpath, exist_ok=False, port=self._port, **kwargs)
234
+ else:
235
+ smbclient.mkdir(wpath, port=self._port, **kwargs)
236
+
237
+ def makedirs(self, path, exist_ok=False):
238
+ if _share_has_path(path):
239
+ wpath = _as_unc_path(self.host, path)
240
+ smbclient.makedirs(wpath, exist_ok=exist_ok, port=self._port)
241
+
242
+ def rmdir(self, path):
243
+ if _share_has_path(path):
244
+ wpath = _as_unc_path(self.host, path)
245
+ smbclient.rmdir(wpath, port=self._port)
246
+
247
+ def info(self, path, **kwargs):
248
+ wpath = _as_unc_path(self.host, path)
249
+ stats = smbclient.stat(wpath, port=self._port, **kwargs)
250
+ if S_ISDIR(stats.st_mode):
251
+ stype = "directory"
252
+ elif S_ISLNK(stats.st_mode):
253
+ stype = "link"
254
+ else:
255
+ stype = "file"
256
+ res = {
257
+ "name": path + "/" if stype == "directory" else path,
258
+ "size": stats.st_size,
259
+ "type": stype,
260
+ "uid": stats.st_uid,
261
+ "gid": stats.st_gid,
262
+ "time": stats.st_atime,
263
+ "mtime": stats.st_mtime,
264
+ }
265
+ return res
266
+
267
+ def created(self, path):
268
+ """Return the created timestamp of a file as a datetime.datetime"""
269
+ wpath = _as_unc_path(self.host, path)
270
+ stats = smbclient.stat(wpath, port=self._port)
271
+ return datetime.datetime.fromtimestamp(stats.st_ctime, tz=datetime.timezone.utc)
272
+
273
+ def modified(self, path):
274
+ """Return the modified timestamp of a file as a datetime.datetime"""
275
+ wpath = _as_unc_path(self.host, path)
276
+ stats = smbclient.stat(wpath, port=self._port)
277
+ return datetime.datetime.fromtimestamp(stats.st_mtime, tz=datetime.timezone.utc)
278
+
279
+ def ls(self, path, detail=True, **kwargs):
280
+ unc = _as_unc_path(self.host, path)
281
+ listed = smbclient.listdir(unc, port=self._port, **kwargs)
282
+ dirs = ["/".join([path.rstrip("/"), p]) for p in listed]
283
+ if detail:
284
+ dirs = [self.info(d) for d in dirs]
285
+ return dirs
286
+
287
+ # pylint: disable=too-many-arguments
288
+ def _open(
289
+ self,
290
+ path,
291
+ mode="rb",
292
+ block_size=-1,
293
+ autocommit=True,
294
+ cache_options=None,
295
+ **kwargs,
296
+ ):
297
+ """
298
+ block_size: int or None
299
+ If 0, no buffering, 1, line buffering, >1, buffer that many bytes
300
+
301
+ Notes
302
+ -----
303
+ By specifying 'share_access' in 'kwargs' it is possible to override the
304
+ default shared access setting applied in the constructor of this object.
305
+ """
306
+ if self.auto_mkdir and "w" in mode:
307
+ self.makedirs(self._parent(path), exist_ok=True)
308
+ bls = block_size if block_size is not None and block_size >= 0 else -1
309
+ wpath = _as_unc_path(self.host, path)
310
+ share_access = kwargs.pop("share_access", self.share_access)
311
+ if "w" in mode and autocommit is False:
312
+ temp = _as_temp_path(self.host, path, self.temppath)
313
+ return SMBFileOpener(
314
+ wpath, temp, mode, port=self._port, block_size=bls, **kwargs
315
+ )
316
+ return smbclient.open_file(
317
+ wpath,
318
+ mode,
319
+ buffering=bls,
320
+ share_access=share_access,
321
+ port=self._port,
322
+ **kwargs,
323
+ )
324
+
325
+ def copy(self, path1, path2, **kwargs):
326
+ """Copy within two locations in the same filesystem"""
327
+ wpath1 = _as_unc_path(self.host, path1)
328
+ wpath2 = _as_unc_path(self.host, path2)
329
+ if self.auto_mkdir:
330
+ self.makedirs(self._parent(path2), exist_ok=True)
331
+ smbclient.copyfile(wpath1, wpath2, port=self._port, **kwargs)
332
+
333
+ def _rm(self, path):
334
+ if _share_has_path(path):
335
+ wpath = _as_unc_path(self.host, path)
336
+ stats = smbclient.stat(wpath, port=self._port)
337
+ if S_ISDIR(stats.st_mode):
338
+ smbclient.rmdir(wpath, port=self._port)
339
+ else:
340
+ smbclient.remove(wpath, port=self._port)
341
+
342
+ def mv(self, path1, path2, recursive=None, maxdepth=None, **kwargs):
343
+ wpath1 = _as_unc_path(self.host, path1)
344
+ wpath2 = _as_unc_path(self.host, path2)
345
+ smbclient.rename(wpath1, wpath2, port=self._port, **kwargs)
346
+
347
+
348
+ def _as_unc_path(host, path):
349
+ rpath = path.replace("/", "\\")
350
+ unc = f"\\\\{host}{rpath}"
351
+ return unc
352
+
353
+
354
+ def _as_temp_path(host, path, temppath):
355
+ share = path.split("/")[1]
356
+ temp_file = f"/{share}{temppath}/{uuid.uuid4()}"
357
+ unc = _as_unc_path(host, temp_file)
358
+ return unc
359
+
360
+
361
+ def _share_has_path(path):
362
+ parts = path.count("/")
363
+ if path.endswith("/"):
364
+ return parts > 2
365
+ return parts > 1
366
+
367
+
368
+ class SMBFileOpener:
369
+ """writes to remote temporary file, move on commit"""
370
+
371
+ def __init__(self, path, temp, mode, port=445, block_size=-1, **kwargs):
372
+ self.path = path
373
+ self.temp = temp
374
+ self.mode = mode
375
+ self.block_size = block_size
376
+ self.kwargs = kwargs
377
+ self.smbfile = None
378
+ self._incontext = False
379
+ self.port = port
380
+ self._open()
381
+
382
+ def _open(self):
383
+ if self.smbfile is None or self.smbfile.closed:
384
+ self.smbfile = smbclient.open_file(
385
+ self.temp,
386
+ self.mode,
387
+ port=self.port,
388
+ buffering=self.block_size,
389
+ **self.kwargs,
390
+ )
391
+
392
+ def commit(self):
393
+ """Move temp file to definitive on success."""
394
+ # TODO: use transaction support in SMB protocol
395
+ smbclient.replace(self.temp, self.path, port=self.port)
396
+
397
+ def discard(self):
398
+ """Remove the temp file on failure."""
399
+ smbclient.remove(self.temp, port=self.port)
400
+
401
+ def __fspath__(self):
402
+ return self.path
403
+
404
+ def __iter__(self):
405
+ return self.smbfile.__iter__()
406
+
407
+ def __getattr__(self, item):
408
+ return getattr(self.smbfile, item)
409
+
410
+ def __enter__(self):
411
+ self._incontext = True
412
+ return self.smbfile.__enter__()
413
+
414
+ def __exit__(self, exc_type, exc_value, traceback):
415
+ self._incontext = False
416
+ self.smbfile.__exit__(exc_type, exc_value, traceback)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/tar.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import re
3
+ import tarfile
4
+
5
+ import fsspec
6
+ from fsspec.archive import AbstractArchiveFileSystem
7
+ from fsspec.compression import compr
8
+ from fsspec.utils import infer_compression
9
+
10
+ typemap = {b"0": "file", b"5": "directory"}
11
+
12
+ logger = logging.getLogger("tar")
13
+
14
+
15
+ class TarFileSystem(AbstractArchiveFileSystem):
16
+ """Compressed Tar archives as a file-system (read-only)
17
+
18
+ Supports the following formats:
19
+ tar.gz, tar.bz2, tar.xz
20
+ """
21
+
22
+ root_marker = ""
23
+ protocol = "tar"
24
+ cachable = False
25
+
26
+ def __init__(
27
+ self,
28
+ fo="",
29
+ index_store=None,
30
+ target_options=None,
31
+ target_protocol=None,
32
+ compression=None,
33
+ **kwargs,
34
+ ):
35
+ super().__init__(**kwargs)
36
+ target_options = target_options or {}
37
+
38
+ if isinstance(fo, str):
39
+ self.of = fsspec.open(fo, protocol=target_protocol, **target_options)
40
+ fo = self.of.open() # keep the reference
41
+
42
+ # Try to infer compression.
43
+ if compression is None:
44
+ name = None
45
+
46
+ # Try different ways to get hold of the filename. `fo` might either
47
+ # be a `fsspec.LocalFileOpener`, an `io.BufferedReader` or an
48
+ # `fsspec.AbstractFileSystem` instance.
49
+ try:
50
+ # Amended io.BufferedReader or similar.
51
+ # This uses a "protocol extension" where original filenames are
52
+ # propagated to archive-like filesystems in order to let them
53
+ # infer the right compression appropriately.
54
+ if hasattr(fo, "original"):
55
+ name = fo.original
56
+
57
+ # fsspec.LocalFileOpener
58
+ elif hasattr(fo, "path"):
59
+ name = fo.path
60
+
61
+ # io.BufferedReader
62
+ elif hasattr(fo, "name"):
63
+ name = fo.name
64
+
65
+ # fsspec.AbstractFileSystem
66
+ elif hasattr(fo, "info"):
67
+ name = fo.info()["name"]
68
+
69
+ except Exception as ex:
70
+ logger.warning(
71
+ f"Unable to determine file name, not inferring compression: {ex}"
72
+ )
73
+
74
+ if name is not None:
75
+ compression = infer_compression(name)
76
+ logger.info(f"Inferred compression {compression} from file name {name}")
77
+
78
+ if compression is not None:
79
+ # TODO: tarfile already implements compression with modes like "'r:gz'",
80
+ # but then would seek to offset in the file work?
81
+ fo = compr[compression](fo)
82
+
83
+ self._fo_ref = fo
84
+ self.fo = fo # the whole instance is a context
85
+ self.tar = tarfile.TarFile(fileobj=self.fo)
86
+ self.dir_cache = None
87
+
88
+ self.index_store = index_store
89
+ self.index = None
90
+ self._index()
91
+
92
+ def _index(self):
93
+ # TODO: load and set saved index, if exists
94
+ out = {}
95
+ for ti in self.tar:
96
+ info = ti.get_info()
97
+ info["type"] = typemap.get(info["type"], "file")
98
+ orig_name = info["name"].rstrip("/")
99
+ # Collapse duplicate slashes in the filesystem-facing name.
100
+ name = re.sub("/+", "/", orig_name)
101
+ info["name"] = name
102
+ out[name] = (info, ti.offset_data, orig_name)
103
+
104
+ self.index = out
105
+ # TODO: save index to self.index_store here, if set
106
+
107
+ def _get_dirs(self):
108
+ if self.dir_cache is not None:
109
+ return
110
+
111
+ # This enables ls to get directories as children as well as files
112
+ self.dir_cache = {
113
+ dirname: {"name": dirname, "size": 0, "type": "directory"}
114
+ for dirname in self._all_dirnames(self.index)
115
+ }
116
+ self.dir_cache.update(
117
+ {info["name"]: info for info, _, _ in self.index.values()}
118
+ )
119
+
120
+ def _open(self, path, mode="rb", **kwargs):
121
+ if mode != "rb":
122
+ raise ValueError("Read-only filesystem implementation")
123
+ # Accept paths containing the archive's duplicate slashes too.
124
+ path = re.sub("/+", "/", path)
125
+ details, _, orig_name = self.index[path]
126
+ if details["type"] != "file":
127
+ raise ValueError("Can only handle regular files")
128
+ return self.tar.extractfile(orig_name)
129
+
130
+ def close(self):
131
+ """Commits any write changes to the file. Done on ``del`` too."""
132
+ self.tar.close()
133
+
134
+ def __del__(self):
135
+ if hasattr(self, "tar"):
136
+ self.close()
137
+ del self.tar
138
+ if hasattr(self, "of") and hasattr(self.of, "__exit__"):
139
+ self.of.__exit__(None, None, None)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/webhdfs.py ADDED
@@ -0,0 +1,503 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://hadoop.apache.org/docs/r1.0.4/webhdfs.html
2
+
3
+ import logging
4
+ import os
5
+ import secrets
6
+ import shutil
7
+ import tempfile
8
+ import uuid
9
+ from contextlib import suppress
10
+ from datetime import datetime
11
+ from urllib.parse import quote
12
+
13
+ import requests
14
+
15
+ from ..spec import AbstractBufferedFile, AbstractFileSystem
16
+ from ..utils import infer_storage_options, tokenize
17
+
18
+ logger = logging.getLogger("webhdfs")
19
+
20
+
21
+ class WebHDFS(AbstractFileSystem):
22
+ """
23
+ Interface to HDFS over HTTP using the WebHDFS API. Supports also HttpFS gateways.
24
+
25
+ Four auth mechanisms are supported:
26
+
27
+ insecure: no auth is done, and the user is assumed to be whoever they
28
+ say they are (parameter ``user``), or a predefined value such as
29
+ "dr.who" if not given
30
+ spnego: when kerberos authentication is enabled, auth is negotiated by
31
+ requests_kerberos https://github.com/requests/requests-kerberos .
32
+ This establishes a session based on existing kinit login and/or
33
+ specified principal/password; parameters are passed with ``kerb_kwargs``
34
+ token: uses an existing Hadoop delegation token from another secured
35
+ service. Indeed, this client can also generate such tokens when
36
+ not insecure. Note that tokens expire, but can be renewed (by a
37
+ previously specified user) and may allow for proxying.
38
+ basic-auth: used when both parameter ``user`` and parameter ``password``
39
+ are provided.
40
+
41
+ """
42
+
43
+ tempdir = str(tempfile.gettempdir())
44
+ protocol = "webhdfs", "webHDFS"
45
+
46
+ def __init__(
47
+ self,
48
+ host,
49
+ port=50070,
50
+ kerberos=False,
51
+ token=None,
52
+ user=None,
53
+ password=None,
54
+ proxy_to=None,
55
+ kerb_kwargs=None,
56
+ data_proxy=None,
57
+ use_https=False,
58
+ session_cert=None,
59
+ session_verify=True,
60
+ **kwargs,
61
+ ):
62
+ """
63
+ Parameters
64
+ ----------
65
+ host: str
66
+ Name-node address
67
+ port: int
68
+ Port for webHDFS
69
+ kerberos: bool
70
+ Whether to authenticate with kerberos for this connection
71
+ token: str or None
72
+ If given, use this token on every call to authenticate. A user
73
+ and user-proxy may be encoded in the token and should not be also
74
+ given
75
+ user: str or None
76
+ If given, assert the user name to connect with
77
+ password: str or None
78
+ If given, assert the password to use for basic auth. If password
79
+ is provided, user must be provided also
80
+ proxy_to: str or None
81
+ If given, the user has the authority to proxy, and this value is
82
+ the user in who's name actions are taken
83
+ kerb_kwargs: dict
84
+ Any extra arguments for HTTPKerberosAuth, see
85
+ `<https://github.com/requests/requests-kerberos/blob/master/requests_kerberos/kerberos_.py>`_
86
+ data_proxy: dict, callable or None
87
+ If given, map data-node addresses. This can be necessary if the
88
+ HDFS cluster is behind a proxy, running on Docker or otherwise has
89
+ a mismatch between the host-names given by the name-node and the
90
+ address by which to refer to them from the client. If a dict,
91
+ maps host names ``host->data_proxy[host]``; if a callable, full
92
+ URLs are passed, and function must conform to
93
+ ``url->data_proxy(url)``.
94
+ use_https: bool
95
+ Whether to connect to the Name-node using HTTPS instead of HTTP
96
+ session_cert: str or Tuple[str, str] or None
97
+ Path to a certificate file, or tuple of (cert, key) files to use
98
+ for the requests.Session
99
+ session_verify: str, bool or None
100
+ Path to a certificate file to use for verifying the requests.Session.
101
+ kwargs
102
+ """
103
+ if self._cached:
104
+ return
105
+ super().__init__(**kwargs)
106
+ self.url = f"{'https' if use_https else 'http'}://{host}:{port}/webhdfs/v1"
107
+ self.kerb = kerberos
108
+ self.kerb_kwargs = kerb_kwargs or {}
109
+ self.pars = {}
110
+ self.proxy = data_proxy or {}
111
+ if token is not None:
112
+ if user is not None or proxy_to is not None:
113
+ raise ValueError(
114
+ "If passing a delegation token, must not set "
115
+ "user or proxy_to, as these are encoded in the"
116
+ " token"
117
+ )
118
+ self.pars["delegation"] = token
119
+ self.user = user
120
+ self.password = password
121
+
122
+ if password is not None:
123
+ if user is None:
124
+ raise ValueError(
125
+ "If passing a password, the user must also be"
126
+ "set in order to set up the basic-auth"
127
+ )
128
+ else:
129
+ if user is not None:
130
+ self.pars["user.name"] = user
131
+
132
+ if proxy_to is not None:
133
+ self.pars["doas"] = proxy_to
134
+ if kerberos and user is not None:
135
+ raise ValueError(
136
+ "If using Kerberos auth, do not specify the "
137
+ "user, this is handled by kinit."
138
+ )
139
+
140
+ self.session_cert = session_cert
141
+ self.session_verify = session_verify
142
+
143
+ self._connect()
144
+
145
+ self._fsid = f"webhdfs_{tokenize(host, port)}"
146
+
147
+ @property
148
+ def fsid(self):
149
+ return self._fsid
150
+
151
+ def _connect(self):
152
+ self.session = requests.Session()
153
+
154
+ if self.session_cert:
155
+ self.session.cert = self.session_cert
156
+
157
+ self.session.verify = self.session_verify
158
+
159
+ if self.kerb:
160
+ from requests_kerberos import HTTPKerberosAuth
161
+
162
+ self.session.auth = HTTPKerberosAuth(**self.kerb_kwargs)
163
+
164
+ if self.user is not None and self.password is not None:
165
+ from requests.auth import HTTPBasicAuth
166
+
167
+ self.session.auth = HTTPBasicAuth(self.user, self.password)
168
+
169
+ def _call(self, op, method="get", path=None, data=None, redirect=True, **kwargs):
170
+ path = self._strip_protocol(path) if path is not None else ""
171
+ url = self._apply_proxy(self.url + quote(path, safe="/="))
172
+ args = kwargs.copy()
173
+ args.update(self.pars)
174
+ args["op"] = op.upper()
175
+ logger.debug("sending %s with %s", url, method)
176
+ out = self.session.request(
177
+ method=method.upper(),
178
+ url=url,
179
+ params=args,
180
+ data=data,
181
+ allow_redirects=redirect,
182
+ )
183
+ if out.status_code in [400, 401, 403, 404, 500]:
184
+ try:
185
+ err = out.json()
186
+ msg = err["RemoteException"]["message"]
187
+ exp = err["RemoteException"]["exception"]
188
+ except (ValueError, KeyError):
189
+ pass
190
+ else:
191
+ if exp in ["IllegalArgumentException", "UnsupportedOperationException"]:
192
+ raise ValueError(msg)
193
+ elif exp in ["SecurityException", "AccessControlException"]:
194
+ raise PermissionError(msg)
195
+ elif exp in ["FileNotFoundException"]:
196
+ raise FileNotFoundError(msg)
197
+ else:
198
+ raise RuntimeError(msg)
199
+ out.raise_for_status()
200
+ return out
201
+
202
+ def _open(
203
+ self,
204
+ path,
205
+ mode="rb",
206
+ block_size=None,
207
+ autocommit=True,
208
+ replication=None,
209
+ permissions=None,
210
+ **kwargs,
211
+ ):
212
+ """
213
+
214
+ Parameters
215
+ ----------
216
+ path: str
217
+ File location
218
+ mode: str
219
+ 'rb', 'wb', etc.
220
+ block_size: int
221
+ Client buffer size for read-ahead or write buffer
222
+ autocommit: bool
223
+ If False, writes to temporary file that only gets put in final
224
+ location upon commit
225
+ replication: int
226
+ Number of copies of file on the cluster, write mode only
227
+ permissions: str or int
228
+ posix permissions, write mode only
229
+ kwargs
230
+
231
+ Returns
232
+ -------
233
+ WebHDFile instance
234
+ """
235
+ block_size = block_size or self.blocksize
236
+ return WebHDFile(
237
+ self,
238
+ path,
239
+ mode=mode,
240
+ block_size=block_size,
241
+ tempdir=self.tempdir,
242
+ autocommit=autocommit,
243
+ replication=replication,
244
+ permissions=permissions,
245
+ )
246
+
247
+ @staticmethod
248
+ def _process_info(info):
249
+ info["type"] = info["type"].lower()
250
+ info["size"] = info["length"]
251
+ return info
252
+
253
+ @classmethod
254
+ def _strip_protocol(cls, path):
255
+ return infer_storage_options(path)["path"]
256
+
257
+ @staticmethod
258
+ def _get_kwargs_from_urls(urlpath):
259
+ out = infer_storage_options(urlpath)
260
+ out.pop("path", None)
261
+ out.pop("protocol", None)
262
+ if "username" in out:
263
+ out["user"] = out.pop("username")
264
+ return out
265
+
266
+ def info(self, path):
267
+ out = self._call("GETFILESTATUS", path=path)
268
+ info = out.json()["FileStatus"]
269
+ info["name"] = path
270
+ return self._process_info(info)
271
+
272
+ def created(self, path):
273
+ """Return the created timestamp of a file as a datetime.datetime"""
274
+ # The API does not provide creation time, so we use modification time
275
+ info = self.info(path)
276
+ mtime = info.get("modificationTime", None)
277
+ if mtime is not None:
278
+ return datetime.fromtimestamp(mtime / 1000)
279
+ raise RuntimeError("Could not retrieve creation time (modification time).")
280
+
281
+ def modified(self, path):
282
+ """Return the modified timestamp of a file as a datetime.datetime"""
283
+ info = self.info(path)
284
+ mtime = info.get("modificationTime", None)
285
+ if mtime is not None:
286
+ return datetime.fromtimestamp(mtime / 1000)
287
+ raise RuntimeError("Could not retrieve modification time.")
288
+
289
+ def ls(self, path, detail=False, **kwargs):
290
+ out = self._call("LISTSTATUS", path=path)
291
+ infos = out.json()["FileStatuses"]["FileStatus"]
292
+ for info in infos:
293
+ self._process_info(info)
294
+ info["name"] = path.rstrip("/") + "/" + info["pathSuffix"]
295
+ if detail:
296
+ return sorted(infos, key=lambda i: i["name"])
297
+ else:
298
+ return sorted(info["name"] for info in infos)
299
+
300
+ def content_summary(self, path):
301
+ """Total numbers of files, directories and bytes under path"""
302
+ out = self._call("GETCONTENTSUMMARY", path=path)
303
+ return out.json()["ContentSummary"]
304
+
305
+ def ukey(self, path):
306
+ """Checksum info of file, giving method and result"""
307
+ out = self._call("GETFILECHECKSUM", path=path, redirect=False)
308
+ if "Location" in out.headers:
309
+ location = self._apply_proxy(out.headers["Location"])
310
+ out2 = self.session.get(location)
311
+ out2.raise_for_status()
312
+ return out2.json()["FileChecksum"]
313
+ else:
314
+ out.raise_for_status()
315
+ return out.json()["FileChecksum"]
316
+
317
+ def home_directory(self):
318
+ """Get user's home directory"""
319
+ out = self._call("GETHOMEDIRECTORY")
320
+ return out.json()["Path"]
321
+
322
+ def get_delegation_token(self, renewer=None):
323
+ """Retrieve token which can give the same authority to other uses
324
+
325
+ Parameters
326
+ ----------
327
+ renewer: str or None
328
+ User who may use this token; if None, will be current user
329
+ """
330
+ if renewer:
331
+ out = self._call("GETDELEGATIONTOKEN", renewer=renewer)
332
+ else:
333
+ out = self._call("GETDELEGATIONTOKEN")
334
+ t = out.json()["Token"]
335
+ if t is None:
336
+ raise ValueError("No token available for this user/security context")
337
+ return t["urlString"]
338
+
339
+ def renew_delegation_token(self, token):
340
+ """Make token live longer. Returns new expiry time"""
341
+ out = self._call("RENEWDELEGATIONTOKEN", method="put", token=token)
342
+ return out.json()["long"]
343
+
344
+ def cancel_delegation_token(self, token):
345
+ """Stop the token from being useful"""
346
+ self._call("CANCELDELEGATIONTOKEN", method="put", token=token)
347
+
348
+ def chmod(self, path, mod):
349
+ """Set the permission at path
350
+
351
+ Parameters
352
+ ----------
353
+ path: str
354
+ location to set (file or directory)
355
+ mod: str or int
356
+ posix epresentation or permission, give as oct string, e.g, '777'
357
+ or 0o777
358
+ """
359
+ self._call("SETPERMISSION", method="put", path=path, permission=mod)
360
+
361
+ def chown(self, path, owner=None, group=None):
362
+ """Change owning user and/or group"""
363
+ kwargs = {}
364
+ if owner is not None:
365
+ kwargs["owner"] = owner
366
+ if group is not None:
367
+ kwargs["group"] = group
368
+ self._call("SETOWNER", method="put", path=path, **kwargs)
369
+
370
+ def set_replication(self, path, replication):
371
+ """
372
+ Set file replication factor
373
+
374
+ Parameters
375
+ ----------
376
+ path: str
377
+ File location (not for directories)
378
+ replication: int
379
+ Number of copies of file on the cluster. Should be smaller than
380
+ number of data nodes; normally 3 on most systems.
381
+ """
382
+ self._call("SETREPLICATION", path=path, method="put", replication=replication)
383
+
384
+ def mkdir(self, path, **kwargs):
385
+ self._call("MKDIRS", method="put", path=path)
386
+
387
+ def makedirs(self, path, exist_ok=False):
388
+ if exist_ok is False and self.exists(path):
389
+ raise FileExistsError(path)
390
+ self.mkdir(path)
391
+
392
+ def mv(self, path1, path2, **kwargs):
393
+ self._call("RENAME", method="put", path=path1, destination=path2)
394
+
395
+ def rm(self, path, recursive=False, **kwargs):
396
+ self._call(
397
+ "DELETE",
398
+ method="delete",
399
+ path=path,
400
+ recursive="true" if recursive else "false",
401
+ )
402
+
403
+ def rm_file(self, path, **kwargs):
404
+ self.rm(path)
405
+
406
+ def cp_file(self, lpath, rpath, **kwargs):
407
+ with self.open(lpath) as lstream:
408
+ tmp_fname = "/".join([self._parent(rpath), f".tmp.{secrets.token_hex(16)}"])
409
+ # Perform an atomic copy (stream to a temporary file and
410
+ # move it to the actual destination).
411
+ try:
412
+ with self.open(tmp_fname, "wb") as rstream:
413
+ shutil.copyfileobj(lstream, rstream)
414
+ self.mv(tmp_fname, rpath)
415
+ except BaseException:
416
+ with suppress(FileNotFoundError):
417
+ self.rm(tmp_fname)
418
+ raise
419
+
420
+ def _apply_proxy(self, location):
421
+ if self.proxy and callable(self.proxy):
422
+ location = self.proxy(location)
423
+ elif self.proxy:
424
+ # as a dict
425
+ for k, v in self.proxy.items():
426
+ location = location.replace(k, v, 1)
427
+ return location
428
+
429
+
430
+ class WebHDFile(AbstractBufferedFile):
431
+ """A file living in HDFS over webHDFS"""
432
+
433
+ def __init__(self, fs, path, **kwargs):
434
+ super().__init__(fs, path, **kwargs)
435
+ kwargs = kwargs.copy()
436
+ if kwargs.get("permissions", None) is None:
437
+ kwargs.pop("permissions", None)
438
+ if kwargs.get("replication", None) is None:
439
+ kwargs.pop("replication", None)
440
+ self.permissions = kwargs.pop("permissions", 511)
441
+ tempdir = kwargs.pop("tempdir")
442
+ if kwargs.pop("autocommit", False) is False:
443
+ self.target = self.path
444
+ self.path = os.path.join(tempdir, str(uuid.uuid4()))
445
+
446
+ def _upload_chunk(self, final=False):
447
+ """Write one part of a multi-block file upload
448
+
449
+ Parameters
450
+ ==========
451
+ final: bool
452
+ This is the last block, so should complete file, if
453
+ self.autocommit is True.
454
+ """
455
+ out = self.fs.session.post(
456
+ self.location,
457
+ data=self.buffer.getvalue(),
458
+ headers={"content-type": "application/octet-stream"},
459
+ )
460
+ out.raise_for_status()
461
+ return True
462
+
463
+ def _initiate_upload(self):
464
+ """Create remote file/upload"""
465
+ kwargs = self.kwargs.copy()
466
+ if "a" in self.mode:
467
+ op, method = "APPEND", "POST"
468
+ else:
469
+ op, method = "CREATE", "PUT"
470
+ kwargs["overwrite"] = "true"
471
+ out = self.fs._call(op, method, self.path, redirect=False, **kwargs)
472
+ location = self.fs._apply_proxy(out.headers["Location"])
473
+ if "w" in self.mode:
474
+ # create empty file to append to
475
+ out2 = self.fs.session.put(
476
+ location, headers={"content-type": "application/octet-stream"}
477
+ )
478
+ out2.raise_for_status()
479
+ # after creating empty file, change location to append to
480
+ out2 = self.fs._call("APPEND", "POST", self.path, redirect=False, **kwargs)
481
+ self.location = self.fs._apply_proxy(out2.headers["Location"])
482
+
483
+ def _fetch_range(self, start, end):
484
+ start = max(start, 0)
485
+ end = min(self.size, end)
486
+ if start >= end or start >= self.size:
487
+ return b""
488
+ out = self.fs._call(
489
+ "OPEN", path=self.path, offset=start, length=end - start, redirect=False
490
+ )
491
+ out.raise_for_status()
492
+ if "Location" in out.headers:
493
+ location = out.headers["Location"]
494
+ out2 = self.fs.session.get(self.fs._apply_proxy(location))
495
+ return out2.content
496
+ else:
497
+ return out.content
498
+
499
+ def commit(self):
500
+ self.fs.mv(self.path, self.target)
501
+
502
+ def discard(self):
503
+ self.fs.rm(self.path)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/zip.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import zipfile
3
+
4
+ import fsspec
5
+ from fsspec.archive import AbstractArchiveFileSystem
6
+
7
+
8
+ class ZipFileSystem(AbstractArchiveFileSystem):
9
+ """Read/Write contents of ZIP archive as a file-system
10
+
11
+ Keeps file object open while instance lives.
12
+
13
+ This class is pickleable, but not necessarily thread-safe
14
+ """
15
+
16
+ root_marker = ""
17
+ protocol = "zip"
18
+ cachable = False
19
+
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
+ Parameters
33
+ ----------
34
+ fo: str or file-like
35
+ Contains ZIP, and must exist. If a str, will fetch file using
36
+ :meth:`~fsspec.open_files`, which must return one file exactly.
37
+ mode: str
38
+ Accept: "r", "w", "a"
39
+ target_protocol: str (optional)
40
+ If ``fo`` is a string, this value can be used to override the
41
+ FS protocol inferred from a URL
42
+ target_options: dict (optional)
43
+ Kwargs passed when instantiating the target FS, if ``fo`` is
44
+ a string.
45
+ compression, allowZip64, compresslevel: passed to ZipFile
46
+ Only relevant when creating a ZIP
47
+ """
48
+ super().__init__(self, **kwargs)
49
+ if mode not in set("rwa"):
50
+ raise ValueError(f"mode '{mode}' no understood")
51
+ self.mode = mode
52
+ 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 = allowZip64
61
+ self.of = fo
62
+ self.fo = fo.__enter__() # the whole instance is a context
63
+ self.zip = zipfile.ZipFile(
64
+ self.fo,
65
+ mode=mode,
66
+ compression=compression,
67
+ allowZip64=allowZip64,
68
+ compresslevel=compresslevel,
69
+ )
70
+ self.dir_cache = None
71
+
72
+ @classmethod
73
+ def _strip_protocol(cls, path):
74
+ # zip file paths are always relative to the archive root
75
+ return super()._strip_protocol(path).lstrip("/")
76
+
77
+ def __del__(self):
78
+ if hasattr(self, "zip"):
79
+ self.close()
80
+ del self.zip
81
+ if hasattr(self, "of") and hasattr(self.of, "__exit__"):
82
+ self.of.__exit__(None, None, None)
83
+
84
+ def close(self):
85
+ """Commits any write changes to the file. Done on ``del`` too."""
86
+ self.zip.close()
87
+
88
+ def _get_dirs(self):
89
+ if self.dir_cache is None or self.mode in set("wa"):
90
+ # when writing, dir_cache is always in the ZipFile's attributes,
91
+ # not read from the file.
92
+ files = self.zip.infolist()
93
+ self.dir_cache = {
94
+ dirname.rstrip("/"): {
95
+ "name": dirname.rstrip("/"),
96
+ "size": 0,
97
+ "type": "directory",
98
+ }
99
+ for dirname in self._all_dirnames(self.zip.namelist())
100
+ }
101
+ for z in files:
102
+ f = {s: getattr(z, s, None) for s in zipfile.ZipInfo.__slots__}
103
+ f.update(
104
+ {
105
+ "name": z.filename.rstrip("/"),
106
+ "size": z.file_size,
107
+ "type": ("directory" if z.is_dir() else "file"),
108
+ }
109
+ )
110
+ self.dir_cache[f["name"]] = f
111
+
112
+ def pipe_file(self, path, value, **kwargs):
113
+ # override upstream, because we know the exact file size in this case
114
+ self.zip.writestr(path, value, **kwargs)
115
+
116
+ def _open(
117
+ self,
118
+ path,
119
+ mode="rb",
120
+ block_size=None,
121
+ autocommit=True,
122
+ cache_options=None,
123
+ **kwargs,
124
+ ):
125
+ path = self._strip_protocol(path)
126
+ if "r" in mode and self.mode in set("wa"):
127
+ if self.exists(path):
128
+ raise OSError("ZipFS can only be open for reading or writing, not both")
129
+ raise FileNotFoundError(path)
130
+ if "r" in self.mode and "w" in mode:
131
+ raise OSError("ZipFS can only be open for reading or writing, not both")
132
+ out = self.zip.open(path, mode.strip("b"), force_zip64=self.force_zip_64)
133
+ if "r" in mode:
134
+ info = self.info(path)
135
+ out.size = info["size"]
136
+ out.name = info["name"]
137
+ return out
138
+
139
+ def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
140
+ if maxdepth is not None and maxdepth < 1:
141
+ raise ValueError("maxdepth must be at least 1")
142
+
143
+ def to_parts(_path: str):
144
+ return list(filter(None, _path.replace("\\", "/").split("/")))
145
+
146
+ if not isinstance(path, str):
147
+ path = str(path)
148
+
149
+ # Remove the leading slash, as the zip file paths are always
150
+ # given without a leading slash
151
+ path = path.lstrip("/")
152
+ path_parts = to_parts(path)
153
+ path_depth = len(path_parts)
154
+
155
+ self._get_dirs()
156
+
157
+ result = {}
158
+ # To match posix find, if an exact file name is given, we should
159
+ # return only that file
160
+ if path in self.dir_cache and self.dir_cache[path]["type"] == "file":
161
+ result[path] = self.dir_cache[path]
162
+ return result if detail else [path]
163
+
164
+ for file_path, file_info in self.dir_cache.items():
165
+ if len(file_parts := to_parts(file_path)) < path_depth or any(
166
+ a != b for a, b in zip(path_parts, file_parts)
167
+ ):
168
+ # skip parent folders and mismatching paths
169
+ continue
170
+
171
+ if file_info["type"] == "directory":
172
+ if withdirs and file_path not in result:
173
+ result[file_path.strip("/")] = file_info
174
+ continue
175
+
176
+ if file_path not in result:
177
+ result[file_path] = file_info if detail else None
178
+
179
+ if maxdepth:
180
+ result = {
181
+ k: v for k, v in result.items() if k.count("/") < maxdepth + path_depth
182
+ }
183
+ return result if detail else sorted(result)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/json.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from collections.abc import Callable, Mapping, Sequence
3
+ from contextlib import suppress
4
+ from pathlib import PurePath
5
+ from typing import Any, ClassVar
6
+
7
+ from .registry import _import_class, get_filesystem_class
8
+ from .spec import AbstractFileSystem
9
+
10
+
11
+ class FilesystemJSONEncoder(json.JSONEncoder):
12
+ include_password: ClassVar[bool] = True
13
+
14
+ def default(self, o: Any) -> Any:
15
+ if isinstance(o, AbstractFileSystem):
16
+ return o.to_dict(include_password=self.include_password)
17
+ if isinstance(o, PurePath):
18
+ cls = type(o)
19
+ return {"cls": f"{cls.__module__}.{cls.__name__}", "str": str(o)}
20
+
21
+ return super().default(o)
22
+
23
+ def make_serializable(self, obj: Any) -> Any:
24
+ """
25
+ Recursively converts an object so that it can be JSON serialized via
26
+ :func:`json.dumps` and :func:`json.dump`, without actually calling
27
+ said functions.
28
+ """
29
+ if isinstance(obj, (str, int, float, bool)):
30
+ return obj
31
+ if isinstance(obj, Mapping):
32
+ return {k: self.make_serializable(v) for k, v in obj.items()}
33
+ if isinstance(obj, Sequence):
34
+ return [self.make_serializable(v) for v in obj]
35
+
36
+ return self.default(obj)
37
+
38
+
39
+ class FilesystemJSONDecoder(json.JSONDecoder):
40
+ def __init__(
41
+ self,
42
+ *,
43
+ object_hook: Callable[[dict[str, Any]], Any] | None = None,
44
+ parse_float: Callable[[str], Any] | None = None,
45
+ parse_int: Callable[[str], Any] | None = None,
46
+ parse_constant: Callable[[str], Any] | None = None,
47
+ strict: bool = True,
48
+ object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None,
49
+ ) -> None:
50
+ self.original_object_hook = object_hook
51
+
52
+ super().__init__(
53
+ object_hook=self.custom_object_hook,
54
+ parse_float=parse_float,
55
+ parse_int=parse_int,
56
+ parse_constant=parse_constant,
57
+ strict=strict,
58
+ object_pairs_hook=object_pairs_hook,
59
+ )
60
+
61
+ @classmethod
62
+ def try_resolve_path_cls(cls, dct: dict[str, Any]):
63
+ with suppress(Exception):
64
+ fqp = dct["cls"]
65
+
66
+ path_cls = _import_class(fqp)
67
+
68
+ if issubclass(path_cls, PurePath):
69
+ return path_cls
70
+
71
+ return None
72
+
73
+ @classmethod
74
+ def try_resolve_fs_cls(cls, dct: dict[str, Any]):
75
+ with suppress(Exception):
76
+ if "cls" in dct:
77
+ try:
78
+ fs_cls = _import_class(dct["cls"])
79
+ if issubclass(fs_cls, AbstractFileSystem):
80
+ return fs_cls
81
+ except Exception:
82
+ if "protocol" in dct: # Fallback if cls cannot be imported
83
+ return get_filesystem_class(dct["protocol"])
84
+
85
+ raise
86
+
87
+ return None
88
+
89
+ def custom_object_hook(self, dct: dict[str, Any]):
90
+ if "cls" in dct:
91
+ if (obj_cls := self.try_resolve_fs_cls(dct)) is not None:
92
+ return AbstractFileSystem.from_dict(dct)
93
+ if (obj_cls := self.try_resolve_path_cls(dct)) is not None:
94
+ return obj_cls(dct["str"])
95
+
96
+ if self.original_object_hook is not None:
97
+ return self.original_object_hook(dct)
98
+
99
+ return dct
100
+
101
+ def unmake_serializable(self, obj: Any) -> Any:
102
+ """
103
+ Inverse function of :meth:`FilesystemJSONEncoder.make_serializable`.
104
+ """
105
+ if isinstance(obj, dict):
106
+ obj = self.custom_object_hook(obj)
107
+ if isinstance(obj, dict):
108
+ return {k: self.unmake_serializable(v) for k, v in obj.items()}
109
+ if isinstance(obj, (list, tuple)):
110
+ return [self.unmake_serializable(v) for v in obj]
111
+
112
+ return obj
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/mapping.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import array
2
+ import logging
3
+ import posixpath
4
+ import warnings
5
+ from collections.abc import MutableMapping
6
+ from functools import cached_property
7
+
8
+ from fsspec.core import url_to_fs
9
+
10
+ logger = logging.getLogger("fsspec.mapping")
11
+
12
+
13
+ class FSMap(MutableMapping):
14
+ """Wrap a FileSystem instance as a mutable wrapping.
15
+
16
+ The keys of the mapping become files under the given root, and the
17
+ values (which must be bytes) the contents of those files.
18
+
19
+ Parameters
20
+ ----------
21
+ root: string
22
+ prefix for all the files
23
+ fs: FileSystem instance
24
+ check: bool (=True)
25
+ performs a touch at the location, to check for write access.
26
+
27
+ Examples
28
+ --------
29
+ >>> fs = FileSystem(**parameters) # doctest: +SKIP
30
+ >>> d = FSMap('my-data/path/', fs) # doctest: +SKIP
31
+ or, more likely
32
+ >>> d = fs.get_mapper('my-data/path/')
33
+
34
+ >>> d['loc1'] = b'Hello World' # doctest: +SKIP
35
+ >>> list(d.keys()) # doctest: +SKIP
36
+ ['loc1']
37
+ >>> d['loc1'] # doctest: +SKIP
38
+ b'Hello World'
39
+ """
40
+
41
+ def __init__(self, root, fs, check=False, create=False, missing_exceptions=None):
42
+ self.fs = fs
43
+ self.root = fs._strip_protocol(root)
44
+ self._root_key_to_str = fs._strip_protocol(posixpath.join(root, "x"))[:-1]
45
+ if missing_exceptions is None:
46
+ missing_exceptions = (
47
+ FileNotFoundError,
48
+ IsADirectoryError,
49
+ NotADirectoryError,
50
+ )
51
+ self.missing_exceptions = missing_exceptions
52
+ self.check = check
53
+ self.create = create
54
+ if create:
55
+ if not self.fs.exists(root):
56
+ self.fs.mkdir(root)
57
+ if check:
58
+ if not self.fs.exists(root):
59
+ raise ValueError(
60
+ f"Path {root} does not exist. Create "
61
+ f" with the ``create=True`` keyword"
62
+ )
63
+ self.fs.touch(root + "/a")
64
+ self.fs.rm(root + "/a")
65
+
66
+ @cached_property
67
+ def dirfs(self):
68
+ """dirfs instance that can be used with the same keys as the mapper"""
69
+ from .implementations.dirfs import DirFileSystem
70
+
71
+ return DirFileSystem(path=self._root_key_to_str, fs=self.fs)
72
+
73
+ def clear(self):
74
+ """Remove all keys below root - empties out mapping"""
75
+ logger.info("Clear mapping at %s", self.root)
76
+ try:
77
+ self.fs.rm(self.root, True)
78
+ self.fs.mkdir(self.root)
79
+ except: # noqa: E722
80
+ pass
81
+
82
+ def getitems(self, keys, on_error="raise"):
83
+ """Fetch multiple items from the store
84
+
85
+ If the backend is async-able, this might proceed concurrently
86
+
87
+ Parameters
88
+ ----------
89
+ keys: list(str)
90
+ They keys to be fetched
91
+ on_error : "raise", "omit", "return"
92
+ If raise, an underlying exception will be raised (converted to KeyError
93
+ if the type is in self.missing_exceptions); if omit, keys with exception
94
+ will simply not be included in the output; if "return", all keys are
95
+ included in the output, but the value will be bytes or an exception
96
+ instance.
97
+
98
+ Returns
99
+ -------
100
+ dict(key, bytes|exception)
101
+ """
102
+ keys2 = [self._key_to_str(k) for k in keys]
103
+ oe = on_error if on_error == "raise" else "return"
104
+ try:
105
+ out = self.fs.cat(keys2, on_error=oe)
106
+ if isinstance(out, bytes):
107
+ out = {keys2[0]: out}
108
+ except self.missing_exceptions as e:
109
+ raise KeyError from e
110
+ out = {
111
+ k: (KeyError() if isinstance(v, self.missing_exceptions) else v)
112
+ for k, v in out.items()
113
+ }
114
+ return {
115
+ key: out[k2] if on_error == "raise" else out.get(k2, KeyError(k2))
116
+ for key, k2 in zip(keys, keys2)
117
+ if on_error == "return" or not isinstance(out[k2], BaseException)
118
+ }
119
+
120
+ def setitems(self, values_dict):
121
+ """Set the values of multiple items in the store
122
+
123
+ Parameters
124
+ ----------
125
+ values_dict: dict(str, bytes)
126
+ """
127
+ values = {self._key_to_str(k): maybe_convert(v) for k, v in values_dict.items()}
128
+ self.fs.pipe(values)
129
+
130
+ def delitems(self, keys):
131
+ """Remove multiple keys from the store"""
132
+ self.fs.rm([self._key_to_str(k) for k in keys])
133
+
134
+ def _key_to_str(self, key):
135
+ """Generate full path for the key"""
136
+ if not isinstance(key, str):
137
+ # raise TypeError("key must be of type `str`, got `{type(key).__name__}`"
138
+ warnings.warn(
139
+ "from fsspec 2023.5 onward FSMap non-str keys will raise TypeError",
140
+ DeprecationWarning,
141
+ )
142
+ if isinstance(key, list):
143
+ key = tuple(key)
144
+ key = str(key)
145
+ return f"{self._root_key_to_str}{key}".rstrip("/")
146
+
147
+ def _str_to_key(self, s):
148
+ """Strip path of to leave key name"""
149
+ return s[len(self.root) :].lstrip("/")
150
+
151
+ def __getitem__(self, key, default=None):
152
+ """Retrieve data"""
153
+ k = self._key_to_str(key)
154
+ try:
155
+ result = self.fs.cat(k)
156
+ except self.missing_exceptions as exc:
157
+ if default is not None:
158
+ return default
159
+ raise KeyError(key) from exc
160
+ return result
161
+
162
+ def pop(self, key, default=None):
163
+ """Pop data"""
164
+ result = self.__getitem__(key, default)
165
+ try:
166
+ del self[key]
167
+ except KeyError:
168
+ pass
169
+ return result
170
+
171
+ def __setitem__(self, key, value):
172
+ """Store value in key"""
173
+ key = self._key_to_str(key)
174
+ self.fs.mkdirs(self.fs._parent(key), exist_ok=True)
175
+ self.fs.pipe_file(key, maybe_convert(value))
176
+
177
+ def __iter__(self):
178
+ return (self._str_to_key(x) for x in self.fs.find(self.root))
179
+
180
+ def __len__(self):
181
+ return len(self.fs.find(self.root))
182
+
183
+ def __delitem__(self, key):
184
+ """Remove key"""
185
+ try:
186
+ self.fs.rm(self._key_to_str(key))
187
+ except Exception as exc:
188
+ raise KeyError from exc
189
+
190
+ def __contains__(self, key):
191
+ """Does key exist in mapping?"""
192
+ path = self._key_to_str(key)
193
+ return self.fs.isfile(path)
194
+
195
+ def __reduce__(self):
196
+ return FSMap, (self.root, self.fs, False, False, self.missing_exceptions)
197
+
198
+
199
+ def maybe_convert(value):
200
+ if isinstance(value, array.array) or hasattr(value, "__array__"):
201
+ # bytes-like things
202
+ if hasattr(value, "dtype") and value.dtype.kind in "Mm":
203
+ # The buffer interface doesn't support datetime64/timdelta64 numpy
204
+ # arrays
205
+ value = value.view("int64")
206
+ value = bytes(memoryview(value))
207
+ return value
208
+
209
+
210
+ def get_mapper(
211
+ url="",
212
+ check=False,
213
+ create=False,
214
+ missing_exceptions=None,
215
+ alternate_root=None,
216
+ **kwargs,
217
+ ):
218
+ """Create key-value interface for given URL and options
219
+
220
+ The URL will be of the form "protocol://location" and point to the root
221
+ of the mapper required. All keys will be file-names below this location,
222
+ and their values the contents of each key.
223
+
224
+ Also accepts compound URLs like zip::s3://bucket/file.zip , see ``fsspec.open``.
225
+
226
+ Parameters
227
+ ----------
228
+ url: str
229
+ Root URL of mapping
230
+ check: bool
231
+ Whether to attempt to read from the location before instantiation, to
232
+ check that the mapping does exist
233
+ create: bool
234
+ Whether to make the directory corresponding to the root before
235
+ instantiating
236
+ missing_exceptions: None or tuple
237
+ If given, these exception types will be regarded as missing keys and
238
+ return KeyError when trying to read data. By default, you get
239
+ (FileNotFoundError, IsADirectoryError, NotADirectoryError)
240
+ alternate_root: None or str
241
+ In cases of complex URLs, the parser may fail to pick the correct part
242
+ for the mapper root, so this arg can override
243
+
244
+ Returns
245
+ -------
246
+ ``FSMap`` instance, the dict-like key-value store.
247
+ """
248
+ # Removing protocol here - could defer to each open() on the backend
249
+ fs, urlpath = url_to_fs(url, **kwargs)
250
+ root = alternate_root if alternate_root is not None else urlpath
251
+ return FSMap(root, fs, check, create, missing_exceptions=missing_exceptions)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/parquet.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import json
3
+ import warnings
4
+
5
+ import fsspec
6
+
7
+ from .core import url_to_fs
8
+ from .spec import AbstractBufferedFile
9
+ from .utils import merge_offset_ranges
10
+
11
+ # Parquet-Specific Utilities for fsspec
12
+ #
13
+ # Most of the functions defined in this module are NOT
14
+ # intended for public consumption. The only exception
15
+ # to this is `open_parquet_file`, which should be used
16
+ # place of `fs.open()` to open parquet-formatted files
17
+ # on remote file systems.
18
+
19
+
20
+ class AlreadyBufferedFile(AbstractBufferedFile):
21
+ def _fetch_range(self, start, end):
22
+ raise NotImplementedError
23
+
24
+
25
+ def open_parquet_files(
26
+ path: list[str],
27
+ fs: None | fsspec.AbstractFileSystem = None,
28
+ metadata=None,
29
+ columns: None | list[str] = None,
30
+ row_groups: None | list[int] = None,
31
+ storage_options: None | dict = None,
32
+ engine: str = "auto",
33
+ max_gap: int = 64_000,
34
+ max_block: int = 256_000_000,
35
+ footer_sample_size: int = 1_000_000,
36
+ filters: None | list[list[list[str]]] = None,
37
+ **kwargs,
38
+ ):
39
+ """
40
+ Return a file-like object for a single Parquet file.
41
+
42
+ The specified parquet `engine` will be used to parse the
43
+ footer metadata, and determine the required byte ranges
44
+ from the file. The target path will then be opened with
45
+ the "parts" (`KnownPartsOfAFile`) caching strategy.
46
+
47
+ Note that this method is intended for usage with remote
48
+ file systems, and is unlikely to improve parquet-read
49
+ performance on local file systems.
50
+
51
+ Parameters
52
+ ----------
53
+ path: str
54
+ Target file path.
55
+ metadata: Any, optional
56
+ Parquet metadata object. Object type must be supported
57
+ by the backend parquet engine. For now, only the "fastparquet"
58
+ engine supports an explicit `ParquetFile` metadata object.
59
+ If a metadata object is supplied, the remote footer metadata
60
+ will not need to be transferred into local memory.
61
+ fs: AbstractFileSystem, optional
62
+ Filesystem object to use for opening the file. If nothing is
63
+ specified, an `AbstractFileSystem` object will be inferred.
64
+ engine : str, default "auto"
65
+ Parquet engine to use for metadata parsing. Allowed options
66
+ include "fastparquet", "pyarrow", and "auto". The specified
67
+ engine must be installed in the current environment. If
68
+ "auto" is specified, and both engines are installed,
69
+ "fastparquet" will take precedence over "pyarrow".
70
+ columns: list, optional
71
+ List of all column names that may be read from the file.
72
+ row_groups : list, optional
73
+ List of all row-groups that may be read from the file. This
74
+ may be a list of row-group indices (integers), or it may be
75
+ a list of `RowGroup` metadata objects (if the "fastparquet"
76
+ engine is used).
77
+ storage_options : dict, optional
78
+ Used to generate an `AbstractFileSystem` object if `fs` was
79
+ not specified.
80
+ max_gap : int, optional
81
+ Neighboring byte ranges will only be merged when their
82
+ inter-range gap is <= `max_gap`. Default is 64KB.
83
+ max_block : int, optional
84
+ Neighboring byte ranges will only be merged when the size of
85
+ the aggregated range is <= `max_block`. Default is 256MB.
86
+ footer_sample_size : int, optional
87
+ Number of bytes to read from the end of the path to look
88
+ for the footer metadata. If the sampled bytes do not contain
89
+ the footer, a second read request will be required, and
90
+ performance will suffer. Default is 1MB.
91
+ filters : list[list], optional
92
+ List of filters to apply to prevent reading row groups, of the
93
+ same format as accepted by the loading engines. Ignored if
94
+ ``row_groups`` is specified.
95
+ **kwargs :
96
+ Optional key-word arguments to pass to `fs.open`
97
+ """
98
+
99
+ # Make sure we have an `AbstractFileSystem` object
100
+ # to work with
101
+ if fs is None:
102
+ path0 = path
103
+ if isinstance(path, (list, tuple)):
104
+ path = path[0]
105
+ fs, path = url_to_fs(path, **(storage_options or {}))
106
+ else:
107
+ path0 = path
108
+
109
+ # For now, `columns == []` not supported, is the same
110
+ # as all columns
111
+ if columns is not None and len(columns) == 0:
112
+ columns = None
113
+
114
+ # Set the engine
115
+ engine = _set_engine(engine)
116
+
117
+ if isinstance(path0, (list, tuple)):
118
+ paths = path0
119
+ elif "*" in path:
120
+ paths = fs.glob(path)
121
+ elif path0.endswith("/"): # or fs.isdir(path):
122
+ paths = [
123
+ _
124
+ for _ in fs.find(path, withdirs=False, detail=False)
125
+ if _.endswith((".parquet", ".parq"))
126
+ ]
127
+ else:
128
+ paths = [path]
129
+
130
+ data = _get_parquet_byte_ranges(
131
+ paths,
132
+ fs,
133
+ metadata=metadata,
134
+ columns=columns,
135
+ row_groups=row_groups,
136
+ engine=engine,
137
+ max_gap=max_gap,
138
+ max_block=max_block,
139
+ footer_sample_size=footer_sample_size,
140
+ filters=filters,
141
+ )
142
+
143
+ # Call self.open with "parts" caching
144
+ options = kwargs.pop("cache_options", {}).copy()
145
+ return [
146
+ AlreadyBufferedFile(
147
+ fs=None,
148
+ path=fn,
149
+ mode="rb",
150
+ cache_type="parts",
151
+ cache_options={
152
+ **options,
153
+ "data": ranges,
154
+ },
155
+ size=max(_[1] for _ in ranges),
156
+ **kwargs,
157
+ )
158
+ for fn, ranges in data.items()
159
+ ]
160
+
161
+
162
+ def open_parquet_file(*args, **kwargs):
163
+ """Create files tailed to reading specific parts of parquet files
164
+
165
+ Please see ``open_parquet_files`` for details of the arguments. The
166
+ difference is, this function always returns a single ``AlreadyBufferedFile``,
167
+ whereas `open_parquet_files`` always returns a list of files, even if
168
+ there are one or zero matching parquet files.
169
+ """
170
+ return open_parquet_files(*args, **kwargs)[0]
171
+
172
+
173
+ def _get_parquet_byte_ranges(
174
+ paths,
175
+ fs,
176
+ metadata=None,
177
+ columns=None,
178
+ row_groups=None,
179
+ max_gap=64_000,
180
+ max_block=256_000_000,
181
+ footer_sample_size=1_000_000,
182
+ engine="auto",
183
+ filters=None,
184
+ ):
185
+ """Get a dictionary of the known byte ranges needed
186
+ to read a specific column/row-group selection from a
187
+ Parquet dataset. Each value in the output dictionary
188
+ is intended for use as the `data` argument for the
189
+ `KnownPartsOfAFile` caching strategy of a single path.
190
+ """
191
+
192
+ # Set engine if necessary
193
+ if isinstance(engine, str):
194
+ engine = _set_engine(engine)
195
+
196
+ # Pass to a specialized function if metadata is defined
197
+ if metadata is not None:
198
+ # Use the provided parquet metadata object
199
+ # to avoid transferring/parsing footer metadata
200
+ return _get_parquet_byte_ranges_from_metadata(
201
+ metadata,
202
+ fs,
203
+ engine,
204
+ columns=columns,
205
+ row_groups=row_groups,
206
+ max_gap=max_gap,
207
+ max_block=max_block,
208
+ filters=filters,
209
+ )
210
+
211
+ # Populate global paths, starts, & ends
212
+ if columns is None and row_groups is None and filters is None:
213
+ # We are NOT selecting specific columns or row-groups.
214
+ #
215
+ # We can avoid sampling the footers, and just transfer
216
+ # all file data with cat_ranges
217
+ result = {path: {(0, len(data)): data} for path, data in fs.cat(paths).items()}
218
+ else:
219
+ # We ARE selecting specific columns or row-groups.
220
+ #
221
+ # Get file sizes asynchronously
222
+ file_sizes = fs.sizes(paths)
223
+ data_paths = []
224
+ data_starts = []
225
+ data_ends = []
226
+ # Gather file footers.
227
+ # We just take the last `footer_sample_size` bytes of each
228
+ # file (or the entire file if it is smaller than that)
229
+ footer_starts = [
230
+ max(0, file_size - footer_sample_size) for file_size in file_sizes
231
+ ]
232
+ footer_samples = fs.cat_ranges(paths, footer_starts, file_sizes)
233
+
234
+ # Check our footer samples and re-sample if necessary.
235
+ large_footer = []
236
+ for i, path in enumerate(paths):
237
+ footer_size = int.from_bytes(footer_samples[i][-8:-4], "little")
238
+ real_footer_start = file_sizes[i] - (footer_size + 8)
239
+ if real_footer_start < footer_starts[i]:
240
+ large_footer.append((i, real_footer_start))
241
+ if large_footer:
242
+ warnings.warn(
243
+ f"Not enough data was used to sample the parquet footer. "
244
+ f"Try setting footer_sample_size >= {large_footer}."
245
+ )
246
+ path0 = [paths[i] for i, _ in large_footer]
247
+ starts = [_[1] for _ in large_footer]
248
+ ends = [file_sizes[i] - footer_sample_size for i, _ in large_footer]
249
+ data = fs.cat_ranges(path0, starts, ends)
250
+ for i, (path, start, block) in enumerate(zip(path0, starts, data)):
251
+ footer_samples[i] = block + footer_samples[i]
252
+ footer_starts[i] = start
253
+ result = {
254
+ path: {(start, size): data}
255
+ for path, start, size, data in zip(
256
+ paths, footer_starts, file_sizes, footer_samples
257
+ )
258
+ }
259
+
260
+ # Calculate required byte ranges for each path
261
+ for i, path in enumerate(paths):
262
+ # Use "engine" to collect data byte ranges
263
+ path_data_starts, path_data_ends = engine._parquet_byte_ranges(
264
+ columns,
265
+ row_groups=row_groups,
266
+ footer=footer_samples[i],
267
+ footer_start=footer_starts[i],
268
+ filters=filters,
269
+ )
270
+
271
+ data_paths += [path] * len(path_data_starts)
272
+ data_starts += path_data_starts
273
+ data_ends += path_data_ends
274
+
275
+ # Merge adjacent offset ranges
276
+ data_paths, data_starts, data_ends = merge_offset_ranges(
277
+ data_paths,
278
+ data_starts,
279
+ data_ends,
280
+ max_gap=max_gap,
281
+ max_block=max_block,
282
+ sort=True,
283
+ )
284
+
285
+ # Transfer the data byte-ranges into local memory
286
+ _transfer_ranges(fs, result, data_paths, data_starts, data_ends)
287
+
288
+ # Add b"PAR1" to headers
289
+ _add_header_magic(result)
290
+
291
+ return result
292
+
293
+
294
+ def _get_parquet_byte_ranges_from_metadata(
295
+ metadata,
296
+ fs,
297
+ engine,
298
+ columns=None,
299
+ row_groups=None,
300
+ max_gap=64_000,
301
+ max_block=256_000_000,
302
+ filters=None,
303
+ ):
304
+ """Simplified version of `_get_parquet_byte_ranges` for
305
+ the case that an engine-specific `metadata` object is
306
+ provided, and the remote footer metadata does not need to
307
+ be transferred before calculating the required byte ranges.
308
+ """
309
+
310
+ # Use "engine" to collect data byte ranges
311
+ data_paths, data_starts, data_ends = engine._parquet_byte_ranges(
312
+ columns, row_groups=row_groups, metadata=metadata, filters=filters
313
+ )
314
+
315
+ # Merge adjacent offset ranges
316
+ data_paths, data_starts, data_ends = merge_offset_ranges(
317
+ data_paths,
318
+ data_starts,
319
+ data_ends,
320
+ max_gap=max_gap,
321
+ max_block=max_block,
322
+ sort=False, # Should be sorted
323
+ )
324
+
325
+ # Transfer the data byte-ranges into local memory
326
+ result = {fn: {} for fn in list(set(data_paths))}
327
+ _transfer_ranges(fs, result, data_paths, data_starts, data_ends)
328
+
329
+ # Add b"PAR1" to header
330
+ _add_header_magic(result)
331
+
332
+ return result
333
+
334
+
335
+ def _transfer_ranges(fs, blocks, paths, starts, ends):
336
+ # Use cat_ranges to gather the data byte_ranges
337
+ ranges = (paths, starts, ends)
338
+ for path, start, stop, data in zip(*ranges, fs.cat_ranges(*ranges)):
339
+ blocks[path][(start, stop)] = data
340
+
341
+
342
+ def _add_header_magic(data):
343
+ # Add b"PAR1" to file headers
344
+ for path in list(data):
345
+ add_magic = True
346
+ for k in data[path]:
347
+ if k[0] == 0 and k[1] >= 4:
348
+ add_magic = False
349
+ break
350
+ if add_magic:
351
+ data[path][(0, 4)] = b"PAR1"
352
+
353
+
354
+ def _set_engine(engine_str):
355
+ # Define a list of parquet engines to try
356
+ if engine_str == "auto":
357
+ try_engines = ("fastparquet", "pyarrow")
358
+ elif not isinstance(engine_str, str):
359
+ raise ValueError(
360
+ "Failed to set parquet engine! "
361
+ "Please pass 'fastparquet', 'pyarrow', or 'auto'"
362
+ )
363
+ elif engine_str not in ("fastparquet", "pyarrow"):
364
+ raise ValueError(f"{engine_str} engine not supported by `fsspec.parquet`")
365
+ else:
366
+ try_engines = [engine_str]
367
+
368
+ # Try importing the engines in `try_engines`,
369
+ # and choose the first one that succeeds
370
+ for engine in try_engines:
371
+ try:
372
+ if engine == "fastparquet":
373
+ return FastparquetEngine()
374
+ elif engine == "pyarrow":
375
+ return PyarrowEngine()
376
+ except ImportError:
377
+ pass
378
+
379
+ # Raise an error if a supported parquet engine
380
+ # was not found
381
+ raise ImportError(
382
+ f"The following parquet engines are not installed "
383
+ f"in your python environment: {try_engines}."
384
+ f"Please install 'fastparquert' or 'pyarrow' to "
385
+ f"utilize the `fsspec.parquet` module."
386
+ )
387
+
388
+
389
+ class FastparquetEngine:
390
+ # The purpose of the FastparquetEngine class is
391
+ # to check if fastparquet can be imported (on initialization)
392
+ # and to define a `_parquet_byte_ranges` method. In the
393
+ # future, this class may also be used to define other
394
+ # methods/logic that are specific to fastparquet.
395
+
396
+ def __init__(self):
397
+ import fastparquet as fp
398
+
399
+ self.fp = fp
400
+
401
+ def _parquet_byte_ranges(
402
+ self,
403
+ columns,
404
+ row_groups=None,
405
+ metadata=None,
406
+ footer=None,
407
+ footer_start=None,
408
+ filters=None,
409
+ ):
410
+ # Initialize offset ranges and define ParqetFile metadata
411
+ pf = metadata
412
+ data_paths, data_starts, data_ends = [], [], []
413
+ if filters and row_groups:
414
+ raise ValueError("filters and row_groups cannot be used together")
415
+ if pf is None:
416
+ pf = self.fp.ParquetFile(io.BytesIO(footer))
417
+
418
+ # Convert columns to a set and add any index columns
419
+ # specified in the pandas metadata (just in case)
420
+ column_set = None if columns is None else {c.split(".", 1)[0] for c in columns}
421
+ if column_set is not None and hasattr(pf, "pandas_metadata"):
422
+ md_index = [
423
+ ind
424
+ for ind in pf.pandas_metadata.get("index_columns", [])
425
+ # Ignore RangeIndex information
426
+ if not isinstance(ind, dict)
427
+ ]
428
+ column_set |= set(md_index)
429
+
430
+ # Check if row_groups is a list of integers
431
+ # or a list of row-group metadata
432
+ if filters:
433
+ from fastparquet.api import filter_row_groups
434
+
435
+ row_group_indices = None
436
+ row_groups = filter_row_groups(pf, filters)
437
+ elif row_groups and not isinstance(row_groups[0], int):
438
+ # Input row_groups contains row-group metadata
439
+ row_group_indices = None
440
+ else:
441
+ # Input row_groups contains row-group indices
442
+ row_group_indices = row_groups
443
+ row_groups = pf.row_groups
444
+ if column_set is not None:
445
+ column_set = [
446
+ _ if isinstance(_, list) else _.split(".") for _ in column_set
447
+ ]
448
+
449
+ # Loop through column chunks to add required byte ranges
450
+ for r, row_group in enumerate(row_groups):
451
+ # Skip this row-group if we are targeting
452
+ # specific row-groups
453
+ if row_group_indices is None or r in row_group_indices:
454
+ # Find the target parquet-file path for `row_group`
455
+ fn = pf.row_group_filename(row_group)
456
+
457
+ for column in row_group.columns:
458
+ name = column.meta_data.path_in_schema
459
+ # Skip this column if we are targeting specific columns
460
+ if column_set is None or _cmp(name, column_set):
461
+ file_offset0 = column.meta_data.dictionary_page_offset
462
+ if file_offset0 is None:
463
+ file_offset0 = column.meta_data.data_page_offset
464
+ num_bytes = column.meta_data.total_compressed_size
465
+ if footer_start is None or file_offset0 < footer_start:
466
+ data_paths.append(fn)
467
+ data_starts.append(file_offset0)
468
+ data_ends.append(
469
+ min(
470
+ file_offset0 + num_bytes,
471
+ footer_start or (file_offset0 + num_bytes),
472
+ )
473
+ )
474
+
475
+ if metadata:
476
+ # The metadata in this call may map to multiple
477
+ # file paths. Need to include `data_paths`
478
+ return data_paths, data_starts, data_ends
479
+ return data_starts, data_ends
480
+
481
+
482
+ class PyarrowEngine:
483
+ # The purpose of the PyarrowEngine class is
484
+ # to check if pyarrow can be imported (on initialization)
485
+ # and to define a `_parquet_byte_ranges` method. In the
486
+ # future, this class may also be used to define other
487
+ # methods/logic that are specific to pyarrow.
488
+
489
+ def __init__(self):
490
+ import pyarrow.parquet as pq
491
+
492
+ self.pq = pq
493
+
494
+ def _parquet_byte_ranges(
495
+ self,
496
+ columns,
497
+ row_groups=None,
498
+ metadata=None,
499
+ footer=None,
500
+ footer_start=None,
501
+ filters=None,
502
+ ):
503
+ if metadata is not None:
504
+ raise ValueError("metadata input not supported for PyarrowEngine")
505
+ if filters:
506
+ # there must be a way!
507
+ raise NotImplementedError
508
+
509
+ data_starts, data_ends = [], []
510
+ md = self.pq.ParquetFile(io.BytesIO(footer)).metadata
511
+
512
+ # Convert columns to a set and add any index columns
513
+ # specified in the pandas metadata (just in case)
514
+ column_set = None if columns is None else set(columns)
515
+ if column_set is not None:
516
+ schema = md.schema.to_arrow_schema()
517
+ has_pandas_metadata = (
518
+ schema.metadata is not None and b"pandas" in schema.metadata
519
+ )
520
+ if has_pandas_metadata:
521
+ md_index = [
522
+ ind
523
+ for ind in json.loads(
524
+ schema.metadata[b"pandas"].decode("utf8")
525
+ ).get("index_columns", [])
526
+ # Ignore RangeIndex information
527
+ if not isinstance(ind, dict)
528
+ ]
529
+ column_set |= set(md_index)
530
+ if column_set is not None:
531
+ column_set = [
532
+ _[:1] if isinstance(_, list) else _.split(".")[:1] for _ in column_set
533
+ ]
534
+
535
+ # Loop through column chunks to add required byte ranges
536
+ for r in range(md.num_row_groups):
537
+ # Skip this row-group if we are targeting
538
+ # specific row-groups
539
+ if row_groups is None or r in row_groups:
540
+ row_group = md.row_group(r)
541
+ for c in range(row_group.num_columns):
542
+ column = row_group.column(c)
543
+ name = column.path_in_schema.split(".")
544
+ # Skip this column if we are targeting specific columns
545
+ if column_set is None or _cmp(name, column_set):
546
+ meta = column.to_dict()
547
+ # Any offset could be the first one
548
+ file_offset0 = min(
549
+ _
550
+ for _ in [
551
+ meta.get("dictionary_page_offset"),
552
+ meta.get("data_page_offset"),
553
+ meta.get("index_page_offset"),
554
+ ]
555
+ if _ is not None
556
+ )
557
+ if file_offset0 < footer_start:
558
+ data_starts.append(file_offset0)
559
+ data_ends.append(
560
+ min(
561
+ meta["total_compressed_size"] + file_offset0,
562
+ footer_start,
563
+ )
564
+ )
565
+
566
+ data_starts.append(footer_start)
567
+ data_ends.append(footer_start + len(footer))
568
+ return data_starts, data_ends
569
+
570
+
571
+ def _cmp(name, column_set):
572
+ return any(all(a == b for a, b in zip(name, _)) for _ in column_set)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/registry.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ import types
5
+ import warnings
6
+
7
+ __all__ = ["registry", "get_filesystem_class", "default"]
8
+
9
+ # internal, mutable
10
+ _registry: dict[str, type] = {}
11
+
12
+ # external, immutable
13
+ registry = types.MappingProxyType(_registry)
14
+ default = "file"
15
+
16
+
17
+ def register_implementation(name, cls, clobber=False, errtxt=None):
18
+ """Add implementation class to the registry
19
+
20
+ Parameters
21
+ ----------
22
+ name: str
23
+ Protocol name to associate with the class
24
+ cls: class or str
25
+ if a class: fsspec-compliant implementation class (normally inherits from
26
+ ``fsspec.AbstractFileSystem``, gets added straight to the registry. If a
27
+ str, the full path to an implementation class like package.module.class,
28
+ which gets added to known_implementations,
29
+ so the import is deferred until the filesystem is actually used.
30
+ clobber: bool (optional)
31
+ Whether to overwrite a protocol with the same name; if False, will raise
32
+ instead.
33
+ errtxt: str (optional)
34
+ If given, then a failure to import the given class will result in this
35
+ text being given.
36
+ """
37
+ if isinstance(cls, str):
38
+ if name in known_implementations and clobber is False:
39
+ if cls != known_implementations[name]["class"]:
40
+ raise ValueError(
41
+ f"Name ({name}) already in the known_implementations and clobber "
42
+ f"is False"
43
+ )
44
+ else:
45
+ known_implementations[name] = {
46
+ "class": cls,
47
+ "err": errtxt or f"{cls} import failed for protocol {name}",
48
+ }
49
+
50
+ else:
51
+ if name in registry and clobber is False:
52
+ if _registry[name] is not cls:
53
+ raise ValueError(
54
+ f"Name ({name}) already in the registry and clobber is False"
55
+ )
56
+ else:
57
+ _registry[name] = cls
58
+
59
+
60
+ # protocols mapped to the class which implements them. This dict can be
61
+ # updated with register_implementation
62
+ known_implementations = {
63
+ "abfs": {
64
+ "class": "adlfs.AzureBlobFileSystem",
65
+ "err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage",
66
+ },
67
+ "adl": {
68
+ "class": "adlfs.AzureDatalakeFileSystem",
69
+ "err": (
70
+ "Azure Data Lake Storage Gen1 is retired and no longer supported. Please "
71
+ "install adlfs and use the `az://` protocol to access Azure Blob Storage "
72
+ "and Azure Data Lake Storage Gen2 instead."
73
+ ),
74
+ },
75
+ "arrow_hdfs": {
76
+ "class": "fsspec.implementations.arrow.HadoopFileSystem",
77
+ "err": "pyarrow and local java libraries required for HDFS",
78
+ },
79
+ "async_wrapper": {
80
+ "class": "fsspec.implementations.asyn_wrapper.AsyncFileSystemWrapper",
81
+ },
82
+ "asynclocal": {
83
+ "class": "morefs.asyn_local.AsyncLocalFileSystem",
84
+ "err": "Install 'morefs[asynclocalfs]' to use AsyncLocalFileSystem",
85
+ },
86
+ "asyncwrapper": {
87
+ "class": "fsspec.implementations.asyn_wrapper.AsyncFileSystemWrapper",
88
+ },
89
+ "az": {
90
+ "class": "adlfs.AzureBlobFileSystem",
91
+ "err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage",
92
+ },
93
+ "blockcache": {"class": "fsspec.implementations.cached.CachingFileSystem"},
94
+ "box": {
95
+ "class": "boxfs.BoxFileSystem",
96
+ "err": "Please install boxfs to access BoxFileSystem",
97
+ },
98
+ "cached": {"class": "fsspec.implementations.cached.CachingFileSystem"},
99
+ "dask": {
100
+ "class": "fsspec.implementations.dask.DaskWorkerFileSystem",
101
+ "err": "Install dask distributed to access worker file system",
102
+ },
103
+ "data": {"class": "fsspec.implementations.data.DataFileSystem"},
104
+ "dbfs": {
105
+ "class": "fsspec.implementations.dbfs.DatabricksFileSystem",
106
+ "err": "Install the requests package to use the DatabricksFileSystem",
107
+ },
108
+ "dir": {"class": "fsspec.implementations.dirfs.DirFileSystem"},
109
+ "dropbox": {
110
+ "class": "dropboxdrivefs.DropboxDriveFileSystem",
111
+ "err": (
112
+ 'DropboxFileSystem requires "dropboxdrivefs","requests" and "'
113
+ '"dropbox" to be installed'
114
+ ),
115
+ },
116
+ "dvc": {
117
+ "class": "dvc.api.DVCFileSystem",
118
+ "err": "Install dvc to access DVCFileSystem",
119
+ },
120
+ "file": {"class": "fsspec.implementations.local.LocalFileSystem"},
121
+ "filecache": {"class": "fsspec.implementations.cached.WholeFileCacheFileSystem"},
122
+ "ftp": {"class": "fsspec.implementations.ftp.FTPFileSystem"},
123
+ "gcs": {
124
+ "class": "gcsfs.GCSFileSystem",
125
+ "err": "Please install gcsfs to access Google Storage",
126
+ },
127
+ "gdrive": {
128
+ "class": "gdrive_fsspec.GoogleDriveFileSystem",
129
+ "err": "Please install gdrive_fs for access to Google Drive",
130
+ },
131
+ "generic": {"class": "fsspec.generic.GenericFileSystem"},
132
+ "gist": {
133
+ "class": "fsspec.implementations.gist.GistFileSystem",
134
+ "err": "Install the requests package to use the gist FS",
135
+ },
136
+ "git": {
137
+ "class": "fsspec.implementations.git.GitFileSystem",
138
+ "err": "Install pygit2 to browse local git repos",
139
+ },
140
+ "github": {
141
+ "class": "fsspec.implementations.github.GithubFileSystem",
142
+ "err": "Install the requests package to use the github FS",
143
+ },
144
+ "gs": {
145
+ "class": "gcsfs.GCSFileSystem",
146
+ "err": "Please install gcsfs to access Google Storage",
147
+ },
148
+ "hdfs": {
149
+ "class": "fsspec.implementations.arrow.HadoopFileSystem",
150
+ "err": "pyarrow and local java libraries required for HDFS",
151
+ },
152
+ "hf": {
153
+ "class": "huggingface_hub.HfFileSystem",
154
+ "err": "Install huggingface_hub to access HfFileSystem",
155
+ },
156
+ "http": {
157
+ "class": "fsspec.implementations.http.HTTPFileSystem",
158
+ "err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed',
159
+ },
160
+ "https": {
161
+ "class": "fsspec.implementations.http.HTTPFileSystem",
162
+ "err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed',
163
+ },
164
+ "jlab": {
165
+ "class": "fsspec.implementations.jupyter.JupyterFileSystem",
166
+ "err": "Jupyter FS requires requests to be installed",
167
+ },
168
+ "jupyter": {
169
+ "class": "fsspec.implementations.jupyter.JupyterFileSystem",
170
+ "err": "Jupyter FS requires requests to be installed",
171
+ },
172
+ "lakefs": {
173
+ "class": "lakefs_spec.LakeFSFileSystem",
174
+ "err": "Please install lakefs-spec to access LakeFSFileSystem",
175
+ },
176
+ "libarchive": {
177
+ "class": "fsspec.implementations.libarchive.LibArchiveFileSystem",
178
+ "err": "LibArchive requires to be installed",
179
+ },
180
+ "local": {"class": "fsspec.implementations.local.LocalFileSystem"},
181
+ "memory": {"class": "fsspec.implementations.memory.MemoryFileSystem"},
182
+ "oci": {
183
+ "class": "ocifs.OCIFileSystem",
184
+ "err": "Install ocifs to access OCI Object Storage",
185
+ },
186
+ "ocilake": {
187
+ "class": "ocifs.OCIFileSystem",
188
+ "err": "Install ocifs to access OCI Data Lake",
189
+ },
190
+ "oss": {
191
+ "class": "ossfs.OSSFileSystem",
192
+ "err": "Install ossfs to access Alibaba Object Storage System",
193
+ },
194
+ "pyscript": {
195
+ "class": "pyscript_fsspec_client.client.PyscriptFileSystem",
196
+ "err": "This only runs in a pyscript context",
197
+ },
198
+ "reference": {"class": "fsspec.implementations.reference.ReferenceFileSystem"},
199
+ "root": {
200
+ "class": "fsspec_xrootd.XRootDFileSystem",
201
+ "err": (
202
+ "Install fsspec-xrootd to access xrootd storage system. "
203
+ "Note: 'root' is the protocol name for xrootd storage systems, "
204
+ "not referring to root directories"
205
+ ),
206
+ },
207
+ "s3": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"},
208
+ "s3a": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"},
209
+ "sftp": {
210
+ "class": "fsspec.implementations.sftp.SFTPFileSystem",
211
+ "err": 'SFTPFileSystem requires "paramiko" to be installed',
212
+ },
213
+ "simplecache": {"class": "fsspec.implementations.cached.SimpleCacheFileSystem"},
214
+ "smb": {
215
+ "class": "fsspec.implementations.smb.SMBFileSystem",
216
+ "err": 'SMB requires "smbprotocol" or "smbprotocol[kerberos]" installed',
217
+ },
218
+ "ssh": {
219
+ "class": "fsspec.implementations.sftp.SFTPFileSystem",
220
+ "err": 'SFTPFileSystem requires "paramiko" to be installed',
221
+ },
222
+ "tar": {"class": "fsspec.implementations.tar.TarFileSystem"},
223
+ "tos": {
224
+ "class": "tosfs.TosFileSystem",
225
+ "err": "Install tosfs to access ByteDance volcano engine Tinder Object Storage",
226
+ },
227
+ "tosfs": {
228
+ "class": "tosfs.TosFileSystem",
229
+ "err": "Install tosfs to access ByteDance volcano engine Tinder Object Storage",
230
+ },
231
+ "wandb": {"class": "wandbfs.WandbFS", "err": "Install wandbfs to access wandb"},
232
+ "webdav": {
233
+ "class": "webdav4.fsspec.WebdavFileSystem",
234
+ "err": "Install webdav4 to access WebDAV",
235
+ },
236
+ "webhdfs": {
237
+ "class": "fsspec.implementations.webhdfs.WebHDFS",
238
+ "err": 'webHDFS access requires "requests" to be installed',
239
+ },
240
+ "zip": {"class": "fsspec.implementations.zip.ZipFileSystem"},
241
+ }
242
+
243
+ assert list(known_implementations) == sorted(known_implementations), (
244
+ "Not in alphabetical order"
245
+ )
246
+
247
+
248
+ def get_filesystem_class(protocol):
249
+ """Fetch named protocol implementation from the registry
250
+
251
+ The dict ``known_implementations`` maps protocol names to the locations
252
+ of classes implementing the corresponding file-system. When used for the
253
+ first time, appropriate imports will happen and the class will be placed in
254
+ the registry. All subsequent calls will fetch directly from the registry.
255
+
256
+ Some protocol implementations require additional dependencies, and so the
257
+ import may fail. In this case, the string in the "err" field of the
258
+ ``known_implementations`` will be given as the error message.
259
+ """
260
+ if not protocol:
261
+ protocol = default
262
+
263
+ if protocol not in registry:
264
+ if protocol not in known_implementations:
265
+ raise ValueError(f"Protocol not known: {protocol}")
266
+ bit = known_implementations[protocol]
267
+ try:
268
+ register_implementation(protocol, _import_class(bit["class"]))
269
+ except ImportError as e:
270
+ raise ImportError(bit.get("err")) from e
271
+ cls = registry[protocol]
272
+ if getattr(cls, "protocol", None) in ("abstract", None):
273
+ cls.protocol = protocol
274
+
275
+ return cls
276
+
277
+
278
+ s3_msg = """Your installed version of s3fs is very old and known to cause
279
+ severe performance issues, see also https://github.com/dask/dask/issues/10276
280
+
281
+ To fix, you should specify a lower version bound on s3fs, or
282
+ update the current installation.
283
+ """
284
+
285
+
286
+ def _import_class(fqp: str):
287
+ """Take a fully-qualified path and return the imported class or identifier.
288
+
289
+ ``fqp`` is of the form "package.module.klass" or
290
+ "package.module:subobject.klass".
291
+
292
+ Warnings
293
+ --------
294
+ This can import arbitrary modules. Make sure you haven't installed any modules
295
+ that may execute malicious code at import time.
296
+ """
297
+ if ":" in fqp:
298
+ mod, name = fqp.rsplit(":", 1)
299
+ else:
300
+ mod, name = fqp.rsplit(".", 1)
301
+
302
+ is_s3 = mod == "s3fs"
303
+ mod = importlib.import_module(mod)
304
+ if is_s3 and mod.__version__.split(".") < ["0", "5"]:
305
+ warnings.warn(s3_msg)
306
+ for part in name.split("."):
307
+ mod = getattr(mod, part)
308
+
309
+ if not isinstance(mod, type):
310
+ raise TypeError(f"{fqp} is not a class")
311
+
312
+ return mod
313
+
314
+
315
+ def filesystem(protocol, **storage_options):
316
+ """Instantiate filesystems for given protocol and arguments
317
+
318
+ ``storage_options`` are specific to the protocol being chosen, and are
319
+ passed directly to the class.
320
+ """
321
+ if protocol == "arrow_hdfs":
322
+ warnings.warn(
323
+ "The 'arrow_hdfs' protocol has been deprecated and will be "
324
+ "removed in the future. Specify it as 'hdfs'.",
325
+ DeprecationWarning,
326
+ )
327
+
328
+ cls = get_filesystem_class(protocol)
329
+ return cls(**storage_options)
330
+
331
+
332
+ def available_protocols():
333
+ """Return a list of the implemented protocols.
334
+
335
+ Note that any given protocol may require extra packages to be importable.
336
+ """
337
+ return list(known_implementations)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/spec.py ADDED
@@ -0,0 +1,2342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import json
5
+ import logging
6
+ import os
7
+ import threading
8
+ import warnings
9
+ import weakref
10
+ from errno import ESPIPE
11
+ from glob import has_magic
12
+ from hashlib import sha256
13
+ from typing import Any, ClassVar
14
+
15
+ from .callbacks import DEFAULT_CALLBACK
16
+ from .config import apply_config, conf
17
+ from .dircache import DirCache
18
+ from .transaction import Transaction
19
+ from .utils import (
20
+ _unstrip_protocol,
21
+ glob_translate,
22
+ isfilelike,
23
+ other_paths,
24
+ read_block,
25
+ stringify_path,
26
+ tokenize,
27
+ )
28
+
29
+ logger = logging.getLogger("fsspec")
30
+
31
+
32
+ def make_instance(cls, args, kwargs):
33
+ return cls(*args, **kwargs)
34
+
35
+
36
+ FORK_AVAILABLE = hasattr(os, "register_at_fork")
37
+
38
+
39
+ if FORK_AVAILABLE:
40
+ _registered_classes = weakref.WeakSet()
41
+
42
+ def _reset_instances_lock():
43
+ for cls in _registered_classes:
44
+ cls._instantiation_lock = threading.RLock()
45
+ cls._cache.clear()
46
+ cls._pid = os.getpid()
47
+
48
+ os.register_at_fork(after_in_child=_reset_instances_lock)
49
+
50
+
51
+ class _Cached(type):
52
+ """
53
+ Metaclass for caching file system instances.
54
+
55
+ Notes
56
+ -----
57
+ Instances are cached according to
58
+
59
+ * The values of the class attributes listed in `_extra_tokenize_attributes`
60
+ * The arguments passed to ``__init__``.
61
+
62
+ This creates an additional reference to the filesystem, which prevents the
63
+ filesystem from being garbage collected when all *user* references go away.
64
+ A call to the :meth:`AbstractFileSystem.clear_instance_cache` must *also*
65
+ be made for a filesystem instance to be garbage collected.
66
+ """
67
+
68
+ def __init__(cls, *args, **kwargs):
69
+ super().__init__(*args, **kwargs)
70
+
71
+ # Note: we intentionally create a reference here, to avoid garbage
72
+ # collecting instances when all other references are gone. To really
73
+ # delete a FileSystem, the cache must be cleared.
74
+ if conf.get("weakref_instance_cache"): # pragma: no cover
75
+ # debug option for analysing fork/spawn conditions
76
+ cls._cache = weakref.WeakValueDictionary()
77
+ else:
78
+ cls._cache = {}
79
+ cls._pid = os.getpid()
80
+ cls._instantiation_lock = threading.RLock()
81
+
82
+ if FORK_AVAILABLE:
83
+ _registered_classes.add(cls)
84
+
85
+ def _check_instance_cache(cls, token):
86
+ inst = cls._cache.get(token)
87
+ if inst is not None:
88
+ cls._latest = token
89
+ return inst
90
+
91
+ def __call__(cls, *args, **kwargs):
92
+ kwargs = apply_config(cls, kwargs)
93
+ extra_tokens = tuple(
94
+ getattr(cls, attr, None) for attr in cls._extra_tokenize_attributes
95
+ )
96
+ strip_tokenize_options = {
97
+ k: kwargs.pop(k) for k in cls._strip_tokenize_options if k in kwargs
98
+ }
99
+ pid = os.getpid()
100
+
101
+ if getattr(cls, "async_impl", False) and not kwargs.get("asynchronous", False):
102
+ token = tokenize(cls, pid, *args, *extra_tokens, **kwargs)
103
+ else:
104
+ token = tokenize(
105
+ cls, pid, threading.get_ident(), *args, *extra_tokens, **kwargs
106
+ )
107
+ skip = kwargs.pop("skip_instance_cache", False)
108
+
109
+ if pid != cls._pid:
110
+ with cls._instantiation_lock:
111
+ if pid != cls._pid:
112
+ cls._cache.clear()
113
+ cls._pid = pid
114
+
115
+ if not skip and cls.cachable:
116
+ inst = cls._check_instance_cache(token)
117
+ if inst is not None:
118
+ return inst
119
+
120
+ with cls._instantiation_lock:
121
+ # protect against the race condition that a new instance was created
122
+ # and inserted into the cache since the initial check just above
123
+ inst = cls._check_instance_cache(token)
124
+ if inst is not None:
125
+ return inst
126
+
127
+ obj = super().__call__(*args, **kwargs, **strip_tokenize_options)
128
+ # Setting _fs_token here causes some static linters to complain.
129
+ obj._fs_token_ = token
130
+ obj.storage_args = args
131
+ obj.storage_options = kwargs
132
+ if obj.async_impl and obj.mirror_sync_methods:
133
+ from .asyn import mirror_sync_methods
134
+
135
+ mirror_sync_methods(obj)
136
+
137
+ if cls.cachable and not skip:
138
+ with cls._instantiation_lock:
139
+ # another thread may have created the instance while we were calling
140
+ # super().__call__(), so we check again.
141
+ inst = cls._check_instance_cache(token)
142
+ if inst is not None:
143
+ return inst
144
+
145
+ cls._latest = token
146
+ cls._cache[token] = obj
147
+ return obj
148
+
149
+
150
+ class AbstractFileSystem(metaclass=_Cached):
151
+ """
152
+ An abstract super-class for pythonic file-systems
153
+
154
+ Implementations are expected to be compatible with or, better, subclass
155
+ from here.
156
+ """
157
+
158
+ cachable = True # this class can be cached, instances reused
159
+ _cached = False
160
+ blocksize = 2**22
161
+ sep = "/"
162
+ protocol: ClassVar[str | tuple[str, ...]] = "abstract"
163
+ _latest = None
164
+ async_impl = False
165
+ mirror_sync_methods = False
166
+ root_marker = "" # For some FSs, may require leading '/' or other character
167
+ transaction_type = Transaction
168
+
169
+ #: Extra *class attributes* that should be considered when hashing.
170
+ _extra_tokenize_attributes = ()
171
+ #: *storage options* that should not be considered when hashing.
172
+ _strip_tokenize_options = ()
173
+
174
+ # Set by _Cached metaclass
175
+ storage_args: tuple[Any, ...]
176
+ storage_options: dict[str, Any]
177
+
178
+ def __init__(self, *args, **storage_options):
179
+ """Create and configure file-system instance
180
+
181
+ Instances may be cachable, so if similar enough arguments are seen
182
+ a new instance is not required. The token attribute exists to allow
183
+ implementations to cache instances if they wish.
184
+
185
+ A reasonable default should be provided if there are no arguments.
186
+
187
+ Subclasses should call this method.
188
+
189
+ Parameters
190
+ ----------
191
+ use_listings_cache, listings_expiry_time, max_paths:
192
+ passed to ``DirCache``, if the implementation supports
193
+ directory listing caching. Pass use_listings_cache=False
194
+ to disable such caching.
195
+ skip_instance_cache: bool
196
+ If this is a cachable implementation, pass True here to force
197
+ creating a new instance even if a matching instance exists, and prevent
198
+ storing this instance.
199
+ asynchronous: bool
200
+ loop: asyncio-compatible IOLoop or None
201
+ """
202
+ if self._cached:
203
+ # reusing instance, don't change
204
+ return
205
+ self._cached = True
206
+ self._intrans = False
207
+ self._transaction = None
208
+ self._invalidated_caches_in_transaction = []
209
+ self.dircache = DirCache(**storage_options)
210
+
211
+ if storage_options.pop("add_docs", None):
212
+ warnings.warn("add_docs is no longer supported.", FutureWarning)
213
+
214
+ if storage_options.pop("add_aliases", None):
215
+ warnings.warn("add_aliases has been removed.", FutureWarning)
216
+ # This is set in _Cached
217
+ self._fs_token_ = None
218
+
219
+ @property
220
+ def fsid(self):
221
+ """Persistent filesystem id that can be used to compare filesystems
222
+ across sessions.
223
+ """
224
+ raise NotImplementedError
225
+
226
+ @property
227
+ def _fs_token(self):
228
+ return self._fs_token_
229
+
230
+ def __dask_tokenize__(self):
231
+ return self._fs_token
232
+
233
+ def __hash__(self):
234
+ return int(self._fs_token, 16)
235
+
236
+ def __eq__(self, other):
237
+ return isinstance(other, type(self)) and self._fs_token == other._fs_token
238
+
239
+ def __reduce__(self):
240
+ return make_instance, (type(self), self.storage_args, self.storage_options)
241
+
242
+ @classmethod
243
+ def _strip_protocol(cls, path):
244
+ """Turn path from fully-qualified to file-system-specific
245
+
246
+ May require FS-specific handling, e.g., for relative paths or links.
247
+ """
248
+ if isinstance(path, list):
249
+ return [cls._strip_protocol(p) for p in path]
250
+ path = stringify_path(path)
251
+ protos = (cls.protocol,) if isinstance(cls.protocol, str) else cls.protocol
252
+ for protocol in protos:
253
+ if path.startswith(protocol + "://"):
254
+ path = path[len(protocol) + 3 :]
255
+ elif path.startswith(protocol + "::"):
256
+ path = path[len(protocol) + 2 :]
257
+ path = path.rstrip("/")
258
+ # use of root_marker to make minimum required path, e.g., "/"
259
+ return path or cls.root_marker
260
+
261
+ def unstrip_protocol(self, name: str) -> str:
262
+ """Format FS-specific path to generic, including protocol"""
263
+ protos = (self.protocol,) if isinstance(self.protocol, str) else self.protocol
264
+ for protocol in protos:
265
+ if name.startswith(f"{protocol}://"):
266
+ return name
267
+ return f"{protos[0]}://{name}"
268
+
269
+ @staticmethod
270
+ def _get_kwargs_from_urls(path):
271
+ """If kwargs can be encoded in the paths, extract them here
272
+
273
+ This should happen before instantiation of the class; incoming paths
274
+ then should be amended to strip the options in methods.
275
+
276
+ Examples may look like an sftp path "sftp://user@host:/my/path", where
277
+ the user and host should become kwargs and later get stripped.
278
+ """
279
+ # by default, nothing happens
280
+ return {}
281
+
282
+ @classmethod
283
+ def current(cls):
284
+ """Return the most recently instantiated FileSystem
285
+
286
+ If no instance has been created, then create one with defaults
287
+ """
288
+ inst = cls._cache.get(cls._latest)
289
+ if inst is not None:
290
+ return inst
291
+ return cls()
292
+
293
+ @property
294
+ def transaction(self):
295
+ """A context within which files are committed together upon exit
296
+
297
+ Requires the file class to implement `.commit()` and `.discard()`
298
+ for the normal and exception cases.
299
+ """
300
+ if self._transaction is None:
301
+ self._transaction = self.transaction_type(self)
302
+ return self._transaction
303
+
304
+ def start_transaction(self):
305
+ """Begin write transaction for deferring files, non-context version"""
306
+ self._intrans = True
307
+ self._transaction = self.transaction_type(self)
308
+ return self.transaction
309
+
310
+ def end_transaction(self):
311
+ """Finish write transaction, non-context version"""
312
+ self.transaction.complete()
313
+ self._transaction = None
314
+ # The invalid cache must be cleared after the transaction is completed.
315
+ for path in self._invalidated_caches_in_transaction:
316
+ self.invalidate_cache(path)
317
+ self._invalidated_caches_in_transaction.clear()
318
+
319
+ def invalidate_cache(self, path=None):
320
+ """
321
+ Discard any cached directory information
322
+
323
+ Parameters
324
+ ----------
325
+ path: string or None
326
+ If None, clear all listings cached else listings at or under given
327
+ path.
328
+ """
329
+ # Not necessary to implement invalidation mechanism, may have no cache.
330
+ # But if have, you should call this method of parent class from your
331
+ # subclass to ensure expiring caches after transacations correctly.
332
+ # See the implementation of FTPFileSystem in ftp.py
333
+ if self._intrans:
334
+ self._invalidated_caches_in_transaction.append(path)
335
+
336
+ def mkdir(self, path, create_parents=True, **kwargs):
337
+ """
338
+ Create directory entry at path
339
+
340
+ For systems that don't have true directories, may create an for
341
+ this instance only and not touch the real filesystem
342
+
343
+ Parameters
344
+ ----------
345
+ path: str
346
+ location
347
+ create_parents: bool
348
+ if True, this is equivalent to ``makedirs``
349
+ kwargs:
350
+ may be permissions, etc.
351
+ """
352
+ pass # not necessary to implement, may not have directories
353
+
354
+ def makedirs(self, path, exist_ok=False):
355
+ """Recursively make directories
356
+
357
+ Creates directory at path and any intervening required directories.
358
+ Raises exception if, for instance, the path already exists but is a
359
+ file.
360
+
361
+ Parameters
362
+ ----------
363
+ path: str
364
+ leaf directory name
365
+ exist_ok: bool (False)
366
+ If False, will error if the target already exists
367
+ """
368
+ pass # not necessary to implement, may not have directories
369
+
370
+ def rmdir(self, path):
371
+ """Remove a directory, if empty"""
372
+ pass # not necessary to implement, may not have directories
373
+
374
+ def ls(self, path, detail=True, **kwargs):
375
+ """List objects at path.
376
+
377
+ This should include subdirectories and files at that location. The
378
+ difference between a file and a directory must be clear when details
379
+ are requested.
380
+
381
+ The specific keys, or perhaps a FileInfo class, or similar, is TBD,
382
+ but must be consistent across implementations.
383
+ Must include:
384
+
385
+ - full path to the entry (without protocol)
386
+ - size of the entry, in bytes. If the value cannot be determined, will
387
+ be ``None``.
388
+ - type of entry, "file", "directory" or other
389
+
390
+ Additional information
391
+ may be present, appropriate to the file-system, e.g., generation,
392
+ checksum, etc.
393
+
394
+ May use refresh=True|False to allow use of self._ls_from_cache to
395
+ check for a saved listing and avoid calling the backend. This would be
396
+ common where listing may be expensive.
397
+
398
+ Parameters
399
+ ----------
400
+ path: str
401
+ detail: bool
402
+ if True, gives a list of dictionaries, where each is the same as
403
+ the result of ``info(path)``. If False, gives a list of paths
404
+ (str).
405
+ kwargs: may have additional backend-specific options, such as version
406
+ information
407
+
408
+ Returns
409
+ -------
410
+ List of strings if detail is False, or list of directory information
411
+ dicts if detail is True.
412
+ """
413
+ raise NotImplementedError
414
+
415
+ def _ls_from_cache(self, path):
416
+ """Check cache for listing
417
+
418
+ Returns listing, if found (may be empty list for a directly that exists
419
+ but contains nothing), None if not in cache.
420
+ """
421
+ parent = self._parent(path)
422
+ try:
423
+ return self.dircache[path.rstrip("/")]
424
+ except KeyError:
425
+ pass
426
+ try:
427
+ files = [
428
+ f
429
+ for f in self.dircache[parent]
430
+ if f["name"] == path
431
+ or (f["name"] == path.rstrip("/") and f["type"] == "directory")
432
+ ]
433
+ if len(files) == 0:
434
+ # parent dir was listed but did not contain this file
435
+ raise FileNotFoundError(path)
436
+ return files
437
+ except KeyError:
438
+ pass
439
+
440
+ def walk(self, path, maxdepth=None, topdown=True, on_error="omit", **kwargs):
441
+ """Return all files under the given path.
442
+
443
+ List all files, recursing into subdirectories; output is iterator-style,
444
+ like ``os.walk()``. For a simple list of files, ``find()`` is available.
445
+
446
+ When topdown is True, the caller can modify the dirnames list in-place (perhaps
447
+ using del or slice assignment), and walk() will
448
+ only recurse into the subdirectories whose names remain in dirnames;
449
+ this can be used to prune the search, impose a specific order of visiting,
450
+ or even to inform walk() about directories the caller creates or renames before
451
+ it resumes walk() again.
452
+ Modifying dirnames when topdown is False has no effect. (see os.walk)
453
+
454
+ Note that the "files" outputted will include anything that is not
455
+ a directory, such as links.
456
+
457
+ Parameters
458
+ ----------
459
+ path: str
460
+ Root to recurse into
461
+ maxdepth: int
462
+ Maximum recursion depth. None means limitless, but not recommended
463
+ on link-based file-systems.
464
+ topdown: bool (True)
465
+ Whether to walk the directory tree from the top downwards or from
466
+ the bottom upwards.
467
+ on_error: "omit", "raise", a callable
468
+ if omit (default), path with exception will simply be empty;
469
+ If raise, an underlying exception will be raised;
470
+ if callable, it will be called with a single OSError instance as argument
471
+ kwargs: passed to ``ls``
472
+ """
473
+ if maxdepth is not None and maxdepth < 1:
474
+ raise ValueError("maxdepth must be at least 1")
475
+
476
+ path = self._strip_protocol(path)
477
+ full_dirs = {}
478
+ dirs = {}
479
+ files = {}
480
+
481
+ detail = kwargs.pop("detail", False)
482
+ try:
483
+ listing = self.ls(path, detail=True, **kwargs)
484
+ except (FileNotFoundError, OSError) as e:
485
+ if on_error == "raise":
486
+ raise
487
+ if callable(on_error):
488
+ on_error(e)
489
+ return
490
+
491
+ for info in listing:
492
+ # each info name must be at least [path]/part , but here
493
+ # we check also for names like [path]/part/
494
+ pathname = info["name"].rstrip("/")
495
+ name = pathname.rsplit("/", 1)[-1]
496
+ if info["type"] == "directory" and pathname != path:
497
+ # do not include "self" path
498
+ full_dirs[name] = pathname
499
+ dirs[name] = info
500
+ elif pathname == path:
501
+ # file-like with same name as give path
502
+ files[""] = info
503
+ else:
504
+ files[name] = info
505
+
506
+ if not detail:
507
+ dirs = list(dirs)
508
+ files = list(files)
509
+
510
+ if topdown:
511
+ # Yield before recursion if walking top down
512
+ yield path, dirs, files
513
+
514
+ if maxdepth is not None:
515
+ maxdepth -= 1
516
+ if maxdepth < 1:
517
+ if not topdown:
518
+ yield path, dirs, files
519
+ return
520
+
521
+ for d in dirs:
522
+ yield from self.walk(
523
+ full_dirs[d],
524
+ maxdepth=maxdepth,
525
+ detail=detail,
526
+ topdown=topdown,
527
+ **kwargs,
528
+ )
529
+
530
+ if not topdown:
531
+ # Yield after recursion if walking bottom up
532
+ yield path, dirs, files
533
+
534
+ def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
535
+ """List all files below path.
536
+
537
+ Like posix ``find`` command without conditions
538
+
539
+ Parameters
540
+ ----------
541
+ path : str
542
+ maxdepth: int or None
543
+ If not None, the maximum number of levels to descend
544
+ withdirs: bool
545
+ Whether to include directory paths in the output. This is True
546
+ when used by glob, but users usually only want files.
547
+ kwargs are passed to ``ls``.
548
+ """
549
+ # TODO: allow equivalent of -name parameter
550
+ path = self._strip_protocol(path)
551
+ out = {}
552
+
553
+ # Add the root directory if withdirs is requested
554
+ # This is needed for posix glob compliance
555
+ if withdirs and path != "" and self.isdir(path):
556
+ out[path] = self.info(path)
557
+
558
+ for _, dirs, files in self.walk(path, maxdepth, detail=True, **kwargs):
559
+ if withdirs:
560
+ files.update(dirs)
561
+ out.update({info["name"]: info for name, info in files.items()})
562
+ if not out and self.isfile(path):
563
+ # walk works on directories, but find should also return [path]
564
+ # when path happens to be a file
565
+ out[path] = {}
566
+ names = sorted(out)
567
+ if not detail:
568
+ return names
569
+ else:
570
+ return {name: out[name] for name in names}
571
+
572
+ def du(self, path, total=True, maxdepth=None, withdirs=False, **kwargs):
573
+ """Space used by files and optionally directories within a path
574
+
575
+ Directory size does not include the size of its contents.
576
+
577
+ Parameters
578
+ ----------
579
+ path: str
580
+ total: bool
581
+ Whether to sum all the file sizes
582
+ maxdepth: int or None
583
+ Maximum number of directory levels to descend, None for unlimited.
584
+ withdirs: bool
585
+ Whether to include directory paths in the output.
586
+ kwargs: passed to ``find``
587
+
588
+ Returns
589
+ -------
590
+ Dict of {path: size} if total=False, or int otherwise, where numbers
591
+ refer to bytes used.
592
+ """
593
+ sizes = {}
594
+ if withdirs and self.isdir(path):
595
+ # Include top-level directory in output
596
+ info = self.info(path)
597
+ sizes[info["name"]] = info["size"]
598
+ for f in self.find(path, maxdepth=maxdepth, withdirs=withdirs, **kwargs):
599
+ info = self.info(f)
600
+ sizes[info["name"]] = info["size"]
601
+ if total:
602
+ return sum(sizes.values())
603
+ else:
604
+ return sizes
605
+
606
+ def glob(self, path, maxdepth=None, **kwargs):
607
+ """Find files by glob-matching.
608
+
609
+ Pattern matching capabilities for finding files that match the given pattern.
610
+
611
+ Parameters
612
+ ----------
613
+ path: str
614
+ The glob pattern to match against
615
+ maxdepth: int or None
616
+ Maximum depth for ``'**'`` patterns. Applied on the first ``'**'`` found.
617
+ Must be at least 1 if provided.
618
+ kwargs:
619
+ Additional arguments passed to ``find`` (e.g., detail=True)
620
+
621
+ Returns
622
+ -------
623
+ List of matched paths, or dict of paths and their info if detail=True
624
+
625
+ Notes
626
+ -----
627
+ Supported patterns:
628
+ - '*': Matches any sequence of characters within a single directory level
629
+ - ``'**'``: Matches any number of directory levels (must be an entire path component)
630
+ - '?': Matches exactly one character
631
+ - '[abc]': Matches any character in the set
632
+ - '[a-z]': Matches any character in the range
633
+ - '[!abc]': Matches any character NOT in the set
634
+
635
+ Special behaviors:
636
+ - If the path ends with '/', only folders are returned
637
+ - Consecutive '*' characters are compressed into a single '*'
638
+ - Empty set '[]' or negated empty negated set '[!]' never match anything
639
+ - Special characters in character classes are escaped properly
640
+
641
+ Limitations:
642
+ - ``'**'`` must be a complete path component (e.g., ``'a/**/b'``, not ``'a**b'``)
643
+ - No brace expansion ('{a,b}.txt')
644
+ - No extended glob patterns ('+(pattern)', '!(pattern)')
645
+ """
646
+ if maxdepth is not None and maxdepth < 1:
647
+ raise ValueError("maxdepth must be at least 1")
648
+
649
+ import re
650
+
651
+ seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,)
652
+ ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash
653
+ path = self._strip_protocol(path)
654
+ append_slash_to_dirname = ends_with_sep or path.endswith(
655
+ tuple(sep + "**" for sep in seps)
656
+ )
657
+ idx_star = path.find("*") if path.find("*") >= 0 else len(path)
658
+ idx_qmark = path.find("?") if path.find("?") >= 0 else len(path)
659
+ idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
660
+
661
+ min_idx = min(idx_star, idx_qmark, idx_brace)
662
+
663
+ detail = kwargs.pop("detail", False)
664
+ withdirs = kwargs.pop("withdirs", True)
665
+
666
+ if not has_magic(path):
667
+ if self.exists(path, **kwargs):
668
+ if not detail:
669
+ return [path]
670
+ else:
671
+ return {path: self.info(path, **kwargs)}
672
+ else:
673
+ if not detail:
674
+ return [] # glob of non-existent returns empty
675
+ else:
676
+ return {}
677
+ elif "/" in path[:min_idx]:
678
+ min_idx = path[:min_idx].rindex("/")
679
+ root = path[: min_idx + 1]
680
+ depth = path[min_idx + 1 :].count("/") + 1
681
+ else:
682
+ root = ""
683
+ depth = path[min_idx + 1 :].count("/") + 1
684
+
685
+ if "**" in path:
686
+ if maxdepth is not None:
687
+ idx_double_stars = path.find("**")
688
+ depth_double_stars = path[idx_double_stars:].count("/") + 1
689
+ depth = depth - depth_double_stars + maxdepth
690
+ else:
691
+ depth = None
692
+
693
+ allpaths = self.find(
694
+ root, maxdepth=depth, withdirs=withdirs, detail=True, **kwargs
695
+ )
696
+
697
+ pattern = glob_translate(path + ("/" if ends_with_sep else ""))
698
+ pattern = re.compile(pattern)
699
+
700
+ out = {
701
+ p: info
702
+ for p, info in sorted(allpaths.items())
703
+ if pattern.match(
704
+ p + "/"
705
+ if append_slash_to_dirname and info["type"] == "directory"
706
+ else p
707
+ )
708
+ }
709
+
710
+ if detail:
711
+ return out
712
+ else:
713
+ return list(out)
714
+
715
+ def exists(self, path, **kwargs):
716
+ """Is there a file at the given path"""
717
+ try:
718
+ self.info(path, **kwargs)
719
+ return True
720
+ except: # noqa: E722
721
+ # any exception allowed bar FileNotFoundError?
722
+ return False
723
+
724
+ def lexists(self, path, **kwargs):
725
+ """If there is a file at the given path (including
726
+ broken links)"""
727
+ return self.exists(path)
728
+
729
+ def info(self, path, **kwargs):
730
+ """Give details of entry at path
731
+
732
+ Returns a single dictionary, with exactly the same information as ``ls``
733
+ would with ``detail=True``.
734
+
735
+ The default implementation calls ls and could be overridden by a
736
+ shortcut. kwargs are passed on to ```ls()``.
737
+
738
+ Some file systems might not be able to measure the file's size, in
739
+ which case, the returned dict will include ``'size': None``.
740
+
741
+ Returns
742
+ -------
743
+ dict with keys: name (full path in the FS), size (in bytes), type (file,
744
+ directory, or something else) and other FS-specific keys.
745
+ """
746
+ path = self._strip_protocol(path)
747
+ out = self.ls(self._parent(path), detail=True, **kwargs)
748
+ out = [o for o in out if o["name"].rstrip("/") == path]
749
+ if out:
750
+ return out[0]
751
+ out = self.ls(path, detail=True, **kwargs)
752
+ path = path.rstrip("/")
753
+ out1 = [o for o in out if o["name"].rstrip("/") == path]
754
+ if len(out1) == 1:
755
+ if "size" not in out1[0]:
756
+ out1[0]["size"] = None
757
+ return out1[0]
758
+ elif len(out1) > 1 or out:
759
+ return {"name": path, "size": 0, "type": "directory"}
760
+ else:
761
+ raise FileNotFoundError(path)
762
+
763
+ def checksum(self, path):
764
+ """Unique value for current version of file
765
+
766
+ If the checksum is the same from one moment to another, the contents
767
+ are guaranteed to be the same. If the checksum changes, the contents
768
+ *might* have changed.
769
+
770
+ This should normally be overridden; default will probably capture
771
+ creation/modification timestamp (which would be good) or maybe
772
+ access timestamp (which would be bad)
773
+ """
774
+ return int(tokenize(self.info(path)), 16)
775
+
776
+ def size(self, path):
777
+ """Size in bytes of file"""
778
+ return self.info(path).get("size", None)
779
+
780
+ def sizes(self, paths):
781
+ """Size in bytes of each file in a list of paths"""
782
+ return [self.size(p) for p in paths]
783
+
784
+ def isdir(self, path):
785
+ """Is this entry directory-like?"""
786
+ try:
787
+ return self.info(path)["type"] == "directory"
788
+ except OSError:
789
+ return False
790
+
791
+ def isfile(self, path):
792
+ """Is this entry file-like?"""
793
+ try:
794
+ return self.info(path)["type"] == "file"
795
+ except: # noqa: E722
796
+ return False
797
+
798
+ def read_text(self, path, encoding=None, errors=None, newline=None, **kwargs):
799
+ """Get the contents of the file as a string.
800
+
801
+ Parameters
802
+ ----------
803
+ path: str
804
+ URL of file on this filesystems
805
+ encoding, errors, newline: same as `open`.
806
+ """
807
+ with self.open(
808
+ path,
809
+ mode="r",
810
+ encoding=encoding,
811
+ errors=errors,
812
+ newline=newline,
813
+ **kwargs,
814
+ ) as f:
815
+ return f.read()
816
+
817
+ def write_text(
818
+ self, path, value, encoding=None, errors=None, newline=None, **kwargs
819
+ ):
820
+ """Write the text to the given file.
821
+
822
+ An existing file will be overwritten.
823
+
824
+ Parameters
825
+ ----------
826
+ path: str
827
+ URL of file on this filesystems
828
+ value: str
829
+ Text to write.
830
+ encoding, errors, newline: same as `open`.
831
+ """
832
+ with self.open(
833
+ path,
834
+ mode="w",
835
+ encoding=encoding,
836
+ errors=errors,
837
+ newline=newline,
838
+ **kwargs,
839
+ ) as f:
840
+ return f.write(value)
841
+
842
+ def cat_file(self, path, start=None, end=None, **kwargs):
843
+ """Get the content of a file
844
+
845
+ Parameters
846
+ ----------
847
+ path: URL of file on this filesystems
848
+ start, end: int
849
+ Bytes limits of the read. If negative, backwards from end,
850
+ like usual python slices. Either can be None for start or
851
+ end of file, respectively
852
+ kwargs: passed to ``open()``.
853
+ """
854
+ # explicitly set buffering off?
855
+ with self.open(path, "rb", **kwargs) as f:
856
+ if start is not None:
857
+ if start >= 0:
858
+ f.seek(start)
859
+ else:
860
+ f.seek(max(0, f.size + start))
861
+ if end is not None:
862
+ if end < 0:
863
+ end = f.size + end
864
+ return f.read(end - f.tell())
865
+ return f.read()
866
+
867
+ def pipe_file(self, path, value, mode="overwrite", **kwargs):
868
+ """Set the bytes of given file"""
869
+ if mode == "create" and self.exists(path):
870
+ # non-atomic but simple way; or could use "xb" in open(), which is likely
871
+ # not as well supported
872
+ raise FileExistsError
873
+ with self.open(path, "wb", **kwargs) as f:
874
+ f.write(value)
875
+
876
+ def pipe(self, path, value=None, **kwargs):
877
+ """Put value into path
878
+
879
+ (counterpart to ``cat``)
880
+
881
+ Parameters
882
+ ----------
883
+ path: string or dict(str, bytes)
884
+ If a string, a single remote location to put ``value`` bytes; if a dict,
885
+ a mapping of {path: bytesvalue}.
886
+ value: bytes, optional
887
+ If using a single path, these are the bytes to put there. Ignored if
888
+ ``path`` is a dict
889
+ """
890
+ if isinstance(path, str):
891
+ self.pipe_file(self._strip_protocol(path), value, **kwargs)
892
+ elif isinstance(path, dict):
893
+ for k, v in path.items():
894
+ self.pipe_file(self._strip_protocol(k), v, **kwargs)
895
+ else:
896
+ raise ValueError("path must be str or dict")
897
+
898
+ def cat_ranges(
899
+ self, paths, starts, ends, max_gap=None, on_error="return", **kwargs
900
+ ):
901
+ """Get the contents of byte ranges from one or more files
902
+
903
+ Parameters
904
+ ----------
905
+ paths: list
906
+ A list of of filepaths on this filesystems
907
+ starts, ends: int or list
908
+ Bytes limits of the read. If using a single int, the same value will be
909
+ used to read all the specified files.
910
+ """
911
+ if max_gap is not None:
912
+ raise NotImplementedError
913
+ if not isinstance(paths, list):
914
+ raise TypeError
915
+ if not isinstance(starts, list):
916
+ starts = [starts] * len(paths)
917
+ if not isinstance(ends, list):
918
+ ends = [ends] * len(paths)
919
+ if len(starts) != len(paths) or len(ends) != len(paths):
920
+ raise ValueError
921
+ out = []
922
+ for p, s, e in zip(paths, starts, ends):
923
+ try:
924
+ out.append(self.cat_file(p, s, e, **kwargs))
925
+ except Exception as e:
926
+ if on_error == "return":
927
+ out.append(e)
928
+ else:
929
+ raise
930
+ return out
931
+
932
+ def cat(self, path, recursive=False, on_error="raise", **kwargs):
933
+ """Fetch (potentially multiple) paths' contents
934
+
935
+ Parameters
936
+ ----------
937
+ recursive: bool
938
+ If True, assume the path(s) are directories, and get all the
939
+ contained files
940
+ on_error : "raise", "omit", "return"
941
+ If raise, an underlying exception will be raised (converted to KeyError
942
+ if the type is in self.missing_exceptions); if omit, keys with exception
943
+ will simply not be included in the output; if "return", all keys are
944
+ included in the output, but the value will be bytes or an exception
945
+ instance.
946
+ kwargs: passed to cat_file
947
+
948
+ Returns
949
+ -------
950
+ dict of {path: contents} if there are multiple paths
951
+ or the path has been otherwise expanded
952
+ """
953
+ paths = self.expand_path(path, recursive=recursive, **kwargs)
954
+ if (
955
+ len(paths) > 1
956
+ or isinstance(path, list)
957
+ or paths[0] != self._strip_protocol(path)
958
+ ):
959
+ out = {}
960
+ for path in paths:
961
+ try:
962
+ out[path] = self.cat_file(path, **kwargs)
963
+ except Exception as e:
964
+ if on_error == "raise":
965
+ raise
966
+ if on_error == "return":
967
+ out[path] = e
968
+ return out
969
+ else:
970
+ return self.cat_file(paths[0], **kwargs)
971
+
972
+ def get_file(self, rpath, lpath, callback=DEFAULT_CALLBACK, outfile=None, **kwargs):
973
+ """Copy single remote file to local"""
974
+ from .implementations.local import LocalFileSystem
975
+
976
+ if isfilelike(lpath):
977
+ outfile = lpath
978
+ elif self.isdir(rpath):
979
+ os.makedirs(lpath, exist_ok=True)
980
+ return None
981
+
982
+ fs = LocalFileSystem(auto_mkdir=True)
983
+ fs.makedirs(fs._parent(lpath), exist_ok=True)
984
+
985
+ with self.open(rpath, "rb", **kwargs) as f1:
986
+ if outfile is None:
987
+ outfile = open(lpath, "wb")
988
+
989
+ try:
990
+ callback.set_size(getattr(f1, "size", None))
991
+ data = True
992
+ while data:
993
+ data = f1.read(self.blocksize)
994
+ segment_len = outfile.write(data)
995
+ if segment_len is None:
996
+ segment_len = len(data)
997
+ callback.relative_update(segment_len)
998
+ finally:
999
+ if not isfilelike(lpath):
1000
+ outfile.close()
1001
+
1002
+ def get(
1003
+ self,
1004
+ rpath,
1005
+ lpath,
1006
+ recursive=False,
1007
+ callback=DEFAULT_CALLBACK,
1008
+ maxdepth=None,
1009
+ **kwargs,
1010
+ ):
1011
+ """Copy file(s) to local.
1012
+
1013
+ Copies a specific file or tree of files (if recursive=True). If lpath
1014
+ ends with a "/", it will be assumed to be a directory, and target files
1015
+ will go within. Can submit a list of paths, which may be glob-patterns
1016
+ and will be expanded.
1017
+
1018
+ Calls get_file for each source.
1019
+ """
1020
+ if isinstance(lpath, list) and isinstance(rpath, list):
1021
+ # No need to expand paths when both source and destination
1022
+ # are provided as lists
1023
+ rpaths = rpath
1024
+ lpaths = lpath
1025
+ else:
1026
+ from .implementations.local import (
1027
+ LocalFileSystem,
1028
+ make_path_posix,
1029
+ trailing_sep,
1030
+ )
1031
+
1032
+ source_is_str = isinstance(rpath, str)
1033
+ rpaths = self.expand_path(
1034
+ rpath, recursive=recursive, maxdepth=maxdepth, **kwargs
1035
+ )
1036
+ if source_is_str and (not recursive or maxdepth is not None):
1037
+ # Non-recursive glob does not copy directories
1038
+ rpaths = [p for p in rpaths if not (trailing_sep(p) or self.isdir(p))]
1039
+ if not rpaths:
1040
+ return
1041
+
1042
+ if isinstance(lpath, str):
1043
+ lpath = make_path_posix(lpath)
1044
+
1045
+ source_is_file = len(rpaths) == 1
1046
+ dest_is_dir = isinstance(lpath, str) and (
1047
+ trailing_sep(lpath) or LocalFileSystem().isdir(lpath)
1048
+ )
1049
+
1050
+ exists = source_is_str and (
1051
+ (has_magic(rpath) and source_is_file)
1052
+ or (not has_magic(rpath) and dest_is_dir and not trailing_sep(rpath))
1053
+ )
1054
+ lpaths = other_paths(
1055
+ rpaths,
1056
+ lpath,
1057
+ exists=exists,
1058
+ flatten=not source_is_str,
1059
+ )
1060
+
1061
+ callback.set_size(len(lpaths))
1062
+ for lpath, rpath in callback.wrap(zip(lpaths, rpaths)):
1063
+ with callback.branched(rpath, lpath) as child:
1064
+ self.get_file(rpath, lpath, callback=child, **kwargs)
1065
+
1066
+ def put_file(
1067
+ self, lpath, rpath, callback=DEFAULT_CALLBACK, mode="overwrite", **kwargs
1068
+ ):
1069
+ """Copy single file to remote"""
1070
+ if mode == "create" and self.exists(rpath):
1071
+ raise FileExistsError
1072
+ if os.path.isdir(lpath):
1073
+ self.makedirs(rpath, exist_ok=True)
1074
+ return None
1075
+
1076
+ with open(lpath, "rb") as f1:
1077
+ size = f1.seek(0, 2)
1078
+ callback.set_size(size)
1079
+ f1.seek(0)
1080
+
1081
+ self.mkdirs(self._parent(os.fspath(rpath)), exist_ok=True)
1082
+ with self.open(rpath, "wb", **kwargs) as f2:
1083
+ while f1.tell() < size:
1084
+ data = f1.read(self.blocksize)
1085
+ segment_len = f2.write(data)
1086
+ if segment_len is None:
1087
+ segment_len = len(data)
1088
+ callback.relative_update(segment_len)
1089
+
1090
+ def put(
1091
+ self,
1092
+ lpath,
1093
+ rpath,
1094
+ recursive=False,
1095
+ callback=DEFAULT_CALLBACK,
1096
+ maxdepth=None,
1097
+ **kwargs,
1098
+ ):
1099
+ """Copy file(s) from local.
1100
+
1101
+ Copies a specific file or tree of files (if recursive=True). If rpath
1102
+ ends with a "/", it will be assumed to be a directory, and target files
1103
+ will go within.
1104
+
1105
+ Calls put_file for each source.
1106
+ """
1107
+ if isinstance(lpath, list) and isinstance(rpath, list):
1108
+ # No need to expand paths when both source and destination
1109
+ # are provided as lists
1110
+ rpaths = rpath
1111
+ lpaths = lpath
1112
+ else:
1113
+ from .implementations.local import (
1114
+ LocalFileSystem,
1115
+ make_path_posix,
1116
+ trailing_sep,
1117
+ )
1118
+
1119
+ source_is_str = isinstance(lpath, str)
1120
+ if source_is_str:
1121
+ lpath = make_path_posix(lpath)
1122
+ fs = LocalFileSystem()
1123
+ lpaths = fs.expand_path(
1124
+ lpath, recursive=recursive, maxdepth=maxdepth, **kwargs
1125
+ )
1126
+ if source_is_str and (not recursive or maxdepth is not None):
1127
+ # Non-recursive glob does not copy directories
1128
+ lpaths = [p for p in lpaths if not (trailing_sep(p) or fs.isdir(p))]
1129
+ if not lpaths:
1130
+ return
1131
+
1132
+ source_is_file = len(lpaths) == 1
1133
+ dest_is_dir = isinstance(rpath, str) and (
1134
+ trailing_sep(rpath) or self.isdir(rpath)
1135
+ )
1136
+
1137
+ rpath = (
1138
+ self._strip_protocol(rpath)
1139
+ if isinstance(rpath, str)
1140
+ else [self._strip_protocol(p) for p in rpath]
1141
+ )
1142
+ exists = source_is_str and (
1143
+ (has_magic(lpath) and source_is_file)
1144
+ or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath))
1145
+ )
1146
+ rpaths = other_paths(
1147
+ lpaths,
1148
+ rpath,
1149
+ exists=exists,
1150
+ flatten=not source_is_str,
1151
+ )
1152
+
1153
+ callback.set_size(len(rpaths))
1154
+ for lpath, rpath in callback.wrap(zip(lpaths, rpaths)):
1155
+ with callback.branched(lpath, rpath) as child:
1156
+ self.put_file(lpath, rpath, callback=child, **kwargs)
1157
+
1158
+ def head(self, path, size=1024):
1159
+ """Get the first ``size`` bytes from file"""
1160
+ with self.open(path, "rb") as f:
1161
+ return f.read(size)
1162
+
1163
+ def tail(self, path, size=1024):
1164
+ """Get the last ``size`` bytes from file"""
1165
+ with self.open(path, "rb") as f:
1166
+ f.seek(max(-size, -f.size), 2)
1167
+ return f.read()
1168
+
1169
+ def cp_file(self, path1, path2, **kwargs):
1170
+ raise NotImplementedError
1171
+
1172
+ def copy(
1173
+ self, path1, path2, recursive=False, maxdepth=None, on_error=None, **kwargs
1174
+ ):
1175
+ """Copy within two locations in the filesystem
1176
+
1177
+ on_error : "raise", "ignore"
1178
+ If raise, any not-found exceptions will be raised; if ignore any
1179
+ not-found exceptions will cause the path to be skipped; defaults to
1180
+ raise unless recursive is true, where the default is ignore
1181
+ """
1182
+ if on_error is None and recursive:
1183
+ on_error = "ignore"
1184
+ elif on_error is None:
1185
+ on_error = "raise"
1186
+
1187
+ if isinstance(path1, list) and isinstance(path2, list):
1188
+ # No need to expand paths when both source and destination
1189
+ # are provided as lists
1190
+ paths1 = path1
1191
+ paths2 = path2
1192
+ else:
1193
+ from .implementations.local import trailing_sep
1194
+
1195
+ source_is_str = isinstance(path1, str)
1196
+ paths1 = self.expand_path(
1197
+ path1, recursive=recursive, maxdepth=maxdepth, **kwargs
1198
+ )
1199
+ if source_is_str and (not recursive or maxdepth is not None):
1200
+ # Non-recursive glob does not copy directories
1201
+ paths1 = [p for p in paths1 if not (trailing_sep(p) or self.isdir(p))]
1202
+ if not paths1:
1203
+ return
1204
+
1205
+ source_is_file = len(paths1) == 1
1206
+ dest_is_dir = isinstance(path2, str) and (
1207
+ trailing_sep(path2) or self.isdir(path2)
1208
+ )
1209
+
1210
+ exists = source_is_str and (
1211
+ (has_magic(path1) and source_is_file)
1212
+ or (not has_magic(path1) and dest_is_dir and not trailing_sep(path1))
1213
+ )
1214
+ paths2 = other_paths(
1215
+ paths1,
1216
+ path2,
1217
+ exists=exists,
1218
+ flatten=not source_is_str,
1219
+ )
1220
+
1221
+ for p1, p2 in zip(paths1, paths2):
1222
+ try:
1223
+ self.cp_file(p1, p2, **kwargs)
1224
+ except FileNotFoundError:
1225
+ if on_error == "raise":
1226
+ raise
1227
+
1228
+ def expand_path(
1229
+ self, path, recursive=False, maxdepth=None, assume_literal=False, **kwargs
1230
+ ):
1231
+ """Turn one or more globs or directories into a list of all matching paths
1232
+ to files or directories.
1233
+
1234
+ kwargs are passed to ``glob`` or ``find``, which may in turn call ``ls``
1235
+ """
1236
+
1237
+ if maxdepth is not None and maxdepth < 1:
1238
+ raise ValueError("maxdepth must be at least 1")
1239
+
1240
+ if isinstance(path, (str, os.PathLike)):
1241
+ out = self.expand_path([path], recursive, maxdepth, **kwargs)
1242
+ else:
1243
+ out = set()
1244
+ path = [self._strip_protocol(p) for p in path]
1245
+ for p in path:
1246
+ if not assume_literal and has_magic(p):
1247
+ bit = set(self.glob(p, maxdepth=maxdepth, **kwargs))
1248
+ out |= bit
1249
+ if recursive:
1250
+ # glob call above expanded one depth so if maxdepth is defined
1251
+ # then decrement it in expand_path call below. If it is zero
1252
+ # after decrementing then avoid expand_path call.
1253
+ if maxdepth is not None and maxdepth <= 1:
1254
+ continue
1255
+ out |= set(
1256
+ self.expand_path(
1257
+ list(bit),
1258
+ recursive=recursive,
1259
+ maxdepth=maxdepth - 1 if maxdepth is not None else None,
1260
+ assume_literal=True,
1261
+ **kwargs,
1262
+ )
1263
+ )
1264
+ continue
1265
+ elif recursive:
1266
+ rec = set(
1267
+ self.find(
1268
+ p, maxdepth=maxdepth, withdirs=True, detail=False, **kwargs
1269
+ )
1270
+ )
1271
+ out |= rec
1272
+ if p not in out and (recursive is False or self.exists(p)):
1273
+ # should only check once, for the root
1274
+ out.add(p)
1275
+ if not out:
1276
+ raise FileNotFoundError(path)
1277
+ return sorted(out)
1278
+
1279
+ def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs):
1280
+ """Move file(s) from one location to another"""
1281
+ if path1 == path2:
1282
+ logger.debug("%s mv: The paths are the same, so no files were moved.", self)
1283
+ else:
1284
+ # explicitly raise exception to prevent data corruption
1285
+ self.copy(
1286
+ path1, path2, recursive=recursive, maxdepth=maxdepth, on_error="raise"
1287
+ )
1288
+ self.rm(path1, recursive=recursive)
1289
+
1290
+ def rm_file(self, path):
1291
+ """Delete a file"""
1292
+ self._rm(path)
1293
+
1294
+ def _rm(self, path):
1295
+ """Delete one file"""
1296
+ # this is the old name for the method, prefer rm_file
1297
+ raise NotImplementedError
1298
+
1299
+ def rm(self, path, recursive=False, maxdepth=None):
1300
+ """Delete files.
1301
+
1302
+ Parameters
1303
+ ----------
1304
+ path: str or list of str
1305
+ File(s) to delete.
1306
+ recursive: bool
1307
+ If file(s) are directories, recursively delete contents and then
1308
+ also remove the directory
1309
+ maxdepth: int or None
1310
+ Depth to pass to walk for finding files to delete, if recursive.
1311
+ If None, there will be no limit and infinite recursion may be
1312
+ possible.
1313
+ """
1314
+ path = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
1315
+ for p in reversed(path):
1316
+ self.rm_file(p)
1317
+
1318
+ @classmethod
1319
+ def _parent(cls, path):
1320
+ path = cls._strip_protocol(path)
1321
+ if "/" in path:
1322
+ parent = path.rsplit("/", 1)[0].lstrip(cls.root_marker)
1323
+ return cls.root_marker + parent
1324
+ else:
1325
+ return cls.root_marker
1326
+
1327
+ def _open(
1328
+ self,
1329
+ path,
1330
+ mode="rb",
1331
+ block_size=None,
1332
+ autocommit=True,
1333
+ cache_options=None,
1334
+ **kwargs,
1335
+ ):
1336
+ """Return raw bytes-mode file-like from the file-system"""
1337
+ return AbstractBufferedFile(
1338
+ self,
1339
+ path,
1340
+ mode,
1341
+ block_size,
1342
+ autocommit,
1343
+ cache_options=cache_options,
1344
+ **kwargs,
1345
+ )
1346
+
1347
+ def open(
1348
+ self,
1349
+ path,
1350
+ mode="rb",
1351
+ block_size=None,
1352
+ cache_options=None,
1353
+ compression=None,
1354
+ **kwargs,
1355
+ ):
1356
+ """
1357
+ Return a file-like object from the filesystem
1358
+
1359
+ The resultant instance must function correctly in a context ``with``
1360
+ block.
1361
+
1362
+ Parameters
1363
+ ----------
1364
+ path: str
1365
+ Target file
1366
+ mode: str like 'rb', 'w'
1367
+ See builtin ``open()``
1368
+ Mode "x" (exclusive write) may be implemented by the backend. Even if
1369
+ it is, whether it is checked up front or on commit, and whether it is
1370
+ atomic is implementation-dependent.
1371
+ block_size: int
1372
+ Some indication of buffering - this is a value in bytes
1373
+ cache_options : dict, optional
1374
+ Extra arguments to pass through to the cache.
1375
+ compression: string or None
1376
+ If given, open file using compression codec. Can either be a compression
1377
+ name (a key in ``fsspec.compression.compr``) or "infer" to guess the
1378
+ compression from the filename suffix.
1379
+ encoding, errors, newline: passed on to TextIOWrapper for text mode
1380
+ """
1381
+ import io
1382
+
1383
+ path = self._strip_protocol(path)
1384
+ if "b" not in mode:
1385
+ mode = mode.replace("t", "") + "b"
1386
+
1387
+ text_kwargs = {
1388
+ k: kwargs.pop(k)
1389
+ for k in ["encoding", "errors", "newline"]
1390
+ if k in kwargs
1391
+ }
1392
+ return io.TextIOWrapper(
1393
+ self.open(
1394
+ path,
1395
+ mode,
1396
+ block_size=block_size,
1397
+ cache_options=cache_options,
1398
+ compression=compression,
1399
+ **kwargs,
1400
+ ),
1401
+ **text_kwargs,
1402
+ )
1403
+ else:
1404
+ ac = kwargs.pop("autocommit", not self._intrans)
1405
+ f = self._open(
1406
+ path,
1407
+ mode=mode,
1408
+ block_size=block_size,
1409
+ autocommit=ac,
1410
+ cache_options=cache_options,
1411
+ **kwargs,
1412
+ )
1413
+ if compression is not None:
1414
+ from fsspec.compression import compr
1415
+ from fsspec.core import get_compression
1416
+
1417
+ compression = get_compression(path, compression)
1418
+ compress = compr[compression]
1419
+ f = compress(f, mode=mode[0])
1420
+
1421
+ if not ac and "r" not in mode:
1422
+ self.transaction.files.append(f)
1423
+ return f
1424
+
1425
+ def touch(self, path, truncate=True, **kwargs):
1426
+ """Create empty file, or update timestamp
1427
+
1428
+ Parameters
1429
+ ----------
1430
+ path: str
1431
+ file location
1432
+ truncate: bool
1433
+ If True, always set file size to 0; if False, update timestamp and
1434
+ leave file unchanged, if backend allows this
1435
+ """
1436
+ if truncate or not self.exists(path):
1437
+ with self.open(path, "wb", **kwargs):
1438
+ pass
1439
+ else:
1440
+ raise NotImplementedError # update timestamp, if possible
1441
+
1442
+ def ukey(self, path):
1443
+ """Hash of file properties, to tell if it has changed"""
1444
+ return sha256(str(self.info(path)).encode()).hexdigest()
1445
+
1446
+ def read_block(self, fn, offset, length, delimiter=None):
1447
+ """Read a block of bytes from
1448
+
1449
+ Starting at ``offset`` of the file, read ``length`` bytes. If
1450
+ ``delimiter`` is set then we ensure that the read starts and stops at
1451
+ delimiter boundaries that follow the locations ``offset`` and ``offset
1452
+ + length``. If ``offset`` is zero then we start at zero. The
1453
+ bytestring returned WILL include the end delimiter string.
1454
+
1455
+ If offset+length is beyond the eof, reads to eof.
1456
+
1457
+ Parameters
1458
+ ----------
1459
+ fn: string
1460
+ Path to filename
1461
+ offset: int
1462
+ Byte offset to start read
1463
+ length: int
1464
+ Number of bytes to read. If None, read to end.
1465
+ delimiter: bytes (optional)
1466
+ Ensure reading starts and stops at delimiter bytestring
1467
+
1468
+ Examples
1469
+ --------
1470
+ >>> fs.read_block('data/file.csv', 0, 13) # doctest: +SKIP
1471
+ b'Alice, 100\\nBo'
1472
+ >>> fs.read_block('data/file.csv', 0, 13, delimiter=b'\\n') # doctest: +SKIP
1473
+ b'Alice, 100\\nBob, 200\\n'
1474
+
1475
+ Use ``length=None`` to read to the end of the file.
1476
+ >>> fs.read_block('data/file.csv', 0, None, delimiter=b'\\n') # doctest: +SKIP
1477
+ b'Alice, 100\\nBob, 200\\nCharlie, 300'
1478
+
1479
+ See Also
1480
+ --------
1481
+ :func:`fsspec.utils.read_block`
1482
+ """
1483
+ with self.open(fn, "rb") as f:
1484
+ size = f.size
1485
+ if length is None:
1486
+ length = size
1487
+ if size is not None and offset + length > size:
1488
+ length = size - offset
1489
+ return read_block(f, offset, length, delimiter)
1490
+
1491
+ def to_json(self, *, include_password: bool = True) -> str:
1492
+ """
1493
+ JSON representation of this filesystem instance.
1494
+
1495
+ Parameters
1496
+ ----------
1497
+ include_password: bool, default True
1498
+ Whether to include the password (if any) in the output.
1499
+
1500
+ Returns
1501
+ -------
1502
+ JSON string with keys ``cls`` (the python location of this class),
1503
+ protocol (text name of this class's protocol, first one in case of
1504
+ multiple), ``args`` (positional args, usually empty), and all other
1505
+ keyword arguments as their own keys.
1506
+
1507
+ Warnings
1508
+ --------
1509
+ Serialized filesystems may contain sensitive information which have been
1510
+ passed to the constructor, such as passwords and tokens. Make sure you
1511
+ store and send them in a secure environment!
1512
+ """
1513
+ from .json import FilesystemJSONEncoder
1514
+
1515
+ return json.dumps(
1516
+ self,
1517
+ cls=type(
1518
+ "_FilesystemJSONEncoder",
1519
+ (FilesystemJSONEncoder,),
1520
+ {"include_password": include_password},
1521
+ ),
1522
+ )
1523
+
1524
+ @staticmethod
1525
+ def from_json(blob: str) -> AbstractFileSystem:
1526
+ """
1527
+ Recreate a filesystem instance from JSON representation.
1528
+
1529
+ See ``.to_json()`` for the expected structure of the input.
1530
+
1531
+ Parameters
1532
+ ----------
1533
+ blob: str
1534
+
1535
+ Returns
1536
+ -------
1537
+ file system instance, not necessarily of this particular class.
1538
+
1539
+ Warnings
1540
+ --------
1541
+ This can import arbitrary modules (as determined by the ``cls`` key).
1542
+ Make sure you haven't installed any modules that may execute malicious code
1543
+ at import time.
1544
+ """
1545
+ from .json import FilesystemJSONDecoder
1546
+
1547
+ return json.loads(blob, cls=FilesystemJSONDecoder)
1548
+
1549
+ def to_dict(self, *, include_password: bool = True) -> dict[str, Any]:
1550
+ """
1551
+ JSON-serializable dictionary representation of this filesystem instance.
1552
+
1553
+ Parameters
1554
+ ----------
1555
+ include_password: bool, default True
1556
+ Whether to include the password (if any) in the output.
1557
+
1558
+ Returns
1559
+ -------
1560
+ Dictionary with keys ``cls`` (the python location of this class),
1561
+ protocol (text name of this class's protocol, first one in case of
1562
+ multiple), ``args`` (positional args, usually empty), and all other
1563
+ keyword arguments as their own keys.
1564
+
1565
+ Warnings
1566
+ --------
1567
+ Serialized filesystems may contain sensitive information which have been
1568
+ passed to the constructor, such as passwords and tokens. Make sure you
1569
+ store and send them in a secure environment!
1570
+ """
1571
+ from .json import FilesystemJSONEncoder
1572
+
1573
+ json_encoder = FilesystemJSONEncoder()
1574
+
1575
+ cls = type(self)
1576
+ proto = self.protocol
1577
+
1578
+ storage_options = dict(self.storage_options)
1579
+ if not include_password:
1580
+ storage_options.pop("password", None)
1581
+
1582
+ return dict(
1583
+ cls=f"{cls.__module__}:{cls.__name__}",
1584
+ protocol=proto[0] if isinstance(proto, (tuple, list)) else proto,
1585
+ args=json_encoder.make_serializable(self.storage_args),
1586
+ **json_encoder.make_serializable(storage_options),
1587
+ )
1588
+
1589
+ @staticmethod
1590
+ def from_dict(dct: dict[str, Any]) -> AbstractFileSystem:
1591
+ """
1592
+ Recreate a filesystem instance from dictionary representation.
1593
+
1594
+ See ``.to_dict()`` for the expected structure of the input.
1595
+
1596
+ Parameters
1597
+ ----------
1598
+ dct: Dict[str, Any]
1599
+
1600
+ Returns
1601
+ -------
1602
+ file system instance, not necessarily of this particular class.
1603
+
1604
+ Warnings
1605
+ --------
1606
+ This can import arbitrary modules (as determined by the ``cls`` key).
1607
+ Make sure you haven't installed any modules that may execute malicious code
1608
+ at import time.
1609
+ """
1610
+ from .json import FilesystemJSONDecoder
1611
+
1612
+ json_decoder = FilesystemJSONDecoder()
1613
+
1614
+ dct = dict(dct) # Defensive copy
1615
+
1616
+ cls = FilesystemJSONDecoder.try_resolve_fs_cls(dct)
1617
+ if cls is None:
1618
+ raise ValueError("Not a serialized AbstractFileSystem")
1619
+
1620
+ dct.pop("cls", None)
1621
+ dct.pop("protocol", None)
1622
+
1623
+ return cls(
1624
+ *json_decoder.unmake_serializable(dct.pop("args", ())),
1625
+ **json_decoder.unmake_serializable(dct),
1626
+ )
1627
+
1628
+ def _get_pyarrow_filesystem(self):
1629
+ """
1630
+ Make a version of the FS instance which will be acceptable to pyarrow
1631
+ """
1632
+ # all instances already also derive from pyarrow
1633
+ return self
1634
+
1635
+ def get_mapper(self, root="", check=False, create=False, missing_exceptions=None):
1636
+ """Create key/value store based on this file-system
1637
+
1638
+ Makes a MutableMapping interface to the FS at the given root path.
1639
+ See ``fsspec.mapping.FSMap`` for further details.
1640
+ """
1641
+ from .mapping import FSMap
1642
+
1643
+ return FSMap(
1644
+ root,
1645
+ self,
1646
+ check=check,
1647
+ create=create,
1648
+ missing_exceptions=missing_exceptions,
1649
+ )
1650
+
1651
+ @classmethod
1652
+ def clear_instance_cache(cls):
1653
+ """
1654
+ Clear the cache of filesystem instances.
1655
+
1656
+ Notes
1657
+ -----
1658
+ Unless overridden by setting the ``cachable`` class attribute to False,
1659
+ the filesystem class stores a reference to newly created instances. This
1660
+ prevents Python's normal rules around garbage collection from working,
1661
+ since the instances refcount will not drop to zero until
1662
+ ``clear_instance_cache`` is called.
1663
+ """
1664
+ cls._cache.clear()
1665
+
1666
+ def created(self, path):
1667
+ """Return the created timestamp of a file as a datetime.datetime"""
1668
+ raise NotImplementedError
1669
+
1670
+ def modified(self, path):
1671
+ """Return the modified timestamp of a file as a datetime.datetime"""
1672
+ raise NotImplementedError
1673
+
1674
+ def tree(
1675
+ self,
1676
+ path: str = "/",
1677
+ recursion_limit: int = 2,
1678
+ max_display: int = 25,
1679
+ display_size: bool = False,
1680
+ prefix: str = "",
1681
+ is_last: bool = True,
1682
+ first: bool = True,
1683
+ indent_size: int = 4,
1684
+ ) -> str:
1685
+ """
1686
+ Return a tree-like structure of the filesystem starting from the given path as a string.
1687
+
1688
+ Parameters
1689
+ ----------
1690
+ path: Root path to start traversal from
1691
+ recursion_limit: Maximum depth of directory traversal
1692
+ max_display: Maximum number of items to display per directory
1693
+ display_size: Whether to display file sizes
1694
+ prefix: Current line prefix for visual tree structure
1695
+ is_last: Whether current item is last in its level
1696
+ first: Whether this is the first call (displays root path)
1697
+ indent_size: Number of spaces by indent
1698
+
1699
+ Returns
1700
+ -------
1701
+ str: A string representing the tree structure.
1702
+
1703
+ Example
1704
+ -------
1705
+ >>> from fsspec import filesystem
1706
+
1707
+ >>> fs = filesystem('ftp', host='test.rebex.net', user='demo', password='password')
1708
+ >>> tree = fs.tree(display_size=True, recursion_limit=3, indent_size=8, max_display=10)
1709
+ >>> print(tree)
1710
+ """
1711
+
1712
+ def format_bytes(n: int) -> str:
1713
+ """Format bytes as text."""
1714
+ for prefix, k in (
1715
+ ("P", 2**50),
1716
+ ("T", 2**40),
1717
+ ("G", 2**30),
1718
+ ("M", 2**20),
1719
+ ("k", 2**10),
1720
+ ):
1721
+ if n >= 0.9 * k:
1722
+ return f"{n / k:.2f} {prefix}b"
1723
+ return f"{n}B"
1724
+
1725
+ result = []
1726
+
1727
+ if first:
1728
+ result.append(path)
1729
+
1730
+ if recursion_limit:
1731
+ indent = " " * indent_size
1732
+ contents = self.ls(path, detail=True)
1733
+ contents.sort(
1734
+ key=lambda x: (x.get("type") != "directory", x.get("name", ""))
1735
+ )
1736
+
1737
+ if max_display is not None and len(contents) > max_display:
1738
+ displayed_contents = contents[:max_display]
1739
+ remaining_count = len(contents) - max_display
1740
+ else:
1741
+ displayed_contents = contents
1742
+ remaining_count = 0
1743
+
1744
+ for i, item in enumerate(displayed_contents):
1745
+ is_last_item = (i == len(displayed_contents) - 1) and (
1746
+ remaining_count == 0
1747
+ )
1748
+
1749
+ branch = (
1750
+ "└" + ("─" * (indent_size - 2))
1751
+ if is_last_item
1752
+ else "├" + ("─" * (indent_size - 2))
1753
+ )
1754
+ branch += " "
1755
+ new_prefix = prefix + (
1756
+ indent if is_last_item else "│" + " " * (indent_size - 1)
1757
+ )
1758
+
1759
+ name = os.path.basename(item.get("name", ""))
1760
+
1761
+ if display_size and item.get("type") == "directory":
1762
+ sub_contents = self.ls(item.get("name", ""), detail=True)
1763
+ num_files = sum(
1764
+ 1 for sub_item in sub_contents if sub_item.get("type") == "file"
1765
+ )
1766
+ num_folders = sum(
1767
+ 1
1768
+ for sub_item in sub_contents
1769
+ if sub_item.get("type") == "directory"
1770
+ )
1771
+
1772
+ if num_files == 0 and num_folders == 0:
1773
+ size = " (empty folder)"
1774
+ elif num_files == 0:
1775
+ size = f" ({num_folders} subfolder{'s' if num_folders > 1 else ''})"
1776
+ elif num_folders == 0:
1777
+ size = f" ({num_files} file{'s' if num_files > 1 else ''})"
1778
+ else:
1779
+ size = f" ({num_files} file{'s' if num_files > 1 else ''}, {num_folders} subfolder{'s' if num_folders > 1 else ''})"
1780
+ elif display_size and item.get("type") == "file":
1781
+ size = f" ({format_bytes(item.get('size', 0))})"
1782
+ else:
1783
+ size = ""
1784
+
1785
+ result.append(f"{prefix}{branch}{name}{size}")
1786
+
1787
+ if item.get("type") == "directory" and recursion_limit > 0:
1788
+ result.append(
1789
+ self.tree(
1790
+ path=item.get("name", ""),
1791
+ recursion_limit=recursion_limit - 1,
1792
+ max_display=max_display,
1793
+ display_size=display_size,
1794
+ prefix=new_prefix,
1795
+ is_last=is_last_item,
1796
+ first=False,
1797
+ indent_size=indent_size,
1798
+ )
1799
+ )
1800
+
1801
+ if remaining_count > 0:
1802
+ more_message = f"{remaining_count} more item(s) not displayed."
1803
+ result.append(
1804
+ f"{prefix}{'└' + ('─' * (indent_size - 2))} {more_message}"
1805
+ )
1806
+
1807
+ return "\n".join(_ for _ in result if _)
1808
+
1809
+ # ------------------------------------------------------------------------
1810
+ # Aliases
1811
+
1812
+ def read_bytes(self, path, start=None, end=None, **kwargs):
1813
+ """Alias of `AbstractFileSystem.cat_file`."""
1814
+ return self.cat_file(path, start=start, end=end, **kwargs)
1815
+
1816
+ def write_bytes(self, path, value, **kwargs):
1817
+ """Alias of `AbstractFileSystem.pipe_file`."""
1818
+ self.pipe_file(path, value, **kwargs)
1819
+
1820
+ def makedir(self, path, create_parents=True, **kwargs):
1821
+ """Alias of `AbstractFileSystem.mkdir`."""
1822
+ return self.mkdir(path, create_parents=create_parents, **kwargs)
1823
+
1824
+ def mkdirs(self, path, exist_ok=False):
1825
+ """Alias of `AbstractFileSystem.makedirs`."""
1826
+ return self.makedirs(path, exist_ok=exist_ok)
1827
+
1828
+ def listdir(self, path, detail=True, **kwargs):
1829
+ """Alias of `AbstractFileSystem.ls`."""
1830
+ return self.ls(path, detail=detail, **kwargs)
1831
+
1832
+ def cp(self, path1, path2, **kwargs):
1833
+ """Alias of `AbstractFileSystem.copy`."""
1834
+ return self.copy(path1, path2, **kwargs)
1835
+
1836
+ def move(self, path1, path2, **kwargs):
1837
+ """Alias of `AbstractFileSystem.mv`."""
1838
+ return self.mv(path1, path2, **kwargs)
1839
+
1840
+ def stat(self, path, **kwargs):
1841
+ """Alias of `AbstractFileSystem.info`."""
1842
+ return self.info(path, **kwargs)
1843
+
1844
+ def disk_usage(self, path, total=True, maxdepth=None, **kwargs):
1845
+ """Alias of `AbstractFileSystem.du`."""
1846
+ return self.du(path, total=total, maxdepth=maxdepth, **kwargs)
1847
+
1848
+ def rename(self, path1, path2, **kwargs):
1849
+ """Alias of `AbstractFileSystem.mv`."""
1850
+ return self.mv(path1, path2, **kwargs)
1851
+
1852
+ def delete(self, path, recursive=False, maxdepth=None):
1853
+ """Alias of `AbstractFileSystem.rm`."""
1854
+ return self.rm(path, recursive=recursive, maxdepth=maxdepth)
1855
+
1856
+ def upload(self, lpath, rpath, recursive=False, **kwargs):
1857
+ """Alias of `AbstractFileSystem.put`."""
1858
+ return self.put(lpath, rpath, recursive=recursive, **kwargs)
1859
+
1860
+ def download(self, rpath, lpath, recursive=False, **kwargs):
1861
+ """Alias of `AbstractFileSystem.get`."""
1862
+ return self.get(rpath, lpath, recursive=recursive, **kwargs)
1863
+
1864
+ def sign(self, path, expiration=100, **kwargs):
1865
+ """Create a signed URL representing the given path
1866
+
1867
+ Some implementations allow temporary URLs to be generated, as a
1868
+ way of delegating credentials.
1869
+
1870
+ Parameters
1871
+ ----------
1872
+ path : str
1873
+ The path on the filesystem
1874
+ expiration : int
1875
+ Number of seconds to enable the URL for (if supported)
1876
+
1877
+ Returns
1878
+ -------
1879
+ URL : str
1880
+ The signed URL
1881
+
1882
+ Raises
1883
+ ------
1884
+ NotImplementedError : if method is not implemented for a filesystem
1885
+ """
1886
+ raise NotImplementedError("Sign is not implemented for this filesystem")
1887
+
1888
+ def _isfilestore(self):
1889
+ # Originally inherited from pyarrow DaskFileSystem. Keeping this
1890
+ # here for backwards compatibility as long as pyarrow uses its
1891
+ # legacy fsspec-compatible filesystems and thus accepts fsspec
1892
+ # filesystems as well
1893
+ return False
1894
+
1895
+
1896
+ class AbstractBufferedFile(io.IOBase):
1897
+ """Convenient class to derive from to provide buffering
1898
+
1899
+ In the case that the backend does not provide a pythonic file-like object
1900
+ already, this class contains much of the logic to build one. The only
1901
+ methods that need to be overridden are ``_upload_chunk``,
1902
+ ``_initiate_upload`` and ``_fetch_range``.
1903
+ """
1904
+
1905
+ DEFAULT_BLOCK_SIZE = 5 * 2**20
1906
+ _details = None
1907
+
1908
+ def __init__(
1909
+ self,
1910
+ fs,
1911
+ path,
1912
+ mode="rb",
1913
+ block_size="default",
1914
+ autocommit=True,
1915
+ cache_type="readahead",
1916
+ cache_options=None,
1917
+ size=None,
1918
+ **kwargs,
1919
+ ):
1920
+ """
1921
+ Template for files with buffered reading and writing
1922
+
1923
+ Parameters
1924
+ ----------
1925
+ fs: instance of FileSystem
1926
+ path: str
1927
+ location in file-system
1928
+ mode: str
1929
+ Normal file modes. Currently only 'wb', 'ab' or 'rb'. Some file
1930
+ systems may be read-only, and some may not support append.
1931
+ block_size: int
1932
+ Buffer size for reading or writing, 'default' for class default
1933
+ autocommit: bool
1934
+ Whether to write to final destination; may only impact what
1935
+ happens when file is being closed.
1936
+ cache_type: {"readahead", "none", "mmap", "bytes"}, default "readahead"
1937
+ Caching policy in read mode. See the definitions in ``core``.
1938
+ cache_options : dict
1939
+ Additional options passed to the constructor for the cache specified
1940
+ by `cache_type`.
1941
+ size: int
1942
+ If given and in read mode, suppressed having to look up the file size
1943
+ kwargs:
1944
+ Gets stored as self.kwargs
1945
+ """
1946
+ from .core import caches
1947
+
1948
+ self.path = path
1949
+ self.fs = fs
1950
+ self.mode = mode
1951
+ self.blocksize = (
1952
+ self.DEFAULT_BLOCK_SIZE if block_size in ["default", None] else block_size
1953
+ )
1954
+ self.loc = 0
1955
+ self.autocommit = autocommit
1956
+ self.end = None
1957
+ self.start = None
1958
+ self.closed = False
1959
+
1960
+ if cache_options is None:
1961
+ cache_options = {}
1962
+
1963
+ if "trim" in kwargs:
1964
+ warnings.warn(
1965
+ "Passing 'trim' to control the cache behavior has been deprecated. "
1966
+ "Specify it within the 'cache_options' argument instead.",
1967
+ FutureWarning,
1968
+ )
1969
+ cache_options["trim"] = kwargs.pop("trim")
1970
+
1971
+ self.kwargs = kwargs
1972
+
1973
+ if mode not in {"ab", "rb", "wb", "xb"}:
1974
+ raise NotImplementedError("File mode not supported")
1975
+ if mode == "rb":
1976
+ if size is not None:
1977
+ self.size = size
1978
+ else:
1979
+ self.size = self.details["size"]
1980
+ self.cache = caches[cache_type](
1981
+ self.blocksize, self._fetch_range, self.size, **cache_options
1982
+ )
1983
+ else:
1984
+ self.buffer = io.BytesIO()
1985
+ self.offset = None
1986
+ self.forced = False
1987
+ self.location = None
1988
+
1989
+ @property
1990
+ def details(self):
1991
+ if self._details is None:
1992
+ self._details = self.fs.info(self.path)
1993
+ return self._details
1994
+
1995
+ @details.setter
1996
+ def details(self, value):
1997
+ self._details = value
1998
+ self.size = value["size"]
1999
+
2000
+ @property
2001
+ def full_name(self):
2002
+ return _unstrip_protocol(self.path, self.fs)
2003
+
2004
+ @property
2005
+ def closed(self):
2006
+ # get around this attr being read-only in IOBase
2007
+ # use getattr here, since this can be called during del
2008
+ return getattr(self, "_closed", True)
2009
+
2010
+ @closed.setter
2011
+ def closed(self, c):
2012
+ self._closed = c
2013
+
2014
+ def __hash__(self):
2015
+ if "w" in self.mode:
2016
+ return id(self)
2017
+ else:
2018
+ return int(tokenize(self.details), 16)
2019
+
2020
+ def __eq__(self, other):
2021
+ """Files are equal if they have the same checksum, only in read mode"""
2022
+ if self is other:
2023
+ return True
2024
+ return (
2025
+ isinstance(other, type(self))
2026
+ and self.mode == "rb"
2027
+ and other.mode == "rb"
2028
+ and hash(self) == hash(other)
2029
+ )
2030
+
2031
+ def commit(self):
2032
+ """Move from temp to final destination"""
2033
+
2034
+ def discard(self):
2035
+ """Throw away temporary file"""
2036
+
2037
+ def info(self):
2038
+ """File information about this path"""
2039
+ if self.readable():
2040
+ return self.details
2041
+ else:
2042
+ raise ValueError("Info not available while writing")
2043
+
2044
+ def tell(self):
2045
+ """Current file location"""
2046
+ return self.loc
2047
+
2048
+ def seek(self, loc, whence=0):
2049
+ """Set current file location
2050
+
2051
+ Parameters
2052
+ ----------
2053
+ loc: int
2054
+ byte location
2055
+ whence: {0, 1, 2}
2056
+ from start of file, current location or end of file, resp.
2057
+ """
2058
+ loc = int(loc)
2059
+ if not self.mode == "rb":
2060
+ raise OSError(ESPIPE, "Seek only available in read mode")
2061
+ if whence == 0:
2062
+ nloc = loc
2063
+ elif whence == 1:
2064
+ nloc = self.loc + loc
2065
+ elif whence == 2:
2066
+ nloc = self.size + loc
2067
+ else:
2068
+ raise ValueError(f"invalid whence ({whence}, should be 0, 1 or 2)")
2069
+ if nloc < 0:
2070
+ raise ValueError("Seek before start of file")
2071
+ self.loc = nloc
2072
+ return self.loc
2073
+
2074
+ def write(self, data):
2075
+ """
2076
+ Write data to buffer.
2077
+
2078
+ Buffer only sent on flush() or if buffer is greater than
2079
+ or equal to blocksize.
2080
+
2081
+ Parameters
2082
+ ----------
2083
+ data: bytes
2084
+ Set of bytes to be written.
2085
+ """
2086
+ if not self.writable():
2087
+ raise ValueError("File not in write mode")
2088
+ if self.closed:
2089
+ raise ValueError("I/O operation on closed file.")
2090
+ if self.forced:
2091
+ raise ValueError("This file has been force-flushed, can only close")
2092
+ out = self.buffer.write(data)
2093
+ self.loc += out
2094
+ if self.buffer.tell() >= self.blocksize:
2095
+ self.flush()
2096
+ return out
2097
+
2098
+ def flush(self, force=False):
2099
+ """
2100
+ Write buffered data to backend store.
2101
+
2102
+ Writes the current buffer, if it is larger than the block-size, or if
2103
+ the file is being closed.
2104
+
2105
+ Parameters
2106
+ ----------
2107
+ force: bool
2108
+ When closing, write the last block even if it is smaller than
2109
+ blocks are allowed to be. Disallows further writing to this file.
2110
+ """
2111
+
2112
+ if self.closed:
2113
+ raise ValueError("Flush on closed file")
2114
+ if force and self.forced:
2115
+ raise ValueError("Force flush cannot be called more than once")
2116
+ if force:
2117
+ self.forced = True
2118
+
2119
+ if self.readable():
2120
+ # no-op to flush on read-mode
2121
+ return
2122
+
2123
+ if not force and self.buffer.tell() < self.blocksize:
2124
+ # Defer write on small block
2125
+ return
2126
+
2127
+ if self.offset is None:
2128
+ # Initialize a multipart upload
2129
+ self.offset = 0
2130
+ try:
2131
+ self._initiate_upload()
2132
+ except Exception:
2133
+ self.closed = True
2134
+ raise
2135
+
2136
+ if self._upload_chunk(final=force) is not False:
2137
+ self.offset += self.buffer.seek(0, 2)
2138
+ self.buffer = io.BytesIO()
2139
+
2140
+ def _upload_chunk(self, final=False):
2141
+ """Write one part of a multi-block file upload
2142
+
2143
+ Parameters
2144
+ ==========
2145
+ final: bool
2146
+ This is the last block, so should complete file, if
2147
+ self.autocommit is True.
2148
+ """
2149
+ # may not yet have been initialized, may need to call _initialize_upload
2150
+
2151
+ def _initiate_upload(self):
2152
+ """Create remote file/upload"""
2153
+ pass
2154
+
2155
+ def _fetch_range(self, start, end):
2156
+ """Get the specified set of bytes from remote"""
2157
+ return self.fs.cat_file(self.path, start=start, end=end)
2158
+
2159
+ def read(self, length=-1):
2160
+ """
2161
+ Return data from cache, or fetch pieces as necessary
2162
+
2163
+ Parameters
2164
+ ----------
2165
+ length: int (-1)
2166
+ Number of bytes to read; if <0, all remaining bytes.
2167
+ """
2168
+ length = -1 if length is None else int(length)
2169
+ if self.mode != "rb":
2170
+ raise ValueError("File not in read mode")
2171
+ if length < 0:
2172
+ length = self.size - self.loc
2173
+ if self.closed:
2174
+ raise ValueError("I/O operation on closed file.")
2175
+ if length == 0:
2176
+ # don't even bother calling fetch
2177
+ return b""
2178
+ out = self.cache._fetch(self.loc, self.loc + length)
2179
+
2180
+ logger.debug(
2181
+ "%s read: %i - %i %s",
2182
+ self,
2183
+ self.loc,
2184
+ self.loc + length,
2185
+ self.cache._log_stats(),
2186
+ )
2187
+ self.loc += len(out)
2188
+ return out
2189
+
2190
+ def readinto(self, b):
2191
+ """mirrors builtin file's readinto method
2192
+
2193
+ https://docs.python.org/3/library/io.html#io.RawIOBase.readinto
2194
+ """
2195
+ out = memoryview(b).cast("B")
2196
+ data = self.read(out.nbytes)
2197
+ out[: len(data)] = data
2198
+ return len(data)
2199
+
2200
+ def readuntil(self, char=b"\n", blocks=None):
2201
+ """Return data between current position and first occurrence of char
2202
+
2203
+ char is included in the output, except if the end of the tile is
2204
+ encountered first.
2205
+
2206
+ Parameters
2207
+ ----------
2208
+ char: bytes
2209
+ Thing to find
2210
+ blocks: None or int
2211
+ How much to read in each go. Defaults to file blocksize - which may
2212
+ mean a new read on every call.
2213
+ """
2214
+ out = []
2215
+ while True:
2216
+ start = self.tell()
2217
+ part = self.read(blocks or self.blocksize)
2218
+ if len(part) == 0:
2219
+ break
2220
+ found = part.find(char)
2221
+ if found > -1:
2222
+ out.append(part[: found + len(char)])
2223
+ self.seek(start + found + len(char))
2224
+ break
2225
+ out.append(part)
2226
+ return b"".join(out)
2227
+
2228
+ def readline(self):
2229
+ """Read until and including the first occurrence of newline character
2230
+
2231
+ Note that, because of character encoding, this is not necessarily a
2232
+ true line ending.
2233
+ """
2234
+ return self.readuntil(b"\n")
2235
+
2236
+ def __next__(self):
2237
+ out = self.readline()
2238
+ if out:
2239
+ return out
2240
+ raise StopIteration
2241
+
2242
+ def __iter__(self):
2243
+ return self
2244
+
2245
+ def readlines(self):
2246
+ """Return all data, split by the newline character, including the newline character"""
2247
+ data = self.read()
2248
+ lines = data.split(b"\n")
2249
+ out = [l + b"\n" for l in lines[:-1]]
2250
+ if data.endswith(b"\n"):
2251
+ return out
2252
+ else:
2253
+ return out + [lines[-1]]
2254
+ # return list(self) ???
2255
+
2256
+ def readinto1(self, b):
2257
+ return self.readinto(b)
2258
+
2259
+ def close(self):
2260
+ """Close file
2261
+
2262
+ Finalizes writes, discards cache
2263
+ """
2264
+ if getattr(self, "_unclosable", False):
2265
+ return
2266
+ if self.closed:
2267
+ return
2268
+ try:
2269
+ if self.mode == "rb":
2270
+ cache = getattr(self, "cache", None)
2271
+ if cache is not None:
2272
+ close = getattr(cache, "close", None)
2273
+ if callable(close):
2274
+ close()
2275
+ self.cache = None
2276
+ else:
2277
+ if not getattr(self, "forced", True):
2278
+ self.flush(force=True)
2279
+
2280
+ if self.fs is not None:
2281
+ self.fs.invalidate_cache(self.path)
2282
+ self.fs.invalidate_cache(self.fs._parent(self.path))
2283
+ finally:
2284
+ self.closed = True
2285
+
2286
+ def readable(self):
2287
+ """Whether opened for reading"""
2288
+ return "r" in self.mode and not self.closed
2289
+
2290
+ def seekable(self):
2291
+ """Whether is seekable (only in read mode)"""
2292
+ return self.readable()
2293
+
2294
+ def writable(self):
2295
+ """Whether opened for writing"""
2296
+ return self.mode in {"wb", "ab", "xb"} and not self.closed
2297
+
2298
+ def __reduce__(self):
2299
+ if self.mode != "rb":
2300
+ raise RuntimeError("Pickling a writeable file is not supported")
2301
+
2302
+ return reopen, (
2303
+ self.fs,
2304
+ self.path,
2305
+ self.mode,
2306
+ self.blocksize,
2307
+ self.loc,
2308
+ self.size,
2309
+ self.autocommit,
2310
+ self.cache.name if self.cache else "none",
2311
+ self.kwargs,
2312
+ )
2313
+
2314
+ def __del__(self):
2315
+ if not self.closed:
2316
+ self.close()
2317
+
2318
+ def __str__(self):
2319
+ return f"<File-like object {type(self.fs).__name__}, {self.path}>"
2320
+
2321
+ __repr__ = __str__
2322
+
2323
+ def __enter__(self):
2324
+ return self
2325
+
2326
+ def __exit__(self, *args):
2327
+ self.close()
2328
+
2329
+
2330
+ def reopen(fs, path, mode, blocksize, loc, size, autocommit, cache_type, kwargs):
2331
+ file = fs.open(
2332
+ path,
2333
+ mode=mode,
2334
+ block_size=blocksize,
2335
+ autocommit=autocommit,
2336
+ cache_type=cache_type,
2337
+ size=size,
2338
+ **kwargs,
2339
+ )
2340
+ if loc > 0:
2341
+ file.seek(loc)
2342
+ return file
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/__init__.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from hashlib import md5
3
+
4
+ import pytest
5
+
6
+ from fsspec.implementations.local import LocalFileSystem
7
+ from fsspec.tests.abstract.copy import AbstractCopyTests # noqa: F401
8
+ from fsspec.tests.abstract.get import AbstractGetTests # noqa: F401
9
+ from fsspec.tests.abstract.open import AbstractOpenTests # noqa: F401
10
+ from fsspec.tests.abstract.pipe import AbstractPipeTests # noqa: F401
11
+ from fsspec.tests.abstract.put import AbstractPutTests # noqa: F401
12
+
13
+
14
+ class BaseAbstractFixtures:
15
+ """
16
+ Abstract base class containing fixtures that are used by but never need to
17
+ be overridden in derived filesystem-specific classes to run the abstract
18
+ tests on such filesystems.
19
+ """
20
+
21
+ @pytest.fixture
22
+ def fs_bulk_operations_scenario_0(self, fs, fs_join, fs_path):
23
+ """
24
+ Scenario on remote filesystem that is used for many cp/get/put tests.
25
+
26
+ Cleans up at the end of each test it which it is used.
27
+ """
28
+ source = self._bulk_operations_scenario_0(fs, fs_join, fs_path)
29
+ yield source
30
+ fs.rm(source, recursive=True)
31
+
32
+ @pytest.fixture
33
+ def fs_glob_edge_cases_files(self, fs, fs_join, fs_path):
34
+ """
35
+ Scenario on remote filesystem that is used for glob edge cases cp/get/put tests.
36
+
37
+ Cleans up at the end of each test it which it is used.
38
+ """
39
+ source = self._glob_edge_cases_files(fs, fs_join, fs_path)
40
+ yield source
41
+ fs.rm(source, recursive=True)
42
+
43
+ @pytest.fixture
44
+ def fs_dir_and_file_with_same_name_prefix(self, fs, fs_join, fs_path):
45
+ """
46
+ Scenario on remote filesystem that is used to check cp/get/put on directory
47
+ and file with the same name prefixes.
48
+
49
+ Cleans up at the end of each test it which it is used.
50
+ """
51
+ source = self._dir_and_file_with_same_name_prefix(fs, fs_join, fs_path)
52
+ yield source
53
+ fs.rm(source, recursive=True)
54
+
55
+ @pytest.fixture
56
+ def fs_10_files_with_hashed_names(self, fs, fs_join, fs_path):
57
+ """
58
+ Scenario on remote filesystem that is used to check cp/get/put files order
59
+ when source and destination are lists.
60
+
61
+ Cleans up at the end of each test it which it is used.
62
+ """
63
+ source = self._10_files_with_hashed_names(fs, fs_join, fs_path)
64
+ yield source
65
+ fs.rm(source, recursive=True)
66
+
67
+ @pytest.fixture
68
+ def fs_target(self, fs, fs_join, fs_path):
69
+ """
70
+ Return name of remote directory that does not yet exist to copy into.
71
+
72
+ Cleans up at the end of each test it which it is used.
73
+ """
74
+ target = fs_join(fs_path, "target")
75
+ yield target
76
+ if fs.exists(target):
77
+ fs.rm(target, recursive=True)
78
+
79
+ @pytest.fixture
80
+ def local_bulk_operations_scenario_0(self, local_fs, local_join, local_path):
81
+ """
82
+ Scenario on local filesystem that is used for many cp/get/put tests.
83
+
84
+ Cleans up at the end of each test it which it is used.
85
+ """
86
+ source = self._bulk_operations_scenario_0(local_fs, local_join, local_path)
87
+ yield source
88
+ local_fs.rm(source, recursive=True)
89
+
90
+ @pytest.fixture
91
+ def local_glob_edge_cases_files(self, local_fs, local_join, local_path):
92
+ """
93
+ Scenario on local filesystem that is used for glob edge cases cp/get/put tests.
94
+
95
+ Cleans up at the end of each test it which it is used.
96
+ """
97
+ source = self._glob_edge_cases_files(local_fs, local_join, local_path)
98
+ yield source
99
+ local_fs.rm(source, recursive=True)
100
+
101
+ @pytest.fixture
102
+ def local_dir_and_file_with_same_name_prefix(
103
+ self, local_fs, local_join, local_path
104
+ ):
105
+ """
106
+ Scenario on local filesystem that is used to check cp/get/put on directory
107
+ and file with the same name prefixes.
108
+
109
+ Cleans up at the end of each test it which it is used.
110
+ """
111
+ source = self._dir_and_file_with_same_name_prefix(
112
+ local_fs, local_join, local_path
113
+ )
114
+ yield source
115
+ local_fs.rm(source, recursive=True)
116
+
117
+ @pytest.fixture
118
+ def local_10_files_with_hashed_names(self, local_fs, local_join, local_path):
119
+ """
120
+ Scenario on local filesystem that is used to check cp/get/put files order
121
+ when source and destination are lists.
122
+
123
+ Cleans up at the end of each test it which it is used.
124
+ """
125
+ source = self._10_files_with_hashed_names(local_fs, local_join, local_path)
126
+ yield source
127
+ local_fs.rm(source, recursive=True)
128
+
129
+ @pytest.fixture
130
+ def local_target(self, local_fs, local_join, local_path):
131
+ """
132
+ Return name of local directory that does not yet exist to copy into.
133
+
134
+ Cleans up at the end of each test it which it is used.
135
+ """
136
+ target = local_join(local_path, "target")
137
+ yield target
138
+ if local_fs.exists(target):
139
+ local_fs.rm(target, recursive=True)
140
+
141
+ def _glob_edge_cases_files(self, some_fs, some_join, some_path):
142
+ """
143
+ Scenario that is used for glob edge cases cp/get/put tests.
144
+ Creates the following directory and file structure:
145
+
146
+ 📁 source
147
+ ├── 📄 file1
148
+ ├── 📄 file2
149
+ ├── 📁 subdir0
150
+ │ ├── 📄 subfile1
151
+ │ ├── 📄 subfile2
152
+ │ └── 📁 nesteddir
153
+ │ └── 📄 nestedfile
154
+ └── 📁 subdir1
155
+ ├── 📄 subfile1
156
+ ├── 📄 subfile2
157
+ └── 📁 nesteddir
158
+ └── 📄 nestedfile
159
+ """
160
+ source = some_join(some_path, "source")
161
+ some_fs.touch(some_join(source, "file1"))
162
+ some_fs.touch(some_join(source, "file2"))
163
+
164
+ for subdir_idx in range(2):
165
+ subdir = some_join(source, f"subdir{subdir_idx}")
166
+ nesteddir = some_join(subdir, "nesteddir")
167
+ some_fs.makedirs(nesteddir)
168
+ some_fs.touch(some_join(subdir, "subfile1"))
169
+ some_fs.touch(some_join(subdir, "subfile2"))
170
+ some_fs.touch(some_join(nesteddir, "nestedfile"))
171
+
172
+ return source
173
+
174
+ def _bulk_operations_scenario_0(self, some_fs, some_join, some_path):
175
+ """
176
+ Scenario that is used for many cp/get/put tests. Creates the following
177
+ directory and file structure:
178
+
179
+ 📁 source
180
+ ├── 📄 file1
181
+ ├── 📄 file2
182
+ └── 📁 subdir
183
+ ├── 📄 subfile1
184
+ ├── 📄 subfile2
185
+ └── 📁 nesteddir
186
+ └── 📄 nestedfile
187
+ """
188
+ source = some_join(some_path, "source")
189
+ subdir = some_join(source, "subdir")
190
+ nesteddir = some_join(subdir, "nesteddir")
191
+ some_fs.makedirs(nesteddir)
192
+ some_fs.touch(some_join(source, "file1"))
193
+ some_fs.touch(some_join(source, "file2"))
194
+ some_fs.touch(some_join(subdir, "subfile1"))
195
+ some_fs.touch(some_join(subdir, "subfile2"))
196
+ some_fs.touch(some_join(nesteddir, "nestedfile"))
197
+ return source
198
+
199
+ def _dir_and_file_with_same_name_prefix(self, some_fs, some_join, some_path):
200
+ """
201
+ Scenario that is used to check cp/get/put on directory and file with
202
+ the same name prefixes. Creates the following directory and file structure:
203
+
204
+ 📁 source
205
+ ├── 📄 subdir.txt
206
+ └── 📁 subdir
207
+ └── 📄 subfile.txt
208
+ """
209
+ source = some_join(some_path, "source")
210
+ subdir = some_join(source, "subdir")
211
+ file = some_join(source, "subdir.txt")
212
+ subfile = some_join(subdir, "subfile.txt")
213
+ some_fs.makedirs(subdir)
214
+ some_fs.touch(file)
215
+ some_fs.touch(subfile)
216
+ return source
217
+
218
+ def _10_files_with_hashed_names(self, some_fs, some_join, some_path):
219
+ """
220
+ Scenario that is used to check cp/get/put files order when source and
221
+ destination are lists. Creates the following directory and file structure:
222
+
223
+ 📁 source
224
+ └── 📄 {hashed([0-9])}.txt
225
+ """
226
+ source = some_join(some_path, "source")
227
+ for i in range(10):
228
+ hashed_i = md5(str(i).encode("utf-8")).hexdigest()
229
+ path = some_join(source, f"{hashed_i}.txt")
230
+ some_fs.pipe(path=path, value=f"{i}".encode())
231
+ return source
232
+
233
+
234
+ class AbstractFixtures(BaseAbstractFixtures):
235
+ """
236
+ Abstract base class containing fixtures that may be overridden in derived
237
+ filesystem-specific classes to run the abstract tests on such filesystems.
238
+
239
+ For any particular filesystem some of these fixtures must be overridden,
240
+ such as ``fs`` and ``fs_path``, and others may be overridden if the
241
+ default functions here are not appropriate, such as ``fs_join``.
242
+ """
243
+
244
+ @pytest.fixture
245
+ def fs(self):
246
+ raise NotImplementedError("This function must be overridden in derived classes")
247
+
248
+ @pytest.fixture
249
+ def fs_join(self):
250
+ """
251
+ Return a function that joins its arguments together into a path.
252
+
253
+ Most fsspec implementations join paths in a platform-dependent way,
254
+ but some will override this to always use a forward slash.
255
+ """
256
+ return os.path.join
257
+
258
+ @pytest.fixture
259
+ def fs_path(self):
260
+ raise NotImplementedError("This function must be overridden in derived classes")
261
+
262
+ @pytest.fixture(scope="class")
263
+ @classmethod
264
+ def local_fs(cls):
265
+ # Maybe need an option for auto_mkdir=False? This is only relevant
266
+ # for certain implementations.
267
+ return LocalFileSystem(auto_mkdir=True)
268
+
269
+ @pytest.fixture
270
+ def local_join(self):
271
+ """
272
+ Return a function that joins its arguments together into a path, on
273
+ the local filesystem.
274
+ """
275
+ return os.path.join
276
+
277
+ @pytest.fixture
278
+ def local_path(self, tmpdir):
279
+ return tmpdir
280
+
281
+ @pytest.fixture
282
+ def supports_empty_directories(self):
283
+ """
284
+ Return whether this implementation supports empty directories.
285
+ """
286
+ return True
287
+
288
+ @pytest.fixture
289
+ def fs_sanitize_path(self):
290
+ return lambda x: x
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/common.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GLOB_EDGE_CASES_TESTS = {
2
+ "argnames": ("path", "recursive", "maxdepth", "expected"),
3
+ "argvalues": [
4
+ ("fil?1", False, None, ["file1"]),
5
+ ("fil?1", True, None, ["file1"]),
6
+ ("file[1-2]", False, None, ["file1", "file2"]),
7
+ ("file[1-2]", True, None, ["file1", "file2"]),
8
+ ("*", False, None, ["file1", "file2"]),
9
+ (
10
+ "*",
11
+ True,
12
+ None,
13
+ [
14
+ "file1",
15
+ "file2",
16
+ "subdir0/subfile1",
17
+ "subdir0/subfile2",
18
+ "subdir0/nesteddir/nestedfile",
19
+ "subdir1/subfile1",
20
+ "subdir1/subfile2",
21
+ "subdir1/nesteddir/nestedfile",
22
+ ],
23
+ ),
24
+ ("*", True, 1, ["file1", "file2"]),
25
+ (
26
+ "*",
27
+ True,
28
+ 2,
29
+ [
30
+ "file1",
31
+ "file2",
32
+ "subdir0/subfile1",
33
+ "subdir0/subfile2",
34
+ "subdir1/subfile1",
35
+ "subdir1/subfile2",
36
+ ],
37
+ ),
38
+ ("*1", False, None, ["file1"]),
39
+ (
40
+ "*1",
41
+ True,
42
+ None,
43
+ [
44
+ "file1",
45
+ "subdir1/subfile1",
46
+ "subdir1/subfile2",
47
+ "subdir1/nesteddir/nestedfile",
48
+ ],
49
+ ),
50
+ ("*1", True, 2, ["file1", "subdir1/subfile1", "subdir1/subfile2"]),
51
+ (
52
+ "**",
53
+ False,
54
+ None,
55
+ [
56
+ "file1",
57
+ "file2",
58
+ "subdir0/subfile1",
59
+ "subdir0/subfile2",
60
+ "subdir0/nesteddir/nestedfile",
61
+ "subdir1/subfile1",
62
+ "subdir1/subfile2",
63
+ "subdir1/nesteddir/nestedfile",
64
+ ],
65
+ ),
66
+ (
67
+ "**",
68
+ True,
69
+ None,
70
+ [
71
+ "file1",
72
+ "file2",
73
+ "subdir0/subfile1",
74
+ "subdir0/subfile2",
75
+ "subdir0/nesteddir/nestedfile",
76
+ "subdir1/subfile1",
77
+ "subdir1/subfile2",
78
+ "subdir1/nesteddir/nestedfile",
79
+ ],
80
+ ),
81
+ ("**", True, 1, ["file1", "file2"]),
82
+ (
83
+ "**",
84
+ True,
85
+ 2,
86
+ [
87
+ "file1",
88
+ "file2",
89
+ "subdir0/subfile1",
90
+ "subdir0/subfile2",
91
+ "subdir0/nesteddir/nestedfile",
92
+ "subdir1/subfile1",
93
+ "subdir1/subfile2",
94
+ "subdir1/nesteddir/nestedfile",
95
+ ],
96
+ ),
97
+ (
98
+ "**",
99
+ False,
100
+ 2,
101
+ [
102
+ "file1",
103
+ "file2",
104
+ "subdir0/subfile1",
105
+ "subdir0/subfile2",
106
+ "subdir1/subfile1",
107
+ "subdir1/subfile2",
108
+ ],
109
+ ),
110
+ ("**/*1", False, None, ["file1", "subdir0/subfile1", "subdir1/subfile1"]),
111
+ (
112
+ "**/*1",
113
+ True,
114
+ None,
115
+ [
116
+ "file1",
117
+ "subdir0/subfile1",
118
+ "subdir1/subfile1",
119
+ "subdir1/subfile2",
120
+ "subdir1/nesteddir/nestedfile",
121
+ ],
122
+ ),
123
+ ("**/*1", True, 1, ["file1"]),
124
+ (
125
+ "**/*1",
126
+ True,
127
+ 2,
128
+ ["file1", "subdir0/subfile1", "subdir1/subfile1", "subdir1/subfile2"],
129
+ ),
130
+ ("**/*1", False, 2, ["file1", "subdir0/subfile1", "subdir1/subfile1"]),
131
+ ("**/subdir0", False, None, []),
132
+ ("**/subdir0", True, None, ["subfile1", "subfile2", "nesteddir/nestedfile"]),
133
+ ("**/subdir0/nested*", False, 2, []),
134
+ ("**/subdir0/nested*", True, 2, ["nestedfile"]),
135
+ ("subdir[1-2]", False, None, []),
136
+ ("subdir[1-2]", True, None, ["subfile1", "subfile2", "nesteddir/nestedfile"]),
137
+ ("subdir[1-2]", True, 2, ["subfile1", "subfile2"]),
138
+ ("subdir[0-1]", False, None, []),
139
+ (
140
+ "subdir[0-1]",
141
+ True,
142
+ None,
143
+ [
144
+ "subdir0/subfile1",
145
+ "subdir0/subfile2",
146
+ "subdir0/nesteddir/nestedfile",
147
+ "subdir1/subfile1",
148
+ "subdir1/subfile2",
149
+ "subdir1/nesteddir/nestedfile",
150
+ ],
151
+ ),
152
+ (
153
+ "subdir[0-1]/*fil[e]*",
154
+ False,
155
+ None,
156
+ [
157
+ "subdir0/subfile1",
158
+ "subdir0/subfile2",
159
+ "subdir1/subfile1",
160
+ "subdir1/subfile2",
161
+ ],
162
+ ),
163
+ (
164
+ "subdir[0-1]/*fil[e]*",
165
+ True,
166
+ None,
167
+ [
168
+ "subdir0/subfile1",
169
+ "subdir0/subfile2",
170
+ "subdir1/subfile1",
171
+ "subdir1/subfile2",
172
+ ],
173
+ ),
174
+ ],
175
+ }
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/copy.py ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from hashlib import md5
2
+ from itertools import product
3
+
4
+ import pytest
5
+
6
+ from fsspec.tests.abstract.common import GLOB_EDGE_CASES_TESTS
7
+
8
+
9
+ class AbstractCopyTests:
10
+ def test_copy_file_to_existing_directory(
11
+ self,
12
+ fs,
13
+ fs_join,
14
+ fs_bulk_operations_scenario_0,
15
+ fs_target,
16
+ supports_empty_directories,
17
+ ):
18
+ # Copy scenario 1a
19
+ source = fs_bulk_operations_scenario_0
20
+
21
+ target = fs_target
22
+ fs.mkdir(target)
23
+ if not supports_empty_directories:
24
+ # Force target directory to exist by adding a dummy file
25
+ fs.touch(fs_join(target, "dummy"))
26
+ assert fs.isdir(target)
27
+
28
+ target_file2 = fs_join(target, "file2")
29
+ target_subfile1 = fs_join(target, "subfile1")
30
+
31
+ # Copy from source directory
32
+ fs.cp(fs_join(source, "file2"), target)
33
+ assert fs.isfile(target_file2)
34
+
35
+ # Copy from sub directory
36
+ fs.cp(fs_join(source, "subdir", "subfile1"), target)
37
+ assert fs.isfile(target_subfile1)
38
+
39
+ # Remove copied files
40
+ fs.rm([target_file2, target_subfile1])
41
+ assert not fs.exists(target_file2)
42
+ assert not fs.exists(target_subfile1)
43
+
44
+ # Repeat with trailing slash on target
45
+ fs.cp(fs_join(source, "file2"), target + "/")
46
+ assert fs.isdir(target)
47
+ assert fs.isfile(target_file2)
48
+
49
+ fs.cp(fs_join(source, "subdir", "subfile1"), target + "/")
50
+ assert fs.isfile(target_subfile1)
51
+
52
+ def test_copy_file_to_new_directory(
53
+ self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target
54
+ ):
55
+ # Copy scenario 1b
56
+ source = fs_bulk_operations_scenario_0
57
+
58
+ target = fs_target
59
+ fs.mkdir(target)
60
+
61
+ fs.cp(
62
+ fs_join(source, "subdir", "subfile1"), fs_join(target, "newdir/")
63
+ ) # Note trailing slash
64
+ assert fs.isdir(target)
65
+ assert fs.isdir(fs_join(target, "newdir"))
66
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
67
+
68
+ def test_copy_file_to_file_in_existing_directory(
69
+ self,
70
+ fs,
71
+ fs_join,
72
+ fs_bulk_operations_scenario_0,
73
+ fs_target,
74
+ supports_empty_directories,
75
+ ):
76
+ # Copy scenario 1c
77
+ source = fs_bulk_operations_scenario_0
78
+
79
+ target = fs_target
80
+ fs.mkdir(target)
81
+ if not supports_empty_directories:
82
+ # Force target directory to exist by adding a dummy file
83
+ fs.touch(fs_join(target, "dummy"))
84
+ assert fs.isdir(target)
85
+
86
+ fs.cp(fs_join(source, "subdir", "subfile1"), fs_join(target, "newfile"))
87
+ assert fs.isfile(fs_join(target, "newfile"))
88
+
89
+ def test_copy_file_to_file_in_new_directory(
90
+ self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target
91
+ ):
92
+ # Copy scenario 1d
93
+ source = fs_bulk_operations_scenario_0
94
+
95
+ target = fs_target
96
+ fs.mkdir(target)
97
+
98
+ fs.cp(
99
+ fs_join(source, "subdir", "subfile1"), fs_join(target, "newdir", "newfile")
100
+ )
101
+ assert fs.isdir(fs_join(target, "newdir"))
102
+ assert fs.isfile(fs_join(target, "newdir", "newfile"))
103
+
104
+ def test_copy_directory_to_existing_directory(
105
+ self,
106
+ fs,
107
+ fs_join,
108
+ fs_bulk_operations_scenario_0,
109
+ fs_target,
110
+ supports_empty_directories,
111
+ ):
112
+ # Copy scenario 1e
113
+ source = fs_bulk_operations_scenario_0
114
+
115
+ target = fs_target
116
+ fs.mkdir(target)
117
+ if not supports_empty_directories:
118
+ # Force target directory to exist by adding a dummy file
119
+ dummy = fs_join(target, "dummy")
120
+ fs.touch(dummy)
121
+ assert fs.isdir(target)
122
+
123
+ for source_slash, target_slash in zip([False, True], [False, True]):
124
+ s = fs_join(source, "subdir")
125
+ if source_slash:
126
+ s += "/"
127
+ t = target + "/" if target_slash else target
128
+
129
+ # Without recursive does nothing
130
+ fs.cp(s, t)
131
+ assert fs.ls(target, detail=False) == (
132
+ [] if supports_empty_directories else [dummy]
133
+ )
134
+
135
+ # With recursive
136
+ fs.cp(s, t, recursive=True)
137
+ if source_slash:
138
+ assert fs.isfile(fs_join(target, "subfile1"))
139
+ assert fs.isfile(fs_join(target, "subfile2"))
140
+ assert fs.isdir(fs_join(target, "nesteddir"))
141
+ assert fs.isfile(fs_join(target, "nesteddir", "nestedfile"))
142
+ assert not fs.exists(fs_join(target, "subdir"))
143
+
144
+ fs.rm(
145
+ [
146
+ fs_join(target, "subfile1"),
147
+ fs_join(target, "subfile2"),
148
+ fs_join(target, "nesteddir"),
149
+ ],
150
+ recursive=True,
151
+ )
152
+ else:
153
+ assert fs.isdir(fs_join(target, "subdir"))
154
+ assert fs.isfile(fs_join(target, "subdir", "subfile1"))
155
+ assert fs.isfile(fs_join(target, "subdir", "subfile2"))
156
+ assert fs.isdir(fs_join(target, "subdir", "nesteddir"))
157
+ assert fs.isfile(fs_join(target, "subdir", "nesteddir", "nestedfile"))
158
+
159
+ fs.rm(fs_join(target, "subdir"), recursive=True)
160
+ assert fs.ls(target, detail=False) == (
161
+ [] if supports_empty_directories else [dummy]
162
+ )
163
+
164
+ # Limit recursive by maxdepth
165
+ fs.cp(s, t, recursive=True, maxdepth=1)
166
+ if source_slash:
167
+ assert fs.isfile(fs_join(target, "subfile1"))
168
+ assert fs.isfile(fs_join(target, "subfile2"))
169
+ assert not fs.exists(fs_join(target, "nesteddir"))
170
+ assert not fs.exists(fs_join(target, "subdir"))
171
+
172
+ fs.rm(
173
+ [
174
+ fs_join(target, "subfile1"),
175
+ fs_join(target, "subfile2"),
176
+ ],
177
+ recursive=True,
178
+ )
179
+ else:
180
+ assert fs.isdir(fs_join(target, "subdir"))
181
+ assert fs.isfile(fs_join(target, "subdir", "subfile1"))
182
+ assert fs.isfile(fs_join(target, "subdir", "subfile2"))
183
+ assert not fs.exists(fs_join(target, "subdir", "nesteddir"))
184
+
185
+ fs.rm(fs_join(target, "subdir"), recursive=True)
186
+ assert fs.ls(target, detail=False) == (
187
+ [] if supports_empty_directories else [dummy]
188
+ )
189
+
190
+ def test_copy_directory_to_new_directory(
191
+ self,
192
+ fs,
193
+ fs_join,
194
+ fs_bulk_operations_scenario_0,
195
+ fs_target,
196
+ supports_empty_directories,
197
+ ):
198
+ # Copy scenario 1f
199
+ source = fs_bulk_operations_scenario_0
200
+
201
+ target = fs_target
202
+ fs.mkdir(target)
203
+
204
+ for source_slash, target_slash in zip([False, True], [False, True]):
205
+ s = fs_join(source, "subdir")
206
+ if source_slash:
207
+ s += "/"
208
+ t = fs_join(target, "newdir")
209
+ if target_slash:
210
+ t += "/"
211
+
212
+ # Without recursive does nothing
213
+ fs.cp(s, t)
214
+ if supports_empty_directories:
215
+ assert fs.ls(target) == []
216
+ else:
217
+ with pytest.raises(FileNotFoundError):
218
+ fs.ls(target)
219
+
220
+ # With recursive
221
+ fs.cp(s, t, recursive=True)
222
+ assert fs.isdir(fs_join(target, "newdir"))
223
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
224
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
225
+ assert fs.isdir(fs_join(target, "newdir", "nesteddir"))
226
+ assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile"))
227
+ assert not fs.exists(fs_join(target, "subdir"))
228
+
229
+ fs.rm(fs_join(target, "newdir"), recursive=True)
230
+ assert not fs.exists(fs_join(target, "newdir"))
231
+
232
+ # Limit recursive by maxdepth
233
+ fs.cp(s, t, recursive=True, maxdepth=1)
234
+ assert fs.isdir(fs_join(target, "newdir"))
235
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
236
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
237
+ assert not fs.exists(fs_join(target, "newdir", "nesteddir"))
238
+ assert not fs.exists(fs_join(target, "subdir"))
239
+
240
+ fs.rm(fs_join(target, "newdir"), recursive=True)
241
+ assert not fs.exists(fs_join(target, "newdir"))
242
+
243
+ def test_copy_glob_to_existing_directory(
244
+ self,
245
+ fs,
246
+ fs_join,
247
+ fs_bulk_operations_scenario_0,
248
+ fs_target,
249
+ supports_empty_directories,
250
+ ):
251
+ # Copy scenario 1g
252
+ source = fs_bulk_operations_scenario_0
253
+
254
+ target = fs_target
255
+ fs.mkdir(target)
256
+ if not supports_empty_directories:
257
+ # Force target directory to exist by adding a dummy file
258
+ dummy = fs_join(target, "dummy")
259
+ fs.touch(dummy)
260
+ assert fs.isdir(target)
261
+
262
+ for target_slash in [False, True]:
263
+ t = target + "/" if target_slash else target
264
+
265
+ # Without recursive
266
+ fs.cp(fs_join(source, "subdir", "*"), t)
267
+ assert fs.isfile(fs_join(target, "subfile1"))
268
+ assert fs.isfile(fs_join(target, "subfile2"))
269
+ assert not fs.isdir(fs_join(target, "nesteddir"))
270
+ assert not fs.exists(fs_join(target, "nesteddir", "nestedfile"))
271
+ assert not fs.exists(fs_join(target, "subdir"))
272
+
273
+ fs.rm(
274
+ [
275
+ fs_join(target, "subfile1"),
276
+ fs_join(target, "subfile2"),
277
+ ],
278
+ recursive=True,
279
+ )
280
+ assert fs.ls(target, detail=False) == (
281
+ [] if supports_empty_directories else [dummy]
282
+ )
283
+
284
+ # With recursive
285
+ for glob, recursive in zip(["*", "**"], [True, False]):
286
+ fs.cp(fs_join(source, "subdir", glob), t, recursive=recursive)
287
+ assert fs.isfile(fs_join(target, "subfile1"))
288
+ assert fs.isfile(fs_join(target, "subfile2"))
289
+ assert fs.isdir(fs_join(target, "nesteddir"))
290
+ assert fs.isfile(fs_join(target, "nesteddir", "nestedfile"))
291
+ assert not fs.exists(fs_join(target, "subdir"))
292
+
293
+ fs.rm(
294
+ [
295
+ fs_join(target, "subfile1"),
296
+ fs_join(target, "subfile2"),
297
+ fs_join(target, "nesteddir"),
298
+ ],
299
+ recursive=True,
300
+ )
301
+ assert fs.ls(target, detail=False) == (
302
+ [] if supports_empty_directories else [dummy]
303
+ )
304
+
305
+ # Limit recursive by maxdepth
306
+ fs.cp(
307
+ fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1
308
+ )
309
+ assert fs.isfile(fs_join(target, "subfile1"))
310
+ assert fs.isfile(fs_join(target, "subfile2"))
311
+ assert not fs.exists(fs_join(target, "nesteddir"))
312
+ assert not fs.exists(fs_join(target, "subdir"))
313
+
314
+ fs.rm(
315
+ [
316
+ fs_join(target, "subfile1"),
317
+ fs_join(target, "subfile2"),
318
+ ],
319
+ recursive=True,
320
+ )
321
+ assert fs.ls(target, detail=False) == (
322
+ [] if supports_empty_directories else [dummy]
323
+ )
324
+
325
+ def test_copy_glob_to_new_directory(
326
+ self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target
327
+ ):
328
+ # Copy scenario 1h
329
+ source = fs_bulk_operations_scenario_0
330
+
331
+ target = fs_target
332
+ fs.mkdir(target)
333
+
334
+ for target_slash in [False, True]:
335
+ t = fs_join(target, "newdir")
336
+ if target_slash:
337
+ t += "/"
338
+
339
+ # Without recursive
340
+ fs.cp(fs_join(source, "subdir", "*"), t)
341
+ assert fs.isdir(fs_join(target, "newdir"))
342
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
343
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
344
+ assert not fs.exists(fs_join(target, "newdir", "nesteddir"))
345
+ assert not fs.exists(fs_join(target, "newdir", "nesteddir", "nestedfile"))
346
+ assert not fs.exists(fs_join(target, "subdir"))
347
+ assert not fs.exists(fs_join(target, "newdir", "subdir"))
348
+
349
+ fs.rm(fs_join(target, "newdir"), recursive=True)
350
+ assert not fs.exists(fs_join(target, "newdir"))
351
+
352
+ # With recursive
353
+ for glob, recursive in zip(["*", "**"], [True, False]):
354
+ fs.cp(fs_join(source, "subdir", glob), t, recursive=recursive)
355
+ assert fs.isdir(fs_join(target, "newdir"))
356
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
357
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
358
+ assert fs.isdir(fs_join(target, "newdir", "nesteddir"))
359
+ assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile"))
360
+ assert not fs.exists(fs_join(target, "subdir"))
361
+ assert not fs.exists(fs_join(target, "newdir", "subdir"))
362
+
363
+ fs.rm(fs_join(target, "newdir"), recursive=True)
364
+ assert not fs.exists(fs_join(target, "newdir"))
365
+
366
+ # Limit recursive by maxdepth
367
+ fs.cp(
368
+ fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1
369
+ )
370
+ assert fs.isdir(fs_join(target, "newdir"))
371
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
372
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
373
+ assert not fs.exists(fs_join(target, "newdir", "nesteddir"))
374
+ assert not fs.exists(fs_join(target, "subdir"))
375
+ assert not fs.exists(fs_join(target, "newdir", "subdir"))
376
+
377
+ fs.rm(fs_join(target, "newdir"), recursive=True)
378
+ assert not fs.exists(fs_join(target, "newdir"))
379
+
380
+ @pytest.mark.parametrize(
381
+ GLOB_EDGE_CASES_TESTS["argnames"],
382
+ GLOB_EDGE_CASES_TESTS["argvalues"],
383
+ )
384
+ def test_copy_glob_edge_cases(
385
+ self,
386
+ path,
387
+ recursive,
388
+ maxdepth,
389
+ expected,
390
+ fs,
391
+ fs_join,
392
+ fs_glob_edge_cases_files,
393
+ fs_target,
394
+ fs_sanitize_path,
395
+ ):
396
+ # Copy scenario 1g
397
+ source = fs_glob_edge_cases_files
398
+
399
+ target = fs_target
400
+
401
+ for new_dir, target_slash in product([True, False], [True, False]):
402
+ fs.mkdir(target)
403
+
404
+ t = fs_join(target, "newdir") if new_dir else target
405
+ t = t + "/" if target_slash else t
406
+
407
+ fs.copy(fs_join(source, path), t, recursive=recursive, maxdepth=maxdepth)
408
+
409
+ output = fs.find(target)
410
+ if new_dir:
411
+ prefixed_expected = [
412
+ fs_sanitize_path(fs_join(target, "newdir", p)) for p in expected
413
+ ]
414
+ else:
415
+ prefixed_expected = [
416
+ fs_sanitize_path(fs_join(target, p)) for p in expected
417
+ ]
418
+ assert sorted(output) == sorted(prefixed_expected)
419
+
420
+ try:
421
+ fs.rm(target, recursive=True)
422
+ except FileNotFoundError:
423
+ pass
424
+
425
+ def test_copy_list_of_files_to_existing_directory(
426
+ self,
427
+ fs,
428
+ fs_join,
429
+ fs_bulk_operations_scenario_0,
430
+ fs_target,
431
+ supports_empty_directories,
432
+ ):
433
+ # Copy scenario 2a
434
+ source = fs_bulk_operations_scenario_0
435
+
436
+ target = fs_target
437
+ fs.mkdir(target)
438
+ if not supports_empty_directories:
439
+ # Force target directory to exist by adding a dummy file
440
+ dummy = fs_join(target, "dummy")
441
+ fs.touch(dummy)
442
+ assert fs.isdir(target)
443
+
444
+ source_files = [
445
+ fs_join(source, "file1"),
446
+ fs_join(source, "file2"),
447
+ fs_join(source, "subdir", "subfile1"),
448
+ ]
449
+
450
+ for target_slash in [False, True]:
451
+ t = target + "/" if target_slash else target
452
+
453
+ fs.cp(source_files, t)
454
+ assert fs.isfile(fs_join(target, "file1"))
455
+ assert fs.isfile(fs_join(target, "file2"))
456
+ assert fs.isfile(fs_join(target, "subfile1"))
457
+
458
+ fs.rm(
459
+ [
460
+ fs_join(target, "file1"),
461
+ fs_join(target, "file2"),
462
+ fs_join(target, "subfile1"),
463
+ ],
464
+ recursive=True,
465
+ )
466
+ assert fs.ls(target, detail=False) == (
467
+ [] if supports_empty_directories else [dummy]
468
+ )
469
+
470
+ def test_copy_list_of_files_to_new_directory(
471
+ self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target
472
+ ):
473
+ # Copy scenario 2b
474
+ source = fs_bulk_operations_scenario_0
475
+
476
+ target = fs_target
477
+ fs.mkdir(target)
478
+
479
+ source_files = [
480
+ fs_join(source, "file1"),
481
+ fs_join(source, "file2"),
482
+ fs_join(source, "subdir", "subfile1"),
483
+ ]
484
+
485
+ fs.cp(source_files, fs_join(target, "newdir") + "/") # Note trailing slash
486
+ assert fs.isdir(fs_join(target, "newdir"))
487
+ assert fs.isfile(fs_join(target, "newdir", "file1"))
488
+ assert fs.isfile(fs_join(target, "newdir", "file2"))
489
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
490
+
491
+ def test_copy_two_files_new_directory(
492
+ self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target
493
+ ):
494
+ # This is a duplicate of test_copy_list_of_files_to_new_directory and
495
+ # can eventually be removed.
496
+ source = fs_bulk_operations_scenario_0
497
+
498
+ target = fs_target
499
+ assert not fs.exists(target)
500
+ fs.cp([fs_join(source, "file1"), fs_join(source, "file2")], target)
501
+
502
+ assert fs.isdir(target)
503
+ assert fs.isfile(fs_join(target, "file1"))
504
+ assert fs.isfile(fs_join(target, "file2"))
505
+
506
+ def test_copy_directory_without_files_with_same_name_prefix(
507
+ self,
508
+ fs,
509
+ fs_join,
510
+ fs_target,
511
+ fs_dir_and_file_with_same_name_prefix,
512
+ supports_empty_directories,
513
+ ):
514
+ # Create the test dirs
515
+ source = fs_dir_and_file_with_same_name_prefix
516
+ target = fs_target
517
+
518
+ # Test without glob
519
+ fs.cp(fs_join(source, "subdir"), target, recursive=True)
520
+
521
+ assert fs.isfile(fs_join(target, "subfile.txt"))
522
+ assert not fs.isfile(fs_join(target, "subdir.txt"))
523
+
524
+ fs.rm([fs_join(target, "subfile.txt")])
525
+ if supports_empty_directories:
526
+ assert fs.ls(target) == []
527
+ else:
528
+ assert not fs.exists(target)
529
+
530
+ # Test with glob
531
+ fs.cp(fs_join(source, "subdir*"), target, recursive=True)
532
+
533
+ assert fs.isdir(fs_join(target, "subdir"))
534
+ assert fs.isfile(fs_join(target, "subdir", "subfile.txt"))
535
+ assert fs.isfile(fs_join(target, "subdir.txt"))
536
+
537
+ def test_copy_with_source_and_destination_as_list(
538
+ self, fs, fs_target, fs_join, fs_10_files_with_hashed_names
539
+ ):
540
+ # Create the test dir
541
+ source = fs_10_files_with_hashed_names
542
+ target = fs_target
543
+
544
+ # Create list of files for source and destination
545
+ source_files = []
546
+ destination_files = []
547
+ for i in range(10):
548
+ hashed_i = md5(str(i).encode("utf-8")).hexdigest()
549
+ source_files.append(fs_join(source, f"{hashed_i}.txt"))
550
+ destination_files.append(fs_join(target, f"{hashed_i}.txt"))
551
+
552
+ # Copy and assert order was kept
553
+ fs.copy(path1=source_files, path2=destination_files)
554
+
555
+ for i in range(10):
556
+ file_content = fs.cat(destination_files[i]).decode("utf-8")
557
+ assert file_content == str(i)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/get.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from hashlib import md5
2
+ from itertools import product
3
+
4
+ import pytest
5
+
6
+ from fsspec.implementations.local import make_path_posix
7
+ from fsspec.tests.abstract.common import GLOB_EDGE_CASES_TESTS
8
+
9
+
10
+ class AbstractGetTests:
11
+ def test_get_file_to_existing_directory(
12
+ self,
13
+ fs,
14
+ fs_join,
15
+ fs_bulk_operations_scenario_0,
16
+ local_fs,
17
+ local_join,
18
+ local_target,
19
+ ):
20
+ # Copy scenario 1a
21
+ source = fs_bulk_operations_scenario_0
22
+
23
+ target = local_target
24
+ local_fs.mkdir(target)
25
+ assert local_fs.isdir(target)
26
+
27
+ target_file2 = local_join(target, "file2")
28
+ target_subfile1 = local_join(target, "subfile1")
29
+
30
+ # Copy from source directory
31
+ fs.get(fs_join(source, "file2"), target)
32
+ assert local_fs.isfile(target_file2)
33
+
34
+ # Copy from sub directory
35
+ fs.get(fs_join(source, "subdir", "subfile1"), target)
36
+ assert local_fs.isfile(target_subfile1)
37
+
38
+ # Remove copied files
39
+ local_fs.rm([target_file2, target_subfile1])
40
+ assert not local_fs.exists(target_file2)
41
+ assert not local_fs.exists(target_subfile1)
42
+
43
+ # Repeat with trailing slash on target
44
+ fs.get(fs_join(source, "file2"), target + "/")
45
+ assert local_fs.isdir(target)
46
+ assert local_fs.isfile(target_file2)
47
+
48
+ fs.get(fs_join(source, "subdir", "subfile1"), target + "/")
49
+ assert local_fs.isfile(target_subfile1)
50
+
51
+ def test_get_file_to_new_directory(
52
+ self,
53
+ fs,
54
+ fs_join,
55
+ fs_bulk_operations_scenario_0,
56
+ local_fs,
57
+ local_join,
58
+ local_target,
59
+ ):
60
+ # Copy scenario 1b
61
+ source = fs_bulk_operations_scenario_0
62
+
63
+ target = local_target
64
+ local_fs.mkdir(target)
65
+
66
+ fs.get(
67
+ fs_join(source, "subdir", "subfile1"), local_join(target, "newdir/")
68
+ ) # Note trailing slash
69
+
70
+ assert local_fs.isdir(target)
71
+ assert local_fs.isdir(local_join(target, "newdir"))
72
+ assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
73
+
74
+ def test_get_file_to_file_in_existing_directory(
75
+ self,
76
+ fs,
77
+ fs_join,
78
+ fs_bulk_operations_scenario_0,
79
+ local_fs,
80
+ local_join,
81
+ local_target,
82
+ ):
83
+ # Copy scenario 1c
84
+ source = fs_bulk_operations_scenario_0
85
+
86
+ target = local_target
87
+ local_fs.mkdir(target)
88
+
89
+ fs.get(fs_join(source, "subdir", "subfile1"), local_join(target, "newfile"))
90
+ assert local_fs.isfile(local_join(target, "newfile"))
91
+
92
+ def test_get_file_to_file_in_new_directory(
93
+ self,
94
+ fs,
95
+ fs_join,
96
+ fs_bulk_operations_scenario_0,
97
+ local_fs,
98
+ local_join,
99
+ local_target,
100
+ ):
101
+ # Copy scenario 1d
102
+ source = fs_bulk_operations_scenario_0
103
+
104
+ target = local_target
105
+ local_fs.mkdir(target)
106
+
107
+ fs.get(
108
+ fs_join(source, "subdir", "subfile1"),
109
+ local_join(target, "newdir", "newfile"),
110
+ )
111
+ assert local_fs.isdir(local_join(target, "newdir"))
112
+ assert local_fs.isfile(local_join(target, "newdir", "newfile"))
113
+
114
+ def test_get_directory_to_existing_directory(
115
+ self,
116
+ fs,
117
+ fs_join,
118
+ fs_bulk_operations_scenario_0,
119
+ local_fs,
120
+ local_join,
121
+ local_target,
122
+ ):
123
+ # Copy scenario 1e
124
+ source = fs_bulk_operations_scenario_0
125
+
126
+ target = local_target
127
+ local_fs.mkdir(target)
128
+ assert local_fs.isdir(target)
129
+
130
+ for source_slash, target_slash in zip([False, True], [False, True]):
131
+ s = fs_join(source, "subdir")
132
+ if source_slash:
133
+ s += "/"
134
+ t = target + "/" if target_slash else target
135
+
136
+ # Without recursive does nothing
137
+ fs.get(s, t)
138
+ assert local_fs.ls(target) == []
139
+
140
+ # With recursive
141
+ fs.get(s, t, recursive=True)
142
+ if source_slash:
143
+ assert local_fs.isfile(local_join(target, "subfile1"))
144
+ assert local_fs.isfile(local_join(target, "subfile2"))
145
+ assert local_fs.isdir(local_join(target, "nesteddir"))
146
+ assert local_fs.isfile(local_join(target, "nesteddir", "nestedfile"))
147
+ assert not local_fs.exists(local_join(target, "subdir"))
148
+
149
+ local_fs.rm(
150
+ [
151
+ local_join(target, "subfile1"),
152
+ local_join(target, "subfile2"),
153
+ local_join(target, "nesteddir"),
154
+ ],
155
+ recursive=True,
156
+ )
157
+ else:
158
+ assert local_fs.isdir(local_join(target, "subdir"))
159
+ assert local_fs.isfile(local_join(target, "subdir", "subfile1"))
160
+ assert local_fs.isfile(local_join(target, "subdir", "subfile2"))
161
+ assert local_fs.isdir(local_join(target, "subdir", "nesteddir"))
162
+ assert local_fs.isfile(
163
+ local_join(target, "subdir", "nesteddir", "nestedfile")
164
+ )
165
+
166
+ local_fs.rm(local_join(target, "subdir"), recursive=True)
167
+ assert local_fs.ls(target) == []
168
+
169
+ # Limit recursive by maxdepth
170
+ fs.get(s, t, recursive=True, maxdepth=1)
171
+ if source_slash:
172
+ assert local_fs.isfile(local_join(target, "subfile1"))
173
+ assert local_fs.isfile(local_join(target, "subfile2"))
174
+ assert not local_fs.exists(local_join(target, "nesteddir"))
175
+ assert not local_fs.exists(local_join(target, "subdir"))
176
+
177
+ local_fs.rm(
178
+ [
179
+ local_join(target, "subfile1"),
180
+ local_join(target, "subfile2"),
181
+ ],
182
+ recursive=True,
183
+ )
184
+ else:
185
+ assert local_fs.isdir(local_join(target, "subdir"))
186
+ assert local_fs.isfile(local_join(target, "subdir", "subfile1"))
187
+ assert local_fs.isfile(local_join(target, "subdir", "subfile2"))
188
+ assert not local_fs.exists(local_join(target, "subdir", "nesteddir"))
189
+
190
+ local_fs.rm(local_join(target, "subdir"), recursive=True)
191
+ assert local_fs.ls(target) == []
192
+
193
+ def test_get_directory_to_new_directory(
194
+ self,
195
+ fs,
196
+ fs_join,
197
+ fs_bulk_operations_scenario_0,
198
+ local_fs,
199
+ local_join,
200
+ local_target,
201
+ ):
202
+ # Copy scenario 1f
203
+ source = fs_bulk_operations_scenario_0
204
+
205
+ target = local_target
206
+ local_fs.mkdir(target)
207
+
208
+ for source_slash, target_slash in zip([False, True], [False, True]):
209
+ s = fs_join(source, "subdir")
210
+ if source_slash:
211
+ s += "/"
212
+ t = local_join(target, "newdir")
213
+ if target_slash:
214
+ t += "/"
215
+
216
+ # Without recursive does nothing
217
+ fs.get(s, t)
218
+ assert local_fs.ls(target) == []
219
+
220
+ # With recursive
221
+ fs.get(s, t, recursive=True)
222
+ assert local_fs.isdir(local_join(target, "newdir"))
223
+ assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
224
+ assert local_fs.isfile(local_join(target, "newdir", "subfile2"))
225
+ assert local_fs.isdir(local_join(target, "newdir", "nesteddir"))
226
+ assert local_fs.isfile(
227
+ local_join(target, "newdir", "nesteddir", "nestedfile")
228
+ )
229
+ assert not local_fs.exists(local_join(target, "subdir"))
230
+
231
+ local_fs.rm(local_join(target, "newdir"), recursive=True)
232
+ assert local_fs.ls(target) == []
233
+
234
+ # Limit recursive by maxdepth
235
+ fs.get(s, t, recursive=True, maxdepth=1)
236
+ assert local_fs.isdir(local_join(target, "newdir"))
237
+ assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
238
+ assert local_fs.isfile(local_join(target, "newdir", "subfile2"))
239
+ assert not local_fs.exists(local_join(target, "newdir", "nesteddir"))
240
+ assert not local_fs.exists(local_join(target, "subdir"))
241
+
242
+ local_fs.rm(local_join(target, "newdir"), recursive=True)
243
+ assert not local_fs.exists(local_join(target, "newdir"))
244
+
245
+ def test_get_glob_to_existing_directory(
246
+ self,
247
+ fs,
248
+ fs_join,
249
+ fs_bulk_operations_scenario_0,
250
+ local_fs,
251
+ local_join,
252
+ local_target,
253
+ ):
254
+ # Copy scenario 1g
255
+ source = fs_bulk_operations_scenario_0
256
+
257
+ target = local_target
258
+ local_fs.mkdir(target)
259
+
260
+ for target_slash in [False, True]:
261
+ t = target + "/" if target_slash else target
262
+
263
+ # Without recursive
264
+ fs.get(fs_join(source, "subdir", "*"), t)
265
+ assert local_fs.isfile(local_join(target, "subfile1"))
266
+ assert local_fs.isfile(local_join(target, "subfile2"))
267
+ assert not local_fs.isdir(local_join(target, "nesteddir"))
268
+ assert not local_fs.exists(local_join(target, "nesteddir", "nestedfile"))
269
+ assert not local_fs.exists(local_join(target, "subdir"))
270
+
271
+ local_fs.rm(
272
+ [
273
+ local_join(target, "subfile1"),
274
+ local_join(target, "subfile2"),
275
+ ],
276
+ recursive=True,
277
+ )
278
+ assert local_fs.ls(target) == []
279
+
280
+ # With recursive
281
+ for glob, recursive in zip(["*", "**"], [True, False]):
282
+ fs.get(fs_join(source, "subdir", glob), t, recursive=recursive)
283
+ assert local_fs.isfile(local_join(target, "subfile1"))
284
+ assert local_fs.isfile(local_join(target, "subfile2"))
285
+ assert local_fs.isdir(local_join(target, "nesteddir"))
286
+ assert local_fs.isfile(local_join(target, "nesteddir", "nestedfile"))
287
+ assert not local_fs.exists(local_join(target, "subdir"))
288
+
289
+ local_fs.rm(
290
+ [
291
+ local_join(target, "subfile1"),
292
+ local_join(target, "subfile2"),
293
+ local_join(target, "nesteddir"),
294
+ ],
295
+ recursive=True,
296
+ )
297
+ assert local_fs.ls(target) == []
298
+
299
+ # Limit recursive by maxdepth
300
+ fs.get(
301
+ fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1
302
+ )
303
+ assert local_fs.isfile(local_join(target, "subfile1"))
304
+ assert local_fs.isfile(local_join(target, "subfile2"))
305
+ assert not local_fs.exists(local_join(target, "nesteddir"))
306
+ assert not local_fs.exists(local_join(target, "subdir"))
307
+
308
+ local_fs.rm(
309
+ [
310
+ local_join(target, "subfile1"),
311
+ local_join(target, "subfile2"),
312
+ ],
313
+ recursive=True,
314
+ )
315
+ assert local_fs.ls(target) == []
316
+
317
+ def test_get_glob_to_new_directory(
318
+ self,
319
+ fs,
320
+ fs_join,
321
+ fs_bulk_operations_scenario_0,
322
+ local_fs,
323
+ local_join,
324
+ local_target,
325
+ ):
326
+ # Copy scenario 1h
327
+ source = fs_bulk_operations_scenario_0
328
+
329
+ target = local_target
330
+ local_fs.mkdir(target)
331
+
332
+ for target_slash in [False, True]:
333
+ t = fs_join(target, "newdir")
334
+ if target_slash:
335
+ t += "/"
336
+
337
+ # Without recursive
338
+ fs.get(fs_join(source, "subdir", "*"), t)
339
+ assert local_fs.isdir(local_join(target, "newdir"))
340
+ assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
341
+ assert local_fs.isfile(local_join(target, "newdir", "subfile2"))
342
+ assert not local_fs.exists(local_join(target, "newdir", "nesteddir"))
343
+ assert not local_fs.exists(
344
+ local_join(target, "newdir", "nesteddir", "nestedfile")
345
+ )
346
+ assert not local_fs.exists(local_join(target, "subdir"))
347
+ assert not local_fs.exists(local_join(target, "newdir", "subdir"))
348
+
349
+ local_fs.rm(local_join(target, "newdir"), recursive=True)
350
+ assert local_fs.ls(target) == []
351
+
352
+ # With recursive
353
+ for glob, recursive in zip(["*", "**"], [True, False]):
354
+ fs.get(fs_join(source, "subdir", glob), t, recursive=recursive)
355
+ assert local_fs.isdir(local_join(target, "newdir"))
356
+ assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
357
+ assert local_fs.isfile(local_join(target, "newdir", "subfile2"))
358
+ assert local_fs.isdir(local_join(target, "newdir", "nesteddir"))
359
+ assert local_fs.isfile(
360
+ local_join(target, "newdir", "nesteddir", "nestedfile")
361
+ )
362
+ assert not local_fs.exists(local_join(target, "subdir"))
363
+ assert not local_fs.exists(local_join(target, "newdir", "subdir"))
364
+
365
+ local_fs.rm(local_join(target, "newdir"), recursive=True)
366
+ assert not local_fs.exists(local_join(target, "newdir"))
367
+
368
+ # Limit recursive by maxdepth
369
+ fs.get(
370
+ fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1
371
+ )
372
+ assert local_fs.isdir(local_join(target, "newdir"))
373
+ assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
374
+ assert local_fs.isfile(local_join(target, "newdir", "subfile2"))
375
+ assert not local_fs.exists(local_join(target, "newdir", "nesteddir"))
376
+ assert not local_fs.exists(local_join(target, "subdir"))
377
+ assert not local_fs.exists(local_join(target, "newdir", "subdir"))
378
+
379
+ local_fs.rm(local_fs.ls(target, detail=False), recursive=True)
380
+ assert not local_fs.exists(local_join(target, "newdir"))
381
+
382
+ @pytest.mark.parametrize(
383
+ GLOB_EDGE_CASES_TESTS["argnames"],
384
+ GLOB_EDGE_CASES_TESTS["argvalues"],
385
+ )
386
+ def test_get_glob_edge_cases(
387
+ self,
388
+ path,
389
+ recursive,
390
+ maxdepth,
391
+ expected,
392
+ fs,
393
+ fs_join,
394
+ fs_glob_edge_cases_files,
395
+ local_fs,
396
+ local_join,
397
+ local_target,
398
+ ):
399
+ # Copy scenario 1g
400
+ source = fs_glob_edge_cases_files
401
+
402
+ target = local_target
403
+
404
+ for new_dir, target_slash in product([True, False], [True, False]):
405
+ local_fs.mkdir(target)
406
+
407
+ t = local_join(target, "newdir") if new_dir else target
408
+ t = t + "/" if target_slash else t
409
+
410
+ fs.get(fs_join(source, path), t, recursive=recursive, maxdepth=maxdepth)
411
+
412
+ output = local_fs.find(target)
413
+ if new_dir:
414
+ prefixed_expected = [
415
+ make_path_posix(local_join(target, "newdir", p)) for p in expected
416
+ ]
417
+ else:
418
+ prefixed_expected = [
419
+ make_path_posix(local_join(target, p)) for p in expected
420
+ ]
421
+ assert sorted(output) == sorted(prefixed_expected)
422
+
423
+ try:
424
+ local_fs.rm(target, recursive=True)
425
+ except FileNotFoundError:
426
+ pass
427
+
428
+ def test_get_list_of_files_to_existing_directory(
429
+ self,
430
+ fs,
431
+ fs_join,
432
+ fs_bulk_operations_scenario_0,
433
+ local_fs,
434
+ local_join,
435
+ local_target,
436
+ ):
437
+ # Copy scenario 2a
438
+ source = fs_bulk_operations_scenario_0
439
+
440
+ target = local_target
441
+ local_fs.mkdir(target)
442
+
443
+ source_files = [
444
+ fs_join(source, "file1"),
445
+ fs_join(source, "file2"),
446
+ fs_join(source, "subdir", "subfile1"),
447
+ ]
448
+
449
+ for target_slash in [False, True]:
450
+ t = target + "/" if target_slash else target
451
+
452
+ fs.get(source_files, t)
453
+ assert local_fs.isfile(local_join(target, "file1"))
454
+ assert local_fs.isfile(local_join(target, "file2"))
455
+ assert local_fs.isfile(local_join(target, "subfile1"))
456
+
457
+ local_fs.rm(
458
+ [
459
+ local_join(target, "file1"),
460
+ local_join(target, "file2"),
461
+ local_join(target, "subfile1"),
462
+ ],
463
+ recursive=True,
464
+ )
465
+ assert local_fs.ls(target) == []
466
+
467
+ def test_get_list_of_files_to_new_directory(
468
+ self,
469
+ fs,
470
+ fs_join,
471
+ fs_bulk_operations_scenario_0,
472
+ local_fs,
473
+ local_join,
474
+ local_target,
475
+ ):
476
+ # Copy scenario 2b
477
+ source = fs_bulk_operations_scenario_0
478
+
479
+ target = local_target
480
+ local_fs.mkdir(target)
481
+
482
+ source_files = [
483
+ fs_join(source, "file1"),
484
+ fs_join(source, "file2"),
485
+ fs_join(source, "subdir", "subfile1"),
486
+ ]
487
+
488
+ fs.get(source_files, local_join(target, "newdir") + "/") # Note trailing slash
489
+ assert local_fs.isdir(local_join(target, "newdir"))
490
+ assert local_fs.isfile(local_join(target, "newdir", "file1"))
491
+ assert local_fs.isfile(local_join(target, "newdir", "file2"))
492
+ assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
493
+
494
+ def test_get_directory_recursive(
495
+ self, fs, fs_join, fs_path, local_fs, local_join, local_target
496
+ ):
497
+ # https://github.com/fsspec/filesystem_spec/issues/1062
498
+ # Recursive cp/get/put of source directory into non-existent target directory.
499
+ src = fs_join(fs_path, "src")
500
+ src_file = fs_join(src, "file")
501
+ fs.mkdir(src)
502
+ fs.touch(src_file)
503
+
504
+ target = local_target
505
+
506
+ # get without slash
507
+ assert not local_fs.exists(target)
508
+ for loop in range(2):
509
+ fs.get(src, target, recursive=True)
510
+ assert local_fs.isdir(target)
511
+
512
+ if loop == 0:
513
+ assert local_fs.isfile(local_join(target, "file"))
514
+ assert not local_fs.exists(local_join(target, "src"))
515
+ else:
516
+ assert local_fs.isfile(local_join(target, "file"))
517
+ assert local_fs.isdir(local_join(target, "src"))
518
+ assert local_fs.isfile(local_join(target, "src", "file"))
519
+
520
+ local_fs.rm(target, recursive=True)
521
+
522
+ # get with slash
523
+ assert not local_fs.exists(target)
524
+ for loop in range(2):
525
+ fs.get(src + "/", target, recursive=True)
526
+ assert local_fs.isdir(target)
527
+ assert local_fs.isfile(local_join(target, "file"))
528
+ assert not local_fs.exists(local_join(target, "src"))
529
+
530
+ def test_get_directory_without_files_with_same_name_prefix(
531
+ self,
532
+ fs,
533
+ fs_join,
534
+ local_fs,
535
+ local_join,
536
+ local_target,
537
+ fs_dir_and_file_with_same_name_prefix,
538
+ ):
539
+ # Create the test dirs
540
+ source = fs_dir_and_file_with_same_name_prefix
541
+ target = local_target
542
+
543
+ # Test without glob
544
+ fs.get(fs_join(source, "subdir"), target, recursive=True)
545
+
546
+ assert local_fs.isfile(local_join(target, "subfile.txt"))
547
+ assert not local_fs.isfile(local_join(target, "subdir.txt"))
548
+
549
+ local_fs.rm([local_join(target, "subfile.txt")])
550
+ assert local_fs.ls(target) == []
551
+
552
+ # Test with glob
553
+ fs.get(fs_join(source, "subdir*"), target, recursive=True)
554
+
555
+ assert local_fs.isdir(local_join(target, "subdir"))
556
+ assert local_fs.isfile(local_join(target, "subdir", "subfile.txt"))
557
+ assert local_fs.isfile(local_join(target, "subdir.txt"))
558
+
559
+ def test_get_with_source_and_destination_as_list(
560
+ self,
561
+ fs,
562
+ fs_join,
563
+ local_fs,
564
+ local_join,
565
+ local_target,
566
+ fs_10_files_with_hashed_names,
567
+ ):
568
+ # Create the test dir
569
+ source = fs_10_files_with_hashed_names
570
+ target = local_target
571
+
572
+ # Create list of files for source and destination
573
+ source_files = []
574
+ destination_files = []
575
+ for i in range(10):
576
+ hashed_i = md5(str(i).encode("utf-8")).hexdigest()
577
+ source_files.append(fs_join(source, f"{hashed_i}.txt"))
578
+ destination_files.append(
579
+ make_path_posix(local_join(target, f"{hashed_i}.txt"))
580
+ )
581
+
582
+ # Copy and assert order was kept
583
+ fs.get(rpath=source_files, lpath=destination_files)
584
+
585
+ for i in range(10):
586
+ file_content = local_fs.cat(destination_files[i]).decode("utf-8")
587
+ assert file_content == str(i)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/mv.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import pytest
4
+
5
+ import fsspec
6
+
7
+
8
+ def test_move_raises_error_with_tmpdir(tmpdir):
9
+ # Create a file in the temporary directory
10
+ source = tmpdir.join("source_file.txt")
11
+ source.write("content")
12
+
13
+ # Define a destination that simulates a protected or invalid path
14
+ destination = tmpdir.join("non_existent_directory/destination_file.txt")
15
+
16
+ # Instantiate the filesystem (assuming the local file system interface)
17
+ fs = fsspec.filesystem("file")
18
+
19
+ # Use the actual file paths as string
20
+ with pytest.raises(FileNotFoundError):
21
+ fs.mv(str(source), str(destination))
22
+
23
+
24
+ @pytest.mark.parametrize("recursive", (True, False))
25
+ def test_move_raises_error_with_tmpdir_permission(recursive, tmpdir):
26
+ # Create a file in the temporary directory
27
+ source = tmpdir.join("source_file.txt")
28
+ source.write("content")
29
+
30
+ # Create a protected directory (non-writable)
31
+ protected_dir = tmpdir.mkdir("protected_directory")
32
+ protected_path = str(protected_dir)
33
+
34
+ # Set the directory to read-only
35
+ if os.name == "nt":
36
+ os.system(f'icacls "{protected_path}" /deny Everyone:(W)')
37
+ else:
38
+ os.chmod(protected_path, 0o555) # Sets the directory to read-only
39
+
40
+ # Define a destination inside the protected directory
41
+ destination = protected_dir.join("destination_file.txt")
42
+
43
+ # Instantiate the filesystem (assuming the local file system interface)
44
+ fs = fsspec.filesystem("file")
45
+
46
+ # Try to move the file to the read-only directory, expecting a permission error
47
+ with pytest.raises(PermissionError):
48
+ fs.mv(str(source), str(destination), recursive=recursive)
49
+
50
+ # Assert the file was not created in the destination
51
+ assert not os.path.exists(destination)
52
+
53
+ # Cleanup: Restore permissions so the directory can be cleaned up
54
+ if os.name == "nt":
55
+ os.system(f'icacls "{protected_path}" /remove:d Everyone')
56
+ else:
57
+ os.chmod(protected_path, 0o755) # Restore write permission for cleanup
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/open.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+
4
+ class AbstractOpenTests:
5
+ def test_open_exclusive(self, fs, fs_target):
6
+ with fs.open(fs_target, "wb") as f:
7
+ f.write(b"data")
8
+ with fs.open(fs_target, "rb") as f:
9
+ assert f.read() == b"data"
10
+ with pytest.raises(FileExistsError):
11
+ fs.open(fs_target, "xb")
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/pipe.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+
4
+ class AbstractPipeTests:
5
+ def test_pipe_exclusive(self, fs, fs_target):
6
+ fs.pipe_file(fs_target, b"data")
7
+ assert fs.cat_file(fs_target) == b"data"
8
+ with pytest.raises(FileExistsError):
9
+ fs.pipe_file(fs_target, b"data", mode="create")
10
+ fs.pipe_file(fs_target, b"new data", mode="overwrite")
11
+ assert fs.cat_file(fs_target) == b"new data"
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/put.py ADDED
@@ -0,0 +1,591 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from hashlib import md5
2
+ from itertools import product
3
+
4
+ import pytest
5
+
6
+ from fsspec.tests.abstract.common import GLOB_EDGE_CASES_TESTS
7
+
8
+
9
+ class AbstractPutTests:
10
+ def test_put_file_to_existing_directory(
11
+ self,
12
+ fs,
13
+ fs_join,
14
+ fs_target,
15
+ local_join,
16
+ local_bulk_operations_scenario_0,
17
+ supports_empty_directories,
18
+ ):
19
+ # Copy scenario 1a
20
+ source = local_bulk_operations_scenario_0
21
+
22
+ target = fs_target
23
+ fs.mkdir(target)
24
+ if not supports_empty_directories:
25
+ # Force target directory to exist by adding a dummy file
26
+ fs.touch(fs_join(target, "dummy"))
27
+ assert fs.isdir(target)
28
+
29
+ target_file2 = fs_join(target, "file2")
30
+ target_subfile1 = fs_join(target, "subfile1")
31
+
32
+ # Copy from source directory
33
+ fs.put(local_join(source, "file2"), target)
34
+ assert fs.isfile(target_file2)
35
+
36
+ # Copy from sub directory
37
+ fs.put(local_join(source, "subdir", "subfile1"), target)
38
+ assert fs.isfile(target_subfile1)
39
+
40
+ # Remove copied files
41
+ fs.rm([target_file2, target_subfile1])
42
+ assert not fs.exists(target_file2)
43
+ assert not fs.exists(target_subfile1)
44
+
45
+ # Repeat with trailing slash on target
46
+ fs.put(local_join(source, "file2"), target + "/")
47
+ assert fs.isdir(target)
48
+ assert fs.isfile(target_file2)
49
+
50
+ fs.put(local_join(source, "subdir", "subfile1"), target + "/")
51
+ assert fs.isfile(target_subfile1)
52
+
53
+ def test_put_file_to_new_directory(
54
+ self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0
55
+ ):
56
+ # Copy scenario 1b
57
+ source = local_bulk_operations_scenario_0
58
+
59
+ target = fs_target
60
+ fs.mkdir(target)
61
+
62
+ fs.put(
63
+ local_join(source, "subdir", "subfile1"), fs_join(target, "newdir/")
64
+ ) # Note trailing slash
65
+ assert fs.isdir(target)
66
+ assert fs.isdir(fs_join(target, "newdir"))
67
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
68
+
69
+ def test_put_file_to_file_in_existing_directory(
70
+ self,
71
+ fs,
72
+ fs_join,
73
+ fs_target,
74
+ local_join,
75
+ supports_empty_directories,
76
+ local_bulk_operations_scenario_0,
77
+ ):
78
+ # Copy scenario 1c
79
+ source = local_bulk_operations_scenario_0
80
+
81
+ target = fs_target
82
+ fs.mkdir(target)
83
+ if not supports_empty_directories:
84
+ # Force target directory to exist by adding a dummy file
85
+ fs.touch(fs_join(target, "dummy"))
86
+ assert fs.isdir(target)
87
+
88
+ fs.put(local_join(source, "subdir", "subfile1"), fs_join(target, "newfile"))
89
+ assert fs.isfile(fs_join(target, "newfile"))
90
+
91
+ def test_put_file_to_file_in_new_directory(
92
+ self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0
93
+ ):
94
+ # Copy scenario 1d
95
+ source = local_bulk_operations_scenario_0
96
+
97
+ target = fs_target
98
+ fs.mkdir(target)
99
+
100
+ fs.put(
101
+ local_join(source, "subdir", "subfile1"),
102
+ fs_join(target, "newdir", "newfile"),
103
+ )
104
+ assert fs.isdir(fs_join(target, "newdir"))
105
+ assert fs.isfile(fs_join(target, "newdir", "newfile"))
106
+
107
+ def test_put_directory_to_existing_directory(
108
+ self,
109
+ fs,
110
+ fs_join,
111
+ fs_target,
112
+ local_bulk_operations_scenario_0,
113
+ supports_empty_directories,
114
+ ):
115
+ # Copy scenario 1e
116
+ source = local_bulk_operations_scenario_0
117
+
118
+ target = fs_target
119
+ fs.mkdir(target)
120
+ if not supports_empty_directories:
121
+ # Force target directory to exist by adding a dummy file
122
+ dummy = fs_join(target, "dummy")
123
+ fs.touch(dummy)
124
+ assert fs.isdir(target)
125
+
126
+ for source_slash, target_slash in zip([False, True], [False, True]):
127
+ s = fs_join(source, "subdir")
128
+ if source_slash:
129
+ s += "/"
130
+ t = target + "/" if target_slash else target
131
+
132
+ # Without recursive does nothing
133
+ fs.put(s, t)
134
+ assert fs.ls(target, detail=False) == (
135
+ [] if supports_empty_directories else [dummy]
136
+ )
137
+
138
+ # With recursive
139
+ fs.put(s, t, recursive=True)
140
+ if source_slash:
141
+ assert fs.isfile(fs_join(target, "subfile1"))
142
+ assert fs.isfile(fs_join(target, "subfile2"))
143
+ assert fs.isdir(fs_join(target, "nesteddir"))
144
+ assert fs.isfile(fs_join(target, "nesteddir", "nestedfile"))
145
+ assert not fs.exists(fs_join(target, "subdir"))
146
+
147
+ fs.rm(
148
+ [
149
+ fs_join(target, "subfile1"),
150
+ fs_join(target, "subfile2"),
151
+ fs_join(target, "nesteddir"),
152
+ ],
153
+ recursive=True,
154
+ )
155
+ else:
156
+ assert fs.isdir(fs_join(target, "subdir"))
157
+ assert fs.isfile(fs_join(target, "subdir", "subfile1"))
158
+ assert fs.isfile(fs_join(target, "subdir", "subfile2"))
159
+ assert fs.isdir(fs_join(target, "subdir", "nesteddir"))
160
+ assert fs.isfile(fs_join(target, "subdir", "nesteddir", "nestedfile"))
161
+
162
+ fs.rm(fs_join(target, "subdir"), recursive=True)
163
+ assert fs.ls(target, detail=False) == (
164
+ [] if supports_empty_directories else [dummy]
165
+ )
166
+
167
+ # Limit recursive by maxdepth
168
+ fs.put(s, t, recursive=True, maxdepth=1)
169
+ if source_slash:
170
+ assert fs.isfile(fs_join(target, "subfile1"))
171
+ assert fs.isfile(fs_join(target, "subfile2"))
172
+ assert not fs.exists(fs_join(target, "nesteddir"))
173
+ assert not fs.exists(fs_join(target, "subdir"))
174
+
175
+ fs.rm(
176
+ [
177
+ fs_join(target, "subfile1"),
178
+ fs_join(target, "subfile2"),
179
+ ],
180
+ recursive=True,
181
+ )
182
+ else:
183
+ assert fs.isdir(fs_join(target, "subdir"))
184
+ assert fs.isfile(fs_join(target, "subdir", "subfile1"))
185
+ assert fs.isfile(fs_join(target, "subdir", "subfile2"))
186
+ assert not fs.exists(fs_join(target, "subdir", "nesteddir"))
187
+
188
+ fs.rm(fs_join(target, "subdir"), recursive=True)
189
+ assert fs.ls(target, detail=False) == (
190
+ [] if supports_empty_directories else [dummy]
191
+ )
192
+
193
+ def test_put_directory_to_new_directory(
194
+ self,
195
+ fs,
196
+ fs_join,
197
+ fs_target,
198
+ local_bulk_operations_scenario_0,
199
+ supports_empty_directories,
200
+ ):
201
+ # Copy scenario 1f
202
+ source = local_bulk_operations_scenario_0
203
+
204
+ target = fs_target
205
+ fs.mkdir(target)
206
+
207
+ for source_slash, target_slash in zip([False, True], [False, True]):
208
+ s = fs_join(source, "subdir")
209
+ if source_slash:
210
+ s += "/"
211
+ t = fs_join(target, "newdir")
212
+ if target_slash:
213
+ t += "/"
214
+
215
+ # Without recursive does nothing
216
+ fs.put(s, t)
217
+ if supports_empty_directories:
218
+ assert fs.ls(target) == []
219
+ else:
220
+ with pytest.raises(FileNotFoundError):
221
+ fs.ls(target)
222
+
223
+ # With recursive
224
+ fs.put(s, t, recursive=True)
225
+ assert fs.isdir(fs_join(target, "newdir"))
226
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
227
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
228
+ assert fs.isdir(fs_join(target, "newdir", "nesteddir"))
229
+ assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile"))
230
+ assert not fs.exists(fs_join(target, "subdir"))
231
+
232
+ fs.rm(fs_join(target, "newdir"), recursive=True)
233
+ assert not fs.exists(fs_join(target, "newdir"))
234
+
235
+ # Limit recursive by maxdepth
236
+ fs.put(s, t, recursive=True, maxdepth=1)
237
+ assert fs.isdir(fs_join(target, "newdir"))
238
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
239
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
240
+ assert not fs.exists(fs_join(target, "newdir", "nesteddir"))
241
+ assert not fs.exists(fs_join(target, "subdir"))
242
+
243
+ fs.rm(fs_join(target, "newdir"), recursive=True)
244
+ assert not fs.exists(fs_join(target, "newdir"))
245
+
246
+ def test_put_glob_to_existing_directory(
247
+ self,
248
+ fs,
249
+ fs_join,
250
+ fs_target,
251
+ local_join,
252
+ supports_empty_directories,
253
+ local_bulk_operations_scenario_0,
254
+ ):
255
+ # Copy scenario 1g
256
+ source = local_bulk_operations_scenario_0
257
+
258
+ target = fs_target
259
+ fs.mkdir(target)
260
+ if not supports_empty_directories:
261
+ # Force target directory to exist by adding a dummy file
262
+ dummy = fs_join(target, "dummy")
263
+ fs.touch(dummy)
264
+ assert fs.isdir(target)
265
+
266
+ for target_slash in [False, True]:
267
+ t = target + "/" if target_slash else target
268
+
269
+ # Without recursive
270
+ fs.put(local_join(source, "subdir", "*"), t)
271
+ assert fs.isfile(fs_join(target, "subfile1"))
272
+ assert fs.isfile(fs_join(target, "subfile2"))
273
+ assert not fs.isdir(fs_join(target, "nesteddir"))
274
+ assert not fs.exists(fs_join(target, "nesteddir", "nestedfile"))
275
+ assert not fs.exists(fs_join(target, "subdir"))
276
+
277
+ fs.rm(
278
+ [
279
+ fs_join(target, "subfile1"),
280
+ fs_join(target, "subfile2"),
281
+ ],
282
+ recursive=True,
283
+ )
284
+ assert fs.ls(target, detail=False) == (
285
+ [] if supports_empty_directories else [dummy]
286
+ )
287
+
288
+ # With recursive
289
+ for glob, recursive in zip(["*", "**"], [True, False]):
290
+ fs.put(local_join(source, "subdir", glob), t, recursive=recursive)
291
+ assert fs.isfile(fs_join(target, "subfile1"))
292
+ assert fs.isfile(fs_join(target, "subfile2"))
293
+ assert fs.isdir(fs_join(target, "nesteddir"))
294
+ assert fs.isfile(fs_join(target, "nesteddir", "nestedfile"))
295
+ assert not fs.exists(fs_join(target, "subdir"))
296
+
297
+ fs.rm(
298
+ [
299
+ fs_join(target, "subfile1"),
300
+ fs_join(target, "subfile2"),
301
+ fs_join(target, "nesteddir"),
302
+ ],
303
+ recursive=True,
304
+ )
305
+ assert fs.ls(target, detail=False) == (
306
+ [] if supports_empty_directories else [dummy]
307
+ )
308
+
309
+ # Limit recursive by maxdepth
310
+ fs.put(
311
+ local_join(source, "subdir", glob),
312
+ t,
313
+ recursive=recursive,
314
+ maxdepth=1,
315
+ )
316
+ assert fs.isfile(fs_join(target, "subfile1"))
317
+ assert fs.isfile(fs_join(target, "subfile2"))
318
+ assert not fs.exists(fs_join(target, "nesteddir"))
319
+ assert not fs.exists(fs_join(target, "subdir"))
320
+
321
+ fs.rm(
322
+ [
323
+ fs_join(target, "subfile1"),
324
+ fs_join(target, "subfile2"),
325
+ ],
326
+ recursive=True,
327
+ )
328
+ assert fs.ls(target, detail=False) == (
329
+ [] if supports_empty_directories else [dummy]
330
+ )
331
+
332
+ def test_put_glob_to_new_directory(
333
+ self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0
334
+ ):
335
+ # Copy scenario 1h
336
+ source = local_bulk_operations_scenario_0
337
+
338
+ target = fs_target
339
+ fs.mkdir(target)
340
+
341
+ for target_slash in [False, True]:
342
+ t = fs_join(target, "newdir")
343
+ if target_slash:
344
+ t += "/"
345
+
346
+ # Without recursive
347
+ fs.put(local_join(source, "subdir", "*"), t)
348
+ assert fs.isdir(fs_join(target, "newdir"))
349
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
350
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
351
+ assert not fs.exists(fs_join(target, "newdir", "nesteddir"))
352
+ assert not fs.exists(fs_join(target, "newdir", "nesteddir", "nestedfile"))
353
+ assert not fs.exists(fs_join(target, "subdir"))
354
+ assert not fs.exists(fs_join(target, "newdir", "subdir"))
355
+
356
+ fs.rm(fs_join(target, "newdir"), recursive=True)
357
+ assert not fs.exists(fs_join(target, "newdir"))
358
+
359
+ # With recursive
360
+ for glob, recursive in zip(["*", "**"], [True, False]):
361
+ fs.put(local_join(source, "subdir", glob), t, recursive=recursive)
362
+ assert fs.isdir(fs_join(target, "newdir"))
363
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
364
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
365
+ assert fs.isdir(fs_join(target, "newdir", "nesteddir"))
366
+ assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile"))
367
+ assert not fs.exists(fs_join(target, "subdir"))
368
+ assert not fs.exists(fs_join(target, "newdir", "subdir"))
369
+
370
+ fs.rm(fs_join(target, "newdir"), recursive=True)
371
+ assert not fs.exists(fs_join(target, "newdir"))
372
+
373
+ # Limit recursive by maxdepth
374
+ fs.put(
375
+ local_join(source, "subdir", glob),
376
+ t,
377
+ recursive=recursive,
378
+ maxdepth=1,
379
+ )
380
+ assert fs.isdir(fs_join(target, "newdir"))
381
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
382
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
383
+ assert not fs.exists(fs_join(target, "newdir", "nesteddir"))
384
+ assert not fs.exists(fs_join(target, "subdir"))
385
+ assert not fs.exists(fs_join(target, "newdir", "subdir"))
386
+
387
+ fs.rm(fs_join(target, "newdir"), recursive=True)
388
+ assert not fs.exists(fs_join(target, "newdir"))
389
+
390
+ @pytest.mark.parametrize(
391
+ GLOB_EDGE_CASES_TESTS["argnames"],
392
+ GLOB_EDGE_CASES_TESTS["argvalues"],
393
+ )
394
+ def test_put_glob_edge_cases(
395
+ self,
396
+ path,
397
+ recursive,
398
+ maxdepth,
399
+ expected,
400
+ fs,
401
+ fs_join,
402
+ fs_target,
403
+ local_glob_edge_cases_files,
404
+ local_join,
405
+ fs_sanitize_path,
406
+ ):
407
+ # Copy scenario 1g
408
+ source = local_glob_edge_cases_files
409
+
410
+ target = fs_target
411
+
412
+ for new_dir, target_slash in product([True, False], [True, False]):
413
+ fs.mkdir(target)
414
+
415
+ t = fs_join(target, "newdir") if new_dir else target
416
+ t = t + "/" if target_slash else t
417
+
418
+ fs.put(local_join(source, path), t, recursive=recursive, maxdepth=maxdepth)
419
+
420
+ output = fs.find(target)
421
+ if new_dir:
422
+ prefixed_expected = [
423
+ fs_sanitize_path(fs_join(target, "newdir", p)) for p in expected
424
+ ]
425
+ else:
426
+ prefixed_expected = [
427
+ fs_sanitize_path(fs_join(target, p)) for p in expected
428
+ ]
429
+ assert sorted(output) == sorted(prefixed_expected)
430
+
431
+ try:
432
+ fs.rm(target, recursive=True)
433
+ except FileNotFoundError:
434
+ pass
435
+
436
+ def test_put_list_of_files_to_existing_directory(
437
+ self,
438
+ fs,
439
+ fs_join,
440
+ fs_target,
441
+ local_join,
442
+ local_bulk_operations_scenario_0,
443
+ supports_empty_directories,
444
+ ):
445
+ # Copy scenario 2a
446
+ source = local_bulk_operations_scenario_0
447
+
448
+ target = fs_target
449
+ fs.mkdir(target)
450
+ if not supports_empty_directories:
451
+ # Force target directory to exist by adding a dummy file
452
+ dummy = fs_join(target, "dummy")
453
+ fs.touch(dummy)
454
+ assert fs.isdir(target)
455
+
456
+ source_files = [
457
+ local_join(source, "file1"),
458
+ local_join(source, "file2"),
459
+ local_join(source, "subdir", "subfile1"),
460
+ ]
461
+
462
+ for target_slash in [False, True]:
463
+ t = target + "/" if target_slash else target
464
+
465
+ fs.put(source_files, t)
466
+ assert fs.isfile(fs_join(target, "file1"))
467
+ assert fs.isfile(fs_join(target, "file2"))
468
+ assert fs.isfile(fs_join(target, "subfile1"))
469
+
470
+ fs.rm(
471
+ [
472
+ fs_join(target, "file1"),
473
+ fs_join(target, "file2"),
474
+ fs_join(target, "subfile1"),
475
+ ],
476
+ recursive=True,
477
+ )
478
+ assert fs.ls(target, detail=False) == (
479
+ [] if supports_empty_directories else [dummy]
480
+ )
481
+
482
+ def test_put_list_of_files_to_new_directory(
483
+ self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0
484
+ ):
485
+ # Copy scenario 2b
486
+ source = local_bulk_operations_scenario_0
487
+
488
+ target = fs_target
489
+ fs.mkdir(target)
490
+
491
+ source_files = [
492
+ local_join(source, "file1"),
493
+ local_join(source, "file2"),
494
+ local_join(source, "subdir", "subfile1"),
495
+ ]
496
+
497
+ fs.put(source_files, fs_join(target, "newdir") + "/") # Note trailing slash
498
+ assert fs.isdir(fs_join(target, "newdir"))
499
+ assert fs.isfile(fs_join(target, "newdir", "file1"))
500
+ assert fs.isfile(fs_join(target, "newdir", "file2"))
501
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
502
+
503
+ def test_put_directory_recursive(
504
+ self, fs, fs_join, fs_target, local_fs, local_join, local_path
505
+ ):
506
+ # https://github.com/fsspec/filesystem_spec/issues/1062
507
+ # Recursive cp/get/put of source directory into non-existent target directory.
508
+ src = local_join(local_path, "src")
509
+ src_file = local_join(src, "file")
510
+ local_fs.mkdir(src)
511
+ local_fs.touch(src_file)
512
+
513
+ target = fs_target
514
+
515
+ # put without slash
516
+ assert not fs.exists(target)
517
+ for loop in range(2):
518
+ fs.put(src, target, recursive=True)
519
+ assert fs.isdir(target)
520
+
521
+ if loop == 0:
522
+ assert fs.isfile(fs_join(target, "file"))
523
+ assert not fs.exists(fs_join(target, "src"))
524
+ else:
525
+ assert fs.isfile(fs_join(target, "file"))
526
+ assert fs.isdir(fs_join(target, "src"))
527
+ assert fs.isfile(fs_join(target, "src", "file"))
528
+
529
+ fs.rm(target, recursive=True)
530
+
531
+ # put with slash
532
+ assert not fs.exists(target)
533
+ for loop in range(2):
534
+ fs.put(src + "/", target, recursive=True)
535
+ assert fs.isdir(target)
536
+ assert fs.isfile(fs_join(target, "file"))
537
+ assert not fs.exists(fs_join(target, "src"))
538
+
539
+ def test_put_directory_without_files_with_same_name_prefix(
540
+ self,
541
+ fs,
542
+ fs_join,
543
+ fs_target,
544
+ local_join,
545
+ local_dir_and_file_with_same_name_prefix,
546
+ supports_empty_directories,
547
+ ):
548
+ # Create the test dirs
549
+ source = local_dir_and_file_with_same_name_prefix
550
+ target = fs_target
551
+
552
+ # Test without glob
553
+ fs.put(local_join(source, "subdir"), fs_target, recursive=True)
554
+
555
+ assert fs.isfile(fs_join(fs_target, "subfile.txt"))
556
+ assert not fs.isfile(fs_join(fs_target, "subdir.txt"))
557
+
558
+ fs.rm([fs_join(target, "subfile.txt")])
559
+ if supports_empty_directories:
560
+ assert fs.ls(target) == []
561
+ else:
562
+ assert not fs.exists(target)
563
+
564
+ # Test with glob
565
+ fs.put(local_join(source, "subdir*"), fs_target, recursive=True)
566
+
567
+ assert fs.isdir(fs_join(fs_target, "subdir"))
568
+ assert fs.isfile(fs_join(fs_target, "subdir", "subfile.txt"))
569
+ assert fs.isfile(fs_join(fs_target, "subdir.txt"))
570
+
571
+ def test_copy_with_source_and_destination_as_list(
572
+ self, fs, fs_target, fs_join, local_join, local_10_files_with_hashed_names
573
+ ):
574
+ # Create the test dir
575
+ source = local_10_files_with_hashed_names
576
+ target = fs_target
577
+
578
+ # Create list of files for source and destination
579
+ source_files = []
580
+ destination_files = []
581
+ for i in range(10):
582
+ hashed_i = md5(str(i).encode("utf-8")).hexdigest()
583
+ source_files.append(local_join(source, f"{hashed_i}.txt"))
584
+ destination_files.append(fs_join(target, f"{hashed_i}.txt"))
585
+
586
+ # Copy and assert order was kept
587
+ fs.put(lpath=source_files, rpath=destination_files)
588
+
589
+ for i in range(10):
590
+ file_content = fs.cat(destination_files[i]).decode("utf-8")
591
+ assert file_content == str(i)
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/transaction.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import deque
2
+
3
+
4
+ class Transaction:
5
+ """Filesystem transaction write context
6
+
7
+ Gathers files for deferred commit or discard, so that several write
8
+ operations can be finalized semi-atomically. This works by having this
9
+ instance as the ``.transaction`` attribute of the given filesystem
10
+ """
11
+
12
+ def __init__(self, fs, **kwargs):
13
+ """
14
+ Parameters
15
+ ----------
16
+ fs: FileSystem instance
17
+ """
18
+ self.fs = fs
19
+ self.files = deque()
20
+
21
+ def __enter__(self):
22
+ self.start()
23
+ return self
24
+
25
+ def __exit__(self, exc_type, exc_val, exc_tb):
26
+ """End transaction and commit, if exit is not due to exception"""
27
+ # only commit if there was no exception
28
+ self.complete(commit=exc_type is None)
29
+ if self.fs:
30
+ self.fs._intrans = False
31
+ self.fs._transaction = None
32
+ self.fs = None
33
+
34
+ def start(self):
35
+ """Start a transaction on this FileSystem"""
36
+ self.files = deque() # clean up after previous failed completions
37
+ self.fs._intrans = True
38
+
39
+ def complete(self, commit=True):
40
+ """Finish transaction: commit or discard all deferred files"""
41
+ while self.files:
42
+ f = self.files.popleft()
43
+ if commit:
44
+ f.commit()
45
+ else:
46
+ f.discard()
47
+ self.fs._intrans = False
48
+ self.fs._transaction = None
49
+ self.fs = None
50
+
51
+
52
+ class FileActor:
53
+ def __init__(self):
54
+ self.files = []
55
+
56
+ def commit(self):
57
+ for f in self.files:
58
+ f.commit()
59
+ self.files.clear()
60
+
61
+ def discard(self):
62
+ for f in self.files:
63
+ f.discard()
64
+ self.files.clear()
65
+
66
+ def append(self, f):
67
+ self.files.append(f)
68
+
69
+
70
+ class DaskTransaction(Transaction):
71
+ def __init__(self, fs):
72
+ """
73
+ Parameters
74
+ ----------
75
+ fs: FileSystem instance
76
+ """
77
+ import distributed
78
+
79
+ super().__init__(fs)
80
+ client = distributed.default_client()
81
+ self.files = client.submit(FileActor, actor=True).result()
82
+
83
+ def complete(self, commit=True):
84
+ """Finish transaction: commit or discard all deferred files"""
85
+ if commit:
86
+ self.files.commit().result()
87
+ else:
88
+ self.files.discard().result()
89
+ self.fs._intrans = False
90
+ self.fs = None
pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/utils.py ADDED
@@ -0,0 +1,757 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import logging
5
+ import math
6
+ import os
7
+ import re
8
+ import sys
9
+ import tempfile
10
+ from collections.abc import Callable, Iterable, Iterator, Sequence
11
+ from functools import partial
12
+ from hashlib import md5
13
+ from importlib.metadata import version
14
+ from typing import IO, TYPE_CHECKING, Any, TypeVar
15
+ from urllib.parse import urlsplit
16
+
17
+ if TYPE_CHECKING:
18
+ import pathlib
19
+ from typing import TypeGuard
20
+
21
+ from fsspec.spec import AbstractFileSystem
22
+
23
+
24
+ DEFAULT_BLOCK_SIZE = 5 * 2**20
25
+
26
+ T = TypeVar("T")
27
+
28
+
29
+ def infer_storage_options(
30
+ urlpath: str, inherit_storage_options: dict[str, Any] | None = None
31
+ ) -> dict[str, Any]:
32
+ """Infer storage options from URL path and merge it with existing storage
33
+ options.
34
+
35
+ Parameters
36
+ ----------
37
+ urlpath: str or unicode
38
+ Either local absolute file path or URL (hdfs://namenode:8020/file.csv)
39
+ inherit_storage_options: dict (optional)
40
+ Its contents will get merged with the inferred information from the
41
+ given path
42
+
43
+ Returns
44
+ -------
45
+ Storage options dict.
46
+
47
+ Examples
48
+ --------
49
+ >>> infer_storage_options('/mnt/datasets/test.csv') # doctest: +SKIP
50
+ {"protocol": "file", "path", "/mnt/datasets/test.csv"}
51
+ >>> infer_storage_options(
52
+ ... 'hdfs://username:pwd@node:123/mnt/datasets/test.csv?q=1',
53
+ ... inherit_storage_options={'extra': 'value'},
54
+ ... ) # doctest: +SKIP
55
+ {"protocol": "hdfs", "username": "username", "password": "pwd",
56
+ "host": "node", "port": 123, "path": "/mnt/datasets/test.csv",
57
+ "url_query": "q=1", "extra": "value"}
58
+ """
59
+
60
+ # Discover Windows paths including disk name in this special case.
61
+ is_filesystem = re.match(r"^[a-zA-Z]:[\\/]", urlpath)
62
+
63
+ # Discover URI according to RFC 3986: Scheme names consist of a
64
+ # sequence of characters beginning with a letter and followed by
65
+ # any combination of letters, digits, plus ("+"), period ("."),
66
+ # or hyphen ("-").
67
+ # https://datatracker.ietf.org/doc/html/rfc3986#section-3.1
68
+ is_uri = re.match(r"^[a-zA-Z0-9+.-]+://", urlpath)
69
+
70
+ if is_filesystem or is_uri is None:
71
+ return {"protocol": "file", "path": urlpath}
72
+
73
+ parsed_path = urlsplit(urlpath)
74
+ protocol = parsed_path.scheme or "file"
75
+ if parsed_path.fragment:
76
+ path = "#".join([parsed_path.path, parsed_path.fragment])
77
+ else:
78
+ path = parsed_path.path
79
+ if protocol == "file":
80
+ # Special case parsing file protocol URL on Windows according to:
81
+ # https://msdn.microsoft.com/en-us/library/jj710207.aspx
82
+ windows_path = re.match(r"^/([a-zA-Z])[:|]([\\/].*)$", path)
83
+ if windows_path:
84
+ drive, path = windows_path.groups()
85
+ path = f"{drive}:{path}"
86
+
87
+ if protocol in ["http", "https"]:
88
+ # for HTTP, we don't want to parse, as requests will anyway
89
+ return {"protocol": protocol, "path": urlpath}
90
+
91
+ options: dict[str, Any] = {"protocol": protocol, "path": path}
92
+
93
+ if parsed_path.netloc:
94
+ # Parse `hostname` from netloc manually because `parsed_path.hostname`
95
+ # lowercases the hostname which is not always desirable (e.g. in S3):
96
+ # https://github.com/dask/dask/issues/1417
97
+ options["host"] = parsed_path.netloc.rsplit("@", 1)[-1].rsplit(":", 1)[0]
98
+
99
+ if protocol in ("s3", "s3a", "gcs", "gs"):
100
+ options["path"] = options["host"] + options["path"]
101
+ else:
102
+ options["host"] = options["host"]
103
+ if parsed_path.port:
104
+ options["port"] = parsed_path.port
105
+ if parsed_path.username:
106
+ options["username"] = parsed_path.username
107
+ if parsed_path.password:
108
+ options["password"] = parsed_path.password
109
+
110
+ if parsed_path.query:
111
+ options["url_query"] = parsed_path.query
112
+ if parsed_path.fragment:
113
+ options["url_fragment"] = parsed_path.fragment
114
+
115
+ if inherit_storage_options:
116
+ update_storage_options(options, inherit_storage_options)
117
+
118
+ return options
119
+
120
+
121
+ def update_storage_options(
122
+ options: dict[str, Any], inherited: dict[str, Any] | None = None
123
+ ) -> None:
124
+ if not inherited:
125
+ inherited = {}
126
+ collisions = set(options) & set(inherited)
127
+ if collisions:
128
+ for collision in collisions:
129
+ if options.get(collision) != inherited.get(collision):
130
+ raise KeyError(
131
+ f"Collision between inferred and specified storage "
132
+ f"option:\n{collision}"
133
+ )
134
+ options.update(inherited)
135
+
136
+
137
+ # Compression extensions registered via fsspec.compression.register_compression
138
+ compressions: dict[str, str] = {}
139
+
140
+
141
+ def infer_compression(filename: str) -> str | None:
142
+ """Infer compression, if available, from filename.
143
+
144
+ Infer a named compression type, if registered and available, from filename
145
+ extension. This includes builtin (gz, bz2, zip) compressions, as well as
146
+ optional compressions. See fsspec.compression.register_compression.
147
+ """
148
+ extension = os.path.splitext(filename)[-1].strip(".").lower()
149
+ if extension in compressions:
150
+ return compressions[extension]
151
+ return None
152
+
153
+
154
+ def build_name_function(max_int: float) -> Callable[[int], str]:
155
+ """Returns a function that receives a single integer
156
+ and returns it as a string padded by enough zero characters
157
+ to align with maximum possible integer
158
+
159
+ >>> name_f = build_name_function(57)
160
+
161
+ >>> name_f(7)
162
+ '07'
163
+ >>> name_f(31)
164
+ '31'
165
+ >>> build_name_function(1000)(42)
166
+ '0042'
167
+ >>> build_name_function(999)(42)
168
+ '042'
169
+ >>> build_name_function(0)(0)
170
+ '0'
171
+ """
172
+ # handle corner cases max_int is 0 or exact power of 10
173
+ max_int += 1e-8
174
+
175
+ pad_length = int(math.ceil(math.log10(max_int)))
176
+
177
+ def name_function(i: int) -> str:
178
+ return str(i).zfill(pad_length)
179
+
180
+ return name_function
181
+
182
+
183
+ def seek_delimiter(file: IO[bytes], delimiter: bytes, blocksize: int) -> bool:
184
+ r"""Seek current file to file start, file end, or byte after delimiter seq.
185
+
186
+ Seeks file to next chunk delimiter, where chunks are defined on file start,
187
+ a delimiting sequence, and file end. Use file.tell() to see location afterwards.
188
+ Note that file start is a valid split, so must be at offset > 0 to seek for
189
+ delimiter.
190
+
191
+ Parameters
192
+ ----------
193
+ file: a file
194
+ delimiter: bytes
195
+ a delimiter like ``b'\n'`` or message sentinel, matching file .read() type
196
+ blocksize: int
197
+ Number of bytes to read from the file at once.
198
+
199
+
200
+ Returns
201
+ -------
202
+ Returns True if a delimiter was found, False if at file start or end.
203
+
204
+ """
205
+
206
+ if file.tell() == 0:
207
+ # beginning-of-file, return without seek
208
+ return False
209
+
210
+ # Interface is for binary IO, with delimiter as bytes, but initialize last
211
+ # with result of file.read to preserve compatibility with text IO.
212
+ last: bytes | None = None
213
+ while True:
214
+ current = file.read(blocksize)
215
+ if not current:
216
+ # end-of-file without delimiter
217
+ return False
218
+ full = last + current if last else current
219
+ try:
220
+ if delimiter in full:
221
+ i = full.index(delimiter)
222
+ file.seek(file.tell() - (len(full) - i) + len(delimiter))
223
+ return True
224
+ elif len(current) < blocksize:
225
+ # end-of-file without delimiter
226
+ return False
227
+ except (OSError, ValueError):
228
+ pass
229
+ last = full[-len(delimiter) :]
230
+
231
+
232
+ def read_block(
233
+ f: IO[bytes],
234
+ offset: int,
235
+ length: int | None,
236
+ delimiter: bytes | None = None,
237
+ split_before: bool = False,
238
+ ) -> bytes:
239
+ """Read a block of bytes from a file
240
+
241
+ Parameters
242
+ ----------
243
+ f: File
244
+ Open file
245
+ offset: int
246
+ Byte offset to start read
247
+ length: int
248
+ Number of bytes to read, read through end of file if None
249
+ delimiter: bytes (optional)
250
+ Ensure reading starts and stops at delimiter bytestring
251
+ split_before: bool (optional)
252
+ Start/stop read *before* delimiter bytestring.
253
+
254
+
255
+ If using the ``delimiter=`` keyword argument we ensure that the read
256
+ starts and stops at delimiter boundaries that follow the locations
257
+ ``offset`` and ``offset + length``. If ``offset`` is zero then we
258
+ start at zero, regardless of delimiter. The bytestring returned WILL
259
+ include the terminating delimiter string.
260
+
261
+ Examples
262
+ --------
263
+
264
+ >>> from io import BytesIO # doctest: +SKIP
265
+ >>> f = BytesIO(b'Alice, 100\\nBob, 200\\nCharlie, 300') # doctest: +SKIP
266
+ >>> read_block(f, 0, 13) # doctest: +SKIP
267
+ b'Alice, 100\\nBo'
268
+
269
+ >>> read_block(f, 0, 13, delimiter=b'\\n') # doctest: +SKIP
270
+ b'Alice, 100\\nBob, 200\\n'
271
+
272
+ >>> read_block(f, 10, 10, delimiter=b'\\n') # doctest: +SKIP
273
+ b'Bob, 200\\nCharlie, 300'
274
+ """
275
+ if delimiter:
276
+ f.seek(offset)
277
+ found_start_delim = seek_delimiter(f, delimiter, 2**16)
278
+ if length is None:
279
+ return f.read()
280
+ start = f.tell()
281
+ length -= start - offset
282
+
283
+ f.seek(start + length)
284
+ found_end_delim = seek_delimiter(f, delimiter, 2**16)
285
+ end = f.tell()
286
+
287
+ # Adjust split location to before delimiter if seek found the
288
+ # delimiter sequence, not start or end of file.
289
+ if found_start_delim and split_before:
290
+ start -= len(delimiter)
291
+
292
+ if found_end_delim and split_before:
293
+ end -= len(delimiter)
294
+
295
+ offset = start
296
+ length = end - start
297
+
298
+ f.seek(offset)
299
+
300
+ # TODO: allow length to be None and read to the end of the file?
301
+ assert length is not None
302
+ b = f.read(length)
303
+ return b
304
+
305
+
306
+ def tokenize(*args: Any, **kwargs: Any) -> str:
307
+ """Deterministic token
308
+
309
+ (modified from dask.base)
310
+
311
+ >>> tokenize([1, 2, '3'])
312
+ '9d71491b50023b06fc76928e6eddb952'
313
+
314
+ >>> tokenize('Hello') == tokenize('Hello')
315
+ True
316
+ """
317
+ if kwargs:
318
+ args += (kwargs,)
319
+ try:
320
+ h = md5(str(args).encode())
321
+ except ValueError:
322
+ # FIPS systems: https://github.com/fsspec/filesystem_spec/issues/380
323
+ h = md5(str(args).encode(), usedforsecurity=False)
324
+ return h.hexdigest()
325
+
326
+
327
+ def stringify_path(filepath: str | os.PathLike[str] | pathlib.Path) -> str:
328
+ """Attempt to convert a path-like object to a string.
329
+
330
+ Parameters
331
+ ----------
332
+ filepath: object to be converted
333
+
334
+ Returns
335
+ -------
336
+ filepath_str: maybe a string version of the object
337
+
338
+ Notes
339
+ -----
340
+ Objects supporting the fspath protocol are coerced according to its
341
+ __fspath__ method.
342
+
343
+ For backwards compatibility with older Python version, pathlib.Path
344
+ objects are specially coerced.
345
+
346
+ Any other object is passed through unchanged, which includes bytes,
347
+ strings, buffers, or anything else that's not even path-like.
348
+ """
349
+ if isinstance(filepath, str):
350
+ return filepath
351
+ elif hasattr(filepath, "__fspath__"):
352
+ return filepath.__fspath__()
353
+ elif hasattr(filepath, "path"):
354
+ return filepath.path
355
+ else:
356
+ return filepath # type: ignore[return-value]
357
+
358
+
359
+ def make_instance(
360
+ cls: Callable[..., T], args: Sequence[Any], kwargs: dict[str, Any]
361
+ ) -> T:
362
+ inst = cls(*args, **kwargs)
363
+ inst._determine_worker() # type: ignore[attr-defined]
364
+ return inst
365
+
366
+
367
+ def common_prefix(paths: Iterable[str]) -> str:
368
+ """For a list of paths, find the shortest prefix common to all"""
369
+ parts = [p.split("/") for p in paths]
370
+ lmax = min(len(p) for p in parts)
371
+ end = 0
372
+ for i in range(lmax):
373
+ end = all(p[i] == parts[0][i] for p in parts)
374
+ if not end:
375
+ break
376
+ i += end
377
+ return "/".join(parts[0][:i])
378
+
379
+
380
+ def other_paths(
381
+ paths: list[str],
382
+ path2: str | list[str],
383
+ exists: bool = False,
384
+ flatten: bool = False,
385
+ ) -> list[str]:
386
+ """In bulk file operations, construct a new file tree from a list of files
387
+
388
+ Parameters
389
+ ----------
390
+ paths: list of str
391
+ The input file tree
392
+ path2: str or list of str
393
+ Root to construct the new list in. If this is already a list of str, we just
394
+ assert it has the right number of elements.
395
+ exists: bool (optional)
396
+ For a str destination, it is already exists (and is a dir), files should
397
+ end up inside.
398
+ flatten: bool (optional)
399
+ Whether to flatten the input directory tree structure so that the output files
400
+ are in the same directory.
401
+
402
+ Returns
403
+ -------
404
+ list of str
405
+ """
406
+
407
+ if isinstance(path2, str):
408
+ path2 = path2.rstrip("/")
409
+
410
+ if flatten:
411
+ path2 = ["/".join((path2, p.split("/")[-1])) for p in paths]
412
+ else:
413
+ cp = common_prefix(paths)
414
+ if exists:
415
+ cp = cp.rsplit("/", 1)[0]
416
+ if not cp and all(not s.startswith("/") for s in paths):
417
+ path2 = ["/".join([path2, p]) for p in paths]
418
+ else:
419
+ path2 = [p.replace(cp, path2, 1) for p in paths]
420
+ else:
421
+ assert len(paths) == len(path2)
422
+ return path2
423
+
424
+
425
+ def is_exception(obj: Any) -> bool:
426
+ return isinstance(obj, BaseException)
427
+
428
+
429
+ def isfilelike(f: Any) -> TypeGuard[IO[bytes]]:
430
+ return all(hasattr(f, attr) for attr in ["read", "close", "tell"])
431
+
432
+
433
+ def get_protocol(url: str) -> str:
434
+ url = stringify_path(url)
435
+ parts = re.split(r"(\:\:|\://)", url, maxsplit=1)
436
+ if len(parts) > 1:
437
+ return parts[0]
438
+ return "file"
439
+
440
+
441
+ def get_file_extension(url: str) -> str:
442
+ url = stringify_path(url)
443
+ # Only consider the final path component: a "." in a parent directory name
444
+ # (e.g. "/path/to.dir/file") is not the file's extension.
445
+ ext_parts = url.rsplit("/", 1)[-1].rsplit(".", 1)
446
+ if len(ext_parts) > 1:
447
+ return ext_parts[-1]
448
+ return ""
449
+
450
+
451
+ def can_be_local(path: str) -> bool:
452
+ """Can the given URL be used with open_local?"""
453
+ from fsspec import get_filesystem_class
454
+
455
+ try:
456
+ return getattr(get_filesystem_class(get_protocol(path)), "local_file", False)
457
+ except (ValueError, ImportError):
458
+ # not in registry or import failed
459
+ return False
460
+
461
+
462
+ def get_package_version_without_import(name: str) -> str | None:
463
+ """For given package name, try to find the version without importing it
464
+
465
+ Import and package.__version__ is still the backup here, so an import
466
+ *might* happen.
467
+
468
+ Returns either the version string, or None if the package
469
+ or the version was not readily found.
470
+ """
471
+ if name in sys.modules:
472
+ mod = sys.modules[name]
473
+ if hasattr(mod, "__version__"):
474
+ return mod.__version__
475
+ try:
476
+ return version(name)
477
+ except: # noqa: E722
478
+ pass
479
+ try:
480
+ import importlib
481
+
482
+ mod = importlib.import_module(name)
483
+ return mod.__version__
484
+ except (ImportError, AttributeError):
485
+ return None
486
+
487
+
488
+ def setup_logging(
489
+ logger: logging.Logger | None = None,
490
+ logger_name: str | None = None,
491
+ level: str = "DEBUG",
492
+ clear: bool = True,
493
+ ) -> logging.Logger:
494
+ if logger is None and logger_name is None:
495
+ raise ValueError("Provide either logger object or logger name")
496
+ logger = logger or logging.getLogger(logger_name)
497
+ handle = logging.StreamHandler()
498
+ formatter = logging.Formatter(
499
+ "%(asctime)s - %(name)s - %(levelname)s - %(funcName)s -- %(message)s"
500
+ )
501
+ handle.setFormatter(formatter)
502
+ if clear:
503
+ logger.handlers.clear()
504
+ logger.addHandler(handle)
505
+ logger.setLevel(level)
506
+ return logger
507
+
508
+
509
+ def _unstrip_protocol(name: str, fs: AbstractFileSystem) -> str:
510
+ return fs.unstrip_protocol(name)
511
+
512
+
513
+ def mirror_from(
514
+ origin_name: str, methods: Iterable[str]
515
+ ) -> Callable[[type[T]], type[T]]:
516
+ """Mirror attributes and methods from the given
517
+ origin_name attribute of the instance to the
518
+ decorated class"""
519
+
520
+ def origin_getter(method: str, self: Any) -> Any:
521
+ origin = getattr(self, origin_name)
522
+ return getattr(origin, method)
523
+
524
+ def wrapper(cls: type[T]) -> type[T]:
525
+ for method in methods:
526
+ wrapped_method = partial(origin_getter, method)
527
+ setattr(cls, method, property(wrapped_method))
528
+ return cls
529
+
530
+ return wrapper
531
+
532
+
533
+ @contextlib.contextmanager
534
+ def nullcontext(obj: T) -> Iterator[T]:
535
+ yield obj
536
+
537
+
538
+ def merge_offset_ranges(
539
+ paths: list[str],
540
+ starts: list[int] | int,
541
+ ends: list[int] | int,
542
+ max_gap: int = 0,
543
+ max_block: int | None = None,
544
+ sort: bool = True,
545
+ ) -> tuple[list[str], list[int], list[int]]:
546
+ """Merge adjacent byte-offset ranges when the inter-range
547
+ gap is <= `max_gap`, and when the merged byte range does not
548
+ exceed `max_block` (if specified). By default, this function
549
+ will re-order the input paths and byte ranges to ensure sorted
550
+ order. If the user can guarantee that the inputs are already
551
+ sorted, passing `sort=False` will skip the re-ordering.
552
+ """
553
+ # Check input
554
+ if not isinstance(paths, list):
555
+ raise TypeError
556
+ if not isinstance(starts, list):
557
+ starts = [starts] * len(paths)
558
+ if not isinstance(ends, list):
559
+ ends = [ends] * len(paths)
560
+ if len(starts) != len(paths) or len(ends) != len(paths):
561
+ raise ValueError
562
+
563
+ # Early Return
564
+ if len(starts) <= 1:
565
+ return paths, starts, ends
566
+
567
+ starts = [s or 0 for s in starts]
568
+ # Sort by paths and then ranges if `sort=True`
569
+ if sort:
570
+ paths, starts, ends = (
571
+ list(v)
572
+ for v in zip(
573
+ *sorted(
574
+ zip(paths, starts, ends),
575
+ )
576
+ )
577
+ )
578
+ remove = []
579
+ for i, (path, start, end) in enumerate(zip(paths, starts, ends)):
580
+ if any(
581
+ e is not None and p == path and start >= s and end <= e and i != i2
582
+ for i2, (p, s, e) in enumerate(zip(paths, starts, ends))
583
+ ):
584
+ remove.append(i)
585
+ paths = [p for i, p in enumerate(paths) if i not in remove]
586
+ starts = [s for i, s in enumerate(starts) if i not in remove]
587
+ ends = [e for i, e in enumerate(ends) if i not in remove]
588
+
589
+ if paths:
590
+ # Loop through the coupled `paths`, `starts`, and
591
+ # `ends`, and merge adjacent blocks when appropriate
592
+ new_paths = paths[:1]
593
+ new_starts = starts[:1]
594
+ new_ends = ends[:1]
595
+ for i in range(1, len(paths)):
596
+ if paths[i] == paths[i - 1] and new_ends[-1] is None:
597
+ continue
598
+ elif (
599
+ paths[i] != paths[i - 1]
600
+ or ((starts[i] - new_ends[-1]) > max_gap)
601
+ or (max_block is not None and (ends[i] - new_starts[-1]) > max_block)
602
+ ):
603
+ # Cannot merge with previous block.
604
+ # Add new `paths`, `starts`, and `ends` elements
605
+ new_paths.append(paths[i])
606
+ new_starts.append(starts[i])
607
+ new_ends.append(ends[i])
608
+ else:
609
+ # Merge with the previous block by updating the
610
+ # last element of `ends`
611
+ new_ends[-1] = ends[i]
612
+ return new_paths, new_starts, new_ends
613
+
614
+ # `paths` is empty. Just return input lists
615
+ return paths, starts, ends
616
+
617
+
618
+ def file_size(filelike: IO[bytes]) -> int:
619
+ """Find length of any open read-mode file-like"""
620
+ pos = filelike.tell()
621
+ try:
622
+ return filelike.seek(0, 2)
623
+ finally:
624
+ filelike.seek(pos)
625
+
626
+
627
+ @contextlib.contextmanager
628
+ def atomic_write(path: str, mode: str = "wb"):
629
+ """
630
+ A context manager that opens a temporary file next to `path` and, on exit,
631
+ replaces `path` with the temporary file, thereby updating `path`
632
+ atomically.
633
+ """
634
+ fd, fn = tempfile.mkstemp(
635
+ dir=os.path.dirname(path), prefix=os.path.basename(path) + "-"
636
+ )
637
+ try:
638
+ with open(fd, mode) as fp:
639
+ yield fp
640
+ except BaseException:
641
+ with contextlib.suppress(FileNotFoundError):
642
+ os.unlink(fn)
643
+ raise
644
+ else:
645
+ os.replace(fn, path)
646
+
647
+
648
+ def _translate(pat, STAR, QUESTION_MARK):
649
+ # Copied from: https://github.com/python/cpython/pull/106703.
650
+ res: list[str] = []
651
+ add = res.append
652
+ i, n = 0, len(pat)
653
+ while i < n:
654
+ c = pat[i]
655
+ i = i + 1
656
+ if c == "*":
657
+ # compress consecutive `*` into one
658
+ if (not res) or res[-1] is not STAR:
659
+ add(STAR)
660
+ elif c == "?":
661
+ add(QUESTION_MARK)
662
+ elif c == "[":
663
+ j = i
664
+ if j < n and pat[j] == "!":
665
+ j = j + 1
666
+ if j < n and pat[j] == "]":
667
+ j = j + 1
668
+ while j < n and pat[j] != "]":
669
+ j = j + 1
670
+ if j >= n:
671
+ add("\\[")
672
+ else:
673
+ stuff = pat[i:j]
674
+ if "-" not in stuff:
675
+ stuff = stuff.replace("\\", r"\\")
676
+ else:
677
+ chunks = []
678
+ k = i + 2 if pat[i] == "!" else i + 1
679
+ while True:
680
+ k = pat.find("-", k, j)
681
+ if k < 0:
682
+ break
683
+ chunks.append(pat[i:k])
684
+ i = k + 1
685
+ k = k + 3
686
+ chunk = pat[i:j]
687
+ if chunk:
688
+ chunks.append(chunk)
689
+ else:
690
+ chunks[-1] += "-"
691
+ # Remove empty ranges -- invalid in RE.
692
+ for k in range(len(chunks) - 1, 0, -1):
693
+ if chunks[k - 1][-1] > chunks[k][0]:
694
+ chunks[k - 1] = chunks[k - 1][:-1] + chunks[k][1:]
695
+ del chunks[k]
696
+ # Escape backslashes and hyphens for set difference (--).
697
+ # Hyphens that create ranges shouldn't be escaped.
698
+ stuff = "-".join(
699
+ s.replace("\\", r"\\").replace("-", r"\-") for s in chunks
700
+ )
701
+ # Escape set operations (&&, ~~ and ||).
702
+ stuff = re.sub(r"([&~|])", r"\\\1", stuff)
703
+ i = j + 1
704
+ if not stuff:
705
+ # Empty range: never match.
706
+ add("(?!)")
707
+ elif stuff == "!":
708
+ # Negated empty range: match any character.
709
+ add(".")
710
+ else:
711
+ if stuff[0] == "!":
712
+ stuff = "^" + stuff[1:]
713
+ elif stuff[0] in ("^", "["):
714
+ stuff = "\\" + stuff
715
+ add(f"[{stuff}]")
716
+ else:
717
+ add(re.escape(c))
718
+ assert i == n
719
+ return res
720
+
721
+
722
+ def glob_translate(pat):
723
+ # Copied from: https://github.com/python/cpython/pull/106703.
724
+ # The keyword parameters' values are fixed to:
725
+ # recursive=True, include_hidden=True, seps=None
726
+ """Translate a pathname with shell wildcards to a regular expression."""
727
+ if os.path.altsep:
728
+ seps = os.path.sep + os.path.altsep
729
+ else:
730
+ seps = os.path.sep
731
+ escaped_seps = "".join(map(re.escape, seps))
732
+ any_sep = f"[{escaped_seps}]" if len(seps) > 1 else escaped_seps
733
+ not_sep = f"[^{escaped_seps}]"
734
+ one_last_segment = f"{not_sep}+"
735
+ one_segment = f"{one_last_segment}{any_sep}"
736
+ any_segments = f"(?:.+{any_sep})?"
737
+ any_last_segments = ".*"
738
+ results = []
739
+ parts = re.split(any_sep, pat)
740
+ last_part_idx = len(parts) - 1
741
+ for idx, part in enumerate(parts):
742
+ if part == "*":
743
+ results.append(one_segment if idx < last_part_idx else one_last_segment)
744
+ continue
745
+ if part == "**":
746
+ results.append(any_segments if idx < last_part_idx else any_last_segments)
747
+ continue
748
+ elif "**" in part:
749
+ raise ValueError(
750
+ "Invalid pattern: '**' can only be an entire path component"
751
+ )
752
+ if part:
753
+ results.extend(_translate(part, f"{not_sep}*", not_sep))
754
+ if idx < last_part_idx:
755
+ results.append(any_sep)
756
+ res = "".join(results)
757
+ return rf"(?s:{res})\Z"
pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_C.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b47cde4dc6a352014f58255ae607df24b9c7dad6da4bce9cd0651c24ec1070c
3
+ size 340912
pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ import torch
7
+ from torch._functorch.deprecated import (
8
+ combine_state_for_ensemble,
9
+ functionalize,
10
+ grad,
11
+ grad_and_value,
12
+ hessian,
13
+ jacfwd,
14
+ jacrev,
15
+ jvp,
16
+ make_functional,
17
+ make_functional_with_buffers,
18
+ vjp,
19
+ vmap,
20
+ )
21
+
22
+ # utilities. Maybe these should go in their own namespace in the future?
23
+ from torch._functorch.make_functional import (
24
+ FunctionalModule,
25
+ FunctionalModuleWithBuffers,
26
+ )
27
+
28
+ # Was never documented
29
+ from torch._functorch.python_key import make_fx
30
+
31
+
32
+ # Top-level APIs. Please think carefully before adding something to the
33
+ # top-level namespace:
34
+ # - private helper functions should go into torch._functorch
35
+ # - very experimental things should go into functorch.experimental
36
+ # - compilation related things should go into functorch.compile
37
+
38
+
39
+ __version__ = torch.__version__
pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (917 Bytes). View file