godlykmathews commited on
Commit
30caf57
·
verified ·
1 Parent(s): 7948113

Upload folder using huggingface_hub (part 3)

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 +2 -0
  2. venv/lib/python3.14/site-packages/fsspec-2026.9.0.dist-info/INSTALLER +1 -0
  3. venv/lib/python3.14/site-packages/fsspec-2026.9.0.dist-info/METADATA +258 -0
  4. venv/lib/python3.14/site-packages/fsspec-2026.9.0.dist-info/RECORD +121 -0
  5. venv/lib/python3.14/site-packages/fsspec-2026.9.0.dist-info/WHEEL +4 -0
  6. venv/lib/python3.14/site-packages/fsspec-2026.9.0.dist-info/licenses/LICENSE +29 -0
  7. venv/lib/python3.14/site-packages/fsspec/generic.py +396 -0
  8. venv/lib/python3.14/site-packages/fsspec/gui.py +417 -0
  9. venv/lib/python3.14/site-packages/fsspec/implementations/__init__.py +0 -0
  10. venv/lib/python3.14/site-packages/fsspec/implementations/arrow.py +328 -0
  11. venv/lib/python3.14/site-packages/fsspec/implementations/asyn_wrapper.py +135 -0
  12. venv/lib/python3.14/site-packages/fsspec/implementations/cache_mapper.py +75 -0
  13. venv/lib/python3.14/site-packages/fsspec/implementations/cache_metadata.py +217 -0
  14. venv/lib/python3.14/site-packages/fsspec/implementations/cached.py +1083 -0
  15. venv/lib/python3.14/site-packages/fsspec/implementations/chained.py +23 -0
  16. venv/lib/python3.14/site-packages/fsspec/implementations/dask.py +152 -0
  17. venv/lib/python3.14/site-packages/fsspec/implementations/data.py +71 -0
  18. venv/lib/python3.14/site-packages/fsspec/implementations/dbfs.py +497 -0
  19. venv/lib/python3.14/site-packages/fsspec/implementations/dirfs.py +478 -0
  20. venv/lib/python3.14/site-packages/fsspec/implementations/ftp.py +442 -0
  21. venv/lib/python3.14/site-packages/fsspec/implementations/gist.py +241 -0
  22. venv/lib/python3.14/site-packages/fsspec/implementations/git.py +114 -0
  23. venv/lib/python3.14/site-packages/fsspec/implementations/github.py +333 -0
  24. venv/lib/python3.14/site-packages/fsspec/implementations/http.py +902 -0
  25. venv/lib/python3.14/site-packages/fsspec/implementations/http_sync.py +937 -0
  26. venv/lib/python3.14/site-packages/fsspec/implementations/jupyter.py +129 -0
  27. venv/lib/python3.14/site-packages/fsspec/implementations/libarchive.py +213 -0
  28. venv/lib/python3.14/site-packages/fsspec/implementations/local.py +525 -0
  29. venv/lib/python3.14/site-packages/fsspec/implementations/memory.py +438 -0
  30. venv/lib/python3.14/site-packages/fsspec/implementations/reference.py +1358 -0
  31. venv/lib/python3.14/site-packages/fsspec/implementations/sftp.py +252 -0
  32. venv/lib/python3.14/site-packages/fsspec/implementations/smb.py +416 -0
  33. venv/lib/python3.14/site-packages/fsspec/implementations/tar.py +166 -0
  34. venv/lib/python3.14/site-packages/fsspec/implementations/webhdfs.py +503 -0
  35. venv/lib/python3.14/site-packages/fsspec/implementations/zip.py +194 -0
  36. venv/lib/python3.14/site-packages/fsspec/json.py +112 -0
  37. venv/lib/python3.14/site-packages/fsspec/mapping.py +259 -0
  38. venv/lib/python3.14/site-packages/fsspec/parquet.py +572 -0
  39. venv/lib/python3.14/site-packages/fsspec/prefetcher.py +873 -0
  40. venv/lib/python3.14/site-packages/fsspec/registry.py +337 -0
  41. venv/lib/python3.14/site-packages/fsspec/spec.py +2353 -0
  42. venv/lib/python3.14/site-packages/fsspec/tests/abstract/__init__.py +290 -0
  43. venv/lib/python3.14/site-packages/fsspec/tests/abstract/common.py +175 -0
  44. venv/lib/python3.14/site-packages/fsspec/tests/abstract/copy.py +557 -0
  45. venv/lib/python3.14/site-packages/fsspec/tests/abstract/get.py +587 -0
  46. venv/lib/python3.14/site-packages/fsspec/tests/abstract/mv.py +57 -0
  47. venv/lib/python3.14/site-packages/fsspec/tests/abstract/open.py +11 -0
  48. venv/lib/python3.14/site-packages/fsspec/tests/abstract/pipe.py +11 -0
  49. venv/lib/python3.14/site-packages/fsspec/tests/abstract/put.py +591 -0
  50. venv/lib/python3.14/site-packages/fsspec/transaction.py +113 -0
.gitattributes CHANGED
@@ -57,3 +57,5 @@ venv/lib/python3.14/site-packages/PIL/_imaging.cpython-314-darwin.so filter=lfs
57
  venv/lib/python3.14/site-packages/PIL/_imagingft.cpython-314-darwin.so filter=lfs diff=lfs merge=lfs -text
58
  venv/lib/python3.14/site-packages/charset_normalizer/cd.cpython-314-darwin.so filter=lfs diff=lfs merge=lfs -text
59
  venv/lib/python3.14/site-packages/charset_normalizer/md.cpython-314-darwin.so filter=lfs diff=lfs merge=lfs -text
 
 
 
57
  venv/lib/python3.14/site-packages/PIL/_imagingft.cpython-314-darwin.so filter=lfs diff=lfs merge=lfs -text
58
  venv/lib/python3.14/site-packages/charset_normalizer/cd.cpython-314-darwin.so filter=lfs diff=lfs merge=lfs -text
59
  venv/lib/python3.14/site-packages/charset_normalizer/md.cpython-314-darwin.so filter=lfs diff=lfs merge=lfs -text
60
+ venv/lib/python3.14/site-packages/google/_upb/_message.abi3.so filter=lfs diff=lfs merge=lfs -text
61
+ venv/lib/python3.14/site-packages/hf_xet/hf_xet.abi3.so filter=lfs diff=lfs merge=lfs -text
venv/lib/python3.14/site-packages/fsspec-2026.9.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
venv/lib/python3.14/site-packages/fsspec-2026.9.0.dist-info/METADATA ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.5
2
+ Name: fsspec
3
+ Version: 2026.9.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
+ Requires-Dist: zarr; extra == 'test-downstream'
109
+ Provides-Extra: test-full
110
+ Requires-Dist: adlfs; extra == 'test-full'
111
+ Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test-full'
112
+ Requires-Dist: backports-zstd; (python_version < '3.14') and extra == 'test-full'
113
+ Requires-Dist: cloudpickle; extra == 'test-full'
114
+ Requires-Dist: dask; extra == 'test-full'
115
+ Requires-Dist: distributed; extra == 'test-full'
116
+ Requires-Dist: dropbox; extra == 'test-full'
117
+ Requires-Dist: dropboxdrivefs; extra == 'test-full'
118
+ Requires-Dist: fastparquet; extra == 'test-full'
119
+ Requires-Dist: fusepy; extra == 'test-full'
120
+ Requires-Dist: gcsfs>=2026.4.0; extra == 'test-full'
121
+ Requires-Dist: jinja2; extra == 'test-full'
122
+ Requires-Dist: kerchunk; extra == 'test-full'
123
+ Requires-Dist: libarchive-c; extra == 'test-full'
124
+ Requires-Dist: lz4; extra == 'test-full'
125
+ Requires-Dist: notebook; extra == 'test-full'
126
+ Requires-Dist: numpy; extra == 'test-full'
127
+ Requires-Dist: ocifs; extra == 'test-full'
128
+ Requires-Dist: pandas<3.0.0; extra == 'test-full'
129
+ Requires-Dist: panel; extra == 'test-full'
130
+ Requires-Dist: paramiko; extra == 'test-full'
131
+ Requires-Dist: pyarrow>=1; extra == 'test-full'
132
+ Requires-Dist: pyftpdlib; extra == 'test-full'
133
+ Requires-Dist: pygit2; extra == 'test-full'
134
+ Requires-Dist: pytest; extra == 'test-full'
135
+ Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test-full'
136
+ Requires-Dist: pytest-benchmark; extra == 'test-full'
137
+ Requires-Dist: pytest-cov; extra == 'test-full'
138
+ Requires-Dist: pytest-mock; extra == 'test-full'
139
+ Requires-Dist: pytest-recording; extra == 'test-full'
140
+ Requires-Dist: pytest-rerunfailures; extra == 'test-full'
141
+ Requires-Dist: python-snappy; extra == 'test-full'
142
+ Requires-Dist: requests; extra == 'test-full'
143
+ Requires-Dist: s3fs>=2026.6.0; extra == 'test-full'
144
+ Requires-Dist: smbprotocol; extra == 'test-full'
145
+ Requires-Dist: tqdm; extra == 'test-full'
146
+ Requires-Dist: urllib3; extra == 'test-full'
147
+ Requires-Dist: zarr<3.2.0; extra == 'test-full'
148
+ Requires-Dist: zstandard; (python_version < '3.14') and extra == 'test-full'
149
+ Provides-Extra: tqdm
150
+ Requires-Dist: tqdm; extra == 'tqdm'
151
+ Description-Content-Type: text/markdown
152
+
153
+ # filesystem_spec
154
+
155
+ [![PyPI version](https://badge.fury.io/py/fsspec.svg)](https://pypi.python.org/pypi/fsspec/)
156
+ [![Anaconda-Server Badge](https://anaconda.org/conda-forge/fsspec/badges/version.svg)](https://anaconda.org/conda-forge/fsspec)
157
+ ![Build](https://github.com/fsspec/filesystem_spec/workflows/CI/badge.svg)
158
+ [![Docs](https://readthedocs.org/projects/filesystem-spec/badge/?version=latest)](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest)
159
+
160
+ A specification for pythonic filesystems.
161
+
162
+ ## Install
163
+
164
+ ```bash
165
+ pip install fsspec
166
+ ```
167
+
168
+ would install the base fsspec. Various optionally supported features might require specification of custom
169
+ extra require, e.g. `pip install fsspec[ssh]` will install dependencies for `ssh` backends support.
170
+ Use `pip install fsspec[full]` for installation of all known extra dependencies.
171
+
172
+ Up-to-date package also provided through conda-forge distribution:
173
+
174
+ ```bash
175
+ conda install -c conda-forge fsspec
176
+ ```
177
+
178
+
179
+ ## Purpose
180
+
181
+ To produce a template or specification for a file-system interface, that specific implementations should follow,
182
+ so that applications making use of them can rely on a common behaviour and not have to worry about the specific
183
+ internal implementation decisions with any given backend. Many such implementations are included in this package,
184
+ or in sister projects such as `s3fs` and `gcsfs`.
185
+
186
+ In addition, if this is well-designed, then additional functionality, such as a key-value store or FUSE
187
+ mounting of the file-system implementation may be available for all implementations "for free".
188
+
189
+ ## Documentation
190
+
191
+ Please refer to [RTD](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest)
192
+
193
+ ## Develop
194
+
195
+ fsspec uses GitHub Actions for CI. Environment files can be found
196
+ in the "ci/" directory. Note that the main environment is called "py38",
197
+ but it is expected that the version of python installed be adjustable at
198
+ CI runtime. For local use, pick a version suitable for you.
199
+
200
+ ```bash
201
+ # For a new environment (mamba / conda).
202
+ mamba create -n fsspec -c conda-forge python=3.10 -y
203
+ conda activate fsspec
204
+
205
+ # Standard dev install with docs and tests.
206
+ pip install -e ".[dev,doc,test]"
207
+
208
+ # Full tests except for downstream
209
+ pip install s3fs
210
+ pip uninstall s3fs
211
+ pip install -e .[dev,doc,test_full]
212
+ pip install s3fs --no-deps
213
+ pytest -v
214
+
215
+ # Downstream tests.
216
+ sh install_s3fs.sh
217
+ # Windows powershell.
218
+ install_s3fs.sh
219
+ ```
220
+
221
+ ### Testing
222
+
223
+ Tests can be run in the dev environment, if activated, via ``pytest fsspec``.
224
+
225
+ The full fsspec suite requires a system-level docker, docker-compose, and fuse
226
+ installation. If only making changes to one backend implementation, it is
227
+ not generally necessary to run all tests locally.
228
+
229
+ It is expected that contributors ensure that any change to fsspec does not
230
+ cause issues or regressions for either other fsspec-related packages such
231
+ as gcsfs and s3fs, nor for downstream users of fsspec. The "downstream" CI
232
+ run and corresponding environment file run a set of tests from the dask
233
+ test suite, and very minimal tests against pandas and zarr from the
234
+ test_downstream.py module in this repo.
235
+
236
+ ### Code Formatting
237
+
238
+ fsspec uses [Black](https://black.readthedocs.io/en/stable) to ensure
239
+ a consistent code format throughout the project.
240
+ Run ``black fsspec`` from the root of the filesystem_spec repository to
241
+ auto-format your code. Additionally, many editors have plugins that will apply
242
+ ``black`` as you edit files. ``black`` is included in the ``tox`` environments.
243
+
244
+ Optionally, you may wish to setup [pre-commit hooks](https://pre-commit.com) to
245
+ automatically run ``black`` when you make a git commit.
246
+ Run ``pre-commit install --install-hooks`` from the root of the
247
+ filesystem_spec repository to setup pre-commit hooks. ``black`` will now be run
248
+ before you commit, reformatting any changed files. You can format without
249
+ committing via ``pre-commit run`` or skip these checks with ``git commit
250
+ --no-verify``.
251
+
252
+ ## Support
253
+
254
+ Work on this repository is supported in part by:
255
+
256
+ "Anaconda, Inc. - Advancing AI through open source."
257
+
258
+ <a href="https://anaconda.com/"><img src="https://camo.githubusercontent.com/b8555ef2222598ed37ce38ac86955febbd25de7619931bb7dd3c58432181d3b6/68747470733a2f2f626565776172652e6f72672f636f6d6d756e6974792f6d656d626572732f616e61636f6e64612f616e61636f6e64612d6c617267652e706e67" alt="anaconda logo" width="40%"/></a>
venv/lib/python3.14/site-packages/fsspec-2026.9.0.dist-info/RECORD ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fsspec-2026.9.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ fsspec-2026.9.0.dist-info/METADATA,sha256=aPWiYnZ1EGOOmxkzsUk_K6rclhb-HmlvYq7dWcjAo3w,10609
3
+ fsspec-2026.9.0.dist-info/RECORD,,
4
+ fsspec-2026.9.0.dist-info/WHEEL,sha256=THafob7ofN-NsuMN7Mg4qZyHaQI7KkD-QlcQatYhXPo,87
5
+ fsspec-2026.9.0.dist-info/licenses/LICENSE,sha256=LcNUls5TpzB5FcAIqESq1T53K0mzTN0ARFBnaRQH7JQ,1513
6
+ fsspec/__init__.py,sha256=xFcoHBD17fc5KamKUQAIA0rePGjLqIN1WBAd9NAoAi8,2111
7
+ fsspec/__pycache__/__init__.cpython-314.pyc,,
8
+ fsspec/__pycache__/_version.cpython-314.pyc,,
9
+ fsspec/__pycache__/archive.cpython-314.pyc,,
10
+ fsspec/__pycache__/asyn.cpython-314.pyc,,
11
+ fsspec/__pycache__/caching.cpython-314.pyc,,
12
+ fsspec/__pycache__/callbacks.cpython-314.pyc,,
13
+ fsspec/__pycache__/compression.cpython-314.pyc,,
14
+ fsspec/__pycache__/config.cpython-314.pyc,,
15
+ fsspec/__pycache__/conftest.cpython-314.pyc,,
16
+ fsspec/__pycache__/core.cpython-314.pyc,,
17
+ fsspec/__pycache__/dircache.cpython-314.pyc,,
18
+ fsspec/__pycache__/exceptions.cpython-314.pyc,,
19
+ fsspec/__pycache__/fuse.cpython-314.pyc,,
20
+ fsspec/__pycache__/generic.cpython-314.pyc,,
21
+ fsspec/__pycache__/gui.cpython-314.pyc,,
22
+ fsspec/__pycache__/json.cpython-314.pyc,,
23
+ fsspec/__pycache__/mapping.cpython-314.pyc,,
24
+ fsspec/__pycache__/parquet.cpython-314.pyc,,
25
+ fsspec/__pycache__/prefetcher.cpython-314.pyc,,
26
+ fsspec/__pycache__/registry.cpython-314.pyc,,
27
+ fsspec/__pycache__/spec.cpython-314.pyc,,
28
+ fsspec/__pycache__/transaction.cpython-314.pyc,,
29
+ fsspec/__pycache__/utils.cpython-314.pyc,,
30
+ fsspec/_version.py,sha256=CFkLh48vGlx4uPc2-xnYbp3Hsx020MfNC44_iizaFTo,526
31
+ fsspec/archive.py,sha256=9RsPnfI5c4WNDdcisBBEnaIXa48MJwgPknKQNm2kDsQ,2733
32
+ fsspec/asyn.py,sha256=_KEgV7OLoRx8Uo1hCjnm0mrGVB00CMuCfMbKV6sZmDk,42244
33
+ fsspec/caching.py,sha256=V_Hr1Ph5c4HFsIeVr81nRdjpn-mmzrSNQ0GR0bFYvY8,38542
34
+ fsspec/callbacks.py,sha256=BDIwLzK6rr_0V5ch557fSzsivCElpdqhXr5dZ9Te-EE,9210
35
+ fsspec/compression.py,sha256=3v_Fe39gzRRWfaeXpzNjAGPqgTzmETYRCo3qHVqD3po,5132
36
+ fsspec/config.py,sha256=mHKzAgjXa_LwqtO_VoTJJ568VqwYkbK3gUp4J6JZJp4,4238
37
+ fsspec/conftest.py,sha256=uWfm_Qs5alPRxOhRpDfQ0-1jqSJ54pni4y96IxOREXM,3446
38
+ fsspec/core.py,sha256=m5jZWbTReNNV6MXFZJlKnFHH_IIqY9ReHrL9OyDt0nU,24428
39
+ fsspec/dircache.py,sha256=YzogWJrhEastHU7vWz-cJiJ7sdtLXFXhEpInGKd4EcM,2717
40
+ fsspec/exceptions.py,sha256=pauSLDMxzTJMOjvX1WEUK0cMyFkrFxpWJsyFywav7A8,331
41
+ fsspec/fuse.py,sha256=Q-3NOOyLqBfYa4Db5E19z_ZY36zzYHtIs1mOUasItBQ,10177
42
+ fsspec/generic.py,sha256=-LIADa9qRN79bfa3Hl9m3HaN6rlU2GNivawLNmybqxE,13752
43
+ fsspec/gui.py,sha256=CQ7QsrTpaDlWSLNOpwNoJc7khOcYXIZxmrAJN9bHWQU,14002
44
+ fsspec/implementations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
45
+ fsspec/implementations/__pycache__/__init__.cpython-314.pyc,,
46
+ fsspec/implementations/__pycache__/arrow.cpython-314.pyc,,
47
+ fsspec/implementations/__pycache__/asyn_wrapper.cpython-314.pyc,,
48
+ fsspec/implementations/__pycache__/cache_mapper.cpython-314.pyc,,
49
+ fsspec/implementations/__pycache__/cache_metadata.cpython-314.pyc,,
50
+ fsspec/implementations/__pycache__/cached.cpython-314.pyc,,
51
+ fsspec/implementations/__pycache__/chained.cpython-314.pyc,,
52
+ fsspec/implementations/__pycache__/dask.cpython-314.pyc,,
53
+ fsspec/implementations/__pycache__/data.cpython-314.pyc,,
54
+ fsspec/implementations/__pycache__/dbfs.cpython-314.pyc,,
55
+ fsspec/implementations/__pycache__/dirfs.cpython-314.pyc,,
56
+ fsspec/implementations/__pycache__/ftp.cpython-314.pyc,,
57
+ fsspec/implementations/__pycache__/gist.cpython-314.pyc,,
58
+ fsspec/implementations/__pycache__/git.cpython-314.pyc,,
59
+ fsspec/implementations/__pycache__/github.cpython-314.pyc,,
60
+ fsspec/implementations/__pycache__/http.cpython-314.pyc,,
61
+ fsspec/implementations/__pycache__/http_sync.cpython-314.pyc,,
62
+ fsspec/implementations/__pycache__/jupyter.cpython-314.pyc,,
63
+ fsspec/implementations/__pycache__/libarchive.cpython-314.pyc,,
64
+ fsspec/implementations/__pycache__/local.cpython-314.pyc,,
65
+ fsspec/implementations/__pycache__/memory.cpython-314.pyc,,
66
+ fsspec/implementations/__pycache__/reference.cpython-314.pyc,,
67
+ fsspec/implementations/__pycache__/sftp.cpython-314.pyc,,
68
+ fsspec/implementations/__pycache__/smb.cpython-314.pyc,,
69
+ fsspec/implementations/__pycache__/tar.cpython-314.pyc,,
70
+ fsspec/implementations/__pycache__/webhdfs.cpython-314.pyc,,
71
+ fsspec/implementations/__pycache__/zip.cpython-314.pyc,,
72
+ fsspec/implementations/arrow.py,sha256=NGtJ9yWBt5SPpvDPTo-p4ry2j0R9cOCTecd5oA6rxFo,9344
73
+ fsspec/implementations/asyn_wrapper.py,sha256=IYrY--XM7GUz-5c3i_4FE7znTQogruyqsp7UhAKwZvk,4304
74
+ fsspec/implementations/cache_mapper.py,sha256=W4wlxyPxZbSp9ItJ0pYRVBMh6bw9eFypgP6kUYuuiI4,2421
75
+ fsspec/implementations/cache_metadata.py,sha256=EPhQV27lgPlYREYprDET1vcMed15pVNMit-Ta1ljoyE,7942
76
+ fsspec/implementations/cached.py,sha256=c6ayv1S6JctBw1iiEDS29fytOU0vhi0fboeE2xcSzBY,38867
77
+ fsspec/implementations/chained.py,sha256=iGivpNaHUFjB_ea0-HAPhcmm6CL8qnDf270PSj7JwuE,680
78
+ fsspec/implementations/dask.py,sha256=CXZbJzIVOhKV8ILcxuy3bTvcacCueAbyQxmvAkbPkrk,4466
79
+ fsspec/implementations/data.py,sha256=9tMcy1fyX1auvzFX2aANPK9CfPoarnxTCDLhX12usvs,2131
80
+ fsspec/implementations/dbfs.py,sha256=yHuLUGNmQd5pUCt9vpXleQNpjOpIZZwVZA08YauQU4U,16249
81
+ fsspec/implementations/dirfs.py,sha256=c8ulhykA0zL7-60tZeMS0VbtkKrCT6pImyooyAG14-Y,15120
82
+ fsspec/implementations/ftp.py,sha256=S_y5XOv_QhBiYBw430qzFB5MfS9AzxNBOs3f87XehC0,13539
83
+ fsspec/implementations/gist.py,sha256=Y6jTDrE-wuTwvpPyAQDuuOMBGxlajafKWoB1_yX6jdY,8528
84
+ fsspec/implementations/git.py,sha256=qBDWMz5LNllPqVjr5jf_1FuNha4P5lyQI3IlhYg-wUE,3731
85
+ fsspec/implementations/github.py,sha256=aCsZL8UvXZgdkcB1RUs3DdLeNrjLKcFsFYeQFDWbBFo,11653
86
+ fsspec/implementations/http.py,sha256=1uWwxllOjPe8mQD54IrCYQJHU1YaAXh_cDmXBk-AoQ8,30894
87
+ fsspec/implementations/http_sync.py,sha256=UmBqd938ebwVjYgVtzg-ysG3ZoGhIJw0wFtQAfxV3Aw,30332
88
+ fsspec/implementations/jupyter.py,sha256=q1PlQ66AAswGFyr8MFKWyobaV2YekMWRtqENBDQtD28,4002
89
+ fsspec/implementations/libarchive.py,sha256=SpIA1F-zf7kb2-VYUVuhMrXTBOhBxUXKgEW1RaAdDoA,7098
90
+ fsspec/implementations/local.py,sha256=pvNJBrPx9LUX6h0eW-SAF_DU0do6TstAfn2kLAVWC_Y,17726
91
+ fsspec/implementations/memory.py,sha256=8tvbep-bodi2Mgw33jOBVCvri024Y05PQkJK0w8KVdU,15956
92
+ fsspec/implementations/reference.py,sha256=0p6uJjPU04PEekuUkJWI-yFKIVTQI8kLWe98hemvxEY,50997
93
+ fsspec/implementations/sftp.py,sha256=a84flSX8eL7csJzUX1H66XXyBLdxesVHmgd325VVpEY,8864
94
+ fsspec/implementations/smb.py,sha256=5fhu8h06nOLBPh2c48aT7WBRqh9cEcbIwtyu06wTjec,15236
95
+ fsspec/implementations/tar.py,sha256=YWwcw_egHABzTgYSauaEgWkZ6_fQN6Ozh03sNISis3Q,5573
96
+ fsspec/implementations/webhdfs.py,sha256=osF2m0nhDil6sbMzYW_4DZzhxF4ygtb59XDiybd9Fyg,17589
97
+ fsspec/implementations/zip.py,sha256=6DJPdq01mIMc8CSnJpMs08LKRNGipFMqJPUC8rou1qU,6712
98
+ fsspec/json.py,sha256=4EBZ-xOmRiyxmIqPIwxmDImosRQ7io7qBM2xjJPsEE4,3768
99
+ fsspec/mapping.py,sha256=gLCwX6LZcw09s6qZUKLnc3gxm1JBtjE6hU70bE8pNmc,8537
100
+ fsspec/parquet.py,sha256=0SzfswUTc2k5nAj7xZNYPPyvUkFNXznFRXXtBRhr-iE,20506
101
+ fsspec/prefetcher.py,sha256=Yg_lWdSSP2eDvbQqv3p-Zajq2M1FeyoocIvVmFLXyXs,32611
102
+ fsspec/registry.py,sha256=KeDNL9HOyHX_D4D4qQGAI-Y3DQhiLeUC1VK2I81NZaE,12344
103
+ fsspec/spec.py,sha256=rdVOdEMNEWf4-fWsU0m-voESNPUFWJndo7SsHFuYYDs,80278
104
+ fsspec/tests/abstract/__init__.py,sha256=V0-8FqQPfHlHZ3xomJ0hyWl6t1QvqsDnQFJYHeSTlEw,10197
105
+ fsspec/tests/abstract/__pycache__/__init__.cpython-314.pyc,,
106
+ fsspec/tests/abstract/__pycache__/common.cpython-314.pyc,,
107
+ fsspec/tests/abstract/__pycache__/copy.cpython-314.pyc,,
108
+ fsspec/tests/abstract/__pycache__/get.cpython-314.pyc,,
109
+ fsspec/tests/abstract/__pycache__/mv.cpython-314.pyc,,
110
+ fsspec/tests/abstract/__pycache__/open.cpython-314.pyc,,
111
+ fsspec/tests/abstract/__pycache__/pipe.cpython-314.pyc,,
112
+ fsspec/tests/abstract/__pycache__/put.cpython-314.pyc,,
113
+ fsspec/tests/abstract/common.py,sha256=1GQwNo5AONzAnzZj0fWgn8NJPLXALehbsuGxS3FzWVU,4973
114
+ fsspec/tests/abstract/copy.py,sha256=gU5-d97U3RSde35Vp4RxPY4rWwL744HiSrJ8IBOp9-8,19967
115
+ fsspec/tests/abstract/get.py,sha256=vNR4HztvTR7Cj56AMo7_tx7TeYz1Jgr_2Wb8Lv-UiBY,20755
116
+ fsspec/tests/abstract/mv.py,sha256=k8eUEBIrRrGMsBY5OOaDXdGnQUKGwDIfQyduB6YD3Ns,1982
117
+ fsspec/tests/abstract/open.py,sha256=Fi2PBPYLbRqysF8cFm0rwnB41kMdQVYjq8cGyDXp3BU,329
118
+ fsspec/tests/abstract/pipe.py,sha256=LFzIrLCB5GLXf9rzFKJmE8AdG7LQ_h4bJo70r8FLPqM,402
119
+ fsspec/tests/abstract/put.py,sha256=7aih17OKB_IZZh1Mkq1eBDIjobhtMQmI8x-Pw-S_aZk,21201
120
+ fsspec/transaction.py,sha256=bS1yQQPEgHlREQSBjw-1DrdqYn27MdctkA55E78nt9s,3392
121
+ fsspec/utils.py,sha256=nTXWV9xEHo9L511ULkj8RDL-AfsGq4ClAVgfGa_Ws10,28458
venv/lib/python3.14/site-packages/fsspec-2026.9.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.3
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
venv/lib/python3.14/site-packages/fsspec-2026.9.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.
venv/lib/python3.14/site-packages/fsspec/generic.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import logging
5
+ import os
6
+ import shutil
7
+ import uuid
8
+
9
+ from .asyn import AsyncFileSystem, _run_coros_in_chunks, sync_wrapper
10
+ from .callbacks import DEFAULT_CALLBACK
11
+ from .core import filesystem, get_filesystem_class, split_protocol, url_to_fs
12
+
13
+ _generic_fs = {}
14
+ logger = logging.getLogger("fsspec.generic")
15
+
16
+
17
+ def set_generic_fs(protocol, **storage_options):
18
+ """Populate the dict used for method=="generic" lookups"""
19
+ _generic_fs[protocol] = filesystem(protocol, **storage_options)
20
+
21
+
22
+ def _resolve_fs(url, method, protocol=None, storage_options=None):
23
+ """Pick instance of backend FS"""
24
+ url = url[0] if isinstance(url, (list, tuple)) else url
25
+ protocol = protocol or split_protocol(url)[0]
26
+ storage_options = storage_options or {}
27
+ if method == "default":
28
+ return filesystem(protocol)
29
+ if method == "generic":
30
+ return _generic_fs[protocol]
31
+ if method == "current":
32
+ cls = get_filesystem_class(protocol)
33
+ return cls.current()
34
+ if method == "options":
35
+ fs, _ = url_to_fs(url, **storage_options.get(protocol, {}))
36
+ return fs
37
+ raise ValueError(f"Unknown FS resolution method: {method}")
38
+
39
+
40
+ def rsync(
41
+ source,
42
+ destination,
43
+ delete_missing=False,
44
+ source_field="size",
45
+ dest_field="size",
46
+ update_cond="different",
47
+ inst_kwargs=None,
48
+ fs=None,
49
+ **kwargs,
50
+ ):
51
+ """Sync files between two directory trees
52
+
53
+ (experimental)
54
+
55
+ Parameters
56
+ ----------
57
+ source: str
58
+ Root of the directory tree to take files from. This must be a directory, but
59
+ do not include any terminating "/" character
60
+ destination: str
61
+ Root path to copy into. The contents of this location should be
62
+ identical to the contents of ``source`` when done. This will be made a
63
+ directory, and the terminal "/" should not be included.
64
+ delete_missing: bool
65
+ If there are paths in the destination that don't exist in the
66
+ source and this is True, delete them. Otherwise, leave them alone.
67
+ source_field: str | callable
68
+ If ``update_field`` is "different", this is the key in the info
69
+ of source files to consider for difference. Maybe a function of the
70
+ info dict.
71
+ dest_field: str | callable
72
+ If ``update_field`` is "different", this is the key in the info
73
+ of destination files to consider for difference. May be a function of
74
+ the info dict.
75
+ update_cond: "different"|"always"|"never"
76
+ If "always", every file is copied, regardless of whether it exists in
77
+ the destination. If "never", files that exist in the destination are
78
+ not copied again. If "different" (default), only copy if the info
79
+ fields given by ``source_field`` and ``dest_field`` (usually "size")
80
+ are different. Other comparisons may be added in the future.
81
+ inst_kwargs: dict|None
82
+ If ``fs`` is None, use this set of keyword arguments to make a
83
+ GenericFileSystem instance
84
+ fs: GenericFileSystem|None
85
+ Instance to use if explicitly given. The instance defines how to
86
+ to make downstream file system instances from paths.
87
+
88
+ Returns
89
+ -------
90
+ dict of the copy operations that were performed, {source: destination}
91
+ """
92
+ fs = fs or GenericFileSystem(**(inst_kwargs or {}))
93
+ source = fs._strip_protocol(source)
94
+ destination = fs._strip_protocol(destination)
95
+ allfiles = fs.find(source, withdirs=True, detail=True)
96
+ if not fs.isdir(source):
97
+ raise ValueError("Can only rsync on a directory")
98
+ otherfiles = fs.find(destination, withdirs=True, detail=True)
99
+ dirs = [
100
+ a
101
+ for a, v in allfiles.items()
102
+ if v["type"] == "directory" and a.replace(source, destination) not in otherfiles
103
+ ]
104
+ logger.debug(f"{len(dirs)} directories to create")
105
+ if dirs:
106
+ fs.make_many_dirs(
107
+ [dirn.replace(source, destination) for dirn in dirs], exist_ok=True
108
+ )
109
+ allfiles = {a: v for a, v in allfiles.items() if v["type"] == "file"}
110
+ logger.debug(f"{len(allfiles)} files to consider for copy")
111
+ to_delete = [
112
+ o
113
+ for o, v in otherfiles.items()
114
+ if o.replace(destination, source) not in allfiles and v["type"] == "file"
115
+ ]
116
+ for k, v in allfiles.copy().items():
117
+ otherfile = k.replace(source, destination)
118
+ if otherfile in otherfiles:
119
+ if update_cond == "always":
120
+ allfiles[k] = otherfile
121
+ elif update_cond == "never":
122
+ allfiles.pop(k)
123
+ elif update_cond == "different":
124
+ inf1 = source_field(v) if callable(source_field) else v[source_field]
125
+ v2 = otherfiles[otherfile]
126
+ inf2 = dest_field(v2) if callable(dest_field) else v2[dest_field]
127
+ if inf1 != inf2:
128
+ # details mismatch, make copy
129
+ allfiles[k] = otherfile
130
+ else:
131
+ # details match, don't copy
132
+ allfiles.pop(k)
133
+ else:
134
+ # file not in target yet
135
+ allfiles[k] = otherfile
136
+ logger.debug(f"{len(allfiles)} files to copy")
137
+ if allfiles:
138
+ source_files, target_files = zip(*allfiles.items())
139
+ fs.cp(source_files, target_files, **kwargs)
140
+ logger.debug(f"{len(to_delete)} files to delete")
141
+ if delete_missing and to_delete:
142
+ fs.rm(to_delete)
143
+ return allfiles
144
+
145
+
146
+ class GenericFileSystem(AsyncFileSystem):
147
+ """Wrapper over all other FS types
148
+
149
+ <experimental!>
150
+
151
+ This implementation is a single unified interface to be able to run FS operations
152
+ over generic URLs, and dispatch to the specific implementations using the URL
153
+ protocol prefix.
154
+
155
+ Note: instances of this FS are always async, even if you never use it with any async
156
+ backend.
157
+ """
158
+
159
+ protocol = "generic" # there is no real reason to ever use a protocol with this FS
160
+
161
+ def __init__(self, default_method="default", storage_options=None, **kwargs):
162
+ """
163
+
164
+ Parameters
165
+ ----------
166
+ default_method: str (optional)
167
+ Defines how to configure backend FS instances. Options are:
168
+ - "default": instantiate like FSClass(), with no
169
+ extra arguments; this is the default instance of that FS, and can be
170
+ configured via the config system
171
+ - "generic": takes instances from the `_generic_fs` dict in this module,
172
+ which you must populate before use. Keys are by protocol
173
+ - "options": expects storage_options, a dict mapping protocol to
174
+ kwargs to use when constructing the filesystem
175
+ - "current": takes the most recently instantiated version of each FS
176
+ """
177
+ self.method = default_method
178
+ self.st_opts = storage_options
179
+ super().__init__(**kwargs)
180
+
181
+ def _parent(self, path):
182
+ fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
183
+ return fs.unstrip_protocol(fs._parent(path))
184
+
185
+ def _strip_protocol(self, path):
186
+ # normalization only
187
+ fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
188
+ return fs.unstrip_protocol(fs._strip_protocol(path))
189
+
190
+ async def _find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
191
+ fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
192
+ if fs.async_impl:
193
+ out = await fs._find(
194
+ path, maxdepth=maxdepth, withdirs=withdirs, detail=True, **kwargs
195
+ )
196
+ else:
197
+ out = fs.find(
198
+ path, maxdepth=maxdepth, withdirs=withdirs, detail=True, **kwargs
199
+ )
200
+ result = {}
201
+ for k, v in out.items():
202
+ v = v.copy() # don't corrupt target FS dircache
203
+ name = fs.unstrip_protocol(k)
204
+ v["name"] = name
205
+ result[name] = v
206
+ if detail:
207
+ return result
208
+ return list(result)
209
+
210
+ async def _info(self, url, **kwargs):
211
+ fs = _resolve_fs(url, self.method, storage_options=self.st_opts)
212
+ if fs.async_impl:
213
+ out = await fs._info(url, **kwargs)
214
+ else:
215
+ out = fs.info(url, **kwargs)
216
+ out = out.copy() # don't edit originals
217
+ out["name"] = fs.unstrip_protocol(out["name"])
218
+ return out
219
+
220
+ async def _ls(
221
+ self,
222
+ url,
223
+ detail=True,
224
+ **kwargs,
225
+ ):
226
+ fs = _resolve_fs(url, self.method, storage_options=self.st_opts)
227
+ if fs.async_impl:
228
+ out = await fs._ls(url, detail=True, **kwargs)
229
+ else:
230
+ out = fs.ls(url, detail=True, **kwargs)
231
+ out = [o.copy() for o in out] # don't edit originals
232
+ for o in out:
233
+ o["name"] = fs.unstrip_protocol(o["name"])
234
+ if detail:
235
+ return out
236
+ else:
237
+ return [o["name"] for o in out]
238
+
239
+ async def _cat_file(
240
+ self,
241
+ url,
242
+ **kwargs,
243
+ ):
244
+ fs = _resolve_fs(url, self.method, storage_options=self.st_opts)
245
+ if fs.async_impl:
246
+ return await fs._cat_file(url, **kwargs)
247
+ else:
248
+ return fs.cat_file(url, **kwargs)
249
+
250
+ async def _pipe_file(
251
+ self,
252
+ path,
253
+ value,
254
+ **kwargs,
255
+ ):
256
+ fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
257
+ if fs.async_impl:
258
+ return await fs._pipe_file(path, value, **kwargs)
259
+ else:
260
+ return fs.pipe_file(path, value, **kwargs)
261
+
262
+ async def _rm(self, url, **kwargs):
263
+ urls = url
264
+ if isinstance(urls, str):
265
+ urls = [urls]
266
+ fs = _resolve_fs(urls[0], self.method, storage_options=self.st_opts)
267
+ if fs.async_impl:
268
+ await fs._rm(urls, **kwargs)
269
+ else:
270
+ fs.rm(url, **kwargs)
271
+
272
+ async def _makedirs(self, path, exist_ok=False):
273
+ logger.debug("Make dir %s", path)
274
+ fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
275
+ if fs.async_impl:
276
+ await fs._makedirs(path, exist_ok=exist_ok)
277
+ else:
278
+ fs.makedirs(path, exist_ok=exist_ok)
279
+
280
+ def rsync(self, source, destination, **kwargs):
281
+ """Sync files between two directory trees
282
+
283
+ See `func:rsync` for more details.
284
+ """
285
+ rsync(source, destination, fs=self, **kwargs)
286
+
287
+ async def _cp_file(
288
+ self,
289
+ url,
290
+ url2,
291
+ blocksize=2**20,
292
+ callback=DEFAULT_CALLBACK,
293
+ tempdir: str | None = None,
294
+ **kwargs,
295
+ ):
296
+ fs = _resolve_fs(url, self.method, storage_options=self.st_opts)
297
+ fs2 = _resolve_fs(url2, self.method, storage_options=self.st_opts)
298
+ if fs is fs2:
299
+ # pure remote
300
+ if fs.async_impl:
301
+ return await fs._copy(url, url2, **kwargs)
302
+ else:
303
+ return fs.copy(url, url2, **kwargs)
304
+ await copy_file_op(fs, [url], fs2, [url2], tempdir, 1, on_error="raise")
305
+
306
+ async def _make_many_dirs(self, urls, exist_ok=True):
307
+ fs = _resolve_fs(urls[0], self.method, storage_options=self.st_opts)
308
+ if fs.async_impl:
309
+ coros = [fs._makedirs(u, exist_ok=exist_ok) for u in urls]
310
+ await _run_coros_in_chunks(coros)
311
+ else:
312
+ for u in urls:
313
+ fs.makedirs(u, exist_ok=exist_ok)
314
+
315
+ make_many_dirs = sync_wrapper(_make_many_dirs)
316
+
317
+ async def _copy(
318
+ self,
319
+ path1: list[str],
320
+ path2: list[str],
321
+ recursive: bool = False,
322
+ on_error: str = "ignore",
323
+ maxdepth: int | None = None,
324
+ batch_size: int | None = None,
325
+ tempdir: str | None = None,
326
+ **kwargs,
327
+ ):
328
+ # TODO: special case for one FS being local, which can use get/put
329
+ # TODO: special case for one being memFS, which can use cat/pipe
330
+ if recursive:
331
+ raise NotImplementedError("Please use fsspec.generic.rsync")
332
+ path1 = [path1] if isinstance(path1, str) else path1
333
+ path2 = [path2] if isinstance(path2, str) else path2
334
+
335
+ fs = _resolve_fs(path1, self.method, storage_options=self.st_opts)
336
+ fs2 = _resolve_fs(path2, self.method, storage_options=self.st_opts)
337
+
338
+ if fs is fs2:
339
+ if fs.async_impl:
340
+ return await fs._copy(path1, path2, **kwargs)
341
+ else:
342
+ return fs.copy(path1, path2, **kwargs)
343
+
344
+ await copy_file_op(
345
+ fs, path1, fs2, path2, tempdir, batch_size, on_error=on_error
346
+ )
347
+
348
+
349
+ async def copy_file_op(
350
+ fs1, url1, fs2, url2, tempdir=None, batch_size=20, on_error="ignore"
351
+ ):
352
+ import tempfile
353
+
354
+ tempdir = tempdir or tempfile.mkdtemp()
355
+ try:
356
+ coros = [
357
+ _copy_file_op(
358
+ fs1,
359
+ u1,
360
+ fs2,
361
+ u2,
362
+ os.path.join(tempdir, uuid.uuid4().hex),
363
+ )
364
+ for u1, u2 in zip(url1, url2)
365
+ ]
366
+ out = await _run_coros_in_chunks(
367
+ coros, batch_size=batch_size, return_exceptions=True
368
+ )
369
+ finally:
370
+ shutil.rmtree(tempdir)
371
+ if on_error == "return":
372
+ return out
373
+ elif on_error == "raise":
374
+ for o in out:
375
+ if isinstance(o, Exception):
376
+ raise o
377
+
378
+
379
+ async def _copy_file_op(fs1, url1, fs2, url2, local, on_error="ignore"):
380
+ if fs1.async_impl:
381
+ await fs1._get_file(url1, local)
382
+ else:
383
+ fs1.get_file(url1, local)
384
+ if fs2.async_impl:
385
+ await fs2._put_file(local, url2)
386
+ else:
387
+ fs2.put_file(local, url2)
388
+ os.unlink(local)
389
+ logger.debug("Copy %s -> %s; done", url1, url2)
390
+
391
+
392
+ async def maybe_await(cor):
393
+ if inspect.iscoroutine(cor):
394
+ return await cor
395
+ else:
396
+ return cor
venv/lib/python3.14/site-packages/fsspec/gui.py ADDED
@@ -0,0 +1,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import contextlib
3
+ import logging
4
+ import os
5
+ import re
6
+ from collections.abc import Sequence
7
+ from typing import ClassVar
8
+
9
+ import panel as pn
10
+
11
+ from .core import OpenFile, get_filesystem_class, split_protocol
12
+ from .registry import known_implementations
13
+
14
+ pn.extension()
15
+ logger = logging.getLogger("fsspec.gui")
16
+
17
+
18
+ class SigSlot:
19
+ """Signal-slot mixin, for Panel event passing
20
+
21
+ Include this class in a widget manager's superclasses to be able to
22
+ register events and callbacks on Panel widgets managed by that class.
23
+
24
+ The method ``_register`` should be called as widgets are added, and external
25
+ code should call ``connect`` to associate callbacks.
26
+
27
+ By default, all signals emit a DEBUG logging statement.
28
+ """
29
+
30
+ # names of signals that this class may emit each of which must be
31
+ # set by _register for any new instance
32
+ signals: ClassVar[Sequence[str]] = []
33
+ # names of actions that this class may respond to
34
+ slots: ClassVar[Sequence[str]] = []
35
+
36
+ # each of which must be a method name
37
+
38
+ def __init__(self):
39
+ self._ignoring_events = False
40
+ self._sigs = {}
41
+ self._map = {}
42
+ self._setup()
43
+
44
+ def _setup(self):
45
+ """Create GUI elements and register signals"""
46
+ self.panel = pn.pane.PaneBase()
47
+ # no signals to set up in the base class
48
+
49
+ def _register(
50
+ self, widget, name, thing="value", log_level=logging.DEBUG, auto=False
51
+ ):
52
+ """Watch the given attribute of a widget and assign it a named event
53
+
54
+ This is normally called at the time a widget is instantiated, in the
55
+ class which owns it.
56
+
57
+ Parameters
58
+ ----------
59
+ widget : pn.layout.Panel or None
60
+ Widget to watch. If None, an anonymous signal not associated with
61
+ any widget.
62
+ name : str
63
+ Name of this event
64
+ thing : str
65
+ Attribute of the given widget to watch
66
+ log_level : int
67
+ When the signal is triggered, a logging event of the given level
68
+ will be fired in the dfviz logger.
69
+ auto : bool
70
+ If True, automatically connects with a method in this class of the
71
+ same name.
72
+ """
73
+ if name not in self.signals:
74
+ raise ValueError(f"Attempt to assign an undeclared signal: {name}")
75
+ self._sigs[name] = {
76
+ "widget": widget,
77
+ "callbacks": [],
78
+ "thing": thing,
79
+ "log": log_level,
80
+ }
81
+ wn = "-".join(
82
+ [
83
+ getattr(widget, "name", str(widget)) if widget is not None else "none",
84
+ thing,
85
+ ]
86
+ )
87
+ self._map[wn] = name
88
+ if widget is not None:
89
+ widget.param.watch(self._signal, thing, onlychanged=True)
90
+ if auto and hasattr(self, name):
91
+ self.connect(name, getattr(self, name))
92
+
93
+ def _repr_mimebundle_(self, *args, **kwargs):
94
+ """Display in a notebook or a server"""
95
+ try:
96
+ return self.panel._repr_mimebundle_(*args, **kwargs)
97
+ except (ValueError, AttributeError) as exc:
98
+ raise NotImplementedError(
99
+ "Panel does not seem to be set up properly"
100
+ ) from exc
101
+
102
+ def connect(self, signal, slot):
103
+ """Associate call back with given event
104
+
105
+ The callback must be a function which takes the "new" value of the
106
+ watched attribute as the only parameter. If the callback return False,
107
+ this cancels any further processing of the given event.
108
+
109
+ Alternatively, the callback can be a string, in which case it means
110
+ emitting the correspondingly-named event (i.e., connect to self)
111
+ """
112
+ self._sigs[signal]["callbacks"].append(slot)
113
+
114
+ def _signal(self, event):
115
+ """This is called by a an action on a widget
116
+
117
+ Within an self.ignore_events context, nothing happens.
118
+
119
+ Tests can execute this method by directly changing the values of
120
+ widget components.
121
+ """
122
+ if not self._ignoring_events:
123
+ wn = "-".join([event.obj.name, event.name])
124
+ if wn in self._map and self._map[wn] in self._sigs:
125
+ self._emit(self._map[wn], event.new)
126
+
127
+ @contextlib.contextmanager
128
+ def ignore_events(self):
129
+ """Temporarily turn off events processing in this instance
130
+
131
+ (does not propagate to children)
132
+ """
133
+ self._ignoring_events = True
134
+ try:
135
+ yield
136
+ finally:
137
+ self._ignoring_events = False
138
+
139
+ def _emit(self, sig, value=None):
140
+ """An event happened, call its callbacks
141
+
142
+ This method can be used in tests to simulate message passing without
143
+ directly changing visual elements.
144
+
145
+ Calling of callbacks will halt whenever one returns False.
146
+ """
147
+ logger.log(self._sigs[sig]["log"], f"{sig}: {value}")
148
+ for callback in self._sigs[sig]["callbacks"]:
149
+ if isinstance(callback, str):
150
+ self._emit(callback)
151
+ else:
152
+ try:
153
+ # running callbacks should not break the interface
154
+ ret = callback(value)
155
+ if ret is False:
156
+ break
157
+ except Exception as e:
158
+ logger.exception(
159
+ "Exception (%s) while executing callback for signal: %s",
160
+ e,
161
+ sig,
162
+ )
163
+
164
+ def show(self, threads=False):
165
+ """Open a new browser tab and display this instance's interface"""
166
+ self.panel.show(threads=threads, verbose=False)
167
+ return self
168
+
169
+
170
+ class SingleSelect(SigSlot):
171
+ """A multiselect which only allows you to select one item for an event"""
172
+
173
+ signals = ["_selected", "selected"] # the first is internal
174
+ slots = ["set_options", "set_selection", "add", "clear", "select"]
175
+
176
+ def __init__(self, **kwargs):
177
+ self.kwargs = kwargs
178
+ super().__init__()
179
+
180
+ def _setup(self):
181
+ self.panel = pn.widgets.MultiSelect(**self.kwargs)
182
+ self._register(self.panel, "_selected", "value")
183
+ self._register(None, "selected")
184
+ self.connect("_selected", self.select_one)
185
+
186
+ def _signal(self, *args, **kwargs):
187
+ super()._signal(*args, **kwargs)
188
+
189
+ def select_one(self, *_):
190
+ with self.ignore_events():
191
+ val = [self.panel.value[-1]] if self.panel.value else []
192
+ self.panel.value = val
193
+ self._emit("selected", self.panel.value)
194
+
195
+ def set_options(self, options):
196
+ self.panel.options = options
197
+
198
+ def clear(self):
199
+ self.panel.options = []
200
+
201
+ @property
202
+ def value(self):
203
+ return self.panel.value
204
+
205
+ def set_selection(self, selection):
206
+ self.panel.value = [selection]
207
+
208
+
209
+ class FileSelector(SigSlot):
210
+ """Panel-based graphical file selector widget
211
+
212
+ Instances of this widget are interactive and can be displayed in jupyter by having
213
+ them as the output of a cell, or in a separate browser tab using ``.show()``.
214
+ """
215
+
216
+ signals = [
217
+ "protocol_changed",
218
+ "selection_changed",
219
+ "directory_entered",
220
+ "home_clicked",
221
+ "up_clicked",
222
+ "go_clicked",
223
+ "filters_changed",
224
+ ]
225
+ slots = ["set_filters", "go_home"]
226
+
227
+ def __init__(self, url=None, filters=None, ignore=None, kwargs=None):
228
+ """
229
+
230
+ Parameters
231
+ ----------
232
+ url : str (optional)
233
+ Initial value of the URL to populate the dialog; should include protocol
234
+ filters : list(str) (optional)
235
+ File endings to include in the listings. If not included, all files are
236
+ allowed. Does not affect directories.
237
+ If given, the endings will appear as checkboxes in the interface
238
+ ignore : list(str) (optional)
239
+ Regex(s) of file basename patterns to ignore, e.g., "\\." for typical
240
+ hidden files on posix
241
+ kwargs : dict (optional)
242
+ To pass to file system instance
243
+ """
244
+ if url:
245
+ self.init_protocol, url = split_protocol(url)
246
+ else:
247
+ self.init_protocol, url = "file", os.getcwd()
248
+ self.init_url = url
249
+ self.init_kwargs = (kwargs if isinstance(kwargs, str) else str(kwargs)) or "{}"
250
+ self.filters = filters
251
+ self.ignore = [re.compile(i) for i in ignore or []]
252
+ self._fs = None
253
+ super().__init__()
254
+
255
+ def _setup(self):
256
+ self.url = pn.widgets.TextInput(
257
+ name="url",
258
+ value=self.init_url,
259
+ align="end",
260
+ sizing_mode="stretch_width",
261
+ width_policy="max",
262
+ )
263
+ self.protocol = pn.widgets.Select(
264
+ options=sorted(known_implementations),
265
+ value=self.init_protocol,
266
+ name="protocol",
267
+ align="center",
268
+ )
269
+ self.kwargs = pn.widgets.TextInput(
270
+ name="kwargs", value=self.init_kwargs, align="center"
271
+ )
272
+ self.go = pn.widgets.Button(name="⇨", align="end", width=45)
273
+ self.main = SingleSelect(size=10)
274
+ self.home = pn.widgets.Button(name="🏠", width=40, height=30, align="end")
275
+ self.up = pn.widgets.Button(name="‹", width=30, height=30, align="end")
276
+
277
+ self._register(self.protocol, "protocol_changed", auto=True)
278
+ self._register(self.go, "go_clicked", "clicks", auto=True)
279
+ self._register(self.up, "up_clicked", "clicks", auto=True)
280
+ self._register(self.home, "home_clicked", "clicks", auto=True)
281
+ self._register(None, "selection_changed")
282
+ self.main.connect("selected", self.selection_changed)
283
+ self._register(None, "directory_entered")
284
+ self.prev_protocol = self.protocol.value
285
+ self.prev_kwargs = self.storage_options
286
+
287
+ self.filter_sel = pn.widgets.CheckBoxGroup(
288
+ value=[], options=[], inline=False, align="end", width_policy="min"
289
+ )
290
+ self._register(self.filter_sel, "filters_changed", auto=True)
291
+
292
+ self.panel = pn.Column(
293
+ pn.Row(self.protocol, self.kwargs),
294
+ pn.Row(self.home, self.up, self.url, self.go, self.filter_sel),
295
+ self.main.panel,
296
+ )
297
+ self.set_filters(self.filters)
298
+ self.go_clicked()
299
+
300
+ def set_filters(self, filters=None):
301
+ self.filters = filters
302
+ if filters:
303
+ self.filter_sel.options = filters
304
+ self.filter_sel.value = filters
305
+ else:
306
+ self.filter_sel.options = []
307
+ self.filter_sel.value = []
308
+
309
+ @property
310
+ def storage_options(self):
311
+ """Value of the kwargs box as a dictionary"""
312
+ return ast.literal_eval(self.kwargs.value) or {}
313
+
314
+ @property
315
+ def fs(self):
316
+ """Current filesystem instance"""
317
+ if self._fs is None:
318
+ cls = get_filesystem_class(self.protocol.value)
319
+ self._fs = cls(**self.storage_options)
320
+ return self._fs
321
+
322
+ @property
323
+ def urlpath(self):
324
+ """URL of currently selected item"""
325
+ return (
326
+ (f"{self.protocol.value}://{self.main.value[0]}")
327
+ if self.main.value
328
+ else None
329
+ )
330
+
331
+ def open_file(self, mode="rb", compression=None, encoding=None):
332
+ """Create OpenFile instance for the currently selected item
333
+
334
+ For example, in a notebook you might do something like
335
+
336
+ .. code-block::
337
+
338
+ [ ]: sel = FileSelector(); sel
339
+
340
+ # user selects their file
341
+
342
+ [ ]: with sel.open_file('rb') as f:
343
+ ... out = f.read()
344
+
345
+ Parameters
346
+ ----------
347
+ mode: str (optional)
348
+ Open mode for the file.
349
+ compression: str (optional)
350
+ The interact with the file as compressed. Set to 'infer' to guess
351
+ compression from the file ending
352
+ encoding: str (optional)
353
+ If using text mode, use this encoding; defaults to UTF8.
354
+ """
355
+ if self.urlpath is None:
356
+ raise ValueError("No file selected")
357
+ return OpenFile(self.fs, self.urlpath, mode, compression, encoding)
358
+
359
+ def filters_changed(self, values):
360
+ self.filters = values
361
+ self.go_clicked()
362
+
363
+ def selection_changed(self, *_):
364
+ if self.urlpath is None:
365
+ return
366
+ if self.fs.isdir(self.urlpath):
367
+ self.url.value = self.fs._strip_protocol(self.urlpath)
368
+ self.go_clicked()
369
+
370
+ def go_clicked(self, *_):
371
+ if (
372
+ self.prev_protocol != self.protocol.value
373
+ or self.prev_kwargs != self.storage_options
374
+ ):
375
+ self._fs = None # causes fs to be recreated
376
+ self.prev_protocol = self.protocol.value
377
+ self.prev_kwargs = self.storage_options
378
+ listing = sorted(
379
+ self.fs.ls(self.url.value, detail=True), key=lambda x: x["name"]
380
+ )
381
+ listing = [
382
+ l
383
+ for l in listing
384
+ if not any(i.match(l["name"].rsplit("/", 1)[-1]) for i in self.ignore)
385
+ ]
386
+ folders = {
387
+ "📁 " + o["name"].rsplit("/", 1)[-1]: o["name"]
388
+ for o in listing
389
+ if o["type"] == "directory"
390
+ }
391
+ files = {
392
+ "📄 " + o["name"].rsplit("/", 1)[-1]: o["name"]
393
+ for o in listing
394
+ if o["type"] == "file"
395
+ }
396
+ if self.filters:
397
+ files = {
398
+ k: v
399
+ for k, v in files.items()
400
+ if any(v.endswith(ext) for ext in self.filters)
401
+ }
402
+ self.main.set_options(dict(**folders, **files))
403
+
404
+ def protocol_changed(self, *_):
405
+ self._fs = None
406
+ self.main.options = []
407
+ self.url.value = ""
408
+
409
+ def home_clicked(self, *_):
410
+ self.protocol.value = self.init_protocol
411
+ self.kwargs.value = self.init_kwargs
412
+ self.url.value = self.init_url
413
+ self.go_clicked()
414
+
415
+ def up_clicked(self, *_):
416
+ self.url.value = self.fs._parent(self.url.value)
417
+ self.go_clicked()
venv/lib/python3.14/site-packages/fsspec/implementations/__init__.py ADDED
File without changes
venv/lib/python3.14/site-packages/fsspec/implementations/arrow.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "readinto",
231
+ "seek",
232
+ "tell",
233
+ "write",
234
+ "flush",
235
+ "readable",
236
+ "writable",
237
+ "close",
238
+ "seekable",
239
+ ],
240
+ )
241
+ class ArrowFile(io.IOBase):
242
+ def __init__(self, fs, stream, path, mode, block_size=None, **kwargs):
243
+ self.path = path
244
+ self.mode = mode
245
+
246
+ self.fs = fs
247
+ self.stream = stream
248
+
249
+ self.blocksize = self.block_size = block_size
250
+ self.kwargs = kwargs
251
+
252
+ def __enter__(self):
253
+ return self
254
+
255
+ @property
256
+ def closed(self):
257
+ return self.stream.closed
258
+
259
+ @property
260
+ def size(self):
261
+ if self.stream.seekable():
262
+ return self.stream.size()
263
+ return None
264
+
265
+ def __exit__(self, *args):
266
+ return self.close()
267
+
268
+
269
+ class HadoopFileSystem(ArrowFSWrapper):
270
+ """A wrapper on top of the pyarrow.fs.HadoopFileSystem
271
+ to connect it's interface with fsspec"""
272
+
273
+ protocol = "hdfs"
274
+
275
+ def __init__(
276
+ self,
277
+ host="default",
278
+ port=0,
279
+ user=None,
280
+ kerb_ticket=None,
281
+ replication=3,
282
+ extra_conf=None,
283
+ **kwargs,
284
+ ):
285
+ """
286
+
287
+ Parameters
288
+ ----------
289
+ host: str
290
+ Hostname, IP or "default" to try to read from Hadoop config
291
+ port: int
292
+ Port to connect on, or default from Hadoop config if 0
293
+ user: str or None
294
+ If given, connect as this username
295
+ kerb_ticket: str or None
296
+ If given, use this ticket for authentication
297
+ replication: int
298
+ set replication factor of file for write operations. default value is 3.
299
+ extra_conf: None or dict
300
+ Passed on to HadoopFileSystem
301
+ """
302
+ from pyarrow.fs import HadoopFileSystem
303
+
304
+ fs = HadoopFileSystem(
305
+ host=host,
306
+ port=port,
307
+ user=user,
308
+ kerb_ticket=kerb_ticket,
309
+ replication=replication,
310
+ extra_conf=extra_conf,
311
+ )
312
+ super().__init__(fs=fs, **kwargs)
313
+
314
+ @staticmethod
315
+ def _get_kwargs_from_urls(path):
316
+ ops = infer_storage_options(path)
317
+ out = {}
318
+ if ops.get("host", None):
319
+ out["host"] = ops["host"]
320
+ if ops.get("username", None):
321
+ out["user"] = ops["username"]
322
+ if ops.get("port", None):
323
+ out["port"] = ops["port"]
324
+ if ops.get("url_query", None):
325
+ queries = parse_qs(ops["url_query"])
326
+ if queries.get("replication", None):
327
+ out["replication"] = int(queries["replication"][0])
328
+ return out
venv/lib/python3.14/site-packages/fsspec/implementations/asyn_wrapper.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # paths must be normalized the way the wrapped filesystem does it
75
+ self.root_marker = self.sync_fs.root_marker
76
+ self._strip_protocol = self.sync_fs._strip_protocol
77
+ self._parent = self.sync_fs._parent
78
+ self.semaphore = semaphore
79
+ self._wrap_all_sync_methods()
80
+
81
+ @property
82
+ def fsid(self):
83
+ return f"async_{self.sync_fs.fsid}"
84
+
85
+ def _wrap_all_sync_methods(self):
86
+ """
87
+ Wrap all synchronous methods of the underlying filesystem with asynchronous versions.
88
+ """
89
+ excluded_methods = {"open"}
90
+ for method_name in dir(self.sync_fs):
91
+ if method_name.startswith("_") or method_name in excluded_methods:
92
+ continue
93
+
94
+ attr = inspect.getattr_static(self.sync_fs, method_name)
95
+ if isinstance(attr, property):
96
+ continue
97
+
98
+ method = getattr(self.sync_fs, method_name)
99
+ # generators such as ``walk`` cannot become coroutines: the async API
100
+ # expects async generators, which AsyncFileSystem already builds on
101
+ # top of the wrapped methods (``_walk`` uses ``_ls``)
102
+ if (
103
+ callable(method)
104
+ and not inspect.iscoroutinefunction(method)
105
+ and not inspect.isgeneratorfunction(method)
106
+ ):
107
+ async_method = async_wrapper(method, obj=self, semaphore=self.semaphore)
108
+ setattr(self, f"_{method_name}", async_method)
109
+
110
+ @classmethod
111
+ def wrap_class(cls, sync_fs_class):
112
+ """
113
+ Create a new class that can be used to instantiate an AsyncFileSystemWrapper
114
+ with lazy instantiation of the underlying synchronous filesystem.
115
+
116
+ Parameters
117
+ ----------
118
+ sync_fs_class : type
119
+ The class of the synchronous filesystem to wrap.
120
+
121
+ Returns
122
+ -------
123
+ type
124
+ A new class that wraps the provided synchronous filesystem class.
125
+ """
126
+
127
+ class GeneratedAsyncFileSystemWrapper(cls):
128
+ def __init__(self, *args, **kwargs):
129
+ sync_fs = sync_fs_class(*args, **kwargs)
130
+ super().__init__(sync_fs)
131
+
132
+ GeneratedAsyncFileSystemWrapper.__name__ = (
133
+ f"Async{sync_fs_class.__name__}Wrapper"
134
+ )
135
+ return GeneratedAsyncFileSystemWrapper
venv/lib/python3.14/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()
venv/lib/python3.14/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
venv/lib/python3.14/site-packages/fsspec/implementations/cached.py ADDED
@@ -0,0 +1,1083 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "_local_paths_for_ranges",
460
+ "get",
461
+ "read_block",
462
+ "tail",
463
+ "head",
464
+ "info",
465
+ "ls",
466
+ "exists",
467
+ "isfile",
468
+ "isdir",
469
+ "_check_file",
470
+ "_check_cache",
471
+ "_makedirs",
472
+ "_mkcache",
473
+ "clear_cache",
474
+ "clear_expired_cache",
475
+ "pop_from_cache",
476
+ "local_file",
477
+ "_paths_from_path",
478
+ "get_mapper",
479
+ "open_many",
480
+ "commit_many",
481
+ "hash_name",
482
+ "__hash__",
483
+ "__eq__",
484
+ "to_json",
485
+ "to_dict",
486
+ "cache_size",
487
+ "pipe_file",
488
+ "pipe",
489
+ "start_transaction",
490
+ "end_transaction",
491
+ }:
492
+ # all the methods defined in this class. Note `open` here, since
493
+ # it calls `_open`, but is actually in superclass
494
+ if hasattr(type(self), item):
495
+ return lambda *args, **kw: getattr(type(self), item).__get__(self)(
496
+ *args, **kw
497
+ )
498
+ # method is in the whitelist but not defined on this subclass;
499
+ # fall through to delegate to the wrapped filesystem below
500
+ if item in ["__reduce_ex__"]:
501
+ raise AttributeError
502
+ if item in ["transaction"]:
503
+ # property
504
+ return type(self).transaction.__get__(self)
505
+ if item in {"_cache", "transaction_type", "protocol"}:
506
+ # class attributes
507
+ return getattr(type(self), item)
508
+ if item == "__class__":
509
+ return type(self)
510
+ d = object.__getattribute__(self, "__dict__")
511
+ fs = d.get("fs", None) # fs is not immediately defined
512
+ if item in d:
513
+ return d[item]
514
+ elif fs is not None:
515
+ if item in fs.__dict__:
516
+ # attribute of instance
517
+ return fs.__dict__[item]
518
+ # attributed belonging to the target filesystem
519
+ cls = type(fs)
520
+ m = getattr(cls, item)
521
+ if (inspect.isfunction(m) or inspect.isdatadescriptor(m)) and (
522
+ not hasattr(m, "__self__") or m.__self__ is None
523
+ ):
524
+ # instance method
525
+ return m.__get__(fs, cls)
526
+ return m # class method or attribute
527
+ else:
528
+ # attributes of the superclass, while target is being set up
529
+ return super().__getattribute__(item)
530
+
531
+ def __eq__(self, other):
532
+ """Test for equality."""
533
+ if self is other:
534
+ return True
535
+ if not isinstance(other, type(self)):
536
+ return False
537
+ return (
538
+ self.storage == other.storage
539
+ and self.kwargs == other.kwargs
540
+ and self.cache_check == other.cache_check
541
+ and self.check_files == other.check_files
542
+ and self.expiry == other.expiry
543
+ and self.compression == other.compression
544
+ and self._mapper == other._mapper
545
+ and self.target_protocol == other.target_protocol
546
+ )
547
+
548
+ def __hash__(self):
549
+ """Calculate hash."""
550
+ return (
551
+ hash(tuple(self.storage))
552
+ ^ hash(str(self.kwargs))
553
+ ^ hash(self.cache_check)
554
+ ^ hash(self.check_files)
555
+ ^ hash(self.expiry)
556
+ ^ hash(self.compression)
557
+ ^ hash(self._mapper)
558
+ ^ hash(self.target_protocol)
559
+ )
560
+
561
+
562
+ class WholeFileCacheFileSystem(CachingFileSystem):
563
+ """Caches whole remote files on first access
564
+
565
+ This class is intended as a layer over any other file system, and
566
+ will make a local copy of each file accessed, so that all subsequent
567
+ reads are local. This is similar to ``CachingFileSystem``, but without
568
+ the block-wise functionality and so can work even when sparse files
569
+ are not allowed. See its docstring for definition of the init
570
+ arguments.
571
+
572
+ The class still needs access to the remote store for listing files,
573
+ and may refresh cached files.
574
+ """
575
+
576
+ protocol = "filecache"
577
+ local_file = True
578
+
579
+ def open_many(self, open_files, **kwargs):
580
+ paths = [of.path for of in open_files]
581
+ if "r" in open_files.mode:
582
+ self._mkcache()
583
+ else:
584
+ return [
585
+ LocalTempFile(
586
+ self.fs,
587
+ path,
588
+ mode=open_files.mode,
589
+ fn=os.path.join(self.storage[-1], self._mapper(path)),
590
+ **kwargs,
591
+ )
592
+ for path in paths
593
+ ]
594
+
595
+ if self.compression:
596
+ raise NotImplementedError
597
+ details = [self._check_file(sp) for sp in paths]
598
+ downpath = [p for p, d in zip(paths, details) if not d]
599
+ downfn0 = [
600
+ os.path.join(self.storage[-1], self._mapper(p))
601
+ for p, d in zip(paths, details)
602
+ ] # keep these path names for opening later
603
+ downfn = [fn for fn, d in zip(downfn0, details) if not d]
604
+ if downpath:
605
+ # skip if all files are already cached and up to date
606
+ self.fs.get(downpath, downfn)
607
+
608
+ # update metadata - only happens when downloads are successful
609
+ newdetail = [
610
+ {
611
+ "original": path,
612
+ "fn": self._mapper(path),
613
+ "blocks": True,
614
+ "time": time.time(),
615
+ "uid": self.fs.ukey(path),
616
+ }
617
+ for path in downpath
618
+ ]
619
+ for path, detail in zip(downpath, newdetail):
620
+ self._metadata.update_file(path, detail)
621
+ self.save_cache()
622
+
623
+ def firstpart(fn):
624
+ # helper to adapt both whole-file and simple-cache
625
+ return fn[1] if isinstance(fn, tuple) else fn
626
+
627
+ return [
628
+ open(firstpart(fn0) if fn0 else fn1, mode=open_files.mode)
629
+ for fn0, fn1 in zip(details, downfn0)
630
+ ]
631
+
632
+ def commit_many(self, open_files):
633
+ self.fs.put([f.fn for f in open_files], [f.path for f in open_files])
634
+ [f.close() for f in open_files]
635
+ for f in open_files:
636
+ # in case autocommit is off, and so close did not already delete
637
+ try:
638
+ os.remove(f.name)
639
+ except FileNotFoundError:
640
+ pass
641
+ self._cache_size = None
642
+
643
+ def _make_local_details(self, path):
644
+ hash = self._mapper(path)
645
+ fn = os.path.join(self.storage[-1], hash)
646
+ detail = {
647
+ "original": path,
648
+ "fn": hash,
649
+ "blocks": True,
650
+ "time": time.time(),
651
+ "uid": self.fs.ukey(path),
652
+ }
653
+ self._metadata.update_file(path, detail)
654
+ logger.debug("Copying %s to local cache", path)
655
+ return fn
656
+
657
+ def cat(
658
+ self,
659
+ path,
660
+ recursive=False,
661
+ on_error="raise",
662
+ callback=DEFAULT_CALLBACK,
663
+ **kwargs,
664
+ ):
665
+ paths = self.expand_path(
666
+ path, recursive=recursive, maxdepth=kwargs.get("maxdepth")
667
+ )
668
+ getpaths = []
669
+ storepaths = []
670
+ fns = []
671
+ out = {}
672
+ for p in paths.copy():
673
+ try:
674
+ detail = self._check_file(p)
675
+ if not detail:
676
+ fn = self._make_local_details(p)
677
+ getpaths.append(p)
678
+ storepaths.append(fn)
679
+ else:
680
+ detail, fn = detail if isinstance(detail, tuple) else (None, detail)
681
+ fns.append(fn)
682
+ except Exception as e:
683
+ if on_error == "raise":
684
+ raise
685
+ if on_error == "return":
686
+ out[p] = e
687
+ paths.remove(p)
688
+
689
+ if getpaths:
690
+ self.fs.get(getpaths, storepaths)
691
+ self.save_cache()
692
+
693
+ callback.set_size(len(paths))
694
+ for p, fn in zip(paths, fns):
695
+ with open(fn, "rb") as f:
696
+ out[p] = f.read()
697
+ callback.relative_update(1)
698
+ if isinstance(path, str) and len(paths) == 1 and recursive is False:
699
+ out = out[paths[0]]
700
+ return out
701
+
702
+ def _get_cached_file_before_open(self, path, **kwargs):
703
+ fn = self._make_local_details(path)
704
+ # call target filesystems open
705
+ self._mkcache()
706
+ if self.compression:
707
+ with self.fs._open(path, mode="rb", **kwargs) as f, open(fn, "wb") as f2:
708
+ if isinstance(f, AbstractBufferedFile):
709
+ # want no type of caching if just downloading whole thing
710
+ f.cache = BaseCache(0, f.cache.fetcher, f.size)
711
+ comp = (
712
+ infer_compression(path)
713
+ if self.compression == "infer"
714
+ else self.compression
715
+ )
716
+ f = compr[comp](f, mode="rb")
717
+ data = True
718
+ while data:
719
+ block = getattr(f, "blocksize", 5 * 2**20)
720
+ data = f.read(block)
721
+ f2.write(data)
722
+ else:
723
+ self.fs.get_file(path, fn)
724
+ self.save_cache()
725
+
726
+ def _open(self, path, mode="rb", **kwargs):
727
+ path = self._strip_protocol(path)
728
+ # For read (or append), (try) download from remote
729
+ if "r" in mode or "a" in mode:
730
+ if not self._check_file(path):
731
+ if self.fs.exists(path):
732
+ self._get_cached_file_before_open(path, **kwargs)
733
+ elif "r" in mode:
734
+ raise FileNotFoundError(path)
735
+
736
+ detail, fn = self._check_file(path)
737
+ _, blocks = detail["fn"], detail["blocks"]
738
+ if blocks is True:
739
+ logger.debug("Opening local copy of %s", path)
740
+ else:
741
+ raise ValueError(
742
+ f"Attempt to open partially cached file {path}"
743
+ f" as a wholly cached file"
744
+ )
745
+
746
+ # Just reading does not need special file handling
747
+ if "r" in mode and "+" not in mode:
748
+ # In order to support downstream filesystems to be able to
749
+ # infer the compression from the original filename, like
750
+ # the `TarFileSystem`, let's extend the `io.BufferedReader`
751
+ # fileobject protocol by adding a dedicated attribute
752
+ # `original`.
753
+ f = open(fn, mode)
754
+ f.original = detail.get("original")
755
+ return f
756
+
757
+ hash = self._mapper(path)
758
+ fn = os.path.join(self.storage[-1], hash)
759
+ user_specified_kwargs = {
760
+ k: v
761
+ for k, v in kwargs.items()
762
+ # those kwargs were added by open(), we don't want them
763
+ if k not in ["autocommit", "block_size", "cache_options"]
764
+ }
765
+ return LocalTempFile(self, path, mode=mode, fn=fn, **user_specified_kwargs)
766
+
767
+ async def _cat_file(self, path, start=None, end=None, **kwargs):
768
+ logger.debug("async cat_file %s", path)
769
+ path = self._strip_protocol(path)
770
+ sha = self._mapper(path)
771
+ fn = self._check_file(path)
772
+
773
+ if not fn:
774
+ fn = os.path.join(self.storage[-1], sha)
775
+ await self.fs._get_file(path, fn, **kwargs)
776
+
777
+ with open(fn, "rb") as f: # noqa ASYNC230
778
+ if start:
779
+ f.seek(start)
780
+ size = -1 if end is None else end - f.tell()
781
+ return f.read(size)
782
+
783
+ def _local_paths_for_ranges(self, paths):
784
+ """Cache file for each of paths, and which remote files to download
785
+
786
+ A path given more than once is downloaded once, and every occurrence
787
+ reads from the same cache file.
788
+ """
789
+ lpaths = []
790
+ local = {}
791
+ download = []
792
+ rpaths = []
793
+ for p in paths:
794
+ if p not in local:
795
+ detail = self._check_file(p)
796
+ if not detail:
797
+ fn = os.path.join(self.storage[-1], self._mapper(p))
798
+ download.append(fn)
799
+ rpaths.append(p)
800
+ else:
801
+ # filecache returns (detail, fn), simplecache just fn
802
+ fn = detail[1] if isinstance(detail, tuple) else detail
803
+ local[p] = fn
804
+ lpaths.append(local[p])
805
+ return lpaths, rpaths, download
806
+
807
+ async def _cat_ranges(
808
+ self, paths, starts, ends, max_gap=None, on_error="return", **kwargs
809
+ ):
810
+ logger.debug("async cat ranges %s", paths)
811
+ lpaths, rpaths, download = self._local_paths_for_ranges(paths)
812
+ if download:
813
+ await self.fs._get(rpaths, download)
814
+
815
+ return LocalFileSystem().cat_ranges(
816
+ lpaths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs
817
+ )
818
+
819
+
820
+ class SimpleCacheFileSystem(WholeFileCacheFileSystem):
821
+ """Caches whole remote files on first access
822
+
823
+ This class is intended as a layer over any other file system, and
824
+ will make a local copy of each file accessed, so that all subsequent
825
+ reads are local. This implementation only copies whole files, and
826
+ does not keep any metadata about the download time or file details.
827
+ It is therefore safer to use in multi-threaded/concurrent situations.
828
+
829
+ This is the only of the caching filesystems that supports write: you will
830
+ be given a real local open file, and upon close and commit, it will be
831
+ uploaded to the target filesystem; the writability or the target URL is
832
+ not checked until that time.
833
+
834
+ """
835
+
836
+ protocol = "simplecache"
837
+ local_file = True
838
+ transaction_type = WriteCachedTransaction
839
+
840
+ def __init__(self, **kwargs):
841
+ kw = kwargs.copy()
842
+ for key in ["cache_check", "expiry_time", "check_files"]:
843
+ kw[key] = False
844
+ super().__init__(**kw)
845
+ for storage in self.storage:
846
+ if not os.path.exists(storage):
847
+ self._makedirs(storage)
848
+
849
+ def _check_file(self, path):
850
+ self._check_cache()
851
+ sha = self._mapper(path)
852
+ for storage in self.storage:
853
+ fn = os.path.join(storage, sha)
854
+ if os.path.exists(fn):
855
+ return fn
856
+
857
+ def save_cache(self):
858
+ pass
859
+
860
+ def load_cache(self):
861
+ pass
862
+
863
+ def clear_expired_cache(self, expiry_time=None):
864
+ """Remove cached files older than ``expiry_time`` seconds.
865
+
866
+ SimpleCache does not store metadata, so cached file modification times
867
+ are used instead. Only the last (writable) cache location is changed.
868
+
869
+ Parameters
870
+ ----------
871
+ expiry_time: int or float
872
+ Maximum age of a cached file in seconds. This must be supplied
873
+ explicitly because SimpleCache has no configured expiry time.
874
+ """
875
+ if expiry_time is None:
876
+ raise ValueError("expiry_time must be provided for simplecache")
877
+ if expiry_time < 0:
878
+ raise ValueError("expiry_time must be non-negative")
879
+
880
+ self._mkcache()
881
+ cutoff = time.time() - expiry_time
882
+ with os.scandir(self.storage[-1]) as entries:
883
+ for entry in entries:
884
+ try:
885
+ if (
886
+ entry.is_file(follow_symlinks=False)
887
+ and entry.stat(follow_symlinks=False).st_mtime < cutoff
888
+ ):
889
+ os.remove(entry.path)
890
+ except FileNotFoundError:
891
+ # Another process may be using the same simple cache.
892
+ pass
893
+ self._cache_size = None
894
+
895
+ def pipe_file(self, path, value=None, **kwargs):
896
+ if self._intrans:
897
+ with self.open(path, "wb") as f:
898
+ f.write(value)
899
+ else:
900
+ super().pipe_file(path, value)
901
+
902
+ def ls(self, path, detail=True, **kwargs):
903
+ path = self._strip_protocol(path)
904
+ details = []
905
+ try:
906
+ details = self.fs.ls(
907
+ path, detail=True, **kwargs
908
+ ).copy() # don't edit original!
909
+ except FileNotFoundError as e:
910
+ ex = e
911
+ else:
912
+ ex = None
913
+ if self._intrans:
914
+ path1 = path.rstrip("/") + "/"
915
+ for f in self.transaction.files:
916
+ if f.path == path:
917
+ details.append(
918
+ {"name": path, "size": f.size or f.tell(), "type": "file"}
919
+ )
920
+ elif f.path.startswith(path1):
921
+ if f.path.count("/") == path1.count("/"):
922
+ details.append(
923
+ {"name": f.path, "size": f.size or f.tell(), "type": "file"}
924
+ )
925
+ else:
926
+ dname = "/".join(f.path.split("/")[: path1.count("/") + 1])
927
+ details.append({"name": dname, "size": 0, "type": "directory"})
928
+ if ex is not None and not details:
929
+ raise ex
930
+ if detail:
931
+ return details
932
+ return sorted(_["name"] for _ in details)
933
+
934
+ def info(self, path, **kwargs):
935
+ path = self._strip_protocol(path)
936
+ if self._intrans:
937
+ f = [_ for _ in self.transaction.files if _.path == path]
938
+ if f:
939
+ size = os.path.getsize(f[0].fn) if f[0].closed else f[0].tell()
940
+ return {"name": path, "size": size, "type": "file"}
941
+ f = any(_.path.startswith(path + "/") for _ in self.transaction.files)
942
+ if f:
943
+ return {"name": path, "size": 0, "type": "directory"}
944
+ return self.fs.info(path, **kwargs)
945
+
946
+ def pipe(self, path, value=None, **kwargs):
947
+ if isinstance(path, str):
948
+ self.pipe_file(self._strip_protocol(path), value, **kwargs)
949
+ elif isinstance(path, dict):
950
+ for k, v in path.items():
951
+ self.pipe_file(self._strip_protocol(k), v, **kwargs)
952
+ else:
953
+ raise ValueError("path must be str or dict")
954
+
955
+ def cat_ranges(
956
+ self, paths, starts, ends, max_gap=None, on_error="return", **kwargs
957
+ ):
958
+ logger.debug("cat ranges %s", paths)
959
+ lpaths, rpaths, download = self._local_paths_for_ranges(paths)
960
+ if download:
961
+ self.fs.get(rpaths, download)
962
+ return LocalFileSystem().cat_ranges(
963
+ lpaths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs
964
+ )
965
+
966
+ def _get_cached_file_before_open(self, path, **kwargs):
967
+ sha = self._mapper(path)
968
+ fn = os.path.join(self.storage[-1], sha)
969
+ logger.debug("Copying %s to local cache", path)
970
+
971
+ self._mkcache()
972
+ self._cache_size = None
973
+
974
+ if self.compression:
975
+ with self.fs._open(path, mode="rb", **kwargs) as f, open(fn, "wb") as f2:
976
+ if isinstance(f, AbstractBufferedFile):
977
+ # want no type of caching if just downloading whole thing
978
+ f.cache = BaseCache(0, f.cache.fetcher, f.size)
979
+ comp = (
980
+ infer_compression(path)
981
+ if self.compression == "infer"
982
+ else self.compression
983
+ )
984
+ f = compr[comp](f, mode="rb")
985
+ data = True
986
+ while data:
987
+ block = getattr(f, "blocksize", 5 * 2**20)
988
+ data = f.read(block)
989
+ f2.write(data)
990
+ else:
991
+ self.fs.get_file(path, fn)
992
+
993
+ def _open(self, path, mode="rb", **kwargs):
994
+ path = self._strip_protocol(path)
995
+ sha = self._mapper(path)
996
+
997
+ # For read (or append), (try) download from remote
998
+ if "r" in mode or "a" in mode:
999
+ if not self._check_file(path):
1000
+ # append does not require an existing file but read does
1001
+ if self.fs.exists(path):
1002
+ self._get_cached_file_before_open(path, **kwargs)
1003
+ elif "r" in mode:
1004
+ raise FileNotFoundError(path)
1005
+
1006
+ fn = self._check_file(path)
1007
+ # Just reading does not need special file handling
1008
+ if "r" in mode and "+" not in mode:
1009
+ return open(fn, mode)
1010
+
1011
+ fn = os.path.join(self.storage[-1], sha)
1012
+ user_specified_kwargs = {
1013
+ k: v
1014
+ for k, v in kwargs.items()
1015
+ if k not in ["autocommit", "block_size", "cache_options"]
1016
+ } # those were added by open()
1017
+ return LocalTempFile(
1018
+ self,
1019
+ path,
1020
+ mode=mode,
1021
+ autocommit=not self._intrans,
1022
+ fn=fn,
1023
+ **user_specified_kwargs,
1024
+ )
1025
+
1026
+
1027
+ class LocalTempFile:
1028
+ """A temporary local file, which will be uploaded on commit"""
1029
+
1030
+ def __init__(self, fs, path, fn, mode="wb", autocommit=True, seek=0, **kwargs):
1031
+ self.fn = fn
1032
+ self.fh = open(fn, mode)
1033
+ self.mode = mode
1034
+ if seek:
1035
+ self.fh.seek(seek)
1036
+ self.path = path
1037
+ self.size = None
1038
+ self.fs = fs
1039
+ self.closed = False
1040
+ self.autocommit = autocommit
1041
+ self.kwargs = kwargs
1042
+
1043
+ def __reduce__(self):
1044
+ # always open in r+b to allow continuing writing at a location
1045
+ return (
1046
+ LocalTempFile,
1047
+ (self.fs, self.path, self.fn, "r+b", self.autocommit, self.tell()),
1048
+ )
1049
+
1050
+ def __enter__(self):
1051
+ return self.fh
1052
+
1053
+ def __exit__(self, exc_type, exc_val, exc_tb):
1054
+ self.close()
1055
+
1056
+ def close(self):
1057
+ # self.size = self.fh.tell()
1058
+ if self.closed:
1059
+ return
1060
+ self.fh.close()
1061
+ self.closed = True
1062
+ if self.autocommit:
1063
+ self.commit()
1064
+
1065
+ def discard(self):
1066
+ self.fh.close()
1067
+ os.remove(self.fn)
1068
+
1069
+ def commit(self):
1070
+ # calling put() with list arguments avoids path expansion and additional operations
1071
+ # like isdir()
1072
+ self.fs.put([self.fn], [self.path], **self.kwargs)
1073
+ # we do not delete the local copy, it's still in the cache.
1074
+
1075
+ @property
1076
+ def name(self):
1077
+ return self.fn
1078
+
1079
+ def __repr__(self) -> str:
1080
+ return f"LocalTempFile: {self.path}"
1081
+
1082
+ def __getattr__(self, item):
1083
+ return getattr(self.fh, item)
venv/lib/python3.14/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"
venv/lib/python3.14/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)
venv/lib/python3.14/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()}"
venv/lib/python3.14/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
venv/lib/python3.14/site-packages/fsspec/implementations/dirfs.py ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def _relpath_detail(self, paths):
102
+ out = {}
103
+ for path, info in paths.items():
104
+ path = self._relpath(path)
105
+ info = info.copy()
106
+ info["name"] = path
107
+ out[path] = info
108
+ return out
109
+
110
+ # Wrappers below
111
+
112
+ @property
113
+ def sep(self):
114
+ return self.fs.sep
115
+
116
+ async def set_session(self, *args, **kwargs):
117
+ return await self.fs.set_session(*args, **kwargs)
118
+
119
+ async def _rm_file(self, path, **kwargs):
120
+ return await self.fs._rm_file(self._join(path), **kwargs)
121
+
122
+ def rm_file(self, path, **kwargs):
123
+ return self.fs.rm_file(self._join(path), **kwargs)
124
+
125
+ async def _rm(self, path, *args, **kwargs):
126
+ return await self.fs._rm(self._join(path), *args, **kwargs)
127
+
128
+ def rm(self, path, *args, **kwargs):
129
+ return self.fs.rm(self._join(path), *args, **kwargs)
130
+
131
+ def delete(self, path, recursive=False, maxdepth=None):
132
+ return self.fs.delete(self._join(path), recursive=recursive, maxdepth=maxdepth)
133
+
134
+ async def _cp_file(self, path1, path2, **kwargs):
135
+ return await self.fs._cp_file(self._join(path1), self._join(path2), **kwargs)
136
+
137
+ def cp_file(self, path1, path2, **kwargs):
138
+ return self.fs.cp_file(self._join(path1), self._join(path2), **kwargs)
139
+
140
+ async def _copy(
141
+ self,
142
+ path1,
143
+ path2,
144
+ *args,
145
+ **kwargs,
146
+ ):
147
+ return await self.fs._copy(
148
+ self._join(path1),
149
+ self._join(path2),
150
+ *args,
151
+ **kwargs,
152
+ )
153
+
154
+ def copy(self, path1, path2, *args, **kwargs):
155
+ return self.fs.copy(
156
+ self._join(path1),
157
+ self._join(path2),
158
+ *args,
159
+ **kwargs,
160
+ )
161
+
162
+ async def _pipe(self, path, *args, **kwargs):
163
+ return await self.fs._pipe(self._join(path), *args, **kwargs)
164
+
165
+ def pipe(self, path, *args, **kwargs):
166
+ return self.fs.pipe(self._join(path), *args, **kwargs)
167
+
168
+ async def _pipe_file(self, path, *args, **kwargs):
169
+ return await self.fs._pipe_file(self._join(path), *args, **kwargs)
170
+
171
+ def pipe_file(self, path, *args, **kwargs):
172
+ return self.fs.pipe_file(self._join(path), *args, **kwargs)
173
+
174
+ def write_text(
175
+ self, path, value, encoding=None, errors=None, newline=None, **kwargs
176
+ ):
177
+ return self.fs.write_text(
178
+ self._join(path),
179
+ value,
180
+ encoding=encoding,
181
+ errors=errors,
182
+ newline=newline,
183
+ **kwargs,
184
+ )
185
+
186
+ async def _cat_file(self, path, *args, **kwargs):
187
+ return await self.fs._cat_file(self._join(path), *args, **kwargs)
188
+
189
+ def cat_file(self, path, *args, **kwargs):
190
+ return self.fs.cat_file(self._join(path), *args, **kwargs)
191
+
192
+ async def _cat(self, path, *args, **kwargs):
193
+ ret = await self.fs._cat(
194
+ self._join(path),
195
+ *args,
196
+ **kwargs,
197
+ )
198
+
199
+ if isinstance(ret, dict):
200
+ return {self._relpath(key): value for key, value in ret.items()}
201
+
202
+ return ret
203
+
204
+ def cat(self, path, *args, **kwargs):
205
+ ret = self.fs.cat(
206
+ self._join(path),
207
+ *args,
208
+ **kwargs,
209
+ )
210
+
211
+ if isinstance(ret, dict):
212
+ return {self._relpath(key): value for key, value in ret.items()}
213
+
214
+ return ret
215
+
216
+ async def _cat_ranges(self, paths, starts, ends, *args, **kwargs):
217
+ return await self.fs._cat_ranges(
218
+ self._join(paths), starts, ends, *args, **kwargs
219
+ )
220
+
221
+ def cat_ranges(self, paths, starts, ends, *args, **kwargs):
222
+ return self.fs.cat_ranges(self._join(paths), starts, ends, *args, **kwargs)
223
+
224
+ async def _put_file(self, lpath, rpath, **kwargs):
225
+ return await self.fs._put_file(lpath, self._join(rpath), **kwargs)
226
+
227
+ def put_file(self, lpath, rpath, **kwargs):
228
+ return self.fs.put_file(lpath, self._join(rpath), **kwargs)
229
+
230
+ async def _put(
231
+ self,
232
+ lpath,
233
+ rpath,
234
+ *args,
235
+ **kwargs,
236
+ ):
237
+ return await self.fs._put(
238
+ lpath,
239
+ self._join(rpath),
240
+ *args,
241
+ **kwargs,
242
+ )
243
+
244
+ def put(self, lpath, rpath, *args, **kwargs):
245
+ return self.fs.put(
246
+ lpath,
247
+ self._join(rpath),
248
+ *args,
249
+ **kwargs,
250
+ )
251
+
252
+ async def _get_file(self, rpath, lpath, **kwargs):
253
+ return await self.fs._get_file(self._join(rpath), lpath, **kwargs)
254
+
255
+ def get_file(self, rpath, lpath, **kwargs):
256
+ return self.fs.get_file(self._join(rpath), lpath, **kwargs)
257
+
258
+ async def _get(self, rpath, *args, **kwargs):
259
+ return await self.fs._get(self._join(rpath), *args, **kwargs)
260
+
261
+ def get(self, rpath, *args, **kwargs):
262
+ return self.fs.get(self._join(rpath), *args, **kwargs)
263
+
264
+ async def _isfile(self, path):
265
+ return await self.fs._isfile(self._join(path))
266
+
267
+ def isfile(self, path):
268
+ return self.fs.isfile(self._join(path))
269
+
270
+ async def _isdir(self, path):
271
+ return await self.fs._isdir(self._join(path))
272
+
273
+ def isdir(self, path):
274
+ return self.fs.isdir(self._join(path))
275
+
276
+ async def _size(self, path):
277
+ return await self.fs._size(self._join(path))
278
+
279
+ def size(self, path):
280
+ return self.fs.size(self._join(path))
281
+
282
+ async def _sizes(self, paths):
283
+ return await self.fs._sizes(self._join(paths))
284
+
285
+ def sizes(self, paths):
286
+ return self.fs.sizes(self._join(paths))
287
+
288
+ def invalidate_cache(self, path=None):
289
+ # With no path, clear only what is cached under this directory. An
290
+ # unrooted dirfs joins to "", which means everything on the wrapped fs.
291
+ self.fs.invalidate_cache(self._join(path or "") or None)
292
+
293
+ def ukey(self, path):
294
+ return self.fs.ukey(self._join(path))
295
+
296
+ def checksum(self, path):
297
+ return self.fs.checksum(self._join(path))
298
+
299
+ async def _exists(self, path):
300
+ return await self.fs._exists(self._join(path))
301
+
302
+ def exists(self, path):
303
+ return self.fs.exists(self._join(path))
304
+
305
+ async def _info(self, path, **kwargs):
306
+ info = await self.fs._info(self._join(path), **kwargs)
307
+ info = info.copy()
308
+ info["name"] = self._relpath(info["name"])
309
+ return info
310
+
311
+ def info(self, path, **kwargs):
312
+ info = self.fs.info(self._join(path), **kwargs)
313
+ info = info.copy()
314
+ info["name"] = self._relpath(info["name"])
315
+ return info
316
+
317
+ async def _ls(self, path, detail=True, **kwargs):
318
+ ret = (await self.fs._ls(self._join(path), detail=detail, **kwargs)).copy()
319
+ if detail:
320
+ out = []
321
+ for entry in ret:
322
+ entry = entry.copy()
323
+ entry["name"] = self._relpath(entry["name"])
324
+ out.append(entry)
325
+ return out
326
+
327
+ return self._relpath(ret)
328
+
329
+ def ls(self, path, detail=True, **kwargs):
330
+ ret = self.fs.ls(self._join(path), detail=detail, **kwargs).copy()
331
+ if detail:
332
+ out = []
333
+ for entry in ret:
334
+ entry = entry.copy()
335
+ entry["name"] = self._relpath(entry["name"])
336
+ out.append(entry)
337
+ return out
338
+
339
+ return self._relpath(ret)
340
+
341
+ def _relpath_walk_entries(self, entries):
342
+ # with detail=True, walk gives dicts keyed by basename whose infos
343
+ # still carry the full name in the wrapped filesystem
344
+ if not isinstance(entries, dict):
345
+ return entries
346
+ return {
347
+ name: {**info, "name": self._relpath(info["name"])}
348
+ for name, info in entries.items()
349
+ }
350
+
351
+ async def _walk(self, path, *args, **kwargs):
352
+ async for root, dirs, files in self.fs._walk(self._join(path), *args, **kwargs):
353
+ yield (
354
+ self._relpath(root),
355
+ self._relpath_walk_entries(dirs),
356
+ self._relpath_walk_entries(files),
357
+ )
358
+
359
+ def walk(self, path, *args, **kwargs):
360
+ for root, dirs, files in self.fs.walk(self._join(path), *args, **kwargs):
361
+ yield (
362
+ self._relpath(root),
363
+ self._relpath_walk_entries(dirs),
364
+ self._relpath_walk_entries(files),
365
+ )
366
+
367
+ async def _glob(self, path, **kwargs):
368
+ detail = kwargs.get("detail", False)
369
+ ret = await self.fs._glob(self._join(path), **kwargs)
370
+ if detail:
371
+ return self._relpath_detail(ret)
372
+ return self._relpath(ret)
373
+
374
+ def glob(self, path, **kwargs):
375
+ detail = kwargs.get("detail", False)
376
+ ret = self.fs.glob(self._join(path), **kwargs)
377
+ if detail:
378
+ return self._relpath_detail(ret)
379
+ return self._relpath(ret)
380
+
381
+ async def _du(self, path, *args, **kwargs):
382
+ total = kwargs.get("total", True)
383
+ ret = await self.fs._du(self._join(path), *args, **kwargs)
384
+ if total:
385
+ return ret
386
+
387
+ return {self._relpath(path): size for path, size in ret.items()}
388
+
389
+ def du(self, path, *args, **kwargs):
390
+ total = kwargs.get("total", True)
391
+ ret = self.fs.du(self._join(path), *args, **kwargs)
392
+ if total:
393
+ return ret
394
+
395
+ return {self._relpath(path): size for path, size in ret.items()}
396
+
397
+ async def _find(self, path, *args, **kwargs):
398
+ detail = kwargs.get("detail", False)
399
+ ret = await self.fs._find(self._join(path), *args, **kwargs)
400
+ if detail:
401
+ return self._relpath_detail(ret)
402
+ return self._relpath(ret)
403
+
404
+ def find(self, path, *args, **kwargs):
405
+ detail = kwargs.get("detail", False)
406
+ ret = self.fs.find(self._join(path), *args, **kwargs)
407
+ if detail:
408
+ return self._relpath_detail(ret)
409
+ return self._relpath(ret)
410
+
411
+ async def _expand_path(self, path, *args, **kwargs):
412
+ return self._relpath(
413
+ await self.fs._expand_path(self._join(path), *args, **kwargs)
414
+ )
415
+
416
+ def expand_path(self, path, *args, **kwargs):
417
+ return self._relpath(self.fs.expand_path(self._join(path), *args, **kwargs))
418
+
419
+ async def _mkdir(self, path, *args, **kwargs):
420
+ return await self.fs._mkdir(self._join(path), *args, **kwargs)
421
+
422
+ def mkdir(self, path, *args, **kwargs):
423
+ return self.fs.mkdir(self._join(path), *args, **kwargs)
424
+
425
+ async def _makedirs(self, path, *args, **kwargs):
426
+ return await self.fs._makedirs(self._join(path), *args, **kwargs)
427
+
428
+ def makedirs(self, path, *args, **kwargs):
429
+ return self.fs.makedirs(self._join(path), *args, **kwargs)
430
+
431
+ def rmdir(self, path):
432
+ return self.fs.rmdir(self._join(path))
433
+
434
+ def mv(self, path1, path2, **kwargs):
435
+ return self.fs.mv(
436
+ self._join(path1),
437
+ self._join(path2),
438
+ **kwargs,
439
+ )
440
+
441
+ def touch(self, path, **kwargs):
442
+ return self.fs.touch(self._join(path), **kwargs)
443
+
444
+ def created(self, path):
445
+ return self.fs.created(self._join(path))
446
+
447
+ def modified(self, path):
448
+ return self.fs.modified(self._join(path))
449
+
450
+ def sign(self, path, *args, **kwargs):
451
+ return self.fs.sign(self._join(path), *args, **kwargs)
452
+
453
+ def __repr__(self):
454
+ return f"{self.__class__.__qualname__}(path='{self.path}', fs={self.fs})"
455
+
456
+ def open(
457
+ self,
458
+ path,
459
+ *args,
460
+ **kwargs,
461
+ ):
462
+ return self.fs.open(
463
+ self._join(path),
464
+ *args,
465
+ **kwargs,
466
+ )
467
+
468
+ async def open_async(
469
+ self,
470
+ path,
471
+ *args,
472
+ **kwargs,
473
+ ):
474
+ return await self.fs.open_async(
475
+ self._join(path),
476
+ *args,
477
+ **kwargs,
478
+ )
venv/lib/python3.14/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
venv/lib/python3.14/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
venv/lib/python3.14/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)
venv/lib/python3.14/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
venv/lib/python3.14/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)
venv/lib/python3.14/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)
venv/lib/python3.14/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)
venv/lib/python3.14/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)
venv/lib/python3.14/site-packages/fsspec/implementations/local.py ADDED
@@ -0,0 +1,525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.compression import compr
12
+ from fsspec.core import get_compression
13
+ from fsspec.utils import isfilelike, stringify_path
14
+
15
+ from ..spec import AbstractFileSystem
16
+
17
+ logger = logging.getLogger("fsspec.local")
18
+
19
+
20
+ class LocalFileSystem(AbstractFileSystem):
21
+ """Interface to files on local storage
22
+
23
+ Parameters
24
+ ----------
25
+ auto_mkdir: bool
26
+ Whether, when opening a file, the directory containing it should
27
+ be created (if it doesn't already exist). This is assumed by pyarrow
28
+ code.
29
+ """
30
+
31
+ root_marker = "/"
32
+ protocol = "file", "local"
33
+ local_file = True
34
+
35
+ def __init__(self, auto_mkdir=False, **kwargs):
36
+ super().__init__(**kwargs)
37
+ self.auto_mkdir = auto_mkdir
38
+
39
+ @property
40
+ def fsid(self):
41
+ return "local"
42
+
43
+ def mkdir(self, path, create_parents=True, **kwargs):
44
+ path = self._strip_protocol(path)
45
+ if self.exists(path):
46
+ raise FileExistsError(path)
47
+ if create_parents:
48
+ self.makedirs(path, exist_ok=True)
49
+ else:
50
+ os.mkdir(path, **kwargs)
51
+
52
+ def makedirs(self, path, exist_ok=False):
53
+ path = self._strip_protocol(path)
54
+ os.makedirs(path, exist_ok=exist_ok)
55
+
56
+ def rmdir(self, path):
57
+ path = self._strip_protocol(path)
58
+ os.rmdir(path)
59
+
60
+ def ls(self, path, detail=False, **kwargs):
61
+ path = self._strip_protocol(path)
62
+ path_info = self.info(path)
63
+ infos = []
64
+ if path_info["type"] == "directory":
65
+ with os.scandir(path) as it:
66
+ for f in it:
67
+ try:
68
+ # Only get the info if requested since it is a bit expensive (the stat call inside)
69
+ # The strip_protocol is also used in info() and calls make_path_posix to always return posix paths
70
+ info = self.info(f) if detail else self._strip_protocol(f.path)
71
+ infos.append(info)
72
+ except FileNotFoundError:
73
+ pass
74
+ else:
75
+ infos = [path_info] if detail else [path_info["name"]]
76
+
77
+ return infos
78
+
79
+ def info(self, path, **kwargs):
80
+ if isinstance(path, os.DirEntry):
81
+ # scandir DirEntry
82
+ out = path.stat(follow_symlinks=False)
83
+ link = path.is_symlink()
84
+ if path.is_dir(follow_symlinks=False):
85
+ t = "directory"
86
+ elif path.is_file(follow_symlinks=False):
87
+ t = "file"
88
+ else:
89
+ t = "other"
90
+
91
+ size = out.st_size
92
+ if link:
93
+ try:
94
+ out2 = path.stat(follow_symlinks=True)
95
+ size = out2.st_size
96
+ except OSError:
97
+ size = 0
98
+ path = self._strip_protocol(path.path)
99
+ else:
100
+ # str or path-like
101
+ path = self._strip_protocol(path)
102
+ out = os.stat(path, follow_symlinks=False)
103
+ link = stat.S_ISLNK(out.st_mode)
104
+ if link:
105
+ out = os.stat(path, follow_symlinks=True)
106
+ size = out.st_size
107
+ if stat.S_ISDIR(out.st_mode):
108
+ t = "directory"
109
+ elif stat.S_ISREG(out.st_mode):
110
+ t = "file"
111
+ else:
112
+ t = "other"
113
+
114
+ # Check for the 'st_birthtime' attribute, which is not always present; fallback to st_ctime
115
+ created_time = getattr(out, "st_birthtime", out.st_ctime)
116
+
117
+ result = {
118
+ "name": path,
119
+ "size": size,
120
+ "type": t,
121
+ "created": created_time,
122
+ "islink": link,
123
+ }
124
+ for field in ["mode", "uid", "gid", "mtime", "ino", "nlink"]:
125
+ result[field] = getattr(out, f"st_{field}")
126
+ if link:
127
+ result["destination"] = os.readlink(path)
128
+ return result
129
+
130
+ def lexists(self, path, **kwargs):
131
+ return osp.lexists(path)
132
+
133
+ def cp_file(self, path1, path2, **kwargs):
134
+ path1 = self._strip_protocol(path1)
135
+ path2 = self._strip_protocol(path2)
136
+ if self.auto_mkdir:
137
+ self.makedirs(self._parent(path2), exist_ok=True)
138
+ if self.isfile(path1):
139
+ shutil.copyfile(path1, path2)
140
+ elif self.isdir(path1):
141
+ self.mkdirs(path2, exist_ok=True)
142
+ else:
143
+ raise FileNotFoundError(path1)
144
+
145
+ def isfile(self, path):
146
+ path = self._strip_protocol(path)
147
+ return os.path.isfile(path)
148
+
149
+ def isdir(self, path):
150
+ path = self._strip_protocol(path)
151
+ return os.path.isdir(path)
152
+
153
+ def get_file(self, path1, path2, callback=None, **kwargs):
154
+ if isfilelike(path2):
155
+ with open(path1, "rb") as f:
156
+ shutil.copyfileobj(f, path2)
157
+ else:
158
+ return self.cp_file(path1, path2, **kwargs)
159
+
160
+ def put_file(self, path1, path2, callback=None, **kwargs):
161
+ return self.cp_file(path1, path2, **kwargs)
162
+
163
+ def mv(self, path1, path2, recursive: bool = True, **kwargs):
164
+ """Move files/directories
165
+ For the specific case of local, all ops on directories are recursive and
166
+ the recursive= kwarg is ignored.
167
+ """
168
+ path1 = self._strip_protocol(path1)
169
+ path2 = self._strip_protocol(path2)
170
+
171
+ if self.auto_mkdir:
172
+ self.makedirs(self._parent(path2), exist_ok=True)
173
+
174
+ shutil.move(path1, path2)
175
+
176
+ def link(self, src, dst, **kwargs):
177
+ src = self._strip_protocol(src)
178
+ dst = self._strip_protocol(dst)
179
+ os.link(src, dst, **kwargs)
180
+
181
+ def symlink(self, src, dst, **kwargs):
182
+ src = self._strip_protocol(src)
183
+ dst = self._strip_protocol(dst)
184
+ os.symlink(src, dst, **kwargs)
185
+
186
+ def islink(self, path) -> bool:
187
+ return os.path.islink(self._strip_protocol(path))
188
+
189
+ def rm_file(self, path):
190
+ os.remove(self._strip_protocol(path))
191
+
192
+ def rm(self, path, recursive=False, maxdepth=None):
193
+ if not isinstance(path, list):
194
+ path = [path]
195
+
196
+ for p in path:
197
+ p = self._strip_protocol(p)
198
+ if self.isdir(p) and not self.islink(p):
199
+ if not recursive:
200
+ raise ValueError("Cannot delete directory, set recursive=True")
201
+ if osp.abspath(p) == os.getcwd():
202
+ raise ValueError("Cannot delete current working directory")
203
+ shutil.rmtree(p)
204
+ else:
205
+ os.remove(p)
206
+
207
+ def unstrip_protocol(self, name):
208
+ protocol = self.protocol if isinstance(self.protocol, str) else self.protocol[0]
209
+ name = self._strip_protocol(name) # normalise for local/win/...
210
+ return f"{protocol}://{name}"
211
+
212
+ def _open(self, path, mode="rb", block_size=None, **kwargs):
213
+ path = self._strip_protocol(path)
214
+ if self.auto_mkdir and ("w" in mode or "x" in mode or "a" in mode):
215
+ self.makedirs(self._parent(path), exist_ok=True)
216
+ return LocalFileOpener(path, mode, fs=self, **kwargs)
217
+
218
+ def touch(self, path, truncate=True, **kwargs):
219
+ path = self._strip_protocol(path)
220
+ if self.auto_mkdir:
221
+ self.makedirs(self._parent(path), exist_ok=True)
222
+ if self.exists(path):
223
+ os.utime(path, None)
224
+ else:
225
+ open(path, "a").close()
226
+ if truncate:
227
+ os.truncate(path, 0)
228
+
229
+ def created(self, path):
230
+ info = self.info(path=path)
231
+ return datetime.datetime.fromtimestamp(
232
+ info["created"], tz=datetime.timezone.utc
233
+ )
234
+
235
+ def modified(self, path):
236
+ info = self.info(path=path)
237
+ return datetime.datetime.fromtimestamp(info["mtime"], tz=datetime.timezone.utc)
238
+
239
+ @classmethod
240
+ def _parent(cls, path):
241
+ path = cls._strip_protocol(path)
242
+ if os.sep == "/":
243
+ # posix native
244
+ return path.rsplit("/", 1)[0] or "/"
245
+ else:
246
+ # NT
247
+ path_ = path.rsplit("/", 1)[0]
248
+ if len(path_) <= 3:
249
+ if path_[1:2] == ":":
250
+ # nt root (something like c:/)
251
+ return path_[0] + ":/"
252
+ # More cases may be required here
253
+ return path_
254
+
255
+ @classmethod
256
+ def _strip_protocol(cls, path):
257
+ path = stringify_path(path)
258
+ protos = (cls.protocol,) if isinstance(cls.protocol, str) else cls.protocol
259
+ prefixes = (protocol + sep for protocol in protos for sep in ("://", ":"))
260
+ for prefix in prefixes:
261
+ if path.startswith(prefix):
262
+ path = path.removeprefix(prefix)
263
+ break
264
+
265
+ path = make_path_posix(path)
266
+ if os.sep != "/":
267
+ # This code-path is a stripped down version of
268
+ # > drive, path = ntpath.splitdrive(path)
269
+ if path[1:2] == ":":
270
+ # Absolute drive-letter path, e.g. X:\Windows
271
+ # Relative path with drive, e.g. X:Windows
272
+ drive, path = path[:2], path[2:]
273
+ elif path[:2] == "//":
274
+ # UNC drives, e.g. \\server\share or \\?\UNC\server\share
275
+ # Device drives, e.g. \\.\device or \\?\device
276
+ if (index1 := path.find("/", 2)) == -1 or (
277
+ index2 := path.find("/", index1 + 1)
278
+ ) == -1:
279
+ drive, path = path, ""
280
+ else:
281
+ drive, path = path[:index2], path[index2:]
282
+ else:
283
+ # Relative path, e.g. Windows
284
+ drive = ""
285
+
286
+ path = path.rstrip("/") or cls.root_marker
287
+ return drive + path
288
+
289
+ else:
290
+ return path.rstrip("/") or cls.root_marker
291
+
292
+ def _isfilestore(self):
293
+ # Inheriting from DaskFileSystem makes this False (S3, etc. were)
294
+ # the original motivation. But we are a posix-like file system.
295
+ # See https://github.com/dask/dask/issues/5526
296
+ return True
297
+
298
+ def chmod(self, path, mode):
299
+ path = stringify_path(path)
300
+ return os.chmod(path, mode)
301
+
302
+
303
+ def make_path_posix(path):
304
+ """Make path generic and absolute for current OS"""
305
+ if not isinstance(path, str):
306
+ if isinstance(path, (list, set, tuple)):
307
+ return type(path)(make_path_posix(p) for p in path)
308
+ else:
309
+ path = stringify_path(path)
310
+ if not isinstance(path, str):
311
+ raise TypeError(f"could not convert {path!r} to string")
312
+ if os.sep == "/":
313
+ # Native posix
314
+ if path.startswith("/"):
315
+ # most common fast case for posix
316
+ return path
317
+ elif path.startswith("~"):
318
+ return osp.expanduser(path)
319
+ elif path.startswith("./"):
320
+ path = path[2:]
321
+ elif path == ".":
322
+ path = ""
323
+ return f"{os.getcwd()}/{path}"
324
+ else:
325
+ # NT handling
326
+ if path[0:1] == "/" and path[2:3] == ":":
327
+ # path is like "/c:/local/path"
328
+ path = path[1:]
329
+ if path[1:2] == ":":
330
+ # windows full path like "C:\\local\\path"
331
+ if len(path) == 2 or (len(path) == 3 and path[2] in "/\\"):
332
+ # nt root (something like c:/). A three-character "c:x" is not a
333
+ # root: it names "x" relative to that drive, so it falls through
334
+ # instead of being collapsed to the drive root.
335
+ return path[0] + ":/"
336
+ path = path.replace("\\", "/")
337
+ return path
338
+ elif path[0:1] == "~":
339
+ return make_path_posix(osp.expanduser(path))
340
+ elif path.startswith(("\\\\", "//")):
341
+ # windows UNC/DFS-style paths
342
+ return "//" + path[2:].replace("\\", "/")
343
+ elif path.startswith(("\\", "/")):
344
+ # windows relative path with root
345
+ path = path.replace("\\", "/")
346
+ return f"{osp.splitdrive(os.getcwd())[0]}{path}"
347
+ else:
348
+ path = path.replace("\\", "/")
349
+ if path.startswith("./"):
350
+ path = path[2:]
351
+ elif path == ".":
352
+ path = ""
353
+ return f"{make_path_posix(os.getcwd())}/{path}"
354
+
355
+
356
+ def trailing_sep(path):
357
+ """Return True if the path ends with a path separator.
358
+
359
+ A forward slash is always considered a path separator, even on Operating
360
+ Systems that normally use a backslash.
361
+ """
362
+ # TODO: if all incoming paths were posix-compliant then separator would
363
+ # always be a forward slash, simplifying this function.
364
+ # See https://github.com/fsspec/filesystem_spec/pull/1250
365
+ return path.endswith(os.sep) or (os.altsep is not None and path.endswith(os.altsep))
366
+
367
+
368
+ @lru_cache(maxsize=1)
369
+ def get_umask(mask: int = 0o666) -> int:
370
+ """Get the current umask.
371
+
372
+ Follows https://stackoverflow.com/a/44130549 to get the umask.
373
+ Temporarily sets the umask to the given value, and then resets it to the
374
+ original value.
375
+ """
376
+ value = os.umask(mask)
377
+ os.umask(value)
378
+ return value
379
+
380
+
381
+ class LocalFileOpener(io.IOBase):
382
+ def __init__(
383
+ self, path, mode, autocommit=True, fs=None, compression=None, **kwargs
384
+ ):
385
+ logger.debug("open file: %s", path)
386
+ self.path = path
387
+ self.mode = mode
388
+ self.fs = fs
389
+ self.f = None
390
+ self.autocommit = autocommit
391
+ self.compression = get_compression(path, compression)
392
+ self.blocksize = io.DEFAULT_BUFFER_SIZE
393
+ self._open()
394
+
395
+ def _open(self):
396
+ if self.f is None or self.f.closed:
397
+ if self.autocommit or "w" not in self.mode:
398
+ self.f = open(self.path, mode=self.mode)
399
+ if self.compression:
400
+ compress = compr[self.compression]
401
+ self.f = compress(self.f, mode=self.mode)
402
+ else:
403
+ # TODO: check if path is writable?
404
+ i, name = tempfile.mkstemp()
405
+ os.close(i) # we want normal open and normal buffered file
406
+ self.temp = name
407
+ self.f = open(name, mode=self.mode)
408
+ if "w" not in self.mode:
409
+ self.size = self.f.seek(0, 2)
410
+ self.f.seek(0)
411
+ self.f.size = self.size
412
+
413
+ def _fetch_range(self, start, end):
414
+ # probably only used by cached FS
415
+ if "r" not in self.mode:
416
+ raise ValueError
417
+ self._open()
418
+ self.f.seek(start)
419
+ return self.f.read(end - start)
420
+
421
+ def __setstate__(self, state):
422
+ self.f = None
423
+ loc = state.pop("loc", None)
424
+ self.__dict__.update(state)
425
+ if "r" in state["mode"]:
426
+ self.f = None
427
+ self._open()
428
+ self.f.seek(loc)
429
+
430
+ def __getstate__(self):
431
+ d = self.__dict__.copy()
432
+ d.pop("f")
433
+ if "r" in self.mode:
434
+ d["loc"] = self.f.tell()
435
+ else:
436
+ if not self.f.closed:
437
+ raise ValueError("Cannot serialise open write-mode local file")
438
+ return d
439
+
440
+ def commit(self):
441
+ if self.autocommit:
442
+ raise RuntimeError("Can only commit if not already set to autocommit")
443
+ if not self.f.closed:
444
+ # a compression wrapper (e.g., GzipFile) does not close the file
445
+ # object it was given, so buffered bytes and any trailer may still
446
+ # be pending here. Windows also refuses to rename an open file.
447
+ self.f.close()
448
+ try:
449
+ shutil.move(self.temp, self.path)
450
+ except PermissionError as e:
451
+ # shutil.move raises PermissionError if os.rename
452
+ # and the default copy2 fallback with shutil.copystats fail.
453
+ # The file should be there nonetheless, but without copied permissions.
454
+ # If it doesn't exist, there was no permission to create the file.
455
+ if not os.path.exists(self.path):
456
+ raise e
457
+ else:
458
+ # If PermissionError is not raised, permissions can be set.
459
+ try:
460
+ mask = 0o666
461
+ os.chmod(self.path, mask & ~get_umask(mask))
462
+ except RuntimeError:
463
+ pass
464
+
465
+ def discard(self):
466
+ if self.autocommit:
467
+ raise RuntimeError("Cannot discard if set to autocommit")
468
+ os.remove(self.temp)
469
+
470
+ def readable(self) -> bool:
471
+ return True
472
+
473
+ def writable(self) -> bool:
474
+ return "r" not in self.mode
475
+
476
+ def read(self, *args, **kwargs):
477
+ return self.f.read(*args, **kwargs)
478
+
479
+ def write(self, *args, **kwargs):
480
+ return self.f.write(*args, **kwargs)
481
+
482
+ def tell(self, *args, **kwargs):
483
+ return self.f.tell(*args, **kwargs)
484
+
485
+ def seek(self, *args, **kwargs):
486
+ return self.f.seek(*args, **kwargs)
487
+
488
+ def seekable(self, *args, **kwargs):
489
+ return self.f.seekable(*args, **kwargs)
490
+
491
+ def readline(self, *args, **kwargs):
492
+ return self.f.readline(*args, **kwargs)
493
+
494
+ def readlines(self, *args, **kwargs):
495
+ return self.f.readlines(*args, **kwargs)
496
+
497
+ def close(self):
498
+ return self.f.close()
499
+
500
+ def truncate(self, size=None) -> int:
501
+ return self.f.truncate(size)
502
+
503
+ @property
504
+ def closed(self):
505
+ return self.f.closed
506
+
507
+ def fileno(self):
508
+ return self.raw.fileno()
509
+
510
+ def flush(self) -> None:
511
+ self.f.flush()
512
+
513
+ def __iter__(self):
514
+ return self.f.__iter__()
515
+
516
+ def __getattr__(self, item):
517
+ return getattr(self.f, item)
518
+
519
+ def __enter__(self):
520
+ self._incontext = True
521
+ return self
522
+
523
+ def __exit__(self, exc_type, exc_value, traceback):
524
+ self._incontext = False
525
+ self.f.__exit__(exc_type, exc_value, traceback)
venv/lib/python3.14/site-packages/fsspec/implementations/memory.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
9
+
10
+ from fsspec import AbstractFileSystem
11
+ from fsspec.implementations.local import LocalFileSystem
12
+ from fsspec.utils import stringify_path, tokenize
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
+ By default, instances share a global in-memory filesystem. Pass
21
+ ``global_store=False, skip_instance_cache=True`` to create a new instance
22
+ with an independent store instead.
23
+ """
24
+
25
+ store: dict[str, Any] = {} # shared by default
26
+ pseudo_dirs = [""] # shared by default
27
+ protocol = "memory"
28
+ root_marker = "/"
29
+
30
+ def __init__(self, *args, global_store=True, **kwargs):
31
+ """Create a memory filesystem.
32
+
33
+ Parameters
34
+ ----------
35
+ global_store: bool
36
+ Share files and directories with other default instances. If False,
37
+ each instance starts with an empty, independent store. The normal
38
+ instance cache still applies; pass ``skip_instance_cache=True``
39
+ to create a new instance on every call. Pickling an
40
+ independent filesystem copies its files and directories; pickling a
41
+ global filesystem retains the reference to the global store.
42
+ """
43
+ super().__init__(*args, **kwargs)
44
+ self.global_store = global_store
45
+ if not global_store:
46
+ self.store = {}
47
+ self.pseudo_dirs = [""]
48
+
49
+ @property
50
+ def _fs_token(self):
51
+ if self.global_store:
52
+ return super()._fs_token
53
+ return tokenize(super()._fs_token, id(self))
54
+
55
+ def __reduce__(self):
56
+ reduced = super().__reduce__()
57
+ if self.global_store:
58
+ return reduced
59
+ factory, (cls, args, kwargs) = reduced
60
+ # Restore into a new instance even when the source is cached.
61
+ kwargs = {**kwargs, "skip_instance_cache": True}
62
+ # Pickle's memo preserves the cycle through each MemoryFile.fs.
63
+ return (
64
+ factory,
65
+ (cls, args, kwargs),
66
+ {"store": self.store, "pseudo_dirs": self.pseudo_dirs},
67
+ )
68
+
69
+ @classmethod
70
+ def _strip_protocol(cls, path):
71
+ if isinstance(path, PurePath):
72
+ if isinstance(path, PureWindowsPath):
73
+ return LocalFileSystem._strip_protocol(path)
74
+ else:
75
+ path = stringify_path(path)
76
+
77
+ path = path.removeprefix("memory://")
78
+ if "::" in path or "://" in path:
79
+ return path.rstrip("/")
80
+ path = path.lstrip("/").rstrip("/")
81
+ return "/" + path if path else ""
82
+
83
+ def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
84
+ # The base implementation calls ls() once per directory, and each ls()
85
+ # scans the whole store, giving O(n_dirs * n_entries) behaviour
86
+ # for a tree. Since the store is a flat mapping of every path, the same
87
+ # result can be produced with a single pass over it.
88
+ if maxdepth is not None and maxdepth < 1:
89
+ raise ValueError("maxdepth must be at least 1")
90
+ path = self._strip_protocol(path)
91
+ if path in self.store:
92
+ # path is itself a file
93
+ if not detail:
94
+ return [path]
95
+ filelike = self.store[path]
96
+ return {
97
+ path: {
98
+ "name": path,
99
+ "size": filelike.size,
100
+ "type": "file",
101
+ "created": filelike.created.timestamp(),
102
+ }
103
+ }
104
+
105
+ # Uniform prefix so that the search root "" (the filesystem root) and a
106
+ # nested path are handled the same way; rel depth is rel.count("/") + 1.
107
+ prefix = path + "/" if path else "/"
108
+ out = {}
109
+ dirs = {}
110
+
111
+ def add_ancestor_dirs(name):
112
+ # Register every directory implied between ``path`` and ``name`` that
113
+ # is within maxdepth, mirroring how walk() surfaces implied dirs.
114
+ idx = name.rfind("/")
115
+ while idx > len(path):
116
+ parent = name[:idx]
117
+ if parent in dirs:
118
+ break
119
+ rel = parent[len(prefix) :]
120
+ if maxdepth is None or rel.count("/") + 1 <= maxdepth:
121
+ dirs[parent] = {"name": parent, "size": 0, "type": "directory"}
122
+ idx = parent.rfind("/")
123
+
124
+ # `store` may be shared by multiple MemoryFileSystem instances, so iterate a
125
+ # snapshot: a concurrent create/delete would otherwise raise
126
+ # "dictionary changed size during iteration". ls() does the same.
127
+ for name, filelike in tuple(self.store.items()):
128
+ if not name.startswith(prefix):
129
+ continue
130
+ rel = name[len(prefix) :]
131
+ if withdirs:
132
+ add_ancestor_dirs(name)
133
+ if maxdepth is not None and rel.count("/") + 1 > maxdepth:
134
+ continue
135
+ out[name] = {
136
+ "name": name,
137
+ "size": filelike.size,
138
+ "type": "file",
139
+ "created": filelike.created.timestamp(),
140
+ }
141
+
142
+ if withdirs:
143
+ # Explicitly-created (possibly empty) directories live in pseudo_dirs.
144
+ for pdir in self.pseudo_dirs:
145
+ if pdir and pdir.startswith(prefix):
146
+ add_ancestor_dirs(pdir + "/")
147
+ out.update(dirs)
148
+ # Mirror the base find(): include the search root itself when it is
149
+ # a directory (needed for posix glob compliance).
150
+ if path != "" and self.isdir(path):
151
+ out[path] = self.info(path)
152
+
153
+ names = sorted(out)
154
+ return {name: out[name] for name in names} if detail else names
155
+
156
+ def ls(self, path, detail=True, **kwargs):
157
+ path = self._strip_protocol(path)
158
+ if path in self.store:
159
+ # there is a key with this exact name
160
+ if not detail:
161
+ return [path]
162
+ return [
163
+ {
164
+ "name": path,
165
+ "size": self.store[path].size,
166
+ "type": "file",
167
+ "created": self.store[path].created.timestamp(),
168
+ }
169
+ ]
170
+ paths = set()
171
+ starter = path + "/"
172
+ out = []
173
+ for p2 in tuple(self.store):
174
+ if p2.startswith(starter):
175
+ if "/" not in p2[len(starter) :]:
176
+ # exact child
177
+ out.append(
178
+ {
179
+ "name": p2,
180
+ "size": self.store[p2].size,
181
+ "type": "file",
182
+ "created": self.store[p2].created.timestamp(),
183
+ }
184
+ )
185
+ elif len(p2) > len(starter):
186
+ # implied child directory
187
+ ppath = starter + p2[len(starter) :].split("/", 1)[0]
188
+ if ppath not in paths:
189
+ out = out or []
190
+ out.append(
191
+ {
192
+ "name": ppath,
193
+ "size": 0,
194
+ "type": "directory",
195
+ }
196
+ )
197
+ paths.add(ppath)
198
+ for p2 in self.pseudo_dirs:
199
+ if p2.startswith(starter):
200
+ if "/" not in p2[len(starter) :]:
201
+ # exact child pdir
202
+ if p2 not in paths:
203
+ out.append({"name": p2, "size": 0, "type": "directory"})
204
+ paths.add(p2)
205
+ else:
206
+ # directory implied by deeper pdir
207
+ ppath = starter + p2[len(starter) :].split("/", 1)[0]
208
+ if ppath not in paths:
209
+ out.append({"name": ppath, "size": 0, "type": "directory"})
210
+ paths.add(ppath)
211
+ if not out:
212
+ if path in self.pseudo_dirs:
213
+ # empty dir
214
+ return []
215
+ raise FileNotFoundError(path)
216
+ if detail:
217
+ return out
218
+ return sorted([f["name"] for f in out])
219
+
220
+ def mkdir(self, path, create_parents=True, **kwargs):
221
+ path = self._strip_protocol(path)
222
+ if path in self.store or path in self.pseudo_dirs:
223
+ raise FileExistsError(path)
224
+ if self._parent(path).strip("/") and self.isfile(self._parent(path)):
225
+ raise NotADirectoryError(self._parent(path))
226
+ if create_parents and self._parent(path).strip("/"):
227
+ try:
228
+ self.mkdir(self._parent(path), create_parents, **kwargs)
229
+ except FileExistsError:
230
+ pass
231
+ if path and path not in self.pseudo_dirs:
232
+ self.pseudo_dirs.append(path)
233
+
234
+ def makedirs(self, path, exist_ok=False):
235
+ try:
236
+ self.mkdir(path, create_parents=True)
237
+ except FileExistsError:
238
+ if not exist_ok:
239
+ raise
240
+
241
+ def pipe_file(self, path, value, mode="overwrite", **kwargs):
242
+ """Set the bytes of given file
243
+
244
+ Avoids copies of the data if possible
245
+ """
246
+ mode = "xb" if mode == "create" else "wb"
247
+ self.open(path, mode=mode, data=value)
248
+
249
+ def rmdir(self, path):
250
+ path = self._strip_protocol(path)
251
+ if path == "":
252
+ # silently avoid deleting FS root
253
+ return
254
+ if path in self.pseudo_dirs:
255
+ if not self.ls(path):
256
+ self.pseudo_dirs.remove(path)
257
+ else:
258
+ raise OSError(ENOTEMPTY, "Directory not empty", path)
259
+ else:
260
+ raise FileNotFoundError(path)
261
+
262
+ def info(self, path, **kwargs):
263
+ logger.debug("info: %s", path)
264
+ path = self._strip_protocol(path)
265
+ if path in self.pseudo_dirs or any(
266
+ p.startswith(path + "/") for p in list(self.store) + self.pseudo_dirs
267
+ ):
268
+ return {
269
+ "name": path,
270
+ "size": 0,
271
+ "type": "directory",
272
+ }
273
+ elif path in self.store:
274
+ filelike = self.store[path]
275
+ return {
276
+ "name": path,
277
+ "size": filelike.size,
278
+ "type": "file",
279
+ "created": getattr(filelike, "created", None),
280
+ }
281
+ else:
282
+ raise FileNotFoundError(path)
283
+
284
+ def _open(
285
+ self,
286
+ path,
287
+ mode="rb",
288
+ block_size=None,
289
+ autocommit=True,
290
+ cache_options=None,
291
+ **kwargs,
292
+ ):
293
+ path = self._strip_protocol(path)
294
+ if "x" in mode and self.exists(path):
295
+ raise FileExistsError
296
+ if path in self.pseudo_dirs:
297
+ raise IsADirectoryError(path)
298
+ parent = path
299
+ while len(parent) > 1:
300
+ parent = self._parent(parent)
301
+ if self.isfile(parent):
302
+ raise FileExistsError(parent)
303
+ if mode in ["rb", "ab", "r+b", "a+b"]:
304
+ if path in self.store:
305
+ f = self.store[path]
306
+ if "a" in mode:
307
+ # position at the end of file
308
+ f.seek(0, 2)
309
+ else:
310
+ # position at the beginning of file
311
+ f.seek(0)
312
+ return f
313
+ elif "a" in mode:
314
+ # append modes create the file if it does not exist, matching
315
+ # builtin open() and LocalFileSystem
316
+ m = MemoryFile(self, path, kwargs.get("data"))
317
+ if not self._intrans:
318
+ m.commit()
319
+ # position at the end of file, like the existing-file path above
320
+ m.seek(0, 2)
321
+ return m
322
+ else:
323
+ raise FileNotFoundError(path)
324
+ elif mode in {"wb", "w+b", "xb", "x+b"}:
325
+ if "x" in mode and self.exists(path):
326
+ raise FileExistsError
327
+ m = MemoryFile(self, path, kwargs.get("data"))
328
+ if not self._intrans:
329
+ m.commit()
330
+ return m
331
+ else:
332
+ name = self.__class__.__name__
333
+ raise ValueError(f"unsupported file mode for {name}: {mode!r}")
334
+
335
+ def cp_file(self, path1, path2, **kwargs):
336
+ path1 = self._strip_protocol(path1)
337
+ path2 = self._strip_protocol(path2)
338
+ if self.isfile(path1):
339
+ self.store[path2] = MemoryFile(
340
+ self, path2, self.store[path1].getvalue()
341
+ ) # implicit copy
342
+ elif self.isdir(path1):
343
+ if path2 not in self.pseudo_dirs:
344
+ self.pseudo_dirs.append(path2)
345
+ else:
346
+ raise FileNotFoundError(path1)
347
+
348
+ def cat_file(self, path, start=None, end=None, **kwargs):
349
+ logger.debug("cat: %s", path)
350
+ path = self._strip_protocol(path)
351
+ try:
352
+ return bytes(self.store[path].getbuffer()[start:end])
353
+ except KeyError as e:
354
+ raise FileNotFoundError(path) from e
355
+
356
+ def _rm(self, path):
357
+ path = self._strip_protocol(path)
358
+ try:
359
+ del self.store[path]
360
+ except KeyError as e:
361
+ raise FileNotFoundError(path) from e
362
+
363
+ def modified(self, path):
364
+ path = self._strip_protocol(path)
365
+ try:
366
+ return self.store[path].modified
367
+ except KeyError as e:
368
+ raise FileNotFoundError(path) from e
369
+
370
+ def created(self, path):
371
+ path = self._strip_protocol(path)
372
+ try:
373
+ return self.store[path].created
374
+ except KeyError as e:
375
+ raise FileNotFoundError(path) from e
376
+
377
+ def isfile(self, path):
378
+ path = self._strip_protocol(path)
379
+ return path in self.store
380
+
381
+ def rm(self, path, recursive=False, maxdepth=None):
382
+ if isinstance(path, str):
383
+ path = self._strip_protocol(path)
384
+ else:
385
+ path = [self._strip_protocol(p) for p in path]
386
+ paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
387
+ # A non-recursive expand keeps a literal path whether or not it exists,
388
+ # so record what exists before anything is deleted.
389
+ existed = {p for p in paths if self.exists(p)}
390
+ for p in reversed(paths):
391
+ if self.isfile(p):
392
+ self.rm_file(p)
393
+ elif not self.exists(p):
394
+ # A directory that is not in self.pseudo_dirs only exists while it
395
+ # has files under it, so deleting those files earlier in this loop
396
+ # makes it vanish. That is expected; a path that never existed is
397
+ # not, and raises like rm_file and the other filesystems do.
398
+ if p not in existed:
399
+ raise FileNotFoundError(p)
400
+ continue
401
+ else:
402
+ self.rmdir(p)
403
+
404
+
405
+ class MemoryFile(BytesIO):
406
+ """A BytesIO which can't close and works as a context manager
407
+
408
+ Can initialise with data. Each path should only be active once at any moment.
409
+
410
+ No need to provide fs, path if auto-committing (default)
411
+ """
412
+
413
+ def __init__(self, fs=None, path=None, data=None):
414
+ logger.debug("open file %s", path)
415
+ self.fs = fs
416
+ self.path = path
417
+ self.created = datetime.now(tz=timezone.utc)
418
+ self.modified = datetime.now(tz=timezone.utc)
419
+ if data:
420
+ super().__init__(data)
421
+ self.seek(0)
422
+
423
+ @property
424
+ def size(self):
425
+ return self.getbuffer().nbytes
426
+
427
+ def __enter__(self):
428
+ return self
429
+
430
+ def close(self):
431
+ pass
432
+
433
+ def discard(self):
434
+ pass
435
+
436
+ def commit(self):
437
+ self.fs.store[self.path] = self
438
+ self.modified = datetime.now(tz=timezone.utc)
venv/lib/python3.14/site-packages/fsspec/implementations/reference.py ADDED
@@ -0,0 +1,1358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ check_contained,
27
+ isfilelike,
28
+ merge_offset_ranges,
29
+ other_paths,
30
+ )
31
+
32
+ logger = logging.getLogger("fsspec.reference")
33
+
34
+
35
+ class ReferenceNotReachable(RuntimeError):
36
+ def __init__(self, reference, target, *args):
37
+ super().__init__(*args)
38
+ self.reference = reference
39
+ self.target = target
40
+
41
+ def __str__(self):
42
+ return f'Reference "{self.reference}" failed to fetch target {self.target}'
43
+
44
+
45
+ def _first(d):
46
+ return next(iter(d.values()))
47
+
48
+
49
+ def _prot_in_references(path, references):
50
+ ref = references.get(path)
51
+ if isinstance(ref, (list, tuple)) and isinstance(ref[0], str):
52
+ return split_protocol(ref[0])[0] if ref[0] else ref[0]
53
+
54
+
55
+ def _protocol_groups(paths, references):
56
+ if isinstance(paths, str):
57
+ return {_prot_in_references(paths, references): [paths]}
58
+ out = {}
59
+ for path in paths:
60
+ protocol = _prot_in_references(path, references)
61
+ out.setdefault(protocol, []).append(path)
62
+ return out
63
+
64
+
65
+ class RefsValuesView(collections.abc.ValuesView):
66
+ def __iter__(self):
67
+ for val in self._mapping.zmetadata.values():
68
+ yield json.dumps(val).encode()
69
+ yield from self._mapping._items.values()
70
+ for field in self._mapping.listdir():
71
+ chunk_sizes = self._mapping._get_chunk_sizes(field)
72
+ if len(chunk_sizes) == 0:
73
+ yield self._mapping[field + "/0"]
74
+ continue
75
+ yield from self._mapping._generate_all_records(field)
76
+
77
+
78
+ class RefsItemsView(collections.abc.ItemsView):
79
+ def __iter__(self):
80
+ return zip(self._mapping.keys(), self._mapping.values())
81
+
82
+
83
+ def ravel_multi_index(idx, sizes):
84
+ val = 0
85
+ mult = 1
86
+ for i, s in zip(idx[::-1], sizes[::-1]):
87
+ val += i * mult
88
+ mult *= s
89
+ return val
90
+
91
+
92
+ class LazyReferenceMapper(collections.abc.MutableMapping):
93
+ """This interface can be used to read/write references from Parquet stores.
94
+ It is not intended for other types of references.
95
+ It can be used with Kerchunk's MultiZarrToZarr method to combine
96
+ references into a parquet store.
97
+ Examples of this use-case can be found here:
98
+ https://fsspec.github.io/kerchunk/advanced.html?highlight=parquet#parquet-storage"""
99
+
100
+ # import is class level to prevent numpy dep requirement for fsspec
101
+ @property
102
+ def np(self):
103
+ import numpy as np
104
+
105
+ return np
106
+
107
+ @property
108
+ def pd(self):
109
+ import pandas as pd
110
+
111
+ return pd
112
+
113
+ def __init__(
114
+ self,
115
+ root,
116
+ fs=None,
117
+ out_root=None,
118
+ cache_size=128,
119
+ categorical_threshold=10,
120
+ engine: Literal["fastparquet", "pyarrow"] = "fastparquet",
121
+ ):
122
+ """
123
+
124
+ This instance will be writable, storing changes in memory until full partitions
125
+ are accumulated or .flush() is called.
126
+
127
+ To create an empty lazy store, use .create()
128
+
129
+ Parameters
130
+ ----------
131
+ root : str
132
+ Root of parquet store
133
+ fs : fsspec.AbstractFileSystem
134
+ fsspec filesystem object, default is local filesystem.
135
+ cache_size : int, default=128
136
+ Maximum size of LRU cache, where cache_size*record_size denotes
137
+ the total number of references that can be loaded in memory at once.
138
+ categorical_threshold : int
139
+ Encode urls as pandas.Categorical to reduce memory footprint if the ratio
140
+ of the number of unique urls to total number of refs for each variable
141
+ is greater than or equal to this number. (default 10)
142
+ engine: Literal["fastparquet","pyarrow"]
143
+ Engine choice for reading parquet files. (default is "fastparquet")
144
+ """
145
+
146
+ self.root = root
147
+ self.chunk_sizes = {}
148
+ self.cat_thresh = categorical_threshold
149
+ self.engine = engine
150
+ self.cache_size = cache_size
151
+ self.url = self.root + "/{field}/refs.{record}.parq"
152
+ # TODO: derive fs from `root`
153
+ self.fs = fsspec.filesystem("file") if fs is None else fs
154
+ self.out_root = self.fs.unstrip_protocol(out_root or self.root)
155
+
156
+ from importlib.util import find_spec
157
+
158
+ if self.engine == "pyarrow" and find_spec("pyarrow") is None:
159
+ raise ImportError("engine choice `pyarrow` is not installed.")
160
+
161
+ # Apply `lru_cache` decorator manually per instance.
162
+ # This way `self` reference is not held on class level.
163
+ # WARNING: However, this means that self and its members are not reflected
164
+ # in the cache key, so we expect they won't be mutated once a value is cached.
165
+ self.listdir = lru_cache()(self.listdir)
166
+ self._key_to_record = lru_cache(maxsize=4096)(self._key_to_record)
167
+
168
+ def __getattr__(self, item):
169
+ if item in ("_items", "record_size", "zmetadata"):
170
+ self.setup()
171
+ # avoid possible recursion if setup fails somehow
172
+ return self.__dict__[item]
173
+ raise AttributeError(item)
174
+
175
+ def setup(self):
176
+ self._items = {}
177
+ self._items[".zmetadata"] = self.fs.cat_file(
178
+ "/".join([self.root, ".zmetadata"])
179
+ )
180
+ met = json.loads(self._items[".zmetadata"])
181
+ self.record_size = met["record_size"]
182
+ self.zmetadata = met["metadata"]
183
+
184
+ # Define function to open and decompress refs
185
+ @lru_cache(maxsize=self.cache_size)
186
+ def open_refs(field, record):
187
+ """cached parquet file loader"""
188
+ path = self.url.format(field=field, record=record)
189
+ data = io.BytesIO(self.fs.cat_file(path))
190
+ try:
191
+ df = self.pd.read_parquet(data, engine=self.engine)
192
+ refs = {c: df[c].to_numpy(copy=True) for c in df.columns}
193
+ except OSError:
194
+ refs = None
195
+ return refs
196
+
197
+ self.open_refs = open_refs
198
+
199
+ @staticmethod
200
+ def create(root, storage_options=None, fs=None, record_size=10000, **kwargs):
201
+ """Make empty parquet reference set
202
+
203
+ First deletes the contents of the given directory, if it exists.
204
+
205
+ Parameters
206
+ ----------
207
+ root: str
208
+ Directory to contain the output; will be created
209
+ storage_options: dict | None
210
+ For making the filesystem to use for writing is fs is None
211
+ fs: FileSystem | None
212
+ Filesystem for writing
213
+ record_size: int
214
+ Number of references per parquet file
215
+ kwargs: passed to __init__
216
+
217
+ Returns
218
+ -------
219
+ LazyReferenceMapper instance
220
+ """
221
+ met = {"metadata": {}, "record_size": record_size}
222
+ if fs is None:
223
+ fs, root = fsspec.core.url_to_fs(root, **(storage_options or {}))
224
+ if fs.exists(root):
225
+ fs.rm(root, recursive=True)
226
+ fs.makedirs(root, exist_ok=True)
227
+ fs.pipe("/".join([root, ".zmetadata"]), json.dumps(met).encode())
228
+ return LazyReferenceMapper(root, fs, **kwargs)
229
+
230
+ def listdir(self):
231
+ """List top-level directories"""
232
+ dirs = (p.rsplit("/", 1)[0] for p in self.zmetadata if not p.startswith(".z"))
233
+ return set(dirs)
234
+
235
+ def ls(self, path="", detail=True):
236
+ """Shortcut file listings"""
237
+ path = path.rstrip("/")
238
+ pathdash = path + "/" if path else ""
239
+ dirnames = self.listdir()
240
+ dirs = [
241
+ d
242
+ for d in dirnames
243
+ if d.startswith(pathdash) and "/" not in d.lstrip(pathdash)
244
+ ]
245
+ if dirs:
246
+ others = {
247
+ f
248
+ for f in chain(
249
+ [".zmetadata"],
250
+ (name for name in self.zmetadata),
251
+ (name for name in self._items),
252
+ )
253
+ if f.startswith(pathdash) and "/" not in f.lstrip(pathdash)
254
+ }
255
+ if detail is False:
256
+ others.update(dirs)
257
+ return sorted(others)
258
+ dirinfo = [{"name": name, "type": "directory", "size": 0} for name in dirs]
259
+ fileinfo = [
260
+ {
261
+ "name": name,
262
+ "type": "file",
263
+ "size": len(
264
+ json.dumps(self.zmetadata[name])
265
+ if name in self.zmetadata
266
+ else self._items[name]
267
+ ),
268
+ }
269
+ for name in others
270
+ ]
271
+ return sorted(dirinfo + fileinfo, key=lambda s: s["name"])
272
+ field = path
273
+ others = set(
274
+ [name for name in self.zmetadata if name.startswith(f"{path}/")]
275
+ + [name for name in self._items if name.startswith(f"{path}/")]
276
+ )
277
+ fileinfo = [
278
+ {
279
+ "name": name,
280
+ "type": "file",
281
+ "size": len(
282
+ json.dumps(self.zmetadata[name])
283
+ if name in self.zmetadata
284
+ else self._items[name]
285
+ ),
286
+ }
287
+ for name in others
288
+ ]
289
+ keys = self._keys_in_field(field)
290
+
291
+ if detail is False:
292
+ return list(others) + list(keys)
293
+ recs = self._generate_all_records(field)
294
+ recinfo = [
295
+ {"name": name, "type": "file", "size": rec[-1]}
296
+ for name, rec in zip(keys, recs)
297
+ if rec[0] # filters out path==None, deleted/missing
298
+ ]
299
+ return fileinfo + recinfo
300
+
301
+ def _load_one_key(self, key):
302
+ """Get the reference for one key
303
+
304
+ Returns bytes, one-element list or three-element list.
305
+ """
306
+ if key in self._items:
307
+ return self._items[key]
308
+ elif key in self.zmetadata:
309
+ return json.dumps(self.zmetadata[key]).encode()
310
+ elif "/" not in key or self._is_meta(key):
311
+ raise KeyError(key)
312
+ field, _ = key.rsplit("/", 1)
313
+ record, ri, chunk_size = self._key_to_record(key)
314
+ maybe = self._items.get((field, record), {}).get(ri, False)
315
+ if maybe is None:
316
+ # explicitly deleted
317
+ raise KeyError
318
+ elif maybe:
319
+ return maybe
320
+ elif chunk_size == 0:
321
+ return b""
322
+
323
+ # Chunk keys can be loaded from row group and cached in LRU cache
324
+ try:
325
+ refs = self.open_refs(field, record)
326
+ except (ValueError, TypeError, FileNotFoundError) as exc:
327
+ raise KeyError(key) from exc
328
+ columns = ["path", "offset", "size", "raw"]
329
+ selection = [refs[c][ri] if c in refs else None for c in columns]
330
+ raw = selection[-1]
331
+ if raw is not None:
332
+ return raw
333
+ if selection[0] is None:
334
+ raise KeyError("This reference does not exist or has been deleted")
335
+ if selection[1:3] == [0, 0]:
336
+ # URL only
337
+ return selection[:1]
338
+ # URL, offset, size
339
+ return selection[:3]
340
+
341
+ def _key_to_record(self, key):
342
+ """Details needed to construct a reference for one key"""
343
+ field, chunk = key.rsplit("/", 1)
344
+ chunk_sizes = self._get_chunk_sizes(field)
345
+ if len(chunk_sizes) == 0:
346
+ return 0, 0, 0
347
+ chunk_idx = [int(c) for c in chunk.split(".")]
348
+ chunk_number = ravel_multi_index(chunk_idx, chunk_sizes)
349
+ record = chunk_number // self.record_size
350
+ ri = chunk_number % self.record_size
351
+ return record, ri, len(chunk_sizes)
352
+
353
+ def _get_chunk_sizes(self, field):
354
+ """The number of chunks along each axis for a given field"""
355
+ if field not in self.chunk_sizes:
356
+ zarray = self.zmetadata[f"{field}/.zarray"]
357
+ size_ratio = [
358
+ math.ceil(s / c) for s, c in zip(zarray["shape"], zarray["chunks"])
359
+ ]
360
+ self.chunk_sizes[field] = size_ratio or [1]
361
+ return self.chunk_sizes[field]
362
+
363
+ def _generate_record(self, field, record):
364
+ """The references for a given parquet file of a given field"""
365
+ refs = self.open_refs(field, record)
366
+ it = iter(zip(*refs.values()))
367
+ if len(refs) == 3:
368
+ # All urls
369
+ return (list(t) for t in it)
370
+ elif len(refs) == 1:
371
+ # All raws
372
+ return refs["raw"]
373
+ else:
374
+ # Mix of urls and raws
375
+ return (list(t[:3]) if not t[3] else t[3] for t in it)
376
+
377
+ def _generate_all_records(self, field):
378
+ """Load all the references within a field by iterating over the parquet files"""
379
+ nrec = 1
380
+ for ch in self._get_chunk_sizes(field):
381
+ nrec *= ch
382
+ nrec = math.ceil(nrec / self.record_size)
383
+ for record in range(nrec):
384
+ yield from self._generate_record(field, record)
385
+
386
+ def values(self):
387
+ return RefsValuesView(self)
388
+
389
+ def items(self):
390
+ return RefsItemsView(self)
391
+
392
+ def __hash__(self):
393
+ return id(self)
394
+
395
+ def __getitem__(self, key):
396
+ return self._load_one_key(key)
397
+
398
+ def __setitem__(self, key, value):
399
+ if "/" in key and not self._is_meta(key):
400
+ field, chunk = key.rsplit("/", 1)
401
+ record, i, _ = self._key_to_record(key)
402
+ subdict = self._items.setdefault((field, record), {})
403
+ subdict[i] = value
404
+ if len(subdict) == self.record_size:
405
+ self.write(field, record)
406
+ else:
407
+ # metadata or top-level
408
+ if hasattr(value, "to_bytes"):
409
+ val = value.to_bytes().decode()
410
+ elif isinstance(value, bytes):
411
+ val = value.decode()
412
+ else:
413
+ val = value
414
+ self._items[key] = val
415
+ new_value = json.loads(val)
416
+ self.zmetadata[key] = {**self.zmetadata.get(key, {}), **new_value}
417
+
418
+ @staticmethod
419
+ def _is_meta(key):
420
+ return key.startswith(".z") or "/.z" in key
421
+
422
+ def __delitem__(self, key):
423
+ if key in self._items:
424
+ del self._items[key]
425
+ elif key in self.zmetadata:
426
+ del self.zmetadata[key]
427
+ else:
428
+ if "/" in key and not self._is_meta(key):
429
+ field, _ = key.rsplit("/", 1)
430
+ record, i, _ = self._key_to_record(key)
431
+ subdict = self._items.setdefault((field, record), {})
432
+ subdict[i] = None
433
+ if len(subdict) == self.record_size:
434
+ self.write(field, record)
435
+ else:
436
+ # metadata or top-level
437
+ self._items[key] = None
438
+
439
+ def write(self, field, record, base_url=None, storage_options=None):
440
+ # extra requirements if writing
441
+ import kerchunk.df
442
+ import numpy as np
443
+ import pandas as pd
444
+
445
+ partition = self._items[(field, record)]
446
+ original = False
447
+ if len(partition) < self.record_size:
448
+ try:
449
+ original = self.open_refs(field, record)
450
+ except OSError:
451
+ pass
452
+
453
+ if original:
454
+ paths = original["path"]
455
+ offsets = original["offset"]
456
+ sizes = original["size"]
457
+ raws = original["raw"]
458
+ else:
459
+ paths = np.full(self.record_size, np.nan, dtype="O")
460
+ offsets = np.zeros(self.record_size, dtype="int64")
461
+ sizes = np.zeros(self.record_size, dtype="int64")
462
+ raws = np.full(self.record_size, np.nan, dtype="O")
463
+ for j, data in partition.items():
464
+ if isinstance(data, list):
465
+ if (
466
+ str(paths.dtype) == "category"
467
+ and data[0] not in paths.dtype.categories
468
+ ):
469
+ paths = paths.add_categories(data[0])
470
+ paths[j] = data[0]
471
+ if len(data) > 1:
472
+ offsets[j] = data[1]
473
+ sizes[j] = data[2]
474
+ elif data is None:
475
+ # delete
476
+ paths[j] = None
477
+ offsets[j] = 0
478
+ sizes[j] = 0
479
+ raws[j] = None
480
+ else:
481
+ # this is the only call into kerchunk, could remove
482
+ raws[j] = kerchunk.df._proc_raw(data)
483
+ # TODO: only save needed columns
484
+ df = pd.DataFrame(
485
+ {
486
+ "path": paths,
487
+ "offset": offsets,
488
+ "size": sizes,
489
+ "raw": raws,
490
+ },
491
+ copy=False,
492
+ )
493
+ if df.path.count() / (df.path.nunique() or 1) > self.cat_thresh:
494
+ df["path"] = df["path"].astype("category")
495
+ object_encoding = {"raw": "bytes", "path": "utf8"}
496
+ has_nulls = ["path", "raw"]
497
+
498
+ fn = f"{base_url or self.out_root}/{field}/refs.{record}.parq"
499
+ self.fs.mkdirs(f"{base_url or self.out_root}/{field}", exist_ok=True)
500
+
501
+ if self.engine == "pyarrow":
502
+ df_backend_kwargs = {"write_statistics": False}
503
+ elif self.engine == "fastparquet":
504
+ df_backend_kwargs = {
505
+ "stats": False,
506
+ "object_encoding": object_encoding,
507
+ "has_nulls": has_nulls,
508
+ }
509
+ else:
510
+ raise NotImplementedError(f"{self.engine} not supported")
511
+ df.to_parquet(
512
+ fn,
513
+ engine=self.engine,
514
+ storage_options=storage_options
515
+ or getattr(self.fs, "storage_options", None),
516
+ compression="zstd",
517
+ index=False,
518
+ **df_backend_kwargs,
519
+ )
520
+
521
+ partition.clear()
522
+ self._items.pop((field, record))
523
+
524
+ def flush(self, base_url=None, storage_options=None):
525
+ """Output any modified or deleted keys
526
+
527
+ Parameters
528
+ ----------
529
+ base_url: str
530
+ Location of the output
531
+ """
532
+
533
+ # write what we have so far and clear sub chunks
534
+ for thing in list(self._items):
535
+ if isinstance(thing, tuple):
536
+ field, record = thing
537
+ self.write(
538
+ field,
539
+ record,
540
+ base_url=base_url,
541
+ storage_options=storage_options,
542
+ )
543
+
544
+ # gather .zmetadata from self._items and write that too
545
+ for k in list(self._items):
546
+ if k != ".zmetadata" and ".z" in k:
547
+ self.zmetadata[k] = json.loads(self._items.pop(k))
548
+ met = {"metadata": self.zmetadata, "record_size": self.record_size}
549
+ self._items.clear()
550
+ self._items[".zmetadata"] = json.dumps(met).encode()
551
+ self.fs.pipe(
552
+ "/".join([base_url or self.out_root, ".zmetadata"]),
553
+ self._items[".zmetadata"],
554
+ )
555
+
556
+ # TODO: only clear those that we wrote to?
557
+ self.open_refs.cache_clear()
558
+
559
+ def __len__(self):
560
+ # Caveat: This counts expected references, not actual - but is fast
561
+ count = 0
562
+ for field in self.listdir():
563
+ if field.startswith("."):
564
+ count += 1
565
+ else:
566
+ count += math.prod(self._get_chunk_sizes(field))
567
+ count += len(self.zmetadata) # all metadata keys
568
+ # any other files not in reference partitions
569
+ count += sum(1 for _ in self._items if not isinstance(_, tuple))
570
+ return count
571
+
572
+ def __iter__(self):
573
+ # Caveat: returns only existing keys, so the number of these does not
574
+ # match len(self)
575
+ metas = set(self.zmetadata)
576
+ metas.update(self._items)
577
+ for bit in metas:
578
+ if isinstance(bit, str):
579
+ yield bit
580
+ for field in self.listdir():
581
+ for k in self._keys_in_field(field):
582
+ if k in self:
583
+ yield k
584
+
585
+ def __contains__(self, item):
586
+ try:
587
+ self._load_one_key(item)
588
+ return True
589
+ except KeyError:
590
+ return False
591
+
592
+ def _keys_in_field(self, field):
593
+ """List key names in given field
594
+
595
+ Produces strings like "field/x.y" appropriate from the chunking of the array
596
+ """
597
+ chunk_sizes = self._get_chunk_sizes(field)
598
+ if len(chunk_sizes) == 0:
599
+ yield field + "/0"
600
+ return
601
+ inds = itertools.product(*(range(i) for i in chunk_sizes))
602
+ for ind in inds:
603
+ yield field + "/" + ".".join([str(c) for c in ind])
604
+
605
+
606
+ class ReferenceFileSystem(AsyncFileSystem):
607
+ """View byte ranges of some other file as a file system
608
+ Initial version: single file system target, which must support
609
+ async, and must allow start and end args in _cat_file. Later versions
610
+ may allow multiple arbitrary URLs for the targets.
611
+ This FileSystem is read-only. It is designed to be used with async
612
+ targets (for now). We do not get original file details from the target FS.
613
+ Configuration is by passing a dict of references at init, or a URL to
614
+ a JSON file containing the same; this dict
615
+ can also contain concrete data for some set of paths.
616
+ Reference dict format:
617
+ {path0: bytes_data, path1: (target_url, offset, size)}
618
+ https://github.com/fsspec/kerchunk/blob/main/README.md
619
+
620
+ simple_references: if True (default), no jinja interpreting is done,
621
+ which is the safe option.
622
+ """
623
+
624
+ protocol = "reference"
625
+ cachable = False
626
+
627
+ def __init__(
628
+ self,
629
+ fo,
630
+ target=None,
631
+ ref_storage_args=None,
632
+ target_protocol=None,
633
+ target_options=None,
634
+ remote_protocol=None,
635
+ remote_options=None,
636
+ fs=None,
637
+ template_overrides=None,
638
+ simple_templates=True,
639
+ max_gap=64_000,
640
+ max_block=256_000_000,
641
+ cache_size=128,
642
+ **kwargs,
643
+ ):
644
+ """
645
+ Parameters
646
+ ----------
647
+ fo : dict or str
648
+ The set of references to use for this instance, with a structure as above.
649
+ If str referencing a JSON file, will use fsspec.open, in conjunction
650
+ with target_options and target_protocol to open and parse JSON at this
651
+ location. If a directory, then assume references are a set of parquet
652
+ files to be loaded lazily.
653
+ target : str
654
+ For any references having target_url as None, this is the default file
655
+ target to use
656
+ ref_storage_args : dict
657
+ If references is a str, use these kwargs for loading the JSON file.
658
+ Deprecated: use target_options instead.
659
+ target_protocol : str
660
+ Used for loading the reference file, if it is a path. If None, protocol
661
+ will be derived from the given path
662
+ target_options : dict
663
+ Extra FS options for loading the reference file ``fo``, if given as a path
664
+ remote_protocol : str
665
+ The protocol of the filesystem on which the references will be evaluated
666
+ (unless fs is provided). If not given, will be derived from the first
667
+ URL that has a protocol in the templates or in the references, in that
668
+ order.
669
+ remote_options : dict
670
+ kwargs to go with remote_protocol
671
+ fs : AbstractFileSystem | dict(str, (AbstractFileSystem | dict))
672
+ Directly provide a file system(s):
673
+ - a single filesystem instance
674
+ - a dict of protocol:filesystem, where each value is either a filesystem
675
+ instance, or a dict of kwargs that can be used to create in
676
+ instance for the given protocol
677
+
678
+ If this is given, remote_options and remote_protocol are ignored.
679
+ template_overrides : dict
680
+ Swap out any templates in the references file with these - useful for
681
+ testing.
682
+ simple_templates: bool
683
+ Whether templates can be processed with simple replace (True) or if
684
+ jinja is needed (False, much slower). All reference sets produced by
685
+ ``kerchunk`` are simple in this sense, but the spec allows for complex.
686
+ max_gap, max_block: int
687
+ For merging multiple concurrent requests to the same remote file.
688
+ Neighboring byte ranges will only be merged when their
689
+ inter-range gap is <= ``max_gap``. Default is 64KB. Set to 0
690
+ to only merge when it requires no extra bytes. Pass a negative
691
+ number to disable merging, appropriate for local target files.
692
+ Neighboring byte ranges will only be merged when the size of
693
+ the aggregated range is <= ``max_block``. Default is 256MB.
694
+ cache_size : int
695
+ Maximum size of LRU cache, where cache_size*record_size denotes
696
+ the total number of references that can be loaded in memory at once.
697
+ Only used for lazily loaded references.
698
+ kwargs : passed to parent class
699
+ """
700
+ super().__init__(**kwargs)
701
+ self.target = target
702
+ self.template_overrides = template_overrides
703
+ self.simple_templates = simple_templates
704
+ self.templates = {}
705
+ self.fss = {}
706
+ self._dircache = {}
707
+ self.max_gap = max_gap
708
+ self.max_block = max_block
709
+ if isinstance(fo, str):
710
+ dic = dict(
711
+ **(ref_storage_args or target_options or {}), protocol=target_protocol
712
+ )
713
+ ref_fs, fo2 = fsspec.core.url_to_fs(fo, **dic)
714
+ if ".json" not in fo2 and (
715
+ fo.endswith(("parq", "parquet", "/")) or ref_fs.isdir(fo2)
716
+ ):
717
+ # Lazy parquet refs
718
+ logger.info("Open lazy reference dict from URL %s", fo)
719
+ self.references = LazyReferenceMapper(
720
+ fo2,
721
+ fs=ref_fs,
722
+ cache_size=cache_size,
723
+ )
724
+ else:
725
+ # text JSON
726
+ with fsspec.open(fo, "rb", **dic) as f:
727
+ logger.info("Read reference from URL %s", fo)
728
+ text = json.load(f)
729
+ self._process_references(text, template_overrides)
730
+ else:
731
+ # dictionaries
732
+ self._process_references(fo, template_overrides)
733
+ if isinstance(fs, dict):
734
+ self.fss = {
735
+ k: (
736
+ fsspec.filesystem(k.split(":", 1)[0], **opts)
737
+ if isinstance(opts, dict)
738
+ else opts
739
+ )
740
+ for k, opts in fs.items()
741
+ }
742
+ if None not in self.fss:
743
+ self.fss[None] = filesystem("file")
744
+ return
745
+ if fs is not None:
746
+ # single remote FS
747
+ remote_protocol = (
748
+ fs.protocol[0] if isinstance(fs.protocol, tuple) else fs.protocol
749
+ )
750
+ self.fss[remote_protocol] = fs
751
+
752
+ if remote_protocol is None:
753
+ # get single protocol from any templates
754
+ for ref in self.templates.values():
755
+ if callable(ref):
756
+ ref = ref()
757
+ protocol, _ = fsspec.core.split_protocol(ref)
758
+ if protocol and protocol not in self.fss:
759
+ fs = filesystem(protocol, **(remote_options or {}))
760
+ self.fss[protocol] = fs
761
+ if remote_protocol is None:
762
+ # get single protocol from references
763
+ # TODO: warning here, since this can be very expensive?
764
+ for ref in self.references.values():
765
+ if callable(ref):
766
+ ref = ref()
767
+ if isinstance(ref, list) and ref[0]:
768
+ protocol, _ = fsspec.core.split_protocol(ref[0])
769
+ if protocol not in self.fss:
770
+ fs = filesystem(protocol, **(remote_options or {}))
771
+ self.fss[protocol] = fs
772
+ # only use first remote URL
773
+ break
774
+
775
+ if remote_protocol and remote_protocol not in self.fss:
776
+ fs = filesystem(remote_protocol, **(remote_options or {}))
777
+ self.fss[remote_protocol] = fs
778
+
779
+ self.fss[None] = fs or filesystem("file") # default one
780
+ # Wrap any non-async filesystems to ensure async methods are available below
781
+ for k, f in self.fss.items():
782
+ if not f.async_impl:
783
+ self.fss[k] = AsyncFileSystemWrapper(f, asynchronous=self.asynchronous)
784
+ elif self.asynchronous ^ f.asynchronous:
785
+ raise ValueError(
786
+ "Reference-FS's target filesystem must have same value "
787
+ "of asynchronous"
788
+ )
789
+
790
+ def _cat_common(self, path, start=None, end=None):
791
+ path = self._strip_protocol(path)
792
+ logger.debug(f"cat: {path}")
793
+ try:
794
+ part = self.references[path]
795
+ except KeyError as exc:
796
+ raise FileNotFoundError(path) from exc
797
+ if isinstance(part, str):
798
+ part = part.encode()
799
+ if hasattr(part, "to_bytes"):
800
+ part = part.to_bytes()
801
+ if isinstance(part, bytes):
802
+ logger.debug(f"Reference: {path}, type bytes")
803
+ if part.startswith(b"base64:"):
804
+ part = base64.b64decode(part[7:])
805
+ return part, None, None
806
+
807
+ if len(part) == 1:
808
+ logger.debug(f"Reference: {path}, whole file => {part}")
809
+ url = part[0]
810
+ start1, end1 = start, end
811
+ else:
812
+ url, start0, size = part
813
+ logger.debug(f"Reference: {path} => {url}, offset {start0}, size {size}")
814
+ end0 = start0 + size
815
+
816
+ # Resolve offsets like slicing the part, so they never reach target
817
+ # bytes outside the referenced range.
818
+ if start is not None:
819
+ if start >= 0:
820
+ start1 = min(start0 + start, end0)
821
+ else:
822
+ start1 = max(end0 + start, start0)
823
+ else:
824
+ start1 = start0
825
+ if end is not None:
826
+ if end >= 0:
827
+ end1 = min(start0 + end, end0)
828
+ else:
829
+ end1 = max(end0 + end, start0)
830
+ else:
831
+ end1 = end0
832
+ if url is None:
833
+ url = self.target
834
+ return url, start1, end1
835
+
836
+ async def _cat_file(self, path, start=None, end=None, **kwargs):
837
+ part_or_url, start0, end0 = self._cat_common(path, start=start, end=end)
838
+ if isinstance(part_or_url, bytes):
839
+ return part_or_url[start:end]
840
+ protocol, _ = split_protocol(part_or_url)
841
+ try:
842
+ return await self.fss[protocol]._cat_file(
843
+ part_or_url, start=start0, end=end0
844
+ )
845
+ except Exception as e:
846
+ raise ReferenceNotReachable(path, part_or_url) from e
847
+
848
+ def cat_file(self, path, start=None, end=None, **kwargs):
849
+ part_or_url, start0, end0 = self._cat_common(path, start=start, end=end)
850
+ if isinstance(part_or_url, bytes):
851
+ return part_or_url[start:end]
852
+ protocol, _ = split_protocol(part_or_url)
853
+ try:
854
+ return self.fss[protocol].cat_file(part_or_url, start=start0, end=end0)
855
+ except Exception as e:
856
+ raise ReferenceNotReachable(path, part_or_url) from e
857
+
858
+ def pipe_file(self, path, value, **_):
859
+ """Temporarily add binary data or reference as a file"""
860
+ self.references[path] = value
861
+
862
+ async def _get_file(self, rpath, lpath, **kwargs):
863
+ if self.isdir(rpath):
864
+ return os.makedirs(lpath, exist_ok=True)
865
+ data = await self._cat_file(rpath)
866
+ with open(lpath, "wb") as f:
867
+ f.write(data)
868
+
869
+ def get_file(self, rpath, lpath, callback=DEFAULT_CALLBACK, **kwargs):
870
+ if self.isdir(rpath):
871
+ return os.makedirs(lpath, exist_ok=True)
872
+ data = self.cat_file(rpath, **kwargs)
873
+ callback.set_size(len(data))
874
+ if isfilelike(lpath):
875
+ lpath.write(data)
876
+ else:
877
+ with open(lpath, "wb") as f:
878
+ f.write(data)
879
+ callback.absolute_update(len(data))
880
+
881
+ def get(self, rpath, lpath, recursive=False, **kwargs):
882
+ if recursive:
883
+ # trigger directory build
884
+ self.ls("")
885
+ rpath = self.expand_path(rpath, recursive=recursive)
886
+ fs = fsspec.filesystem("file", auto_mkdir=True)
887
+ targets = other_paths(rpath, lpath)
888
+ if isinstance(lpath, str):
889
+ # The names came from the source listing; ".." in one of them
890
+ # would otherwise place the copy above the destination. When
891
+ # lpath is a list the caller named every destination itself.
892
+ check_contained(lpath, targets)
893
+ if recursive:
894
+ data = self.cat([r for r in rpath if not self.isdir(r)])
895
+ else:
896
+ data = self.cat(rpath)
897
+ for remote, local in zip(rpath, targets):
898
+ if remote in data:
899
+ fs.pipe_file(local, data[remote])
900
+
901
+ def cat(self, path, recursive=False, on_error="raise", **kwargs):
902
+ if isinstance(path, str) and recursive:
903
+ raise NotImplementedError
904
+ if isinstance(path, list) and (recursive or any("*" in p for p in path)):
905
+ raise NotImplementedError
906
+ # TODO: if references is lazy, pre-fetch all paths in batch before access
907
+ proto_dict = _protocol_groups(path, self.references)
908
+ out = {}
909
+ for proto, paths in proto_dict.items():
910
+ fs = self.fss[proto]
911
+ urls, starts, ends, valid_paths = [], [], [], []
912
+ for p in paths:
913
+ # find references or label not-found. Early exit if any not
914
+ # found and on_error is "raise"
915
+ try:
916
+ u, s, e = self._cat_common(p)
917
+ if not isinstance(u, (bytes, str)):
918
+ # nan/None from parquet
919
+ continue
920
+ except FileNotFoundError as err:
921
+ if on_error == "raise":
922
+ raise
923
+ if on_error != "omit":
924
+ out[p] = err
925
+ else:
926
+ urls.append(u)
927
+ starts.append(s)
928
+ ends.append(e)
929
+ valid_paths.append(p)
930
+
931
+ # process references into form for merging
932
+ urls2 = []
933
+ starts2 = []
934
+ ends2 = []
935
+ paths2 = []
936
+ whole_files = set()
937
+ for u, s, e, p in zip(urls, starts, ends, valid_paths):
938
+ if isinstance(u, bytes):
939
+ # data
940
+ out[p] = u
941
+ elif s is None:
942
+ # whole file - limits are None, None, but no further
943
+ # entries take for this file
944
+ whole_files.add(u)
945
+ urls2.append(u)
946
+ starts2.append(s)
947
+ ends2.append(e)
948
+ paths2.append(p)
949
+ for u, s, e, p in zip(urls, starts, ends, valid_paths):
950
+ # second run to account for files that are to be loaded whole
951
+ if s is not None and u not in whole_files:
952
+ urls2.append(u)
953
+ starts2.append(s)
954
+ ends2.append(e)
955
+ paths2.append(p)
956
+
957
+ # merge and fetch consolidated ranges
958
+ new_paths, new_starts, new_ends = merge_offset_ranges(
959
+ list(urls2),
960
+ list(starts2),
961
+ list(ends2),
962
+ sort=True,
963
+ max_gap=self.max_gap,
964
+ max_block=self.max_block,
965
+ )
966
+ bytes_out = fs.cat_ranges(new_paths, new_starts, new_ends)
967
+
968
+ # unbundle from merged bytes - simple approach
969
+ for u, s, e, p in zip(urls, starts, ends, valid_paths):
970
+ if p in out:
971
+ continue # was bytes, already handled
972
+ for np, ns, ne, b in zip(new_paths, new_starts, new_ends, bytes_out):
973
+ if np == u and (ns is None or ne is None):
974
+ if isinstance(b, Exception):
975
+ out[p] = b
976
+ else:
977
+ out[p] = b[s:e]
978
+ elif np == u and s >= ns and e <= ne:
979
+ if isinstance(b, Exception):
980
+ out[p] = b
981
+ else:
982
+ out[p] = b[s - ns : (e - ne) or None]
983
+
984
+ for k, v in out.copy().items():
985
+ # these were valid references, but fetch failed, so transform exc
986
+ if isinstance(v, Exception) and k in self.references:
987
+ ex = out[k]
988
+ new_ex = ReferenceNotReachable(k, self.references[k])
989
+ new_ex.__cause__ = ex
990
+ if on_error == "raise":
991
+ raise new_ex
992
+ elif on_error != "omit":
993
+ out[k] = new_ex
994
+
995
+ if len(out) == 1 and isinstance(path, str) and "*" not in path:
996
+ return _first(out)
997
+ return out
998
+
999
+ def _process_references(self, references, template_overrides=None):
1000
+ vers = references.get("version", None)
1001
+ if vers is None:
1002
+ self._process_references0(references)
1003
+ elif vers == 1:
1004
+ self._process_references1(references, template_overrides=template_overrides)
1005
+ else:
1006
+ raise ValueError(f"Unknown reference spec version: {vers}")
1007
+ # TODO: we make dircache by iterating over all entries, but for Spec >= 1,
1008
+ # can replace with programmatic. Is it even needed for mapper interface?
1009
+
1010
+ def _process_references0(self, references):
1011
+ """Make reference dict for Spec Version 0"""
1012
+ if isinstance(references, dict):
1013
+ # do not do this for lazy/parquet backend, which will not make dicts,
1014
+ # but must remain writable in the original object
1015
+ references = {
1016
+ key: json.dumps(val) if isinstance(val, dict) else val
1017
+ for key, val in references.items()
1018
+ }
1019
+ self.references = references
1020
+
1021
+ def _process_references1(self, references, template_overrides=None):
1022
+ if not self.simple_templates or self.templates:
1023
+ import jinja2.sandbox
1024
+ self.references = {}
1025
+ self._process_templates(references.get("templates", {}))
1026
+
1027
+ @lru_cache(1000)
1028
+ def _render_jinja(u):
1029
+ return (
1030
+ jinja2.sandbox.SandboxedEnvironment()
1031
+ .from_string(u)
1032
+ .render(**self.templates)
1033
+ )
1034
+
1035
+ for k, v in references.get("refs", {}).items():
1036
+ if isinstance(v, str):
1037
+ if v.startswith("base64:"):
1038
+ self.references[k] = base64.b64decode(v[7:])
1039
+ self.references[k] = v
1040
+ elif isinstance(v, dict):
1041
+ self.references[k] = json.dumps(v)
1042
+ elif self.templates:
1043
+ u = v[0]
1044
+ if "{{" in u:
1045
+ if self.simple_templates:
1046
+ u = (
1047
+ u.replace("{{", "{")
1048
+ .replace("}}", "}")
1049
+ .format(**self.templates)
1050
+ )
1051
+ else:
1052
+ u = _render_jinja(u)
1053
+ self.references[k] = [u] if len(v) == 1 else [u, v[1], v[2]]
1054
+ else:
1055
+ self.references[k] = v
1056
+ self.references.update(self._process_gen(references.get("gen", [])))
1057
+
1058
+ def _process_templates(self, tmp):
1059
+ self.templates = {}
1060
+ if self.template_overrides is not None:
1061
+ tmp.update(self.template_overrides)
1062
+ for k, v in tmp.items():
1063
+ if "{{" in v:
1064
+ import jinja2.sandbox
1065
+
1066
+ self.templates[k] = (
1067
+ lambda temp=v, **kwargs: jinja2.sandbox.SandboxedEnvironment()
1068
+ .from_string(temp)
1069
+ .render(**kwargs)
1070
+ )
1071
+ else:
1072
+ self.templates[k] = v
1073
+
1074
+ def _process_gen(self, gens):
1075
+ out = {}
1076
+ if self.simple_templates:
1077
+ return out
1078
+ for gen in gens:
1079
+ dimension = {
1080
+ k: (
1081
+ v
1082
+ if isinstance(v, list)
1083
+ else range(v.get("start", 0), v["stop"], v.get("step", 1))
1084
+ )
1085
+ for k, v in gen["dimensions"].items()
1086
+ }
1087
+ products = (
1088
+ dict(zip(dimension.keys(), values))
1089
+ for values in itertools.product(*dimension.values())
1090
+ )
1091
+ for pr in products:
1092
+ import jinja2.sandbox
1093
+
1094
+ key = (
1095
+ jinja2.sandbox.SandboxedEnvironment()
1096
+ .from_string(gen["key"])
1097
+ .render(**pr, **self.templates)
1098
+ )
1099
+ url = (
1100
+ jinja2.sandbox.SandboxedEnvironment()
1101
+ .from_string(gen["url"])
1102
+ .render(**pr, **self.templates)
1103
+ )
1104
+ if ("offset" in gen) and ("length" in gen):
1105
+ offset = int(
1106
+ jinja2.sandbox.SandboxedEnvironment()
1107
+ .from_string(gen["offset"])
1108
+ .render(**pr, **self.templates)
1109
+ )
1110
+ length = int(
1111
+ jinja2.sandbox.SandboxedEnvironment()
1112
+ .from_string(gen["length"])
1113
+ .render(**pr, **self.templates)
1114
+ )
1115
+ out[key] = [url, offset, length]
1116
+ elif ("offset" in gen) ^ ("length" in gen):
1117
+ raise ValueError(
1118
+ "Both 'offset' and 'length' are required for a "
1119
+ "reference generator entry if either is provided."
1120
+ )
1121
+ else:
1122
+ out[key] = [url]
1123
+ return out
1124
+
1125
+ def _dircache_from_items(self):
1126
+ self.dircache = {"": []}
1127
+ it = self.references.items()
1128
+ for path, part in it:
1129
+ if isinstance(part, (bytes, str)) or hasattr(part, "to_bytes"):
1130
+ size = len(part)
1131
+ elif len(part) == 1:
1132
+ size = None
1133
+ else:
1134
+ _, _, size = part
1135
+ par = path.rsplit("/", 1)[0] if "/" in path else ""
1136
+ par0 = par
1137
+ subdirs = [par0]
1138
+ while par0 and par0 not in self.dircache:
1139
+ # collect parent directories
1140
+ par0 = self._parent(par0)
1141
+ subdirs.append(par0)
1142
+
1143
+ subdirs.reverse()
1144
+ for parent, child in zip(subdirs, subdirs[1:]):
1145
+ # register newly discovered directories
1146
+ assert child not in self.dircache
1147
+ assert parent in self.dircache
1148
+ self.dircache[parent].append(
1149
+ {"name": child, "type": "directory", "size": 0}
1150
+ )
1151
+ self.dircache[child] = []
1152
+
1153
+ self.dircache[par].append({"name": path, "type": "file", "size": size})
1154
+
1155
+ def _open(self, path, mode="rb", block_size=None, cache_options=None, **kwargs):
1156
+ part_or_url, start0, end0 = self._cat_common(path)
1157
+ # This logic is kept outside `ReferenceFile` to avoid unnecessary redirection.
1158
+ # That does mean `_cat_common` gets called twice if it eventually reaches `ReferenceFile`.
1159
+ if isinstance(part_or_url, bytes):
1160
+ return io.BytesIO(part_or_url[start0:end0])
1161
+
1162
+ protocol, _ = split_protocol(part_or_url)
1163
+ if start0 is None and end0 is None:
1164
+ return self.fss[protocol]._open(
1165
+ part_or_url,
1166
+ mode,
1167
+ block_size=block_size,
1168
+ cache_options=cache_options,
1169
+ **kwargs,
1170
+ )
1171
+
1172
+ return ReferenceFile(
1173
+ self,
1174
+ path,
1175
+ mode,
1176
+ block_size=block_size,
1177
+ cache_options=cache_options,
1178
+ **kwargs,
1179
+ )
1180
+
1181
+ def ls(self, path, detail=True, **kwargs):
1182
+ logger.debug("list %s", path)
1183
+ path = self._strip_protocol(path)
1184
+ if isinstance(self.references, LazyReferenceMapper):
1185
+ try:
1186
+ return self.references.ls(path, detail)
1187
+ except KeyError:
1188
+ pass
1189
+ raise FileNotFoundError(f"'{path}' is not a known key")
1190
+ if not self.dircache:
1191
+ self._dircache_from_items()
1192
+ out = self._ls_from_cache(path)
1193
+ if out is None:
1194
+ raise FileNotFoundError(path)
1195
+ if detail:
1196
+ return out
1197
+ return [o["name"] for o in out]
1198
+
1199
+ def exists(self, path, **kwargs): # overwrite auto-sync version
1200
+ return self.isdir(path) or self.isfile(path)
1201
+
1202
+ def isdir(self, path): # overwrite auto-sync version
1203
+ if self.dircache:
1204
+ return path in self.dircache
1205
+ elif isinstance(self.references, LazyReferenceMapper):
1206
+ return path in self.references.listdir()
1207
+ else:
1208
+ # this may be faster than building dircache for single calls, but
1209
+ # by looping will be slow for many calls; could cache it?
1210
+ return any(_.startswith(f"{path}/") for _ in self.references)
1211
+
1212
+ def isfile(self, path): # overwrite auto-sync version
1213
+ return path in self.references
1214
+
1215
+ async def _ls(self, path, detail=True, **kwargs): # calls fast sync code
1216
+ return self.ls(path, detail, **kwargs)
1217
+
1218
+ def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
1219
+ if withdirs:
1220
+ return super().find(
1221
+ path, maxdepth=maxdepth, withdirs=withdirs, detail=detail, **kwargs
1222
+ )
1223
+ if path:
1224
+ path = self._strip_protocol(path)
1225
+ r = sorted(k for k in self.references if k.startswith(path))
1226
+ else:
1227
+ r = sorted(self.references)
1228
+ if detail:
1229
+ if not self.dircache:
1230
+ self._dircache_from_items()
1231
+ return {k: self._ls_from_cache(k)[0] for k in r}
1232
+ else:
1233
+ return r
1234
+
1235
+ def info(self, path, **kwargs):
1236
+ out = self.references.get(path)
1237
+ if out is not None:
1238
+ if isinstance(out, (str, bytes)):
1239
+ # decode base64 here
1240
+ return {"name": path, "type": "file", "size": len(out)}
1241
+ elif len(out) > 1:
1242
+ return {"name": path, "type": "file", "size": out[2]}
1243
+ else:
1244
+ out0 = [{"name": path, "type": "file", "size": None}]
1245
+ else:
1246
+ out = self.ls(path, True)
1247
+ out0 = [o for o in out if o["name"] == path]
1248
+ if not out0:
1249
+ return {"name": path, "type": "directory", "size": 0}
1250
+ if out0[0]["size"] is None:
1251
+ # if this is a whole remote file, update size using remote FS
1252
+ prot, _ = split_protocol(self.references[path][0])
1253
+ out0[0]["size"] = self.fss[prot].size(self.references[path][0])
1254
+ return out0[0]
1255
+
1256
+ async def _info(self, path, **kwargs):
1257
+ out = self.references.get(path)
1258
+ if isinstance(out, (list, tuple)) and len(out) == 1:
1259
+ # whole remote file: the size must come from the remote FS, which
1260
+ # cannot be called synchronously from inside the event loop
1261
+ prot, _ = split_protocol(out[0])
1262
+ fs = self.fss[prot]
1263
+ if fs.async_impl:
1264
+ size = await fs._size(out[0])
1265
+ else:
1266
+ size = fs.size(out[0])
1267
+ return {"name": path, "type": "file", "size": size}
1268
+ return self.info(path) # calls fast sync code
1269
+
1270
+ async def _rm_file(self, path, **kwargs):
1271
+ self.references.pop(
1272
+ path, None
1273
+ ) # ignores FileNotFound, just as well for directories
1274
+ self.dircache.clear() # this is a bit heavy handed
1275
+
1276
+ async def _pipe_file(self, path, data, mode="overwrite", **kwargs):
1277
+ if mode == "create" and self.exists(path):
1278
+ raise FileExistsError
1279
+ # can be str or bytes
1280
+ self.references[path] = data
1281
+ self.dircache.clear() # this is a bit heavy handed
1282
+
1283
+ async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs):
1284
+ # puts binary
1285
+ if mode == "create" and self.exists(rpath):
1286
+ raise FileExistsError
1287
+ with open(lpath, "rb") as f:
1288
+ self.references[rpath] = f.read()
1289
+ self.dircache.clear() # this is a bit heavy handed
1290
+
1291
+ def save_json(self, url, **storage_options):
1292
+ """Write modified references into new location"""
1293
+ out = {}
1294
+ for k, v in self.references.items():
1295
+ if isinstance(v, bytes):
1296
+ try:
1297
+ out[k] = v.decode("ascii")
1298
+ except UnicodeDecodeError:
1299
+ out[k] = (b"base64:" + base64.b64encode(v)).decode()
1300
+ else:
1301
+ out[k] = v
1302
+ with fsspec.open(url, "wb", **storage_options) as f:
1303
+ f.write(json.dumps({"version": 1, "refs": out}).encode())
1304
+
1305
+
1306
+ class ReferenceFile(AbstractBufferedFile):
1307
+ def __init__(
1308
+ self,
1309
+ fs,
1310
+ path,
1311
+ mode="rb",
1312
+ block_size="default",
1313
+ autocommit=True,
1314
+ cache_type="readahead",
1315
+ cache_options=None,
1316
+ size=None,
1317
+ **kwargs,
1318
+ ):
1319
+ super().__init__(
1320
+ fs,
1321
+ path,
1322
+ mode=mode,
1323
+ block_size=block_size,
1324
+ autocommit=autocommit,
1325
+ size=size,
1326
+ cache_type=cache_type,
1327
+ cache_options=cache_options,
1328
+ **kwargs,
1329
+ )
1330
+ part_or_url, self.start, self.end = self.fs._cat_common(self.path)
1331
+ protocol, _ = split_protocol(part_or_url)
1332
+ self.src_fs = self.fs.fss[protocol]
1333
+ self.src_path = part_or_url
1334
+ self._f = None
1335
+
1336
+ @property
1337
+ def f(self):
1338
+ if self._f is None or self._f.closed:
1339
+ self._f = self.src_fs._open(
1340
+ self.src_path,
1341
+ mode=self.mode,
1342
+ block_size=self.blocksize,
1343
+ autocommit=self.autocommit,
1344
+ cache_type="none",
1345
+ **self.kwargs,
1346
+ )
1347
+ return self._f
1348
+
1349
+ def close(self):
1350
+ if self._f is not None:
1351
+ self._f.close()
1352
+ return super().close()
1353
+
1354
+ def _fetch_range(self, start, end):
1355
+ start = start + self.start
1356
+ end = min(end + self.start, self.end)
1357
+ self.f.seek(start)
1358
+ return self.f.read(end - start)
venv/lib/python3.14/site-packages/fsspec/implementations/sftp.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #: Short names for the missing host key policies built into paramiko, accepted
16
+ #: as the ``host_key_policy`` argument of ``SFTPFileSystem``.
17
+ HOST_KEY_POLICIES = {
18
+ "auto_add": paramiko.AutoAddPolicy,
19
+ "reject": paramiko.RejectPolicy,
20
+ "warning": paramiko.WarningPolicy,
21
+ }
22
+
23
+
24
+ def _resolve_host_key_policy(policy):
25
+ """Turn a ``host_key_policy`` argument into a paramiko policy instance."""
26
+ if policy is None:
27
+ return paramiko.AutoAddPolicy()
28
+ if isinstance(policy, str):
29
+ try:
30
+ return HOST_KEY_POLICIES[policy]()
31
+ except KeyError:
32
+ raise ValueError(
33
+ f"Unknown host_key_policy {policy!r}; expected one of "
34
+ f"{sorted(HOST_KEY_POLICIES)} or a paramiko.MissingHostKeyPolicy"
35
+ ) from None
36
+ if isinstance(policy, type) and issubclass(policy, paramiko.MissingHostKeyPolicy):
37
+ return policy()
38
+ if isinstance(policy, paramiko.MissingHostKeyPolicy):
39
+ return policy
40
+ raise TypeError(
41
+ "host_key_policy must be one of "
42
+ f"{sorted(HOST_KEY_POLICIES)}, a paramiko.MissingHostKeyPolicy subclass "
43
+ f"or instance, not {type(policy).__name__}"
44
+ )
45
+
46
+
47
+ class SFTPFileSystem(AbstractFileSystem):
48
+ """Files over SFTP/SSH
49
+
50
+ Peer-to-peer filesystem over SSH using paramiko.
51
+
52
+ Note: if using this with the ``open`` or ``open_files``, with full URLs,
53
+ there is no way to tell if a path is relative, so all paths are assumed
54
+ to be absolute.
55
+ """
56
+
57
+ protocol = "sftp", "ssh"
58
+
59
+ def __init__(self, host, **ssh_kwargs):
60
+ """
61
+
62
+ Parameters
63
+ ----------
64
+ host: str
65
+ Hostname or IP as a string
66
+ temppath: str
67
+ Location on the server to put files, when within a transaction
68
+ host_key_policy: str or paramiko.MissingHostKeyPolicy, optional
69
+ Policy applied when the server presents a host key that is not
70
+ known yet, passed to
71
+ ``paramiko.SSHClient.set_missing_host_key_policy``. Either one of
72
+ the strings ``"auto_add"`` (default, ``paramiko.AutoAddPolicy``:
73
+ accept and remember any unknown key), ``"warning"``
74
+ (``paramiko.WarningPolicy``: log a warning and accept) or
75
+ ``"reject"`` (``paramiko.RejectPolicy``: refuse to connect), or a
76
+ ``paramiko.MissingHostKeyPolicy`` subclass or instance.
77
+
78
+ The default, ``"auto_add"``, trusts any host key presented on the
79
+ first connection to a host, so a man-in-the-middle attacker can
80
+ impersonate the server. Pass ``"reject"`` to only connect to hosts
81
+ whose keys are already in the known hosts of the process.
82
+ ssh_kwargs: dict
83
+ Parameters passed on to connection. See details in
84
+ https://docs.paramiko.org/en/3.3/api/client.html#paramiko.client.SSHClient.connect
85
+ May include port, username, password...
86
+ """
87
+ if self._cached:
88
+ return
89
+ super().__init__(**ssh_kwargs)
90
+ self.temppath = ssh_kwargs.pop("temppath", "/tmp") # remote temp directory
91
+ self.host_key_policy = _resolve_host_key_policy(
92
+ ssh_kwargs.pop("host_key_policy", None)
93
+ )
94
+ self.host = host
95
+ self.ssh_kwargs = ssh_kwargs
96
+ self._connect()
97
+
98
+ def _connect(self):
99
+ logger.debug("Connecting to SFTP server %s", self.host)
100
+ self.client = paramiko.SSHClient()
101
+ self.client.set_missing_host_key_policy(self.host_key_policy)
102
+ self.client.connect(self.host, **self.ssh_kwargs)
103
+ self.ftp = self.client.open_sftp()
104
+
105
+ @classmethod
106
+ def _strip_protocol(cls, path):
107
+ return infer_storage_options(path)["path"]
108
+
109
+ @staticmethod
110
+ def _get_kwargs_from_urls(urlpath):
111
+ out = infer_storage_options(urlpath)
112
+ out.pop("path", None)
113
+ out.pop("protocol", None)
114
+ return out
115
+
116
+ def mkdir(self, path, create_parents=True, mode=511):
117
+ path = self._strip_protocol(path)
118
+ logger.debug("Creating folder %s", path)
119
+ if self.exists(path):
120
+ raise FileExistsError(f"File exists: {path}")
121
+
122
+ if create_parents:
123
+ self.makedirs(path)
124
+ else:
125
+ self.ftp.mkdir(path, mode)
126
+
127
+ def makedirs(self, path, exist_ok=False, mode=511):
128
+ if self.exists(path) and not exist_ok:
129
+ raise FileExistsError(f"File exists: {path}")
130
+
131
+ parts = path.split("/")
132
+ new_path = "/" if path[:1] == "/" else ""
133
+
134
+ for part in parts:
135
+ if part:
136
+ new_path = f"{new_path}/{part}" if new_path else part
137
+ if not self.exists(new_path):
138
+ self.ftp.mkdir(new_path, mode)
139
+
140
+ def rmdir(self, path):
141
+ path = self._strip_protocol(path)
142
+ logger.debug("Removing folder %s", path)
143
+ self.ftp.rmdir(path)
144
+
145
+ def info(self, path):
146
+ path = self._strip_protocol(path)
147
+ stat = self._decode_stat(self.ftp.stat(path))
148
+ stat["name"] = path
149
+ return stat
150
+
151
+ def created(self, path):
152
+ """Return the created timestamp of a file as a datetime.datetime"""
153
+ # The API does not provide creation time, so we use modification time
154
+ info = self.info(path)
155
+ mtime = info.get("mtime", None)
156
+ if mtime is not None:
157
+ return mtime
158
+ raise RuntimeError("Could not retrieve creation time (modification time).")
159
+
160
+ def modified(self, path):
161
+ """Return the modified timestamp of a file as a datetime.datetime"""
162
+ info = self.info(path)
163
+ mtime = info.get("mtime", None)
164
+ if mtime is not None:
165
+ return mtime
166
+ raise RuntimeError("Could not retrieve modification time.")
167
+
168
+ @staticmethod
169
+ def _decode_stat(stat, parent_path=None):
170
+ if S_ISDIR(stat.st_mode):
171
+ t = "directory"
172
+ elif S_ISLNK(stat.st_mode):
173
+ t = "link"
174
+ else:
175
+ t = "file"
176
+ out = {
177
+ "name": "",
178
+ "size": stat.st_size,
179
+ "type": t,
180
+ "uid": stat.st_uid,
181
+ "gid": stat.st_gid,
182
+ "time": datetime.datetime.fromtimestamp(
183
+ stat.st_atime, tz=datetime.timezone.utc
184
+ ),
185
+ "mtime": datetime.datetime.fromtimestamp(
186
+ stat.st_mtime, tz=datetime.timezone.utc
187
+ ),
188
+ }
189
+ if parent_path:
190
+ out["name"] = "/".join([parent_path.rstrip("/"), stat.filename])
191
+ return out
192
+
193
+ def ls(self, path, detail=False):
194
+ path = self._strip_protocol(path)
195
+ logger.debug("Listing folder %s", path)
196
+ stats = [self._decode_stat(stat, path) for stat in self.ftp.listdir_iter(path)]
197
+ if detail:
198
+ return stats
199
+ else:
200
+ paths = [stat["name"] for stat in stats]
201
+ return sorted(paths)
202
+
203
+ def put_file(self, lpath, rpath, callback=None, **kwargs):
204
+ self.mkdirs(self._parent(os.fspath(rpath)), exist_ok=True)
205
+ logger.debug("Put file %s into %s", lpath, rpath)
206
+ self.ftp.put(lpath, rpath)
207
+
208
+ def get_file(self, rpath, lpath, **kwargs):
209
+ if self.isdir(rpath):
210
+ os.makedirs(lpath, exist_ok=True)
211
+ else:
212
+ self.ftp.get(self._strip_protocol(rpath), lpath)
213
+
214
+ def _open(self, path, mode="rb", block_size=None, **kwargs):
215
+ """
216
+ block_size: int or None
217
+ If 0, no buffering, if 1, line buffering, if >1, buffer that many
218
+ bytes, if None use default from paramiko.
219
+ """
220
+ logger.debug("Opening file %s", path)
221
+ if kwargs.get("autocommit", True) is False:
222
+ # writes to temporary file, move on commit
223
+ path2 = "/".join([self.temppath, str(uuid.uuid4())])
224
+ f = self.ftp.open(path2, mode, bufsize=block_size if block_size else -1)
225
+ f.temppath = path2
226
+ f.targetpath = path
227
+ f.fs = self
228
+ f.commit = types.MethodType(commit_a_file, f)
229
+ f.discard = types.MethodType(discard_a_file, f)
230
+ else:
231
+ f = self.ftp.open(path, mode, bufsize=block_size if block_size else -1)
232
+ return f
233
+
234
+ def _rm(self, path):
235
+ if self.isdir(path):
236
+ self.ftp.rmdir(path)
237
+ else:
238
+ self.ftp.remove(path)
239
+
240
+ def mv(self, old, new):
241
+ new = self._strip_protocol(new)
242
+ old = self._strip_protocol(old)
243
+ logger.debug("Renaming %s into %s", old, new)
244
+ self.ftp.posix_rename(old, new)
245
+
246
+
247
+ def commit_a_file(self):
248
+ self.fs.mv(self.temppath, self.targetpath)
249
+
250
+
251
+ def discard_a_file(self):
252
+ self.fs._rm(self.temppath)
venv/lib/python3.14/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)
venv/lib/python3.14/site-packages/fsspec/implementations/tar.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ @classmethod
27
+ def _strip_protocol(cls, path):
28
+ # file paths are always relative to the archive root
29
+ return super()._strip_protocol(path).lstrip("/")
30
+
31
+ def __init__(
32
+ self,
33
+ fo="",
34
+ index_store=None,
35
+ target_options=None,
36
+ target_protocol=None,
37
+ compression=None,
38
+ **kwargs,
39
+ ):
40
+ super().__init__(**kwargs)
41
+ target_options = target_options or {}
42
+
43
+ if isinstance(fo, str):
44
+ self.of = fsspec.open(fo, protocol=target_protocol, **target_options)
45
+ fo = self.of.open() # keep the reference
46
+
47
+ # Try to infer compression.
48
+ if compression is None:
49
+ name = None
50
+
51
+ # Try different ways to get hold of the filename. `fo` might either
52
+ # be a `fsspec.LocalFileOpener`, an `io.BufferedReader` or an
53
+ # `fsspec.AbstractFileSystem` instance.
54
+ try:
55
+ # Amended io.BufferedReader or similar.
56
+ # This uses a "protocol extension" where original filenames are
57
+ # propagated to archive-like filesystems in order to let them
58
+ # infer the right compression appropriately.
59
+ if hasattr(fo, "original"):
60
+ name = fo.original
61
+
62
+ # fsspec.LocalFileOpener
63
+ elif hasattr(fo, "path"):
64
+ name = fo.path
65
+
66
+ # io.BufferedReader
67
+ elif hasattr(fo, "name"):
68
+ name = fo.name
69
+
70
+ # fsspec.AbstractFileSystem
71
+ elif hasattr(fo, "info"):
72
+ name = fo.info()["name"]
73
+
74
+ except Exception as ex:
75
+ logger.warning(
76
+ f"Unable to determine file name, not inferring compression: {ex}"
77
+ )
78
+
79
+ if name is not None:
80
+ compression = infer_compression(name)
81
+ logger.info(f"Inferred compression {compression} from file name {name}")
82
+
83
+ if compression is not None:
84
+ # TODO: tarfile already implements compression with modes like "'r:gz'",
85
+ # but then would seek to offset in the file work?
86
+ fo = compr[compression](fo)
87
+
88
+ self._fo_ref = fo
89
+ self.fo = fo # the whole instance is a context
90
+ self.tar = tarfile.TarFile(fileobj=self.fo)
91
+ self.dir_cache = None
92
+
93
+ self.index_store = index_store
94
+ self.index = None
95
+ self._index()
96
+
97
+ def _index(self):
98
+ # TODO: load and set saved index, if exists
99
+ out = {}
100
+ for ti in self.tar:
101
+ info = ti.get_info()
102
+ info["type"] = typemap.get(info["type"], "file")
103
+ orig_name = info["name"].rstrip("/")
104
+ # Collapse duplicate slashes in the filesystem-facing name.
105
+ name = re.sub("/+", "/", orig_name)
106
+ info["name"] = name
107
+ if ti.islnk() or ti.issym():
108
+ # extractfile follows links, so report the size of the target
109
+ info["size"] = self._link_target_size(ti)
110
+ out[name] = (info, ti.offset_data, orig_name)
111
+
112
+ self.index = out
113
+ # TODO: save index to self.index_store here, if set
114
+
115
+ def _link_target_size(self, ti):
116
+ seen = set()
117
+ while ti.islnk() or ti.issym():
118
+ if ti.name in seen:
119
+ return 0
120
+ seen.add(ti.name)
121
+ try:
122
+ ti = self.tar._find_link_target(ti)
123
+ except KeyError:
124
+ # dangling link; opening it fails as well
125
+ return 0
126
+ return ti.size
127
+
128
+ def _get_dirs(self):
129
+ if self.dir_cache is not None:
130
+ return
131
+
132
+ # This enables ls to get directories as children as well as files
133
+ self.dir_cache = {
134
+ dirname: {"name": dirname, "size": 0, "type": "directory"}
135
+ for dirname in self._all_dirnames(self.index)
136
+ }
137
+ self.dir_cache.update(
138
+ {info["name"]: info for info, _, _ in self.index.values()}
139
+ )
140
+
141
+ def _open(self, path, mode="rb", **kwargs):
142
+ if mode != "rb":
143
+ raise ValueError("Read-only filesystem implementation")
144
+ # Accept paths containing the archive's duplicate slashes too.
145
+ path = re.sub("/+", "/", path)
146
+ try:
147
+ details, _, orig_name = self.index[path]
148
+ except KeyError as exc:
149
+ raise FileNotFoundError(path) from exc
150
+ if details["type"] != "file":
151
+ raise ValueError("Can only handle regular files")
152
+ out = self.tar.extractfile(orig_name)
153
+ # cat_file needs the size to resolve negative offsets, as zip provides.
154
+ out.size = details["size"]
155
+ return out
156
+
157
+ def close(self):
158
+ """Commits any write changes to the file. Done on ``del`` too."""
159
+ self.tar.close()
160
+
161
+ def __del__(self):
162
+ if hasattr(self, "tar"):
163
+ self.close()
164
+ del self.tar
165
+ if hasattr(self, "of") and hasattr(self.of, "__exit__"):
166
+ self.of.__exit__(None, None, None)
venv/lib/python3.14/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)
venv/lib/python3.14/site-packages/fsspec/implementations/zip.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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. In append mode, a missing archive is created.
36
+ If a str, will fetch file using
37
+ :meth:`~fsspec.open_files`, which must return one file exactly.
38
+ mode: str
39
+ Accept: "r", "w", "a"
40
+ target_protocol: str (optional)
41
+ If ``fo`` is a string, this value can be used to override the
42
+ FS protocol inferred from a URL
43
+ target_options: dict (optional)
44
+ Kwargs passed when instantiating the target FS, if ``fo`` is
45
+ a string.
46
+ compression, allowZip64, compresslevel: passed to ZipFile
47
+ Only relevant when creating a ZIP
48
+ """
49
+ super().__init__(self, **kwargs)
50
+ if mode not in set("rwa"):
51
+ raise ValueError(f"mode '{mode}' no understood")
52
+ self.mode = mode
53
+ if isinstance(fo, (str, os.PathLike)):
54
+ if mode == "a":
55
+ m = "r+b"
56
+ else:
57
+ m = mode + "b"
58
+ fo = fsspec.open(
59
+ fo, mode=m, protocol=target_protocol, **(target_options or {})
60
+ )
61
+ self.force_zip_64 = allowZip64
62
+ self.of = fo
63
+ try:
64
+ self.fo = fo.__enter__() # the whole instance is a context
65
+ except FileNotFoundError:
66
+ if mode != "a" or not isinstance(fo, fsspec.core.OpenFile):
67
+ raise
68
+ fo.mode = "w+b"
69
+ self.fo = fo.__enter__()
70
+ self.zip = zipfile.ZipFile(
71
+ self.fo,
72
+ mode=mode,
73
+ compression=compression,
74
+ allowZip64=allowZip64,
75
+ compresslevel=compresslevel,
76
+ )
77
+ self.dir_cache = None
78
+
79
+ @classmethod
80
+ def _strip_protocol(cls, path):
81
+ # zip file paths are always relative to the archive root
82
+ return super()._strip_protocol(path).lstrip("/")
83
+
84
+ def __del__(self):
85
+ if hasattr(self, "zip"):
86
+ self.close()
87
+ del self.zip
88
+ if hasattr(self, "of") and hasattr(self.of, "__exit__"):
89
+ self.of.__exit__(None, None, None)
90
+
91
+ def close(self):
92
+ """Commits any write changes to the file. Done on ``del`` too."""
93
+ self.zip.close()
94
+
95
+ def _get_dirs(self):
96
+ if self.dir_cache is None or self.mode in set("wa"):
97
+ # when writing, dir_cache is always in the ZipFile's attributes,
98
+ # not read from the file.
99
+ files = self.zip.infolist()
100
+ self.dir_cache = {
101
+ dirname.rstrip("/"): {
102
+ "name": dirname.rstrip("/"),
103
+ "size": 0,
104
+ "type": "directory",
105
+ }
106
+ for dirname in self._all_dirnames(self.zip.namelist())
107
+ }
108
+ for z in files:
109
+ f = {s: getattr(z, s, None) for s in zipfile.ZipInfo.__slots__}
110
+ f.update(
111
+ {
112
+ "name": z.filename.rstrip("/"),
113
+ "size": z.file_size,
114
+ "type": ("directory" if z.is_dir() else "file"),
115
+ }
116
+ )
117
+ self.dir_cache[f["name"]] = f
118
+
119
+ def pipe_file(self, path, value, **kwargs):
120
+ # override upstream, because we know the exact file size in this case
121
+ path = self._strip_protocol(path)
122
+ self.zip.writestr(path, value, **kwargs)
123
+
124
+ def _open(
125
+ self,
126
+ path,
127
+ mode="rb",
128
+ block_size=None,
129
+ autocommit=True,
130
+ cache_options=None,
131
+ **kwargs,
132
+ ):
133
+ path = self._strip_protocol(path)
134
+ if "r" in mode and self.mode in set("wa"):
135
+ if self.exists(path):
136
+ raise OSError("ZipFS can only be open for reading or writing, not both")
137
+ raise FileNotFoundError(path)
138
+ if "r" in self.mode and "w" in mode:
139
+ raise OSError("ZipFS can only be open for reading or writing, not both")
140
+ try:
141
+ out = self.zip.open(path, mode.strip("b"), force_zip64=self.force_zip_64)
142
+ except KeyError as exc:
143
+ # zipfile reports a missing member as KeyError; fsspec callers,
144
+ # including FSMap's missing_exceptions, expect FileNotFoundError.
145
+ raise FileNotFoundError(path) from exc
146
+ if "r" in mode:
147
+ info = self.info(path)
148
+ out.size = info["size"]
149
+ out.name = info["name"]
150
+ return out
151
+
152
+ def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
153
+ if maxdepth is not None and maxdepth < 1:
154
+ raise ValueError("maxdepth must be at least 1")
155
+
156
+ def to_parts(_path: str):
157
+ return list(filter(None, _path.replace("\\", "/").split("/")))
158
+
159
+ if not isinstance(path, str):
160
+ path = str(path)
161
+
162
+ path = self._strip_protocol(path)
163
+ path_parts = to_parts(path)
164
+ path_depth = len(path_parts)
165
+
166
+ self._get_dirs()
167
+
168
+ result = {}
169
+ # To match posix find, if an exact file name is given, we should
170
+ # return only that file
171
+ if path in self.dir_cache and self.dir_cache[path]["type"] == "file":
172
+ result[path] = self.dir_cache[path]
173
+ return result if detail else [path]
174
+
175
+ for file_path, file_info in self.dir_cache.items():
176
+ if len(file_parts := to_parts(file_path)) < path_depth or any(
177
+ a != b for a, b in zip(path_parts, file_parts)
178
+ ):
179
+ # skip parent folders and mismatching paths
180
+ continue
181
+
182
+ if file_info["type"] == "directory":
183
+ if withdirs and file_path not in result:
184
+ result[file_path.strip("/")] = file_info
185
+ continue
186
+
187
+ if file_path not in result:
188
+ result[file_path] = file_info if detail else None
189
+
190
+ if maxdepth:
191
+ result = {
192
+ k: v for k, v in result.items() if k.count("/") < maxdepth + path_depth
193
+ }
194
+ return result if detail else sorted(result)
venv/lib/python3.14/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
venv/lib/python3.14/site-packages/fsspec/mapping.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import array
2
+ import logging
3
+ import posixpath
4
+ import uuid
5
+ import warnings
6
+ from collections.abc import MutableMapping
7
+ from functools import cached_property
8
+
9
+ from fsspec.core import url_to_fs
10
+
11
+ logger = logging.getLogger("fsspec.mapping")
12
+ _MISSING = object()
13
+
14
+
15
+ class FSMap(MutableMapping):
16
+ """Wrap a FileSystem instance as a mutable wrapping.
17
+
18
+ The keys of the mapping become files under the given root, and the
19
+ values (which must be bytes) the contents of those files.
20
+
21
+ Parameters
22
+ ----------
23
+ root: string
24
+ prefix for all the files
25
+ fs: FileSystem instance
26
+ check: bool (=True)
27
+ performs a touch at the location, to check for write access.
28
+
29
+ Examples
30
+ --------
31
+ >>> fs = FileSystem(**parameters) # doctest: +SKIP
32
+ >>> d = FSMap('my-data/path/', fs) # doctest: +SKIP
33
+ or, more likely
34
+ >>> d = fs.get_mapper('my-data/path/')
35
+
36
+ >>> d['loc1'] = b'Hello World' # doctest: +SKIP
37
+ >>> list(d.keys()) # doctest: +SKIP
38
+ ['loc1']
39
+ >>> d['loc1'] # doctest: +SKIP
40
+ b'Hello World'
41
+ """
42
+
43
+ def __init__(self, root, fs, check=False, create=False, missing_exceptions=None):
44
+ self.fs = fs
45
+ self.root = fs._strip_protocol(root)
46
+ self._root_key_to_str = fs._strip_protocol(posixpath.join(root, "x"))[:-1]
47
+ if missing_exceptions is None:
48
+ missing_exceptions = (
49
+ FileNotFoundError,
50
+ IsADirectoryError,
51
+ NotADirectoryError,
52
+ )
53
+ self.missing_exceptions = missing_exceptions
54
+ self.check = check
55
+ self.create = create
56
+ if create:
57
+ if not self.fs.exists(root):
58
+ self.fs.mkdir(root)
59
+ if check:
60
+ if not self.fs.exists(root):
61
+ raise ValueError(
62
+ f"Path {root} does not exist. Create "
63
+ f" with the ``create=True`` keyword"
64
+ )
65
+ check_path = f"{root}/{uuid.uuid4().hex}"
66
+ self.fs.touch(check_path)
67
+ self.fs.rm(check_path)
68
+
69
+ @cached_property
70
+ def dirfs(self):
71
+ """dirfs instance that can be used with the same keys as the mapper"""
72
+ from .implementations.dirfs import DirFileSystem
73
+
74
+ return DirFileSystem(path=self._root_key_to_str, fs=self.fs)
75
+
76
+ def clear(self):
77
+ """Remove all keys below root - empties out mapping"""
78
+ logger.info("Clear mapping at %s", self.root)
79
+ try:
80
+ self.fs.rm(self.root, True)
81
+ self.fs.mkdir(self.root)
82
+ except: # noqa: E722
83
+ pass
84
+
85
+ def getitems(self, keys, on_error="raise"):
86
+ """Fetch multiple items from the store
87
+
88
+ If the backend is async-able, this might proceed concurrently
89
+
90
+ Parameters
91
+ ----------
92
+ keys: list(str)
93
+ They keys to be fetched
94
+ on_error : "raise", "omit", "return"
95
+ If raise, an underlying exception will be raised (converted to KeyError
96
+ if the type is in self.missing_exceptions); if omit, keys with exception
97
+ will simply not be included in the output; if "return", all keys are
98
+ included in the output, but the value will be bytes or an exception
99
+ instance.
100
+
101
+ Returns
102
+ -------
103
+ dict(key, bytes|exception)
104
+ """
105
+ keys2 = [self._key_to_str(k) for k in keys]
106
+ oe = on_error if on_error == "raise" else "return"
107
+ try:
108
+ out = self.fs.cat(keys2, on_error=oe)
109
+ if isinstance(out, bytes):
110
+ out = {keys2[0]: out}
111
+ except self.missing_exceptions as e:
112
+ raise KeyError from e
113
+ out = {
114
+ k: (KeyError() if isinstance(v, self.missing_exceptions) else v)
115
+ for k, v in out.items()
116
+ }
117
+ return {
118
+ key: out[k2] if on_error == "raise" else out.get(k2, KeyError(k2))
119
+ for key, k2 in zip(keys, keys2)
120
+ if on_error == "return" or not isinstance(out[k2], BaseException)
121
+ }
122
+
123
+ def setitems(self, values_dict):
124
+ """Set the values of multiple items in the store
125
+
126
+ Parameters
127
+ ----------
128
+ values_dict: dict(str, bytes)
129
+ """
130
+ values = {self._key_to_str(k): maybe_convert(v) for k, v in values_dict.items()}
131
+ self.fs.pipe(values)
132
+
133
+ def delitems(self, keys):
134
+ """Remove multiple keys from the store"""
135
+ self.fs.rm([self._key_to_str(k) for k in keys])
136
+
137
+ def _key_to_str(self, key):
138
+ """Generate full path for the key"""
139
+ if not isinstance(key, str):
140
+ # raise TypeError("key must be of type `str`, got `{type(key).__name__}`"
141
+ warnings.warn(
142
+ "from fsspec 2023.5 onward FSMap non-str keys will raise TypeError",
143
+ DeprecationWarning,
144
+ )
145
+ if isinstance(key, list):
146
+ key = tuple(key)
147
+ key = str(key)
148
+ return f"{self._root_key_to_str}{key}".rstrip("/")
149
+
150
+ def _str_to_key(self, s):
151
+ """Strip path of to leave key name"""
152
+ return s[len(self.root) :].lstrip("/")
153
+
154
+ def __getitem__(self, key, default=None):
155
+ """Retrieve data"""
156
+ k = self._key_to_str(key)
157
+ try:
158
+ result = self.fs.cat(k)
159
+ except self.missing_exceptions as exc:
160
+ if default is not None:
161
+ return default
162
+ raise KeyError(key) from exc
163
+ return result
164
+
165
+ def pop(self, key, default=_MISSING):
166
+ """Pop data"""
167
+ try:
168
+ result = self[key]
169
+ except KeyError:
170
+ if default is _MISSING:
171
+ raise
172
+ return default
173
+ try:
174
+ del self[key]
175
+ except KeyError:
176
+ pass
177
+ return result
178
+
179
+ def __setitem__(self, key, value):
180
+ """Store value in key"""
181
+ key = self._key_to_str(key)
182
+ self.fs.mkdirs(self.fs._parent(key), exist_ok=True)
183
+ self.fs.pipe_file(key, maybe_convert(value))
184
+
185
+ def __iter__(self):
186
+ return (self._str_to_key(x) for x in self.fs.find(self.root))
187
+
188
+ def __len__(self):
189
+ return len(self.fs.find(self.root))
190
+
191
+ def __delitem__(self, key):
192
+ """Remove key"""
193
+ try:
194
+ self.fs.rm(self._key_to_str(key))
195
+ except Exception as exc:
196
+ raise KeyError from exc
197
+
198
+ def __contains__(self, key):
199
+ """Does key exist in mapping?"""
200
+ path = self._key_to_str(key)
201
+ return self.fs.isfile(path)
202
+
203
+ def __reduce__(self):
204
+ return FSMap, (self.root, self.fs, False, False, self.missing_exceptions)
205
+
206
+
207
+ def maybe_convert(value):
208
+ if isinstance(value, array.array) or hasattr(value, "__array__"):
209
+ # bytes-like things
210
+ if hasattr(value, "dtype") and value.dtype.kind in "Mm":
211
+ # The buffer interface doesn't support datetime64/timdelta64 numpy
212
+ # arrays
213
+ value = value.view("int64")
214
+ value = bytes(memoryview(value))
215
+ return value
216
+
217
+
218
+ def get_mapper(
219
+ url="",
220
+ check=False,
221
+ create=False,
222
+ missing_exceptions=None,
223
+ alternate_root=None,
224
+ **kwargs,
225
+ ):
226
+ """Create key-value interface for given URL and options
227
+
228
+ The URL will be of the form "protocol://location" and point to the root
229
+ of the mapper required. All keys will be file-names below this location,
230
+ and their values the contents of each key.
231
+
232
+ Also accepts compound URLs like zip::s3://bucket/file.zip , see ``fsspec.open``.
233
+
234
+ Parameters
235
+ ----------
236
+ url: str
237
+ Root URL of mapping
238
+ check: bool
239
+ Whether to attempt to read from the location before instantiation, to
240
+ check that the mapping does exist
241
+ create: bool
242
+ Whether to make the directory corresponding to the root before
243
+ instantiating
244
+ missing_exceptions: None or tuple
245
+ If given, these exception types will be regarded as missing keys and
246
+ return KeyError when trying to read data. By default, you get
247
+ (FileNotFoundError, IsADirectoryError, NotADirectoryError)
248
+ alternate_root: None or str
249
+ In cases of complex URLs, the parser may fail to pick the correct part
250
+ for the mapper root, so this arg can override
251
+
252
+ Returns
253
+ -------
254
+ ``FSMap`` instance, the dict-like key-value store.
255
+ """
256
+ # Removing protocol here - could defer to each open() on the backend
257
+ fs, urlpath = url_to_fs(url, **kwargs)
258
+ root = alternate_root if alternate_root is not None else urlpath
259
+ return FSMap(root, fs, check, create, missing_exceptions=missing_exceptions)
venv/lib/python3.14/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)
venv/lib/python3.14/site-packages/fsspec/prefetcher.py ADDED
@@ -0,0 +1,873 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ import weakref
4
+ from collections import deque
5
+
6
+ from . import asyn as fsspec_asyn
7
+ from .asyn import sync_teardown
8
+ from .utils import _fast_slice
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class RunningAverageTracker:
14
+ """Tracks a running average of values over a sliding window.
15
+
16
+ This is used to monitor read sizes and adaptively scale the
17
+ prefetching strategy based on recent user behavior.
18
+ """
19
+
20
+ def __init__(self, maxlen=10):
21
+ """Initializes the tracker with a specific window size.
22
+
23
+ Args:
24
+ maxlen (int): The maximum number of historical values to keep.
25
+ """
26
+ logger.debug("Initializing RunningAverageTracker with maxlen: %d", maxlen)
27
+ self._history = deque(maxlen=maxlen)
28
+ self._sum = 0
29
+
30
+ def add(self, value: int):
31
+ """Adds a new value to the sliding window and updates the rolling sum.
32
+
33
+ Args:
34
+ value (int): The integer value to add to the history.
35
+ """
36
+ if value <= 0:
37
+ raise ValueError(
38
+ "Internal error, RunningAverageTracker tried inserting negative value"
39
+ )
40
+ if len(self._history) == self._history.maxlen:
41
+ self._sum -= self._history[0]
42
+
43
+ self._history.append(value)
44
+ self._sum += value
45
+ logger.debug(
46
+ "RunningAverageTracker added value: %d, new sum: %d", value, self._sum
47
+ )
48
+
49
+ @property
50
+ def average(self) -> int:
51
+ """Calculates and returns the current running average.
52
+
53
+ Returns:
54
+ int: The integer average of the current history.
55
+ """
56
+ count = len(self._history)
57
+ if count == 0:
58
+ return 1024 * 1024 # 1MB
59
+ return self._sum // count
60
+
61
+ @property
62
+ def is_variable(self) -> bool:
63
+ """Determines if the history contains distinct chunk sizes."""
64
+ count = len(self._history)
65
+ if count < 2:
66
+ return False
67
+
68
+ return len(set(self._history)) > 1
69
+
70
+ @property
71
+ def last_value(self) -> int:
72
+ """Returns the most recent entry in the history."""
73
+ if not self._history:
74
+ raise RuntimeError("No entry found in history")
75
+
76
+ return self._history[-1]
77
+
78
+ def clear(self):
79
+ """Clears the history and resets the sum to zero."""
80
+ logger.debug("Clearing RunningAverageTracker history.")
81
+ self._history.clear()
82
+ self._sum = 0
83
+
84
+
85
+ class PrefetchProducer:
86
+ """Background worker that fetches sequential blocks of data.
87
+
88
+ This class handles the network requests. It spawns asynchronous tasks
89
+ to fetch data ahead of the user's current reading position and
90
+ places those task promises into a queue for the consumer.
91
+ """
92
+
93
+ # If the request is too small, and prefetch window is expanded till 5MB
94
+ # we then make request in 5MB blocks.
95
+ MIN_CHUNK_SIZE = 5 * 1024 * 1024
96
+
97
+ # If user doesn't specify any max_prefetch_size, the prefetcher defaults
98
+ # to maximum of 2 * io_size and 128MB
99
+ MIN_PREFETCH_SIZE = 128 * 1024 * 1024
100
+
101
+ # The prefetching starts on the third read.
102
+ MIN_STREAKS_FOR_PREFETCHING = 3
103
+
104
+ # Threshold for disabling proactive prefetching on large, variable reads.
105
+ #
106
+ # If the average read size exceeds this value and patterns are variable,
107
+ # prefetching shifts from an I/O bottleneck to a memory(CPU) bottleneck. When a user
108
+ # requests random massive sizes (e.g., jumping between 64MB and INF), the
109
+ # producer still fetches chunks based on the rolling average. The consumer
110
+ # then has to pick up multiple chunks and stitch them together to match the
111
+ # exact requested size.
112
+ #
113
+ # For small average read sizes, this byte assembly is fast and the bottleneck
114
+ # remains the network I/O. However, for massive reads (>= 64MB), the extra
115
+ # step of copying and assembling huge byte strings in memory severely slows
116
+ # down the operation.
117
+ VARIABLE_IO_THRESHOLD = 64 * 1024 * 1024
118
+
119
+ def __init__(
120
+ self,
121
+ fetcher,
122
+ size: int,
123
+ concurrency: int,
124
+ queue: asyncio.Queue,
125
+ wakeup_event: asyncio.Event,
126
+ consumer: "PrefetchConsumer",
127
+ tracker: RunningAverageTracker,
128
+ orchestrator: "BackgroundPrefetcher",
129
+ user_max_prefetch_size=None,
130
+ ):
131
+ """Initializes the background producer.
132
+
133
+ Args:
134
+ fetcher (Callable): A coroutine function to fetch bytes from a remote source.
135
+ size (int): Total size of the file being fetched.
136
+ concurrency (int): Maximum number of concurrent fetch tasks.
137
+ queue (asyncio.Queue): The shared queue to push download tasks into.
138
+ wakeup_event (asyncio.Event): Event used to wake the producer from an idle state.
139
+ consumer (PrefetchConsumer): The consumer reading the prefetched chunks.
140
+ tracker (RunningAverageTracker): Tracker for history of read sizes.
141
+ orchestrator (BackgroundPrefetcher): The parent object managing the operation.
142
+ user_max_prefetch_size (int, optional): A hard limit for prefetch size overrides.
143
+ """
144
+ logger.debug(
145
+ "Initializing PrefetchProducer: size=%d, concurrency=%d, user_max_prefetch_size=%s",
146
+ size,
147
+ concurrency,
148
+ user_max_prefetch_size,
149
+ )
150
+ self.fetcher = fetcher
151
+ self.size = size
152
+ self.concurrency = concurrency
153
+ self.queue = queue
154
+ self.wakeup_event = wakeup_event
155
+
156
+ self.consumer = consumer
157
+ self.tracker = tracker
158
+ self.orchestrator = weakref.proxy(orchestrator)
159
+ self._user_max_prefetch_size = user_max_prefetch_size
160
+
161
+ self.current_offset = 0
162
+ self.is_stopped = False
163
+ self._active_tasks = set()
164
+ self._producer_task = None
165
+
166
+ @property
167
+ def max_prefetch_size(self) -> int:
168
+ """Calculates the maximum prefetch size based on user intent or io size.
169
+
170
+ Returns:
171
+ int: The maximum number of bytes to prefetch ahead.
172
+ """
173
+ if self._user_max_prefetch_size is not None:
174
+ return min(
175
+ self._user_max_prefetch_size,
176
+ max(2 * self.tracker.average, self.MIN_PREFETCH_SIZE),
177
+ )
178
+ return max(2 * self.tracker.average, self.MIN_PREFETCH_SIZE)
179
+
180
+ def start(self):
181
+ """Starts the background producer loop.
182
+
183
+ This clears any previous wakeup events and spawns the main loop task.
184
+ """
185
+ logger.debug("Starting PrefetchProducer loop.")
186
+ self.is_stopped = False
187
+ self.wakeup_event.clear()
188
+ self._producer_task = asyncio.create_task(self._loop())
189
+
190
+ async def stop(self):
191
+ """Cancels all active fetch tasks and shuts down the producer loop.
192
+
193
+ This method ensures the queue is flushed and waits for cancelled
194
+ tasks to finish cleaning up.
195
+ """
196
+ logger.debug(
197
+ "Stopping PrefetchProducer. Active fetch tasks: %d", len(self._active_tasks)
198
+ )
199
+ self.is_stopped = True
200
+ self.wakeup_event.set()
201
+
202
+ tasks_to_wait = []
203
+ if self._producer_task and not self._producer_task.done():
204
+ self._producer_task.cancel()
205
+ tasks_to_wait.append(self._producer_task)
206
+
207
+ tasks_to_wait.extend(
208
+ task for task in list(self._active_tasks) if not task.done()
209
+ )
210
+
211
+ # We do not cancel the network task, instead we wait on them.
212
+ # This is intentionally done to avoid MRD stream disruption.
213
+ self._active_tasks.clear()
214
+
215
+ # Clear out any leftover items in the queue
216
+ cleared_items = 0
217
+ while not self.queue.empty():
218
+ try:
219
+ item = self.queue.get_nowait()
220
+ if (
221
+ isinstance(item, asyncio.Task)
222
+ and item.done()
223
+ and not item.cancelled()
224
+ ):
225
+ item.exception()
226
+ cleared_items += 1
227
+ except asyncio.QueueEmpty:
228
+ break
229
+
230
+ if cleared_items > 0:
231
+ logger.debug(
232
+ "Cleared %d leftover items from the queue during stop.", cleared_items
233
+ )
234
+
235
+ if tasks_to_wait:
236
+ logger.debug(
237
+ "Waiting for %d cancelled tasks to finish their teardown.",
238
+ len(tasks_to_wait),
239
+ )
240
+ await asyncio.gather(*tasks_to_wait, return_exceptions=True)
241
+
242
+ self.wakeup_event.clear()
243
+
244
+ async def restart(self, new_offset: int):
245
+ """Stops current tasks and restarts the background loop at a new byte offset.
246
+
247
+ Args:
248
+ new_offset (int): The new byte position to start prefetching from.
249
+ """
250
+ logger.debug("Restarting PrefetchProducer at new offset: %d", new_offset)
251
+ await self.stop()
252
+ self.current_offset = new_offset
253
+ self.start()
254
+
255
+ async def _loop(self):
256
+ """The main background loop that delegates calculations and spawns tasks."""
257
+ logger.debug("PrefetchProducer internal loop is now running.")
258
+ try:
259
+ while not self.is_stopped:
260
+ await self.wakeup_event.wait()
261
+ self.wakeup_event.clear()
262
+
263
+ if self.is_stopped:
264
+ break
265
+
266
+ await self._process_prefetch_cycle()
267
+
268
+ except asyncio.CancelledError:
269
+ logger.debug("PrefetchProducer loop was cancelled.")
270
+ except Exception as e:
271
+ logger.exception("PrefetchProducer loop encountered an unexpected error.")
272
+ self.is_stopped = True
273
+ self.orchestrator.set_error(e)
274
+ await self.queue.put(e)
275
+
276
+ def _calculate_prefetch_params(self) -> tuple[int, int, int]:
277
+ """
278
+ Evaluates current trackers and state to determine sizes.
279
+
280
+ Returns:
281
+ tuple: (prefetch_size, io_size, effective_prefetch_size)
282
+ """
283
+ avg_io_size = self.tracker.average
284
+ streak = self.consumer.sequential_streak
285
+ is_variable = self.tracker.is_variable
286
+ last_read_size = self.tracker.last_value
287
+
288
+ exceeds_user_max = (
289
+ self._user_max_prefetch_size is not None
290
+ and avg_io_size > self._user_max_prefetch_size
291
+ )
292
+
293
+ # Disable prefetching ahead if variable AND average > 64MB, or if it exceeds user max
294
+ if (
295
+ is_variable and avg_io_size > self.VARIABLE_IO_THRESHOLD
296
+ ) or exceeds_user_max:
297
+ logger.debug(
298
+ "Large IO detected (variable > 64MB or > user max). Disabling background prefetching."
299
+ )
300
+ prefetch_multiplier = 1
301
+ elif streak < self.MIN_STREAKS_FOR_PREFETCHING:
302
+ prefetch_multiplier = 1
303
+ else:
304
+ prefetch_multiplier = streak - self.MIN_STREAKS_FOR_PREFETCHING + 1
305
+
306
+ if self.queue.empty() or prefetch_multiplier == 1:
307
+ io_size = last_read_size
308
+ else:
309
+ io_size = avg_io_size
310
+
311
+ prefetch_size = min(prefetch_multiplier * io_size, self.max_prefetch_size)
312
+ if self.consumer.offset + prefetch_size < self.consumer.target_offset:
313
+ prefetch_size = self.consumer.target_offset - self.consumer.offset
314
+
315
+ if is_variable:
316
+ effective_prefetch_size = prefetch_size
317
+ else:
318
+ effective_prefetch_size = (prefetch_size // io_size) * io_size
319
+ if effective_prefetch_size == 0:
320
+ effective_prefetch_size = prefetch_size
321
+
322
+ return prefetch_size, io_size, effective_prefetch_size
323
+
324
+ async def _process_prefetch_cycle(self):
325
+ """Executes a single cycle of enqueuing fetch tasks."""
326
+ prefetch_size, io_size, effective_prefetch_size = (
327
+ self._calculate_prefetch_params()
328
+ )
329
+
330
+ logger.debug(
331
+ "Producer awake. Current offset: %d, User offset: %d, Prefetch size: %d",
332
+ self.current_offset,
333
+ self.consumer.offset,
334
+ prefetch_size,
335
+ )
336
+
337
+ while (
338
+ not self.is_stopped
339
+ and (self.current_offset - self.consumer.offset) < prefetch_size
340
+ and self.current_offset < self.size
341
+ ):
342
+ user_offset = self.consumer.offset
343
+ space_remaining = self.size - self.current_offset
344
+ prefetch_space_available = prefetch_size - (
345
+ self.current_offset - user_offset
346
+ )
347
+
348
+ if prefetch_size >= self.MIN_CHUNK_SIZE:
349
+ if prefetch_space_available >= self.MIN_CHUNK_SIZE:
350
+ actual_size = min(
351
+ max(self.MIN_CHUNK_SIZE, io_size), space_remaining
352
+ )
353
+ else:
354
+ break
355
+ else:
356
+ actual_size = min(io_size, space_remaining)
357
+
358
+ if prefetch_space_available < actual_size:
359
+ if (
360
+ self.tracker.is_variable
361
+ or prefetch_space_available == prefetch_size
362
+ ):
363
+ actual_size = prefetch_space_available
364
+ else:
365
+ break
366
+
367
+ streak = self.consumer.sequential_streak
368
+ if streak < self.MIN_STREAKS_FOR_PREFETCHING:
369
+ sfactor = self.concurrency
370
+ else:
371
+ sfactor = min(
372
+ self.concurrency,
373
+ max(
374
+ 1,
375
+ actual_size * self.concurrency // effective_prefetch_size,
376
+ ),
377
+ )
378
+
379
+ logger.debug(
380
+ "Spawning fetch task. Offset: %d, Size: %d, Split Factor: %d",
381
+ self.current_offset,
382
+ actual_size,
383
+ sfactor,
384
+ )
385
+
386
+ download_task = asyncio.create_task(
387
+ self.fetcher(self.current_offset, actual_size, split_factor=sfactor)
388
+ )
389
+ self._active_tasks.add(download_task)
390
+ download_task.add_done_callback(self._active_tasks.discard)
391
+
392
+ await self.queue.put(download_task)
393
+ self.current_offset += actual_size
394
+
395
+ if self.current_offset >= self.size:
396
+ logger.debug("Producer reached EOF. Exiting background loop.")
397
+ self.is_stopped = True
398
+
399
+
400
+ class PrefetchConsumer:
401
+ """Consumes prefetched chunks from the queue and manages byte slicing.
402
+
403
+ This class pulls data out of the shared queue and slices it into the
404
+ exact byte sizes requested by the user. It also manages the local block buffer.
405
+ """
406
+
407
+ def __init__(
408
+ self,
409
+ queue: asyncio.Queue,
410
+ wakeup_event: asyncio.Event,
411
+ tracker: RunningAverageTracker,
412
+ orchestrator: "BackgroundPrefetcher",
413
+ ):
414
+ """Initializes the consumer.
415
+
416
+ Args:
417
+ queue (asyncio.Queue): The shared queue containing fetch tasks.
418
+ wakeup_event (asyncio.Event): Event used to wake the producer when more data is needed.
419
+ tracker (RunningAverageTracker): Tracker for history of read sizes.
420
+ orchestrator (BackgroundPrefetcher): The parent object managing the operation.
421
+ """
422
+ logger.debug("Initializing PrefetchConsumer.")
423
+ self.queue = queue
424
+ self.wakeup_event = wakeup_event
425
+ self.tracker = tracker
426
+ self.orchestrator = weakref.proxy(orchestrator)
427
+ self.sequential_streak = 0
428
+ self.offset = 0
429
+ self.target_offset = 0
430
+ self._current_block = b""
431
+ self._current_block_idx = 0
432
+
433
+ def seek(self, new_offset: int):
434
+ """Clears the buffer and resets the internal offset for a hard seek.
435
+
436
+ Args:
437
+ new_offset (int): The byte position the consumer is jumping to.
438
+ """
439
+ logger.debug(
440
+ "Consumer executing hard seek to offset %d. Clearing internal buffer.",
441
+ new_offset,
442
+ )
443
+ self.offset = new_offset
444
+ self.target_offset = new_offset
445
+ self.sequential_streak = 0
446
+ self._current_block = b""
447
+ self._current_block_idx = 0
448
+
449
+ def clear_buffer(self):
450
+ """Discards the local byte buffer. Useful during shutdown or resets."""
451
+ logger.debug("Consumer local block buffer cleared.")
452
+ self._current_block = b""
453
+ self._current_block_idx = 0
454
+
455
+ async def _advance(self, size: int, save_data: bool) -> list[bytes]:
456
+ """Internal method to advance the offset and optionally extract data.
457
+
458
+ Handles queue exhaustion, producer wakeups, and streak tracking.
459
+ """
460
+ if size <= 0:
461
+ return []
462
+
463
+ chunks = []
464
+ processed = 0
465
+ self.target_offset = self.offset + size
466
+
467
+ while processed < size:
468
+ available = len(self._current_block) - self._current_block_idx
469
+ trigger_wakeup = False
470
+
471
+ if not available:
472
+ is_producer_stopped = (
473
+ self.orchestrator.producer is None
474
+ or self.orchestrator.producer.is_stopped
475
+ )
476
+ if is_producer_stopped and self.queue.empty():
477
+ logger.debug("Consumer reached EOF.")
478
+ break
479
+
480
+ if self.queue.empty():
481
+ logger.debug("Queue is empty. Waking up producer.")
482
+ self.wakeup_event.set()
483
+
484
+ task = await self.queue.get()
485
+
486
+ if isinstance(task, Exception):
487
+ logger.error("Consumer retrieved an exception: %s", task)
488
+ self.orchestrator.set_error(task)
489
+ raise task
490
+
491
+ try:
492
+ block = await task
493
+
494
+ self.sequential_streak += 1
495
+ if (
496
+ self.sequential_streak
497
+ >= PrefetchProducer.MIN_STREAKS_FOR_PREFETCHING
498
+ ):
499
+ exceeds_user_max = (
500
+ self.orchestrator.max_prefetch_size is not None
501
+ and self.tracker.average
502
+ > self.orchestrator.max_prefetch_size
503
+ )
504
+ is_massive_variable = (
505
+ self.tracker.is_variable
506
+ and self.tracker.average
507
+ > PrefetchProducer.VARIABLE_IO_THRESHOLD
508
+ )
509
+
510
+ # Suppress proactive wakeups to prevent large CPU assembly
511
+ # on erratic large reads or exceeding max
512
+ if not (is_massive_variable or exceeds_user_max):
513
+ trigger_wakeup = True
514
+ else:
515
+ logger.debug(
516
+ "Suppressing proactive producer wakeup due to massive variable"
517
+ " workload or exceeding user max prefetch."
518
+ )
519
+
520
+ self._current_block = block
521
+ self._current_block_idx = 0
522
+ available = len(self._current_block)
523
+ except asyncio.CancelledError:
524
+ raise
525
+ except Exception as e:
526
+ logger.exception("Consumer caught an error.")
527
+ self.orchestrator.set_error(e)
528
+ raise e
529
+
530
+ if not self._current_block:
531
+ break
532
+
533
+ needed = size - processed
534
+ take = min(needed, available)
535
+
536
+ if save_data:
537
+ if take == len(self._current_block) and self._current_block_idx == 0:
538
+ chunk = self._current_block
539
+ else:
540
+ # Native Python slicing was GIL bound in my experiments.
541
+ chunk = await asyncio.to_thread(
542
+ _fast_slice, self._current_block, self._current_block_idx, take
543
+ )
544
+ chunks.append(chunk)
545
+
546
+ self._current_block_idx += take
547
+ processed += take
548
+ self.offset += take
549
+ if trigger_wakeup:
550
+ self.wakeup_event.set()
551
+
552
+ return chunks
553
+
554
+ async def consume(self, size: int) -> bytes:
555
+ """Pulls exactly 'size' bytes from the local block or the task queue.
556
+
557
+ If the local block is exhausted, this will wait on the queue for the next
558
+ available chunk of data.
559
+
560
+ Args:
561
+ size (int): The exact number of bytes to retrieve.
562
+
563
+ Returns:
564
+ bytes: The requested bytes. This may be shorter than 'size' if EOF is reached.
565
+
566
+ Raises:
567
+ Exception: Re-raises any exceptions encountered by the producer fetch tasks.
568
+ """
569
+ if size <= 0:
570
+ return b""
571
+
572
+ chunks = await self._advance(size, save_data=True)
573
+
574
+ if not chunks:
575
+ return b""
576
+
577
+ if len(chunks) == 1:
578
+ return chunks[0]
579
+
580
+ return await asyncio.to_thread(b"".join, chunks)
581
+
582
+ async def skip(self, size: int) -> None:
583
+ """Advances the consumer offset without allocating memory."""
584
+ await self._advance(size, save_data=False)
585
+
586
+
587
+ class BackgroundPrefetcher:
588
+ """Orchestrator that manages reading behavior and coordinates background work.
589
+
590
+ This acts as the main public interface for the file reader. It tracks the
591
+ user's reading history, routes seek operations, and links the producer's
592
+ network tasks with the consumer's data slicing logic.
593
+ """
594
+
595
+ producer = None
596
+
597
+ def __init__(
598
+ self, fetcher, size: int, concurrency: int, max_prefetch_size=None, loop=None
599
+ ):
600
+ """Initializes the background prefetcher.
601
+
602
+ Args:
603
+ fetcher (Callable): A coroutine of the form `f(start, end)` which gets bytes from the remote.
604
+ size (int): Total byte size of the file being read.
605
+ concurrency (int): Number of concurrent network requests to use for large chunks.
606
+ max_prefetch_size (int, optional): Maximum bytes to prefetch ahead of the current user offset.
607
+ loop (asyncio.AbstractEventLoop, optional): The event loop to attach the prefetcher to.
608
+ If executing synchronously, this should be the fsspec background loop. If executing
609
+ asynchronously (asynchronous=True), this should be None so it can automatically
610
+ inherit the user's currently running event loop.
611
+
612
+ Raises:
613
+ ValueError: If max_prefetch_size is provided but is not a positive integer.
614
+ """
615
+ logger.debug(
616
+ "Starting BackgroundPrefetcher. Size: %d, Concurrency: %d, Max Prefetch: %s",
617
+ size,
618
+ concurrency,
619
+ max_prefetch_size,
620
+ )
621
+ self.size = size
622
+ self.concurrency = concurrency
623
+ self.max_prefetch_size = max_prefetch_size
624
+
625
+ if max_prefetch_size is not None and max_prefetch_size <= 0:
626
+ logger.error("Invalid max_prefetch_size provided: %s", max_prefetch_size)
627
+ raise ValueError(
628
+ "max_prefetch_size should be a positive integer to use adaptive prefetching!"
629
+ )
630
+
631
+ self.loop = loop
632
+ self._error = None
633
+ self.is_stopped = False
634
+ self.user_offset = 0
635
+ self.read_tracker = RunningAverageTracker(maxlen=10)
636
+
637
+ self.queue = None
638
+ self.wakeup_event = None
639
+ self._async_lock = None
640
+ self.consumer = None
641
+ self.producer = None
642
+
643
+ def _start():
644
+ # Ensures all primitives bind directly to `self.loop`
645
+ self.queue = asyncio.Queue()
646
+ self.wakeup_event = asyncio.Event()
647
+ self._async_lock = asyncio.Lock()
648
+
649
+ self.consumer = PrefetchConsumer(
650
+ queue=self.queue,
651
+ wakeup_event=self.wakeup_event,
652
+ tracker=self.read_tracker,
653
+ orchestrator=self,
654
+ )
655
+
656
+ self.producer = PrefetchProducer(
657
+ fetcher=fetcher,
658
+ size=self.size,
659
+ concurrency=self.concurrency,
660
+ queue=self.queue,
661
+ wakeup_event=self.wakeup_event,
662
+ consumer=self.consumer,
663
+ tracker=self.read_tracker,
664
+ orchestrator=self,
665
+ user_max_prefetch_size=max_prefetch_size,
666
+ )
667
+ self.producer.start()
668
+
669
+ try:
670
+ current_loop = asyncio.get_running_loop()
671
+ except RuntimeError:
672
+ current_loop = None
673
+
674
+ if current_loop is self.loop and self.loop is not None:
675
+ # We are already safely running inside the fsspec background loop
676
+ _start()
677
+ elif self.loop is not None:
678
+ # We are on the main thread; schedule setup on the fsspec background loop
679
+ async def _start_wrapper():
680
+ _start()
681
+
682
+ fsspec_asyn.sync(self.loop, _start_wrapper)
683
+ elif current_loop is not None:
684
+ # asynchronous=True: use the user's active event loop
685
+ self.loop = current_loop
686
+ _start()
687
+ else:
688
+ # asynchronous=True but called completely outside of an async context
689
+ raise RuntimeError("No event loop found")
690
+
691
+ logger.debug("BackgroundPrefetcher initialization complete.")
692
+
693
+ def __enter__(self):
694
+ """Context manager entry point."""
695
+ return self
696
+
697
+ def __exit__(self, exc_type, exc_val, exc_tb):
698
+ """Context manager exit point. Ensures the prefetcher is cleanly closed."""
699
+ self.close()
700
+
701
+ async def __aenter__(self):
702
+ """Async context manager entry point."""
703
+ return self
704
+
705
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
706
+ """Async context manager exit point. Ensures the prefetcher is cleanly closed."""
707
+ await self.aclose()
708
+
709
+ def set_error(self, e: Exception):
710
+ logger.error("Global error state set in BackgroundPrefetcher: %s", e)
711
+ self._error = e
712
+
713
+ async def _restart_producer(self, new_offset: int):
714
+ logger.debug(
715
+ "Handling seek request. Restarting producer at offset: %d", new_offset
716
+ )
717
+ self._error = None
718
+ await self.producer.restart(new_offset)
719
+ self.consumer.seek(new_offset)
720
+ self.read_tracker.clear()
721
+
722
+ async def _async_fetch(self, start, end):
723
+ """Core internal async fetching logic, protected safely by the async lock."""
724
+ async with self._async_lock:
725
+ try:
726
+ if self.is_stopped:
727
+ raise RuntimeError("The file instance has been closed.")
728
+
729
+ logger.debug("Executing _async_fetch for range %d - %d.", start, end)
730
+
731
+ # If the prefetcher is in error state, let's do a hard seek to start offset.
732
+ if self._error:
733
+ logger.info(
734
+ "Recovering from error state. Restarting producer at offset: %d",
735
+ start,
736
+ )
737
+ self.user_offset = start
738
+ await self._restart_producer(start)
739
+ elif start != self.user_offset:
740
+ block_offset = (
741
+ self.consumer.offset - self.consumer._current_block_idx
742
+ )
743
+ if self.user_offset < start <= self.producer.current_offset:
744
+ logger.debug(
745
+ "Soft seek detected. Skipping ahead from %d to %d.",
746
+ self.user_offset,
747
+ start,
748
+ )
749
+ skip_amount = start - self.user_offset
750
+ await self.consumer.skip(skip_amount)
751
+ self.user_offset = start
752
+ elif block_offset <= start < self.consumer.offset:
753
+ logger.debug(
754
+ "Local seek performed. User offset moved from %d to %d. "
755
+ "Adjusting buffer index from %d to %d.",
756
+ self.user_offset,
757
+ start,
758
+ self.consumer._current_block_idx,
759
+ start - block_offset,
760
+ )
761
+ self.consumer._current_block_idx = start - block_offset
762
+ self.consumer.offset = start
763
+ self.consumer.target_offset = start
764
+ self.user_offset = start
765
+ else:
766
+ logger.debug(
767
+ "Hard seek detected. Moving user offset from %d to %d.",
768
+ self.user_offset,
769
+ start,
770
+ )
771
+ self.user_offset = start
772
+ await self._restart_producer(start)
773
+
774
+ requested_size = end - start
775
+ self.read_tracker.add(requested_size)
776
+
777
+ chunk = await self.consumer.consume(requested_size)
778
+ self.user_offset += len(chunk)
779
+
780
+ logger.debug("Completed _async_fetch. Returned %d bytes.", len(chunk))
781
+ return chunk
782
+ except asyncio.CancelledError as e:
783
+ self._error = e
784
+ raise
785
+ except Exception as e:
786
+ logger.exception("Exception raised during asynchronous fetch.")
787
+ self._error = e
788
+ if self.producer and not self.producer.is_stopped:
789
+ await self.producer.stop()
790
+ raise
791
+
792
+ async def _async_close(self):
793
+ """Asynchronous teardown logic protected by the async lock.
794
+
795
+ Held for the duration of teardown so a concurrent in-flight
796
+ ``_async_fetch`` cannot observe a stopped producer/empty queue as
797
+ EOF and silently return a truncated read.
798
+ """
799
+ async with self._async_lock:
800
+ logger.debug("Signaling prefetcher stop and tearing down producer.")
801
+
802
+ if self.producer and not self.producer.is_stopped:
803
+ await self.producer.stop()
804
+
805
+ self.consumer.clear_buffer()
806
+ logger.debug("BackgroundPrefetcher closed successfully.")
807
+
808
+ async def afetch(self, start: int | None, end: int | None) -> bytes:
809
+ """Asynchronous API counterpart to `_fetch`."""
810
+ if start is None:
811
+ start = 0
812
+ if end is None:
813
+ end = self.size
814
+
815
+ end = min(end, self.size)
816
+ logger.debug(
817
+ "Asynchronous afetch called for bounds start=%s, end=%s.", start, end
818
+ )
819
+
820
+ if start >= self.size or start >= end:
821
+ return b""
822
+
823
+ if self.is_stopped:
824
+ logger.error(
825
+ "Cannot fetch data: BackgroundPrefetcher is stopped or closed."
826
+ )
827
+ raise RuntimeError(
828
+ "The file instance has been closed. This can occur if a close operation "
829
+ "is executed concurrently while a read operation is still in progress."
830
+ )
831
+
832
+ return await self._async_fetch(start, end)
833
+
834
+ def fetch(self, start: int | None, end: int | None) -> bytes:
835
+ """Synchronous API wrapper delegating to `afetch`."""
836
+ # Delegates all boundaries, checking, and fetching to the async event loop perfectly
837
+ return fsspec_asyn.sync(self.loop, self.afetch, start, end)
838
+
839
+ async def aclose(self):
840
+ """Safely shuts down the prefetcher from an asynchronous context."""
841
+ self.is_stopped = True
842
+ await self._async_close()
843
+
844
+ def close(self, timeout: float | None = 10.0):
845
+ """Safely shuts down the prefetcher from a synchronous context.
846
+
847
+ Schedules teardown on the IO loop. If the wait times out, teardown
848
+ continues in the background to let in-flight reads finish cleanly.
849
+
850
+ Args:
851
+ timeout: Maximum seconds to wait for teardown to finish. Defaults
852
+ to 10.0 seconds. If 0 or negative, teardown runs fire-and-forget.
853
+ If None, waits indefinitely.
854
+ """
855
+ self.is_stopped = True
856
+
857
+ try:
858
+ sync_teardown(
859
+ self.loop,
860
+ self._async_close,
861
+ timeout=timeout,
862
+ description="BackgroundPrefetcher teardown",
863
+ )
864
+ except fsspec_asyn.FSTimeoutError:
865
+ logger.warning(
866
+ "BackgroundPrefetcher teardown did not complete within %ss; "
867
+ "it will keep running in the background.",
868
+ timeout,
869
+ )
870
+ except Exception:
871
+ logger.warning(
872
+ "Exception while closing BackgroundPrefetcher", exc_info=True
873
+ )
venv/lib/python3.14/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)
venv/lib/python3.14/site-packages/fsspec/spec.py ADDED
@@ -0,0 +1,2353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
+ check_contained,
22
+ glob_translate,
23
+ isfilelike,
24
+ other_paths,
25
+ read_block,
26
+ stringify_path,
27
+ tokenize,
28
+ )
29
+
30
+ logger = logging.getLogger("fsspec")
31
+
32
+
33
+ def make_instance(cls, args, kwargs):
34
+ return cls(*args, **kwargs)
35
+
36
+
37
+ FORK_AVAILABLE = hasattr(os, "register_at_fork")
38
+
39
+
40
+ if FORK_AVAILABLE:
41
+ _registered_classes = weakref.WeakSet()
42
+
43
+ def _reset_instances_lock():
44
+ for cls in _registered_classes:
45
+ cls._instantiation_lock = threading.RLock()
46
+ cls._cache.clear()
47
+ cls._pid = os.getpid()
48
+
49
+ os.register_at_fork(after_in_child=_reset_instances_lock)
50
+
51
+
52
+ class _Cached(type):
53
+ """
54
+ Metaclass for caching file system instances.
55
+
56
+ Notes
57
+ -----
58
+ Instances are cached according to
59
+
60
+ * The values of the class attributes listed in `_extra_tokenize_attributes`
61
+ * The arguments passed to ``__init__``.
62
+
63
+ This creates an additional reference to the filesystem, which prevents the
64
+ filesystem from being garbage collected when all *user* references go away.
65
+ A call to the :meth:`AbstractFileSystem.clear_instance_cache` must *also*
66
+ be made for a filesystem instance to be garbage collected.
67
+ """
68
+
69
+ def __init__(cls, *args, **kwargs):
70
+ super().__init__(*args, **kwargs)
71
+
72
+ # Note: we intentionally create a reference here, to avoid garbage
73
+ # collecting instances when all other references are gone. To really
74
+ # delete a FileSystem, the cache must be cleared.
75
+ if conf.get("weakref_instance_cache"): # pragma: no cover
76
+ # debug option for analysing fork/spawn conditions
77
+ cls._cache = weakref.WeakValueDictionary()
78
+ else:
79
+ cls._cache = {}
80
+ cls._pid = os.getpid()
81
+ cls._instantiation_lock = threading.RLock()
82
+
83
+ if FORK_AVAILABLE:
84
+ _registered_classes.add(cls)
85
+
86
+ def _check_instance_cache(cls, token):
87
+ inst = cls._cache.get(token)
88
+ if inst is not None:
89
+ cls._latest = token
90
+ return inst
91
+
92
+ def __call__(cls, *args, **kwargs):
93
+ kwargs = apply_config(cls, kwargs)
94
+ extra_tokens = tuple(
95
+ getattr(cls, attr, None) for attr in cls._extra_tokenize_attributes
96
+ )
97
+ strip_tokenize_options = {
98
+ k: kwargs.pop(k) for k in cls._strip_tokenize_options if k in kwargs
99
+ }
100
+ pid = os.getpid()
101
+
102
+ if getattr(cls, "async_impl", False) and not kwargs.get("asynchronous", False):
103
+ token = tokenize(cls, pid, *args, *extra_tokens, **kwargs)
104
+ else:
105
+ token = tokenize(
106
+ cls, pid, threading.get_ident(), *args, *extra_tokens, **kwargs
107
+ )
108
+ skip = kwargs.pop("skip_instance_cache", False)
109
+
110
+ if pid != cls._pid:
111
+ with cls._instantiation_lock:
112
+ if pid != cls._pid:
113
+ cls._cache.clear()
114
+ cls._pid = pid
115
+
116
+ if not skip and cls.cachable:
117
+ inst = cls._check_instance_cache(token)
118
+ if inst is not None:
119
+ return inst
120
+
121
+ with cls._instantiation_lock:
122
+ # protect against the race condition that a new instance was created
123
+ # and inserted into the cache since the initial check just above
124
+ inst = cls._check_instance_cache(token)
125
+ if inst is not None:
126
+ return inst
127
+
128
+ obj = super().__call__(*args, **kwargs, **strip_tokenize_options)
129
+ # Setting _fs_token here causes some static linters to complain.
130
+ obj._fs_token_ = token
131
+ obj.storage_args = args
132
+ obj.storage_options = kwargs
133
+ if obj.async_impl and obj.mirror_sync_methods:
134
+ from .asyn import mirror_sync_methods
135
+
136
+ mirror_sync_methods(obj)
137
+
138
+ if cls.cachable and not skip:
139
+ with cls._instantiation_lock:
140
+ # another thread may have created the instance while we were calling
141
+ # super().__call__(), so we check again.
142
+ inst = cls._check_instance_cache(token)
143
+ if inst is not None:
144
+ return inst
145
+
146
+ cls._latest = token
147
+ cls._cache[token] = obj
148
+ return obj
149
+
150
+
151
+ class AbstractFileSystem(metaclass=_Cached):
152
+ """
153
+ An abstract super-class for pythonic file-systems
154
+
155
+ Implementations are expected to be compatible with or, better, subclass
156
+ from here.
157
+ """
158
+
159
+ cachable = True # this class can be cached, instances reused
160
+ _cached = False
161
+ blocksize = 2**22
162
+ sep = "/"
163
+ # Implementations may select their protocol per instance (for example, a
164
+ # single adapter class backed by different storage implementations).
165
+ protocol: str | tuple[str, ...] = "abstract"
166
+ _latest = None
167
+ async_impl = False
168
+ mirror_sync_methods = False
169
+ root_marker = "" # For some FSs, may require leading '/' or other character
170
+ transaction_type = Transaction
171
+
172
+ #: Extra *class attributes* that should be considered when hashing.
173
+ _extra_tokenize_attributes = ()
174
+ #: *storage options* that should not be considered when hashing.
175
+ _strip_tokenize_options = ()
176
+
177
+ # Set by _Cached metaclass
178
+ storage_args: tuple[Any, ...]
179
+ storage_options: dict[str, Any]
180
+
181
+ def __init__(self, *args, **storage_options):
182
+ """Create and configure file-system instance
183
+
184
+ Instances may be cachable, so if similar enough arguments are seen
185
+ a new instance is not required. The token attribute exists to allow
186
+ implementations to cache instances if they wish.
187
+
188
+ A reasonable default should be provided if there are no arguments.
189
+
190
+ Subclasses should call this method.
191
+
192
+ Parameters
193
+ ----------
194
+ use_listings_cache, listings_expiry_time, max_paths:
195
+ passed to ``DirCache``, if the implementation supports
196
+ directory listing caching. Pass use_listings_cache=False
197
+ to disable such caching.
198
+ skip_instance_cache: bool
199
+ If this is a cachable implementation, pass True here to force
200
+ creating a new instance even if a matching instance exists, and prevent
201
+ storing this instance.
202
+ asynchronous: bool
203
+ loop: asyncio-compatible IOLoop or None
204
+ """
205
+ if self._cached:
206
+ # reusing instance, don't change
207
+ return
208
+ self._cached = True
209
+ self._intrans = False
210
+ self._transaction = None
211
+ self._invalidated_caches_in_transaction = []
212
+ self.dircache = DirCache(**storage_options)
213
+
214
+ if storage_options.pop("add_docs", None):
215
+ warnings.warn("add_docs is no longer supported.", FutureWarning)
216
+
217
+ if storage_options.pop("add_aliases", None):
218
+ warnings.warn("add_aliases has been removed.", FutureWarning)
219
+ # This is set in _Cached
220
+ self._fs_token_ = None
221
+
222
+ @property
223
+ def fsid(self):
224
+ """Persistent filesystem id that can be used to compare filesystems
225
+ across sessions.
226
+ """
227
+ raise NotImplementedError
228
+
229
+ @property
230
+ def _fs_token(self):
231
+ return self._fs_token_
232
+
233
+ def __dask_tokenize__(self):
234
+ return self._fs_token
235
+
236
+ def __hash__(self):
237
+ return int(self._fs_token, 16)
238
+
239
+ def __eq__(self, other):
240
+ return isinstance(other, type(self)) and self._fs_token == other._fs_token
241
+
242
+ def __reduce__(self):
243
+ return make_instance, (type(self), self.storage_args, self.storage_options)
244
+
245
+ @classmethod
246
+ def _strip_protocol(cls, path):
247
+ """Turn path from fully-qualified to file-system-specific
248
+
249
+ May require FS-specific handling, e.g., for relative paths or links.
250
+ """
251
+ if isinstance(path, list):
252
+ return [cls._strip_protocol(p) for p in path]
253
+ path = stringify_path(path)
254
+ protos = (cls.protocol,) if isinstance(cls.protocol, str) else cls.protocol
255
+ for protocol in protos:
256
+ if path.startswith(protocol + "://"):
257
+ path = path[len(protocol) + 3 :]
258
+ elif path.startswith(protocol + "::"):
259
+ path = path[len(protocol) + 2 :]
260
+ path = path.rstrip("/")
261
+ # use of root_marker to make minimum required path, e.g., "/"
262
+ return path or cls.root_marker
263
+
264
+ def unstrip_protocol(self, name: str) -> str:
265
+ """Format FS-specific path to generic, including protocol"""
266
+ protos = (self.protocol,) if isinstance(self.protocol, str) else self.protocol
267
+ for protocol in protos:
268
+ if name.startswith(f"{protocol}://"):
269
+ return name
270
+ return f"{protos[0]}://{name}"
271
+
272
+ @staticmethod
273
+ def _get_kwargs_from_urls(path):
274
+ """If kwargs can be encoded in the paths, extract them here
275
+
276
+ This should happen before instantiation of the class; incoming paths
277
+ then should be amended to strip the options in methods.
278
+
279
+ Examples may look like an sftp path "sftp://user@host:/my/path", where
280
+ the user and host should become kwargs and later get stripped.
281
+ """
282
+ # by default, nothing happens
283
+ return {}
284
+
285
+ @classmethod
286
+ def current(cls):
287
+ """Return the most recently instantiated FileSystem
288
+
289
+ If no instance has been created, then create one with defaults
290
+ """
291
+ inst = cls._cache.get(cls._latest)
292
+ if inst is not None:
293
+ return inst
294
+ return cls()
295
+
296
+ @property
297
+ def transaction(self):
298
+ """A context within which files are committed together upon exit
299
+
300
+ Requires the file class to implement `.commit()` and `.discard()`
301
+ for the normal and exception cases.
302
+ """
303
+ if self._transaction is None:
304
+ self._transaction = self.transaction_type(self)
305
+ return self._transaction
306
+
307
+ def start_transaction(self):
308
+ """Begin write transaction for deferring files, non-context version"""
309
+ self._intrans = True
310
+ self._transaction = self.transaction_type(self)
311
+ return self.transaction
312
+
313
+ def end_transaction(self):
314
+ """Finish write transaction, non-context version"""
315
+ self.transaction.complete()
316
+ self._transaction = None
317
+ # The invalid cache must be cleared after the transaction is completed.
318
+ for path in self._invalidated_caches_in_transaction:
319
+ self.invalidate_cache(path)
320
+ self._invalidated_caches_in_transaction.clear()
321
+
322
+ def invalidate_cache(self, path=None):
323
+ """
324
+ Discard any cached directory information
325
+
326
+ Parameters
327
+ ----------
328
+ path: string or None
329
+ If None, clear all listings cached else listings at or under given
330
+ path.
331
+ """
332
+ # Not necessary to implement invalidation mechanism, may have no cache.
333
+ # But if have, you should call this method of parent class from your
334
+ # subclass to ensure expiring caches after transacations correctly.
335
+ # See the implementation of FTPFileSystem in ftp.py
336
+ if self._intrans:
337
+ self._invalidated_caches_in_transaction.append(path)
338
+
339
+ def mkdir(self, path, create_parents=True, **kwargs):
340
+ """
341
+ Create directory entry at path
342
+
343
+ For systems that don't have true directories, may create an for
344
+ this instance only and not touch the real filesystem
345
+
346
+ Parameters
347
+ ----------
348
+ path: str
349
+ location
350
+ create_parents: bool
351
+ if True, this is equivalent to ``makedirs``
352
+ kwargs:
353
+ may be permissions, etc.
354
+ """
355
+ pass # not necessary to implement, may not have directories
356
+
357
+ def makedirs(self, path, exist_ok=False):
358
+ """Recursively make directories
359
+
360
+ Creates directory at path and any intervening required directories.
361
+ Raises exception if, for instance, the path already exists but is a
362
+ file.
363
+
364
+ Parameters
365
+ ----------
366
+ path: str
367
+ leaf directory name
368
+ exist_ok: bool (False)
369
+ If False, will error if the target already exists
370
+ """
371
+ pass # not necessary to implement, may not have directories
372
+
373
+ def rmdir(self, path):
374
+ """Remove a directory, if empty"""
375
+ pass # not necessary to implement, may not have directories
376
+
377
+ def ls(self, path, detail=True, **kwargs):
378
+ """List objects at path.
379
+
380
+ This should include subdirectories and files at that location. The
381
+ difference between a file and a directory must be clear when details
382
+ are requested.
383
+
384
+ The specific keys, or perhaps a FileInfo class, or similar, is TBD,
385
+ but must be consistent across implementations.
386
+ Must include:
387
+
388
+ - full path to the entry (without protocol)
389
+ - size of the entry, in bytes. If the value cannot be determined, will
390
+ be ``None``.
391
+ - type of entry, "file", "directory" or other
392
+
393
+ Additional information
394
+ may be present, appropriate to the file-system, e.g., generation,
395
+ checksum, etc.
396
+
397
+ May use refresh=True|False to allow use of self._ls_from_cache to
398
+ check for a saved listing and avoid calling the backend. This would be
399
+ common where listing may be expensive.
400
+
401
+ Parameters
402
+ ----------
403
+ path: str
404
+ detail: bool
405
+ if True, gives a list of dictionaries, where each is the same as
406
+ the result of ``info(path)``. If False, gives a list of paths
407
+ (str).
408
+ kwargs: may have additional backend-specific options, such as version
409
+ information
410
+
411
+ Returns
412
+ -------
413
+ List of strings if detail is False, or list of directory information
414
+ dicts if detail is True.
415
+ """
416
+ raise NotImplementedError
417
+
418
+ def _ls_from_cache(self, path):
419
+ """Check cache for listing
420
+
421
+ Returns listing, if found (may be empty list for a directly that exists
422
+ but contains nothing), None if not in cache.
423
+ """
424
+ parent = self._parent(path)
425
+ try:
426
+ return self.dircache[path.rstrip("/")]
427
+ except KeyError:
428
+ pass
429
+ try:
430
+ files = [
431
+ f
432
+ for f in self.dircache[parent]
433
+ if f["name"] == path
434
+ or (f["name"] == path.rstrip("/") and f["type"] == "directory")
435
+ ]
436
+ if len(files) == 0:
437
+ # parent dir was listed but did not contain this file
438
+ raise FileNotFoundError(path)
439
+ return files
440
+ except KeyError:
441
+ pass
442
+
443
+ def walk(self, path, maxdepth=None, topdown=True, on_error="omit", **kwargs):
444
+ """Return all files under the given path.
445
+
446
+ List all files, recursing into subdirectories; output is iterator-style,
447
+ like ``os.walk()``. For a simple list of files, ``find()`` is available.
448
+
449
+ When topdown is True, the caller can modify the dirnames list in-place (perhaps
450
+ using del or slice assignment), and walk() will
451
+ only recurse into the subdirectories whose names remain in dirnames;
452
+ this can be used to prune the search, impose a specific order of visiting,
453
+ or even to inform walk() about directories the caller creates or renames before
454
+ it resumes walk() again.
455
+ Modifying dirnames when topdown is False has no effect. (see os.walk)
456
+
457
+ Note that the "files" outputted will include anything that is not
458
+ a directory, such as links.
459
+
460
+ Parameters
461
+ ----------
462
+ path: str
463
+ Root to recurse into
464
+ maxdepth: int
465
+ Maximum recursion depth. None means limitless, but not recommended
466
+ on link-based file-systems.
467
+ topdown: bool (True)
468
+ Whether to walk the directory tree from the top downwards or from
469
+ the bottom upwards.
470
+ on_error: "omit", "raise", a callable
471
+ if omit (default), path with exception will simply be empty;
472
+ If raise, an underlying exception will be raised;
473
+ if callable, it will be called with a single OSError instance as argument
474
+ kwargs: passed to ``ls``
475
+ """
476
+ if maxdepth is not None and maxdepth < 1:
477
+ raise ValueError("maxdepth must be at least 1")
478
+
479
+ path = self._strip_protocol(path)
480
+ full_dirs = {}
481
+ dirs = {}
482
+ files = {}
483
+
484
+ detail = kwargs.pop("detail", False)
485
+ try:
486
+ listing = self.ls(path, detail=True, **kwargs)
487
+ except (FileNotFoundError, OSError) as e:
488
+ if on_error == "raise":
489
+ raise
490
+ if callable(on_error):
491
+ on_error(e)
492
+ return
493
+
494
+ for info in listing:
495
+ # each info name must be at least [path]/part , but here
496
+ # we check also for names like [path]/part/
497
+ pathname = info["name"].rstrip("/")
498
+ name = pathname.rsplit("/", 1)[-1]
499
+ if info["type"] == "directory" and pathname != path:
500
+ # do not include "self" path
501
+ full_dirs[name] = pathname
502
+ dirs[name] = info
503
+ elif pathname == path:
504
+ # file-like with same name as give path
505
+ files[""] = info
506
+ else:
507
+ files[name] = info
508
+
509
+ if not detail:
510
+ dirs = list(dirs)
511
+ files = list(files)
512
+
513
+ if topdown:
514
+ # Yield before recursion if walking top down
515
+ yield path, dirs, files
516
+
517
+ if maxdepth is not None:
518
+ maxdepth -= 1
519
+ if maxdepth < 1:
520
+ if not topdown:
521
+ yield path, dirs, files
522
+ return
523
+
524
+ for d in dirs:
525
+ yield from self.walk(
526
+ full_dirs[d],
527
+ maxdepth=maxdepth,
528
+ detail=detail,
529
+ topdown=topdown,
530
+ **kwargs,
531
+ )
532
+
533
+ if not topdown:
534
+ # Yield after recursion if walking bottom up
535
+ yield path, dirs, files
536
+
537
+ def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
538
+ """List all files below path.
539
+
540
+ Like posix ``find`` command without conditions
541
+
542
+ Parameters
543
+ ----------
544
+ path : str
545
+ maxdepth: int or None
546
+ If not None, the maximum number of levels to descend
547
+ withdirs: bool
548
+ Whether to include directory paths in the output. This is True
549
+ when used by glob, but users usually only want files.
550
+ kwargs are passed to ``ls``.
551
+ """
552
+ # TODO: allow equivalent of -name parameter
553
+ path = self._strip_protocol(path)
554
+ out = {}
555
+
556
+ # Add the root directory if withdirs is requested
557
+ # This is needed for posix glob compliance
558
+ if withdirs and path != "" and self.isdir(path):
559
+ out[path] = self.info(path)
560
+
561
+ for _, dirs, files in self.walk(path, maxdepth, detail=True, **kwargs):
562
+ if withdirs:
563
+ files.update(dirs)
564
+ out.update({info["name"]: info for name, info in files.items()})
565
+ if not out and self.isfile(path):
566
+ # walk works on directories, but find should also return [path]
567
+ # when path happens to be a file
568
+ out[path] = {}
569
+ names = sorted(out)
570
+ if not detail:
571
+ return names
572
+ else:
573
+ return {name: out[name] for name in names}
574
+
575
+ def du(self, path, total=True, maxdepth=None, withdirs=False, **kwargs):
576
+ """Space used by files and optionally directories within a path
577
+
578
+ Directory size does not include the size of its contents.
579
+
580
+ Parameters
581
+ ----------
582
+ path: str
583
+ total: bool
584
+ Whether to sum all the file sizes
585
+ maxdepth: int or None
586
+ Maximum number of directory levels to descend, None for unlimited.
587
+ withdirs: bool
588
+ Whether to include directory paths in the output.
589
+ kwargs: passed to ``find``
590
+
591
+ Returns
592
+ -------
593
+ Dict of {path: size} if total=False, or int otherwise, where numbers
594
+ refer to bytes used.
595
+ """
596
+ sizes = {}
597
+ if withdirs and self.isdir(path):
598
+ # Include top-level directory in output
599
+ info = self.info(path)
600
+ sizes[info["name"]] = info["size"]
601
+ for f in self.find(path, maxdepth=maxdepth, withdirs=withdirs, **kwargs):
602
+ info = self.info(f)
603
+ sizes[info["name"]] = info["size"]
604
+ if total:
605
+ return sum(sizes.values())
606
+ else:
607
+ return sizes
608
+
609
+ def glob(self, path, maxdepth=None, **kwargs):
610
+ """Find files by glob-matching.
611
+
612
+ Pattern matching capabilities for finding files that match the given pattern.
613
+
614
+ Parameters
615
+ ----------
616
+ path: str
617
+ The glob pattern to match against
618
+ maxdepth: int or None
619
+ Maximum depth for ``'**'`` patterns. Applied on the first ``'**'`` found.
620
+ Must be at least 1 if provided.
621
+ kwargs:
622
+ Additional arguments passed to ``find`` (e.g., detail=True)
623
+
624
+ Returns
625
+ -------
626
+ List of matched paths, or dict of paths and their info if detail=True
627
+
628
+ Notes
629
+ -----
630
+ Supported patterns:
631
+ - '*': Matches any sequence of characters within a single directory level
632
+ - ``'**'``: Matches any number of directory levels (must be an entire path component)
633
+ - '?': Matches exactly one character
634
+ - '[abc]': Matches any character in the set
635
+ - '[a-z]': Matches any character in the range
636
+ - '[!abc]': Matches any character NOT in the set
637
+
638
+ Special behaviors:
639
+ - If the path ends with '/', only folders are returned
640
+ - Consecutive '*' characters are compressed into a single '*'
641
+ - Empty set '[]' or negated empty negated set '[!]' never match anything
642
+ - Special characters in character classes are escaped properly
643
+
644
+ Limitations:
645
+ - ``'**'`` must be a complete path component (e.g., ``'a/**/b'``, not ``'a**b'``)
646
+ - No brace expansion ('{a,b}.txt')
647
+ - No extended glob patterns ('+(pattern)', '!(pattern)')
648
+ """
649
+ if maxdepth is not None and maxdepth < 1:
650
+ raise ValueError("maxdepth must be at least 1")
651
+
652
+ import re
653
+
654
+ seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,)
655
+ ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash
656
+ path = self._strip_protocol(path)
657
+ append_slash_to_dirname = ends_with_sep or path.endswith(
658
+ tuple(sep + "**" for sep in seps)
659
+ )
660
+ idx_star = path.find("*") if path.find("*") >= 0 else len(path)
661
+ idx_qmark = path.find("?") if path.find("?") >= 0 else len(path)
662
+ idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
663
+
664
+ min_idx = min(idx_star, idx_qmark, idx_brace)
665
+
666
+ detail = kwargs.pop("detail", False)
667
+ withdirs = kwargs.pop("withdirs", True)
668
+
669
+ if not has_magic(path):
670
+ if self.exists(path, **kwargs):
671
+ if not detail:
672
+ return [path]
673
+ else:
674
+ return {path: self.info(path, **kwargs)}
675
+ else:
676
+ if not detail:
677
+ return [] # glob of non-existent returns empty
678
+ else:
679
+ return {}
680
+ elif "/" in path[:min_idx]:
681
+ min_idx = path[:min_idx].rindex("/")
682
+ root = path[: min_idx + 1]
683
+ depth = path[min_idx + 1 :].count("/") + 1
684
+ else:
685
+ root = ""
686
+ depth = path[min_idx + 1 :].count("/") + 1
687
+
688
+ if "**" in path:
689
+ if maxdepth is not None:
690
+ idx_double_stars = path.find("**")
691
+ depth_double_stars = path[idx_double_stars:].count("/") + 1
692
+ depth = depth - depth_double_stars + maxdepth
693
+ else:
694
+ depth = None
695
+
696
+ allpaths = self.find(
697
+ root, maxdepth=depth, withdirs=withdirs, detail=True, **kwargs
698
+ )
699
+
700
+ pattern = glob_translate(path + ("/" if ends_with_sep else ""))
701
+ pattern = re.compile(pattern)
702
+
703
+ out = {
704
+ p: info
705
+ for p, info in sorted(allpaths.items())
706
+ if pattern.match(
707
+ p + "/"
708
+ if append_slash_to_dirname and info["type"] == "directory"
709
+ else p
710
+ )
711
+ }
712
+
713
+ if detail:
714
+ return out
715
+ else:
716
+ return list(out)
717
+
718
+ def exists(self, path, **kwargs):
719
+ """Is there a file at the given path"""
720
+ try:
721
+ self.info(path, **kwargs)
722
+ return True
723
+ except: # noqa: E722
724
+ # any exception allowed bar FileNotFoundError?
725
+ return False
726
+
727
+ def lexists(self, path, **kwargs):
728
+ """If there is a file at the given path (including
729
+ broken links)"""
730
+ return self.exists(path)
731
+
732
+ def info(self, path, **kwargs):
733
+ """Give details of entry at path
734
+
735
+ Returns a single dictionary, with exactly the same information as ``ls``
736
+ would with ``detail=True``.
737
+
738
+ The default implementation calls ls and could be overridden by a
739
+ shortcut. kwargs are passed on to ```ls()``.
740
+
741
+ Some file systems might not be able to measure the file's size, in
742
+ which case, the returned dict will include ``'size': None``.
743
+
744
+ Returns
745
+ -------
746
+ dict with keys: name (full path in the FS), size (in bytes), type (file,
747
+ directory, or something else) and other FS-specific keys.
748
+ """
749
+ path = self._strip_protocol(path)
750
+ out = self.ls(self._parent(path), detail=True, **kwargs)
751
+ out = [o for o in out if o["name"].rstrip("/") == path]
752
+ if out:
753
+ return out[0]
754
+ out = self.ls(path, detail=True, **kwargs)
755
+ path = path.rstrip("/")
756
+ out1 = [o for o in out if o["name"].rstrip("/") == path]
757
+ if len(out1) == 1:
758
+ if "size" not in out1[0]:
759
+ out1[0]["size"] = None
760
+ return out1[0]
761
+ elif len(out1) > 1 or out:
762
+ return {"name": path, "size": 0, "type": "directory"}
763
+ else:
764
+ raise FileNotFoundError(path)
765
+
766
+ def checksum(self, path):
767
+ """Unique value for current version of file
768
+
769
+ If the checksum is the same from one moment to another, the contents
770
+ are guaranteed to be the same. If the checksum changes, the contents
771
+ *might* have changed.
772
+
773
+ This should normally be overridden; default will probably capture
774
+ creation/modification timestamp (which would be good) or maybe
775
+ access timestamp (which would be bad)
776
+ """
777
+ return int(tokenize(self.info(path)), 16)
778
+
779
+ def size(self, path):
780
+ """Size in bytes of file"""
781
+ return self.info(path).get("size", None)
782
+
783
+ def sizes(self, paths):
784
+ """Size in bytes of each file in a list of paths"""
785
+ return [self.size(p) for p in paths]
786
+
787
+ def isdir(self, path):
788
+ """Is this entry directory-like?"""
789
+ try:
790
+ return self.info(path)["type"] == "directory"
791
+ except OSError:
792
+ return False
793
+
794
+ def isfile(self, path):
795
+ """Is this entry file-like?"""
796
+ try:
797
+ return self.info(path)["type"] == "file"
798
+ except Exception:
799
+ return False
800
+
801
+ def read_text(self, path, encoding=None, errors=None, newline=None, **kwargs):
802
+ """Get the contents of the file as a string.
803
+
804
+ Parameters
805
+ ----------
806
+ path: str
807
+ URL of file on this filesystems
808
+ encoding, errors, newline: same as `open`.
809
+ """
810
+ with self.open(
811
+ path,
812
+ mode="r",
813
+ encoding=encoding,
814
+ errors=errors,
815
+ newline=newline,
816
+ **kwargs,
817
+ ) as f:
818
+ return f.read()
819
+
820
+ def write_text(
821
+ self, path, value, encoding=None, errors=None, newline=None, **kwargs
822
+ ):
823
+ """Write the text to the given file.
824
+
825
+ An existing file will be overwritten.
826
+
827
+ Parameters
828
+ ----------
829
+ path: str
830
+ URL of file on this filesystems
831
+ value: str
832
+ Text to write.
833
+ encoding, errors, newline: same as `open`.
834
+ """
835
+ with self.open(
836
+ path,
837
+ mode="w",
838
+ encoding=encoding,
839
+ errors=errors,
840
+ newline=newline,
841
+ **kwargs,
842
+ ) as f:
843
+ return f.write(value)
844
+
845
+ def cat_file(self, path, start=None, end=None, **kwargs):
846
+ """Get the content of a file
847
+
848
+ Parameters
849
+ ----------
850
+ path: URL of file on this filesystems
851
+ start, end: int
852
+ Bytes limits of the read. If negative, backwards from end,
853
+ like usual python slices. Either can be None for start or
854
+ end of file, respectively
855
+ kwargs: passed to ``open()``.
856
+ """
857
+ # explicitly set buffering off?
858
+ with self.open(path, "rb", **kwargs) as f:
859
+ if start is not None:
860
+ if start >= 0:
861
+ f.seek(start)
862
+ else:
863
+ f.seek(max(0, f.size + start))
864
+ if end is not None:
865
+ if end < 0:
866
+ end = f.size + end
867
+ return f.read(end - f.tell())
868
+ return f.read()
869
+
870
+ def pipe_file(self, path, value, mode="overwrite", **kwargs):
871
+ """Set the bytes of given file"""
872
+ if mode == "create" and self.exists(path):
873
+ # non-atomic but simple way; or could use "xb" in open(), which is likely
874
+ # not as well supported
875
+ raise FileExistsError
876
+ with self.open(path, "wb", **kwargs) as f:
877
+ f.write(value)
878
+
879
+ def pipe(self, path, value=None, **kwargs):
880
+ """Put value into path
881
+
882
+ (counterpart to ``cat``)
883
+
884
+ Parameters
885
+ ----------
886
+ path: string or dict(str, bytes)
887
+ If a string, a single remote location to put ``value`` bytes; if a dict,
888
+ a mapping of {path: bytesvalue}.
889
+ value: bytes, optional
890
+ If using a single path, these are the bytes to put there. Ignored if
891
+ ``path`` is a dict
892
+ """
893
+ if isinstance(path, str):
894
+ self.pipe_file(self._strip_protocol(path), value, **kwargs)
895
+ elif isinstance(path, dict):
896
+ for k, v in path.items():
897
+ self.pipe_file(self._strip_protocol(k), v, **kwargs)
898
+ else:
899
+ raise ValueError("path must be str or dict")
900
+
901
+ def cat_ranges(
902
+ self, paths, starts, ends, max_gap=None, on_error="return", **kwargs
903
+ ):
904
+ """Get the contents of byte ranges from one or more files
905
+
906
+ Parameters
907
+ ----------
908
+ paths: list
909
+ A list of of filepaths on this filesystems
910
+ starts, ends: int or list
911
+ Bytes limits of the read. If using a single int, the same value will be
912
+ used to read all the specified files.
913
+ """
914
+ if max_gap is not None:
915
+ raise NotImplementedError
916
+ if not isinstance(paths, list):
917
+ raise TypeError
918
+ if not isinstance(starts, list):
919
+ starts = [starts] * len(paths)
920
+ if not isinstance(ends, list):
921
+ ends = [ends] * len(paths)
922
+ if len(starts) != len(paths) or len(ends) != len(paths):
923
+ raise ValueError
924
+ out = []
925
+ for p, s, e in zip(paths, starts, ends):
926
+ try:
927
+ out.append(self.cat_file(p, s, e, **kwargs))
928
+ except Exception as e:
929
+ if on_error == "return":
930
+ out.append(e)
931
+ else:
932
+ raise
933
+ return out
934
+
935
+ def cat(self, path, recursive=False, on_error="raise", **kwargs):
936
+ """Fetch (potentially multiple) paths' contents
937
+
938
+ Parameters
939
+ ----------
940
+ recursive: bool
941
+ If True, assume the path(s) are directories, and get all the
942
+ contained files
943
+ on_error : "raise", "omit", "return"
944
+ If raise, an underlying exception will be raised (converted to KeyError
945
+ if the type is in self.missing_exceptions); if omit, keys with exception
946
+ will simply not be included in the output; if "return", all keys are
947
+ included in the output, but the value will be bytes or an exception
948
+ instance.
949
+ kwargs: passed to cat_file
950
+
951
+ Returns
952
+ -------
953
+ dict of {path: contents} if there are multiple paths
954
+ or the path has been otherwise expanded
955
+ """
956
+ paths = self.expand_path(path, recursive=recursive, **kwargs)
957
+ if (
958
+ len(paths) > 1
959
+ or isinstance(path, list)
960
+ or paths[0] != self._strip_protocol(path)
961
+ ):
962
+ out = {}
963
+ for path in paths:
964
+ try:
965
+ out[path] = self.cat_file(path, **kwargs)
966
+ except Exception as e:
967
+ if on_error == "raise":
968
+ raise
969
+ if on_error == "return":
970
+ out[path] = e
971
+ return out
972
+ else:
973
+ return self.cat_file(paths[0], **kwargs)
974
+
975
+ def get_file(
976
+ self, rpath, lpath=None, callback=DEFAULT_CALLBACK, outfile=None, **kwargs
977
+ ):
978
+ """Copy single remote file to local"""
979
+ from .implementations.local import LocalFileSystem
980
+
981
+ if outfile is None and isfilelike(lpath):
982
+ outfile = lpath
983
+ elif outfile is None and self.isdir(rpath):
984
+ os.makedirs(lpath, exist_ok=True)
985
+ return None
986
+
987
+ if outfile is None:
988
+ fs = LocalFileSystem(auto_mkdir=True)
989
+ fs.makedirs(fs._parent(lpath), exist_ok=True)
990
+
991
+ with self.open(rpath, "rb", **kwargs) as f1:
992
+ close_outfile = outfile is None
993
+ if close_outfile:
994
+ outfile = open(lpath, "wb")
995
+
996
+ try:
997
+ callback.set_size(getattr(f1, "size", None))
998
+ data = True
999
+ while data:
1000
+ data = f1.read(self.blocksize)
1001
+ segment_len = outfile.write(data)
1002
+ if segment_len is None:
1003
+ segment_len = len(data)
1004
+ callback.relative_update(segment_len)
1005
+ finally:
1006
+ if close_outfile:
1007
+ outfile.close()
1008
+
1009
+ def get(
1010
+ self,
1011
+ rpath,
1012
+ lpath,
1013
+ recursive=False,
1014
+ callback=DEFAULT_CALLBACK,
1015
+ maxdepth=None,
1016
+ **kwargs,
1017
+ ):
1018
+ """Copy file(s) to local.
1019
+
1020
+ Copies a specific file or tree of files (if recursive=True). If lpath
1021
+ ends with a "/", it will be assumed to be a directory, and target files
1022
+ will go within. Can submit a list of paths, which may be glob-patterns
1023
+ and will be expanded.
1024
+
1025
+ Calls get_file for each source.
1026
+ """
1027
+ if isinstance(lpath, list) and isinstance(rpath, list):
1028
+ # No need to expand paths when both source and destination
1029
+ # are provided as lists
1030
+ rpaths = rpath
1031
+ lpaths = lpath
1032
+ else:
1033
+ from .implementations.local import (
1034
+ LocalFileSystem,
1035
+ make_path_posix,
1036
+ trailing_sep,
1037
+ )
1038
+
1039
+ source_is_str = isinstance(rpath, str)
1040
+ rpaths = self.expand_path(
1041
+ rpath, recursive=recursive, maxdepth=maxdepth, **kwargs
1042
+ )
1043
+ if source_is_str and (not recursive or maxdepth is not None):
1044
+ # Non-recursive glob does not copy directories
1045
+ rpaths = [p for p in rpaths if not (trailing_sep(p) or self.isdir(p))]
1046
+ if not rpaths:
1047
+ return
1048
+
1049
+ if isinstance(lpath, str):
1050
+ lpath = make_path_posix(lpath)
1051
+
1052
+ source_is_file = len(rpaths) == 1
1053
+ dest_is_dir = isinstance(lpath, str) and (
1054
+ trailing_sep(lpath) or LocalFileSystem().isdir(lpath)
1055
+ )
1056
+
1057
+ exists = source_is_str and (
1058
+ (has_magic(rpath) and source_is_file)
1059
+ or (not has_magic(rpath) and dest_is_dir and not trailing_sep(rpath))
1060
+ )
1061
+ lpaths = other_paths(
1062
+ rpaths,
1063
+ lpath,
1064
+ exists=exists,
1065
+ flatten=not source_is_str,
1066
+ )
1067
+ if isinstance(lpath, str):
1068
+ # The names came from the source listing; ".." in one of them
1069
+ # would otherwise place the copy above the destination. When
1070
+ # lpath is a list the caller named every destination itself.
1071
+ check_contained(lpath, lpaths)
1072
+
1073
+ callback.set_size(len(lpaths))
1074
+ for lpath, rpath in callback.wrap(zip(lpaths, rpaths)):
1075
+ with callback.branched(rpath, lpath) as child:
1076
+ self.get_file(rpath, lpath, callback=child, **kwargs)
1077
+
1078
+ def put_file(
1079
+ self, lpath, rpath, callback=DEFAULT_CALLBACK, mode="overwrite", **kwargs
1080
+ ):
1081
+ """Copy single file to remote"""
1082
+ if mode == "create" and self.exists(rpath):
1083
+ raise FileExistsError
1084
+ if os.path.isdir(lpath):
1085
+ self.makedirs(rpath, exist_ok=True)
1086
+ return None
1087
+
1088
+ with open(lpath, "rb") as f1:
1089
+ size = f1.seek(0, 2)
1090
+ callback.set_size(size)
1091
+ f1.seek(0)
1092
+
1093
+ self.mkdirs(self._parent(os.fspath(rpath)), exist_ok=True)
1094
+ with self.open(rpath, "wb", **kwargs) as f2:
1095
+ while f1.tell() < size:
1096
+ data = f1.read(self.blocksize)
1097
+ segment_len = f2.write(data)
1098
+ if segment_len is None:
1099
+ segment_len = len(data)
1100
+ callback.relative_update(segment_len)
1101
+
1102
+ def put(
1103
+ self,
1104
+ lpath,
1105
+ rpath,
1106
+ recursive=False,
1107
+ callback=DEFAULT_CALLBACK,
1108
+ maxdepth=None,
1109
+ **kwargs,
1110
+ ):
1111
+ """Copy file(s) from local.
1112
+
1113
+ Copies a specific file or tree of files (if recursive=True). If rpath
1114
+ ends with a "/", it will be assumed to be a directory, and target files
1115
+ will go within.
1116
+
1117
+ Calls put_file for each source.
1118
+ """
1119
+ if isinstance(lpath, list) and isinstance(rpath, list):
1120
+ # No need to expand paths when both source and destination
1121
+ # are provided as lists
1122
+ rpaths = rpath
1123
+ lpaths = lpath
1124
+ else:
1125
+ from .implementations.local import (
1126
+ LocalFileSystem,
1127
+ make_path_posix,
1128
+ trailing_sep,
1129
+ )
1130
+
1131
+ source_is_str = isinstance(lpath, str)
1132
+ if source_is_str:
1133
+ lpath = make_path_posix(lpath)
1134
+ fs = LocalFileSystem()
1135
+ lpaths = fs.expand_path(
1136
+ lpath, recursive=recursive, maxdepth=maxdepth, **kwargs
1137
+ )
1138
+ if source_is_str and (not recursive or maxdepth is not None):
1139
+ # Non-recursive glob does not copy directories
1140
+ lpaths = [p for p in lpaths if not (trailing_sep(p) or fs.isdir(p))]
1141
+ if not lpaths:
1142
+ return
1143
+
1144
+ source_is_file = len(lpaths) == 1
1145
+ dest_is_dir = isinstance(rpath, str) and (
1146
+ trailing_sep(rpath) or self.isdir(rpath)
1147
+ )
1148
+
1149
+ rpath = (
1150
+ self._strip_protocol(rpath)
1151
+ if isinstance(rpath, str)
1152
+ else [self._strip_protocol(p) for p in rpath]
1153
+ )
1154
+ exists = source_is_str and (
1155
+ (has_magic(lpath) and source_is_file)
1156
+ or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath))
1157
+ )
1158
+ rpaths = other_paths(
1159
+ lpaths,
1160
+ rpath,
1161
+ exists=exists,
1162
+ flatten=not source_is_str,
1163
+ )
1164
+
1165
+ callback.set_size(len(rpaths))
1166
+ for lpath, rpath in callback.wrap(zip(lpaths, rpaths)):
1167
+ with callback.branched(lpath, rpath) as child:
1168
+ self.put_file(lpath, rpath, callback=child, **kwargs)
1169
+
1170
+ def head(self, path, size=1024):
1171
+ """Get the first ``size`` bytes from file"""
1172
+ with self.open(path, "rb") as f:
1173
+ return f.read(size)
1174
+
1175
+ def tail(self, path, size=1024):
1176
+ """Get the last ``size`` bytes from file"""
1177
+ with self.open(path, "rb") as f:
1178
+ f.seek(0, 2)
1179
+ f.seek(max(f.tell() - size, 0))
1180
+ return f.read()
1181
+
1182
+ def cp_file(self, path1, path2, **kwargs):
1183
+ raise NotImplementedError
1184
+
1185
+ def copy(
1186
+ self, path1, path2, recursive=False, maxdepth=None, on_error=None, **kwargs
1187
+ ):
1188
+ """Copy within two locations in the filesystem
1189
+
1190
+ on_error : "raise", "ignore"
1191
+ If raise, any not-found exceptions will be raised; if ignore any
1192
+ not-found exceptions will cause the path to be skipped; defaults to
1193
+ raise unless recursive is true, where the default is ignore
1194
+ """
1195
+ if on_error is None and recursive:
1196
+ on_error = "ignore"
1197
+ elif on_error is None:
1198
+ on_error = "raise"
1199
+
1200
+ if isinstance(path1, list) and isinstance(path2, list):
1201
+ # No need to expand paths when both source and destination
1202
+ # are provided as lists
1203
+ paths1 = path1
1204
+ paths2 = path2
1205
+ else:
1206
+ from .implementations.local import trailing_sep
1207
+
1208
+ source_is_str = isinstance(path1, str)
1209
+ paths1 = self.expand_path(
1210
+ path1, recursive=recursive, maxdepth=maxdepth, **kwargs
1211
+ )
1212
+ if source_is_str and (not recursive or maxdepth is not None):
1213
+ # Non-recursive glob does not copy directories
1214
+ paths1 = [p for p in paths1 if not (trailing_sep(p) or self.isdir(p))]
1215
+ if not paths1:
1216
+ return
1217
+
1218
+ source_is_file = len(paths1) == 1
1219
+ dest_is_dir = isinstance(path2, str) and (
1220
+ trailing_sep(path2) or self.isdir(path2)
1221
+ )
1222
+
1223
+ exists = source_is_str and (
1224
+ (has_magic(path1) and source_is_file)
1225
+ or (not has_magic(path1) and dest_is_dir and not trailing_sep(path1))
1226
+ )
1227
+ paths2 = other_paths(
1228
+ paths1,
1229
+ path2,
1230
+ exists=exists,
1231
+ flatten=not source_is_str,
1232
+ )
1233
+
1234
+ for p1, p2 in zip(paths1, paths2):
1235
+ try:
1236
+ self.cp_file(p1, p2, **kwargs)
1237
+ except FileNotFoundError:
1238
+ if on_error == "raise":
1239
+ raise
1240
+
1241
+ def expand_path(
1242
+ self, path, recursive=False, maxdepth=None, assume_literal=False, **kwargs
1243
+ ):
1244
+ """Turn one or more globs or directories into a list of all matching paths
1245
+ to files or directories.
1246
+
1247
+ kwargs are passed to ``glob`` or ``find``, which may in turn call ``ls``
1248
+ """
1249
+
1250
+ if maxdepth is not None and maxdepth < 1:
1251
+ raise ValueError("maxdepth must be at least 1")
1252
+
1253
+ if isinstance(path, (str, os.PathLike)):
1254
+ out = self.expand_path([path], recursive, maxdepth, **kwargs)
1255
+ else:
1256
+ out = set()
1257
+ path = [self._strip_protocol(p) for p in path]
1258
+ for p in path:
1259
+ if not assume_literal and has_magic(p):
1260
+ bit = set(self.glob(p, maxdepth=maxdepth, **kwargs))
1261
+ out |= bit
1262
+ if recursive:
1263
+ # glob call above expanded one depth so if maxdepth is defined
1264
+ # then decrement it in expand_path call below. If it is zero
1265
+ # after decrementing then avoid expand_path call.
1266
+ if maxdepth is not None and maxdepth <= 1:
1267
+ continue
1268
+ out |= set(
1269
+ self.expand_path(
1270
+ list(bit),
1271
+ recursive=recursive,
1272
+ maxdepth=maxdepth - 1 if maxdepth is not None else None,
1273
+ assume_literal=True,
1274
+ **kwargs,
1275
+ )
1276
+ )
1277
+ continue
1278
+ elif recursive:
1279
+ rec = set(
1280
+ self.find(
1281
+ p, maxdepth=maxdepth, withdirs=True, detail=False, **kwargs
1282
+ )
1283
+ )
1284
+ out |= rec
1285
+ if p not in out and (recursive is False or self.exists(p)):
1286
+ # should only check once, for the root
1287
+ out.add(p)
1288
+ if not out:
1289
+ raise FileNotFoundError(path)
1290
+ return sorted(out)
1291
+
1292
+ def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs):
1293
+ """Move file(s) from one location to another"""
1294
+ if path1 == path2:
1295
+ logger.debug("%s mv: The paths are the same, so no files were moved.", self)
1296
+ else:
1297
+ # explicitly raise exception to prevent data corruption
1298
+ self.copy(
1299
+ path1, path2, recursive=recursive, maxdepth=maxdepth, on_error="raise"
1300
+ )
1301
+ self.rm(path1, recursive=recursive)
1302
+
1303
+ def rm_file(self, path):
1304
+ """Delete a file"""
1305
+ self._rm(path)
1306
+
1307
+ def _rm(self, path):
1308
+ """Delete one file"""
1309
+ # this is the old name for the method, prefer rm_file
1310
+ raise NotImplementedError
1311
+
1312
+ def rm(self, path, recursive=False, maxdepth=None):
1313
+ """Delete files or directories.
1314
+
1315
+ Parameters
1316
+ ----------
1317
+ path: str or list of str
1318
+ Files or directories to delete.
1319
+ recursive: bool
1320
+ If True, recursively delete directories and their contents.
1321
+ maxdepth: int or None
1322
+ Depth to pass to walk for finding files to delete, if recursive.
1323
+ If None, there will be no limit and infinite recursion may be
1324
+ possible.
1325
+ """
1326
+ path = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
1327
+ for p in reversed(path):
1328
+ self.rm_file(p)
1329
+
1330
+ @classmethod
1331
+ def _parent(cls, path):
1332
+ path = cls._strip_protocol(path)
1333
+ if "/" in path:
1334
+ parent = path.rsplit("/", 1)[0].lstrip(cls.root_marker)
1335
+ return cls.root_marker + parent
1336
+ else:
1337
+ return cls.root_marker
1338
+
1339
+ def _open(
1340
+ self,
1341
+ path,
1342
+ mode="rb",
1343
+ block_size=None,
1344
+ autocommit=True,
1345
+ cache_options=None,
1346
+ **kwargs,
1347
+ ):
1348
+ """Return raw bytes-mode file-like from the file-system"""
1349
+ return AbstractBufferedFile(
1350
+ self,
1351
+ path,
1352
+ mode,
1353
+ block_size,
1354
+ autocommit,
1355
+ cache_options=cache_options,
1356
+ **kwargs,
1357
+ )
1358
+
1359
+ def open(
1360
+ self,
1361
+ path,
1362
+ mode="rb",
1363
+ block_size=None,
1364
+ cache_options=None,
1365
+ compression=None,
1366
+ **kwargs,
1367
+ ):
1368
+ """
1369
+ Return a file-like object from the filesystem
1370
+
1371
+ The resultant instance must function correctly in a context ``with``
1372
+ block.
1373
+
1374
+ Parameters
1375
+ ----------
1376
+ path: str
1377
+ Target file
1378
+ mode: str like 'rb', 'w'
1379
+ See builtin ``open()``
1380
+ Mode "x" (exclusive write) may be implemented by the backend. Even if
1381
+ it is, whether it is checked up front or on commit, and whether it is
1382
+ atomic is implementation-dependent.
1383
+ block_size: int
1384
+ Some indication of buffering - this is a value in bytes
1385
+ cache_options : dict, optional
1386
+ Extra arguments to pass through to the cache.
1387
+ compression: string or None
1388
+ If given, open file using compression codec. Can either be a compression
1389
+ name (a key in ``fsspec.compression.compr``) or "infer" to guess the
1390
+ compression from the filename suffix.
1391
+ encoding, errors, newline: passed on to TextIOWrapper for text mode
1392
+ """
1393
+ import io
1394
+
1395
+ path = self._strip_protocol(path)
1396
+ if "b" not in mode:
1397
+ mode = mode.replace("t", "") + "b"
1398
+
1399
+ text_kwargs = {
1400
+ k: kwargs.pop(k)
1401
+ for k in ["encoding", "errors", "newline"]
1402
+ if k in kwargs
1403
+ }
1404
+ return io.TextIOWrapper(
1405
+ self.open(
1406
+ path,
1407
+ mode,
1408
+ block_size=block_size,
1409
+ cache_options=cache_options,
1410
+ compression=compression,
1411
+ **kwargs,
1412
+ ),
1413
+ **text_kwargs,
1414
+ )
1415
+ else:
1416
+ ac = kwargs.pop("autocommit", not self._intrans)
1417
+ f = self._open(
1418
+ path,
1419
+ mode=mode,
1420
+ block_size=block_size,
1421
+ autocommit=ac,
1422
+ cache_options=cache_options,
1423
+ **kwargs,
1424
+ )
1425
+ if not ac and "r" not in mode:
1426
+ self.transaction.files.append(f)
1427
+ if compression is not None:
1428
+ from fsspec.compression import compr
1429
+ from fsspec.core import get_compression
1430
+
1431
+ compression = get_compression(path, compression)
1432
+ compress = compr[compression]
1433
+ f = compress(f, mode=mode[0])
1434
+ return f
1435
+
1436
+ def touch(self, path, truncate=True, **kwargs):
1437
+ """Create empty file, or update timestamp
1438
+
1439
+ Parameters
1440
+ ----------
1441
+ path: str
1442
+ file location
1443
+ truncate: bool
1444
+ If True, always set file size to 0; if False, update timestamp and
1445
+ leave file unchanged, if backend allows this
1446
+ """
1447
+ if truncate or not self.exists(path):
1448
+ with self.open(path, "wb", **kwargs):
1449
+ pass
1450
+ else:
1451
+ raise NotImplementedError # update timestamp, if possible
1452
+
1453
+ def ukey(self, path):
1454
+ """Hash of file properties, to tell if it has changed"""
1455
+ return sha256(str(self.info(path)).encode()).hexdigest()
1456
+
1457
+ def read_block(self, fn, offset, length, delimiter=None):
1458
+ """Read a block of bytes from
1459
+
1460
+ Starting at ``offset`` of the file, read ``length`` bytes. If
1461
+ ``delimiter`` is set then we ensure that the read starts and stops at
1462
+ delimiter boundaries that follow the locations ``offset`` and ``offset
1463
+ + length``. If ``offset`` is zero then we start at zero. The
1464
+ bytestring returned WILL include the end delimiter string.
1465
+
1466
+ If offset+length is beyond the eof, reads to eof.
1467
+
1468
+ Parameters
1469
+ ----------
1470
+ fn: string
1471
+ Path to filename
1472
+ offset: int
1473
+ Byte offset to start read
1474
+ length: int
1475
+ Number of bytes to read. If None, read to end.
1476
+ delimiter: bytes (optional)
1477
+ Ensure reading starts and stops at delimiter bytestring
1478
+
1479
+ Examples
1480
+ --------
1481
+ >>> fs.read_block('data/file.csv', 0, 13) # doctest: +SKIP
1482
+ b'Alice, 100\\nBo'
1483
+ >>> fs.read_block('data/file.csv', 0, 13, delimiter=b'\\n') # doctest: +SKIP
1484
+ b'Alice, 100\\nBob, 200\\n'
1485
+
1486
+ Use ``length=None`` to read to the end of the file.
1487
+ >>> fs.read_block('data/file.csv', 0, None, delimiter=b'\\n') # doctest: +SKIP
1488
+ b'Alice, 100\\nBob, 200\\nCharlie, 300'
1489
+
1490
+ See Also
1491
+ --------
1492
+ :func:`fsspec.utils.read_block`
1493
+ """
1494
+ with self.open(fn, "rb") as f:
1495
+ size = f.size
1496
+ if length is None:
1497
+ length = size
1498
+ if size is not None and offset + length > size:
1499
+ length = size - offset
1500
+ return read_block(f, offset, length, delimiter)
1501
+
1502
+ def to_json(self, *, include_password: bool = True) -> str:
1503
+ """
1504
+ JSON representation of this filesystem instance.
1505
+
1506
+ Parameters
1507
+ ----------
1508
+ include_password: bool, default True
1509
+ Whether to include the password (if any) in the output.
1510
+
1511
+ Returns
1512
+ -------
1513
+ JSON string with keys ``cls`` (the python location of this class),
1514
+ protocol (text name of this class's protocol, first one in case of
1515
+ multiple), ``args`` (positional args, usually empty), and all other
1516
+ keyword arguments as their own keys.
1517
+
1518
+ Warnings
1519
+ --------
1520
+ Serialized filesystems may contain sensitive information which have been
1521
+ passed to the constructor, such as passwords and tokens. Make sure you
1522
+ store and send them in a secure environment!
1523
+ """
1524
+ from .json import FilesystemJSONEncoder
1525
+
1526
+ return json.dumps(
1527
+ self,
1528
+ cls=type(
1529
+ "_FilesystemJSONEncoder",
1530
+ (FilesystemJSONEncoder,),
1531
+ {"include_password": include_password},
1532
+ ),
1533
+ )
1534
+
1535
+ @staticmethod
1536
+ def from_json(blob: str) -> AbstractFileSystem:
1537
+ """
1538
+ Recreate a filesystem instance from JSON representation.
1539
+
1540
+ See ``.to_json()`` for the expected structure of the input.
1541
+
1542
+ Parameters
1543
+ ----------
1544
+ blob: str
1545
+
1546
+ Returns
1547
+ -------
1548
+ file system instance, not necessarily of this particular class.
1549
+
1550
+ Warnings
1551
+ --------
1552
+ This can import arbitrary modules (as determined by the ``cls`` key).
1553
+ Make sure you haven't installed any modules that may execute malicious code
1554
+ at import time.
1555
+ """
1556
+ from .json import FilesystemJSONDecoder
1557
+
1558
+ return json.loads(blob, cls=FilesystemJSONDecoder)
1559
+
1560
+ def to_dict(self, *, include_password: bool = True) -> dict[str, Any]:
1561
+ """
1562
+ JSON-serializable dictionary representation of this filesystem instance.
1563
+
1564
+ Parameters
1565
+ ----------
1566
+ include_password: bool, default True
1567
+ Whether to include the password (if any) in the output.
1568
+
1569
+ Returns
1570
+ -------
1571
+ Dictionary with keys ``cls`` (the python location of this class),
1572
+ protocol (text name of this class's protocol, first one in case of
1573
+ multiple), ``args`` (positional args, usually empty), and all other
1574
+ keyword arguments as their own keys.
1575
+
1576
+ Warnings
1577
+ --------
1578
+ Serialized filesystems may contain sensitive information which have been
1579
+ passed to the constructor, such as passwords and tokens. Make sure you
1580
+ store and send them in a secure environment!
1581
+ """
1582
+ from .json import FilesystemJSONEncoder
1583
+
1584
+ json_encoder = FilesystemJSONEncoder()
1585
+
1586
+ cls = type(self)
1587
+ proto = self.protocol
1588
+
1589
+ storage_options = dict(self.storage_options)
1590
+ if not include_password:
1591
+ storage_options.pop("password", None)
1592
+
1593
+ return dict(
1594
+ cls=f"{cls.__module__}:{cls.__name__}",
1595
+ protocol=proto[0] if isinstance(proto, (tuple, list)) else proto,
1596
+ args=json_encoder.make_serializable(self.storage_args),
1597
+ **json_encoder.make_serializable(storage_options),
1598
+ )
1599
+
1600
+ @staticmethod
1601
+ def from_dict(dct: dict[str, Any]) -> AbstractFileSystem:
1602
+ """
1603
+ Recreate a filesystem instance from dictionary representation.
1604
+
1605
+ See ``.to_dict()`` for the expected structure of the input.
1606
+
1607
+ Parameters
1608
+ ----------
1609
+ dct: Dict[str, Any]
1610
+
1611
+ Returns
1612
+ -------
1613
+ file system instance, not necessarily of this particular class.
1614
+
1615
+ Warnings
1616
+ --------
1617
+ This can import arbitrary modules (as determined by the ``cls`` key).
1618
+ Make sure you haven't installed any modules that may execute malicious code
1619
+ at import time.
1620
+ """
1621
+ from .json import FilesystemJSONDecoder
1622
+
1623
+ json_decoder = FilesystemJSONDecoder()
1624
+
1625
+ dct = dict(dct) # Defensive copy
1626
+
1627
+ cls = FilesystemJSONDecoder.try_resolve_fs_cls(dct)
1628
+ if cls is None:
1629
+ raise ValueError("Not a serialized AbstractFileSystem")
1630
+
1631
+ dct.pop("cls", None)
1632
+ dct.pop("protocol", None)
1633
+
1634
+ return cls(
1635
+ *json_decoder.unmake_serializable(dct.pop("args", ())),
1636
+ **json_decoder.unmake_serializable(dct),
1637
+ )
1638
+
1639
+ def _get_pyarrow_filesystem(self):
1640
+ """
1641
+ Make a version of the FS instance which will be acceptable to pyarrow
1642
+ """
1643
+ # all instances already also derive from pyarrow
1644
+ return self
1645
+
1646
+ def get_mapper(self, root="", check=False, create=False, missing_exceptions=None):
1647
+ """Create key/value store based on this file-system
1648
+
1649
+ Makes a MutableMapping interface to the FS at the given root path.
1650
+ See ``fsspec.mapping.FSMap`` for further details.
1651
+ """
1652
+ from .mapping import FSMap
1653
+
1654
+ return FSMap(
1655
+ root,
1656
+ self,
1657
+ check=check,
1658
+ create=create,
1659
+ missing_exceptions=missing_exceptions,
1660
+ )
1661
+
1662
+ @classmethod
1663
+ def clear_instance_cache(cls):
1664
+ """
1665
+ Clear the cache of filesystem instances.
1666
+
1667
+ Notes
1668
+ -----
1669
+ Unless overridden by setting the ``cachable`` class attribute to False,
1670
+ the filesystem class stores a reference to newly created instances. This
1671
+ prevents Python's normal rules around garbage collection from working,
1672
+ since the instances refcount will not drop to zero until
1673
+ ``clear_instance_cache`` is called.
1674
+ """
1675
+ cls._cache.clear()
1676
+
1677
+ def created(self, path):
1678
+ """Return the created timestamp of a file as a datetime.datetime"""
1679
+ raise NotImplementedError
1680
+
1681
+ def modified(self, path):
1682
+ """Return the modified timestamp of a file as a datetime.datetime"""
1683
+ raise NotImplementedError
1684
+
1685
+ def tree(
1686
+ self,
1687
+ path: str = "/",
1688
+ recursion_limit: int = 2,
1689
+ max_display: int = 25,
1690
+ display_size: bool = False,
1691
+ prefix: str = "",
1692
+ is_last: bool = True,
1693
+ first: bool = True,
1694
+ indent_size: int = 4,
1695
+ ) -> str:
1696
+ """
1697
+ Return a tree-like structure of the filesystem starting from the given path as a string.
1698
+
1699
+ Parameters
1700
+ ----------
1701
+ path: Root path to start traversal from
1702
+ recursion_limit: Maximum depth of directory traversal
1703
+ max_display: Maximum number of items to display per directory
1704
+ display_size: Whether to display file sizes
1705
+ prefix: Current line prefix for visual tree structure
1706
+ is_last: Whether current item is last in its level
1707
+ first: Whether this is the first call (displays root path)
1708
+ indent_size: Number of spaces by indent
1709
+
1710
+ Returns
1711
+ -------
1712
+ str: A string representing the tree structure.
1713
+
1714
+ Example
1715
+ -------
1716
+ >>> from fsspec import filesystem
1717
+
1718
+ >>> fs = filesystem('ftp', host='test.rebex.net', user='demo', password='password')
1719
+ >>> tree = fs.tree(display_size=True, recursion_limit=3, indent_size=8, max_display=10)
1720
+ >>> print(tree)
1721
+ """
1722
+
1723
+ def format_bytes(n: int) -> str:
1724
+ """Format bytes as text."""
1725
+ for prefix, k in (
1726
+ ("P", 2**50),
1727
+ ("T", 2**40),
1728
+ ("G", 2**30),
1729
+ ("M", 2**20),
1730
+ ("k", 2**10),
1731
+ ):
1732
+ if n >= 0.9 * k:
1733
+ return f"{n / k:.2f} {prefix}b"
1734
+ return f"{n}B"
1735
+
1736
+ result = []
1737
+
1738
+ if first:
1739
+ result.append(path)
1740
+
1741
+ if recursion_limit:
1742
+ indent = " " * indent_size
1743
+ contents = self.ls(path, detail=True)
1744
+ contents.sort(
1745
+ key=lambda x: (x.get("type") != "directory", x.get("name", ""))
1746
+ )
1747
+
1748
+ if max_display is not None and len(contents) > max_display:
1749
+ displayed_contents = contents[:max_display]
1750
+ remaining_count = len(contents) - max_display
1751
+ else:
1752
+ displayed_contents = contents
1753
+ remaining_count = 0
1754
+
1755
+ for i, item in enumerate(displayed_contents):
1756
+ is_last_item = (i == len(displayed_contents) - 1) and (
1757
+ remaining_count == 0
1758
+ )
1759
+
1760
+ branch = (
1761
+ "└" + ("─" * (indent_size - 2))
1762
+ if is_last_item
1763
+ else "├" + ("─" * (indent_size - 2))
1764
+ )
1765
+ branch += " "
1766
+ new_prefix = prefix + (
1767
+ indent if is_last_item else "│" + " " * (indent_size - 1)
1768
+ )
1769
+
1770
+ name = os.path.basename(item.get("name", ""))
1771
+
1772
+ if display_size and item.get("type") == "directory":
1773
+ sub_contents = self.ls(item.get("name", ""), detail=True)
1774
+ num_files = sum(
1775
+ 1 for sub_item in sub_contents if sub_item.get("type") == "file"
1776
+ )
1777
+ num_folders = sum(
1778
+ 1
1779
+ for sub_item in sub_contents
1780
+ if sub_item.get("type") == "directory"
1781
+ )
1782
+
1783
+ if num_files == 0 and num_folders == 0:
1784
+ size = " (empty folder)"
1785
+ elif num_files == 0:
1786
+ size = f" ({num_folders} subfolder{'s' if num_folders > 1 else ''})"
1787
+ elif num_folders == 0:
1788
+ size = f" ({num_files} file{'s' if num_files > 1 else ''})"
1789
+ else:
1790
+ size = f" ({num_files} file{'s' if num_files > 1 else ''}, {num_folders} subfolder{'s' if num_folders > 1 else ''})"
1791
+ elif display_size and item.get("type") == "file":
1792
+ size = f" ({format_bytes(item.get('size', 0))})"
1793
+ else:
1794
+ size = ""
1795
+
1796
+ result.append(f"{prefix}{branch}{name}{size}")
1797
+
1798
+ if item.get("type") == "directory" and recursion_limit > 0:
1799
+ result.append(
1800
+ self.tree(
1801
+ path=item.get("name", ""),
1802
+ recursion_limit=recursion_limit - 1,
1803
+ max_display=max_display,
1804
+ display_size=display_size,
1805
+ prefix=new_prefix,
1806
+ is_last=is_last_item,
1807
+ first=False,
1808
+ indent_size=indent_size,
1809
+ )
1810
+ )
1811
+
1812
+ if remaining_count > 0:
1813
+ more_message = f"{remaining_count} more item(s) not displayed."
1814
+ result.append(
1815
+ f"{prefix}{'└' + ('─' * (indent_size - 2))} {more_message}"
1816
+ )
1817
+
1818
+ return "\n".join(_ for _ in result if _)
1819
+
1820
+ # ------------------------------------------------------------------------
1821
+ # Aliases
1822
+
1823
+ def read_bytes(self, path, start=None, end=None, **kwargs):
1824
+ """Alias of `AbstractFileSystem.cat_file`."""
1825
+ return self.cat_file(path, start=start, end=end, **kwargs)
1826
+
1827
+ def write_bytes(self, path, value, **kwargs):
1828
+ """Alias of `AbstractFileSystem.pipe_file`."""
1829
+ self.pipe_file(path, value, **kwargs)
1830
+
1831
+ def makedir(self, path, create_parents=True, **kwargs):
1832
+ """Alias of `AbstractFileSystem.mkdir`."""
1833
+ return self.mkdir(path, create_parents=create_parents, **kwargs)
1834
+
1835
+ def mkdirs(self, path, exist_ok=False):
1836
+ """Alias of `AbstractFileSystem.makedirs`."""
1837
+ return self.makedirs(path, exist_ok=exist_ok)
1838
+
1839
+ def listdir(self, path, detail=True, **kwargs):
1840
+ """Alias of `AbstractFileSystem.ls`."""
1841
+ return self.ls(path, detail=detail, **kwargs)
1842
+
1843
+ def cp(self, path1, path2, **kwargs):
1844
+ """Alias of `AbstractFileSystem.copy`."""
1845
+ return self.copy(path1, path2, **kwargs)
1846
+
1847
+ def move(self, path1, path2, **kwargs):
1848
+ """Alias of `AbstractFileSystem.mv`."""
1849
+ return self.mv(path1, path2, **kwargs)
1850
+
1851
+ def stat(self, path, **kwargs):
1852
+ """Alias of `AbstractFileSystem.info`."""
1853
+ return self.info(path, **kwargs)
1854
+
1855
+ def disk_usage(self, path, total=True, maxdepth=None, **kwargs):
1856
+ """Alias of `AbstractFileSystem.du`."""
1857
+ return self.du(path, total=total, maxdepth=maxdepth, **kwargs)
1858
+
1859
+ def rename(self, path1, path2, **kwargs):
1860
+ """Alias of `AbstractFileSystem.mv`."""
1861
+ return self.mv(path1, path2, **kwargs)
1862
+
1863
+ def delete(self, path, recursive=False, maxdepth=None):
1864
+ """Alias of `AbstractFileSystem.rm`."""
1865
+ return self.rm(path, recursive=recursive, maxdepth=maxdepth)
1866
+
1867
+ def upload(self, lpath, rpath, recursive=False, **kwargs):
1868
+ """Alias of `AbstractFileSystem.put`."""
1869
+ return self.put(lpath, rpath, recursive=recursive, **kwargs)
1870
+
1871
+ def download(self, rpath, lpath, recursive=False, **kwargs):
1872
+ """Alias of `AbstractFileSystem.get`."""
1873
+ return self.get(rpath, lpath, recursive=recursive, **kwargs)
1874
+
1875
+ def sign(self, path, expiration=100, **kwargs):
1876
+ """Create a signed URL representing the given path
1877
+
1878
+ Some implementations allow temporary URLs to be generated, as a
1879
+ way of delegating credentials.
1880
+
1881
+ Parameters
1882
+ ----------
1883
+ path : str
1884
+ The path on the filesystem
1885
+ expiration : int
1886
+ Number of seconds to enable the URL for (if supported)
1887
+
1888
+ Returns
1889
+ -------
1890
+ URL : str
1891
+ The signed URL
1892
+
1893
+ Raises
1894
+ ------
1895
+ NotImplementedError : if method is not implemented for a filesystem
1896
+ """
1897
+ raise NotImplementedError("Sign is not implemented for this filesystem")
1898
+
1899
+ def _isfilestore(self):
1900
+ # Originally inherited from pyarrow DaskFileSystem. Keeping this
1901
+ # here for backwards compatibility as long as pyarrow uses its
1902
+ # legacy fsspec-compatible filesystems and thus accepts fsspec
1903
+ # filesystems as well
1904
+ return False
1905
+
1906
+
1907
+ class AbstractBufferedFile(io.IOBase):
1908
+ """Convenient class to derive from to provide buffering
1909
+
1910
+ In the case that the backend does not provide a pythonic file-like object
1911
+ already, this class contains much of the logic to build one. The only
1912
+ methods that need to be overridden are ``_upload_chunk``,
1913
+ ``_initiate_upload`` and ``_fetch_range``.
1914
+ """
1915
+
1916
+ DEFAULT_BLOCK_SIZE = 5 * 2**20
1917
+ _details = None
1918
+
1919
+ def __init__(
1920
+ self,
1921
+ fs,
1922
+ path,
1923
+ mode="rb",
1924
+ block_size="default",
1925
+ autocommit=True,
1926
+ cache_type="readahead",
1927
+ cache_options=None,
1928
+ size=None,
1929
+ **kwargs,
1930
+ ):
1931
+ """
1932
+ Template for files with buffered reading and writing
1933
+
1934
+ Parameters
1935
+ ----------
1936
+ fs: instance of FileSystem
1937
+ path: str
1938
+ location in file-system
1939
+ mode: str
1940
+ Normal file modes. Currently only 'wb', 'ab' or 'rb'. Some file
1941
+ systems may be read-only, and some may not support append.
1942
+ block_size: int
1943
+ Buffer size for reading or writing, 'default' for class default
1944
+ autocommit: bool
1945
+ Whether to write to final destination; may only impact what
1946
+ happens when file is being closed.
1947
+ cache_type: {"readahead", "none", "mmap", "bytes"}, default "readahead"
1948
+ Caching policy in read mode. See the definitions in ``core``.
1949
+ cache_options : dict
1950
+ Additional options passed to the constructor for the cache specified
1951
+ by `cache_type`.
1952
+ size: int
1953
+ If given and in read mode, suppressed having to look up the file size
1954
+ kwargs:
1955
+ Gets stored as self.kwargs
1956
+ """
1957
+ from .core import caches
1958
+
1959
+ self.path = path
1960
+ self.fs = fs
1961
+ self.mode = mode
1962
+ self.blocksize = (
1963
+ self.DEFAULT_BLOCK_SIZE if block_size in ["default", None] else block_size
1964
+ )
1965
+ self.loc = 0
1966
+ self.autocommit = autocommit
1967
+ self.end = None
1968
+ self.start = None
1969
+ self.closed = False
1970
+
1971
+ if cache_options is None:
1972
+ cache_options = {}
1973
+
1974
+ if "trim" in kwargs:
1975
+ warnings.warn(
1976
+ "Passing 'trim' to control the cache behavior has been deprecated. "
1977
+ "Specify it within the 'cache_options' argument instead.",
1978
+ FutureWarning,
1979
+ )
1980
+ cache_options["trim"] = kwargs.pop("trim")
1981
+
1982
+ self.kwargs = kwargs
1983
+
1984
+ if mode not in {"ab", "rb", "wb", "xb"}:
1985
+ raise NotImplementedError("File mode not supported")
1986
+ if mode == "rb":
1987
+ if size is not None:
1988
+ self.size = size
1989
+ else:
1990
+ self.size = self.details["size"]
1991
+ self.cache = caches[cache_type](
1992
+ self.blocksize, self._fetch_range, self.size, **cache_options
1993
+ )
1994
+ else:
1995
+ self.buffer = io.BytesIO()
1996
+ self.offset = None
1997
+ self.forced = False
1998
+ self.location = None
1999
+
2000
+ @property
2001
+ def details(self):
2002
+ if self._details is None:
2003
+ self._details = self.fs.info(self.path)
2004
+ return self._details
2005
+
2006
+ @details.setter
2007
+ def details(self, value):
2008
+ self._details = value
2009
+ self.size = value["size"]
2010
+
2011
+ @property
2012
+ def full_name(self):
2013
+ return _unstrip_protocol(self.path, self.fs)
2014
+
2015
+ @property
2016
+ def closed(self):
2017
+ # get around this attr being read-only in IOBase
2018
+ # use getattr here, since this can be called during del
2019
+ return getattr(self, "_closed", True)
2020
+
2021
+ @closed.setter
2022
+ def closed(self, c):
2023
+ self._closed = c
2024
+
2025
+ def __hash__(self):
2026
+ if "w" in self.mode:
2027
+ return id(self)
2028
+ else:
2029
+ return int(tokenize(self.details), 16)
2030
+
2031
+ def __eq__(self, other):
2032
+ """Files are equal if they have the same checksum, only in read mode"""
2033
+ if self is other:
2034
+ return True
2035
+ return (
2036
+ isinstance(other, type(self))
2037
+ and self.mode == "rb"
2038
+ and other.mode == "rb"
2039
+ and hash(self) == hash(other)
2040
+ )
2041
+
2042
+ def commit(self):
2043
+ """Move from temp to final destination"""
2044
+
2045
+ def discard(self):
2046
+ """Throw away temporary file"""
2047
+
2048
+ def info(self):
2049
+ """File information about this path"""
2050
+ if self.readable():
2051
+ return self.details
2052
+ else:
2053
+ raise ValueError("Info not available while writing")
2054
+
2055
+ def tell(self):
2056
+ """Current file location"""
2057
+ return self.loc
2058
+
2059
+ def seek(self, loc, whence=0):
2060
+ """Set current file location
2061
+
2062
+ Parameters
2063
+ ----------
2064
+ loc: int
2065
+ byte location
2066
+ whence: {0, 1, 2}
2067
+ from start of file, current location or end of file, resp.
2068
+ """
2069
+ loc = int(loc)
2070
+ if not self.mode == "rb":
2071
+ raise OSError(ESPIPE, "Seek only available in read mode")
2072
+ if whence == 0:
2073
+ nloc = loc
2074
+ elif whence == 1:
2075
+ nloc = self.loc + loc
2076
+ elif whence == 2:
2077
+ nloc = self.size + loc
2078
+ else:
2079
+ raise ValueError(f"invalid whence ({whence}, should be 0, 1 or 2)")
2080
+ if nloc < 0:
2081
+ raise ValueError("Seek before start of file")
2082
+ self.loc = nloc
2083
+ return self.loc
2084
+
2085
+ def write(self, data):
2086
+ """
2087
+ Write data to buffer.
2088
+
2089
+ Buffer only sent on flush() or if buffer is greater than
2090
+ or equal to blocksize.
2091
+
2092
+ Parameters
2093
+ ----------
2094
+ data: bytes
2095
+ Set of bytes to be written.
2096
+ """
2097
+ if not self.writable():
2098
+ raise ValueError("File not in write mode")
2099
+ if self.closed:
2100
+ raise ValueError("I/O operation on closed file.")
2101
+ if self.forced:
2102
+ raise ValueError("This file has been force-flushed, can only close")
2103
+ out = self.buffer.write(data)
2104
+ self.loc += out
2105
+ if self.buffer.tell() >= self.blocksize:
2106
+ self.flush()
2107
+ return out
2108
+
2109
+ def flush(self, force=False):
2110
+ """
2111
+ Write buffered data to backend store.
2112
+
2113
+ Writes the current buffer, if it is larger than the block-size, or if
2114
+ the file is being closed.
2115
+
2116
+ Parameters
2117
+ ----------
2118
+ force: bool
2119
+ When closing, write the last block even if it is smaller than
2120
+ blocks are allowed to be. Disallows further writing to this file.
2121
+ """
2122
+
2123
+ if self.closed:
2124
+ raise ValueError("Flush on closed file")
2125
+ if force and self.forced:
2126
+ raise ValueError("Force flush cannot be called more than once")
2127
+ if force:
2128
+ self.forced = True
2129
+
2130
+ if self.readable():
2131
+ # no-op to flush on read-mode
2132
+ return
2133
+
2134
+ if not force and self.buffer.tell() < self.blocksize:
2135
+ # Defer write on small block
2136
+ return
2137
+
2138
+ if self.offset is None:
2139
+ # Initialize a multipart upload
2140
+ self.offset = 0
2141
+ try:
2142
+ self._initiate_upload()
2143
+ except Exception:
2144
+ self.closed = True
2145
+ raise
2146
+
2147
+ if self._upload_chunk(final=force) is not False:
2148
+ self.offset += self.buffer.seek(0, 2)
2149
+ self.buffer = io.BytesIO()
2150
+
2151
+ def _upload_chunk(self, final=False):
2152
+ """Write one part of a multi-block file upload
2153
+
2154
+ Parameters
2155
+ ==========
2156
+ final: bool
2157
+ This is the last block, so should complete file, if
2158
+ self.autocommit is True.
2159
+ """
2160
+ # may not yet have been initialized, may need to call _initialize_upload
2161
+
2162
+ def _initiate_upload(self):
2163
+ """Create remote file/upload"""
2164
+ pass
2165
+
2166
+ def _fetch_range(self, start, end):
2167
+ """Get the specified set of bytes from remote"""
2168
+ return self.fs.cat_file(self.path, start=start, end=end)
2169
+
2170
+ def read(self, length=-1):
2171
+ """
2172
+ Return data from cache, or fetch pieces as necessary
2173
+
2174
+ Parameters
2175
+ ----------
2176
+ length: int (-1)
2177
+ Number of bytes to read; if <0, all remaining bytes.
2178
+ """
2179
+ length = -1 if length is None else int(length)
2180
+ if self.mode != "rb":
2181
+ raise ValueError("File not in read mode")
2182
+ if length < 0:
2183
+ length = self.size - self.loc
2184
+ if self.closed:
2185
+ raise ValueError("I/O operation on closed file.")
2186
+ if length == 0:
2187
+ # don't even bother calling fetch
2188
+ return b""
2189
+ out = self.cache._fetch(self.loc, self.loc + length)
2190
+
2191
+ logger.debug(
2192
+ "%s read: %i - %i %s",
2193
+ self,
2194
+ self.loc,
2195
+ self.loc + length,
2196
+ self.cache._log_stats(),
2197
+ )
2198
+ self.loc += len(out)
2199
+ return out
2200
+
2201
+ def readinto(self, b):
2202
+ """mirrors builtin file's readinto method
2203
+
2204
+ https://docs.python.org/3/library/io.html#io.RawIOBase.readinto
2205
+ """
2206
+ out = memoryview(b).cast("B")
2207
+ data = self.read(out.nbytes)
2208
+ out[: len(data)] = data
2209
+ return len(data)
2210
+
2211
+ def readuntil(self, char=b"\n", blocks=None):
2212
+ """Return data between current position and first occurrence of char
2213
+
2214
+ char is included in the output, except if the end of the tile is
2215
+ encountered first.
2216
+
2217
+ Parameters
2218
+ ----------
2219
+ char: bytes
2220
+ Thing to find
2221
+ blocks: None or int
2222
+ How much to read in each go. Defaults to file blocksize - which may
2223
+ mean a new read on every call.
2224
+ """
2225
+ out = []
2226
+ while True:
2227
+ start = self.tell()
2228
+ part = self.read(blocks or self.blocksize)
2229
+ if len(part) == 0:
2230
+ break
2231
+ found = part.find(char)
2232
+ if found > -1:
2233
+ out.append(part[: found + len(char)])
2234
+ self.seek(start + found + len(char))
2235
+ break
2236
+ out.append(part)
2237
+ return b"".join(out)
2238
+
2239
+ def readline(self):
2240
+ """Read until and including the first occurrence of newline character
2241
+
2242
+ Note that, because of character encoding, this is not necessarily a
2243
+ true line ending.
2244
+ """
2245
+ return self.readuntil(b"\n")
2246
+
2247
+ def __next__(self):
2248
+ out = self.readline()
2249
+ if out:
2250
+ return out
2251
+ raise StopIteration
2252
+
2253
+ def __iter__(self):
2254
+ return self
2255
+
2256
+ def readlines(self):
2257
+ """Return all data, split by the newline character, including the newline character"""
2258
+ data = self.read()
2259
+ lines = data.split(b"\n")
2260
+ out = [l + b"\n" for l in lines[:-1]]
2261
+ if data.endswith(b"\n"):
2262
+ return out
2263
+ else:
2264
+ return out + [lines[-1]]
2265
+ # return list(self) ???
2266
+
2267
+ def readinto1(self, b):
2268
+ return self.readinto(b)
2269
+
2270
+ def close(self):
2271
+ """Close file
2272
+
2273
+ Finalizes writes, discards cache
2274
+ """
2275
+ if getattr(self, "_unclosable", False):
2276
+ return
2277
+ if self.closed:
2278
+ return
2279
+ try:
2280
+ if self.mode == "rb":
2281
+ cache = getattr(self, "cache", None)
2282
+ if cache is not None:
2283
+ close = getattr(cache, "close", None)
2284
+ if callable(close):
2285
+ close()
2286
+ self.cache = None
2287
+ else:
2288
+ if not getattr(self, "forced", True):
2289
+ self.flush(force=True)
2290
+
2291
+ if self.fs is not None:
2292
+ self.fs.invalidate_cache(self.path)
2293
+ self.fs.invalidate_cache(self.fs._parent(self.path))
2294
+ finally:
2295
+ self.closed = True
2296
+
2297
+ def readable(self):
2298
+ """Whether opened for reading"""
2299
+ return "r" in self.mode and not self.closed
2300
+
2301
+ def seekable(self):
2302
+ """Whether is seekable (only in read mode)"""
2303
+ return self.readable()
2304
+
2305
+ def writable(self):
2306
+ """Whether opened for writing"""
2307
+ return self.mode in {"wb", "ab", "xb"} and not self.closed
2308
+
2309
+ def __reduce__(self):
2310
+ if self.mode != "rb":
2311
+ raise RuntimeError("Pickling a writeable file is not supported")
2312
+
2313
+ return reopen, (
2314
+ self.fs,
2315
+ self.path,
2316
+ self.mode,
2317
+ self.blocksize,
2318
+ self.loc,
2319
+ self.size,
2320
+ self.autocommit,
2321
+ self.cache.name if self.cache else "none",
2322
+ self.kwargs,
2323
+ )
2324
+
2325
+ def __del__(self):
2326
+ if not self.closed:
2327
+ self.close()
2328
+
2329
+ def __str__(self):
2330
+ return f"<File-like object {type(self.fs).__name__}, {self.path}>"
2331
+
2332
+ __repr__ = __str__
2333
+
2334
+ def __enter__(self):
2335
+ return self
2336
+
2337
+ def __exit__(self, *args):
2338
+ self.close()
2339
+
2340
+
2341
+ def reopen(fs, path, mode, blocksize, loc, size, autocommit, cache_type, kwargs):
2342
+ file = fs.open(
2343
+ path,
2344
+ mode=mode,
2345
+ block_size=blocksize,
2346
+ autocommit=autocommit,
2347
+ cache_type=cache_type,
2348
+ size=size,
2349
+ **kwargs,
2350
+ )
2351
+ if loc > 0:
2352
+ file.seek(loc)
2353
+ return file
venv/lib/python3.14/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
venv/lib/python3.14/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
+ }
venv/lib/python3.14/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)
venv/lib/python3.14/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)
venv/lib/python3.14/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
venv/lib/python3.14/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")
venv/lib/python3.14/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"
venv/lib/python3.14/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)
venv/lib/python3.14/site-packages/fsspec/transaction.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from collections import deque
3
+
4
+ logger = logging.getLogger("fsspec")
5
+
6
+
7
+ class Transaction:
8
+ """Filesystem transaction write context
9
+
10
+ Gathers files for deferred commit or discard, so that several write
11
+ operations can be finalized semi-atomically. This works by having this
12
+ instance as the ``.transaction`` attribute of the given filesystem
13
+ """
14
+
15
+ def __init__(self, fs, **kwargs):
16
+ """
17
+ Parameters
18
+ ----------
19
+ fs: FileSystem instance
20
+ """
21
+ self.fs = fs
22
+ self.files = deque()
23
+
24
+ def __enter__(self):
25
+ self.start()
26
+ return self
27
+
28
+ def __exit__(self, exc_type, exc_val, exc_tb):
29
+ """End transaction and commit, if exit is not due to exception"""
30
+ # only commit if there was no exception
31
+ self.complete(commit=exc_type is None)
32
+ if self.fs:
33
+ self.fs._intrans = False
34
+ self.fs._transaction = None
35
+ self.fs = None
36
+
37
+ def start(self):
38
+ """Start a transaction on this FileSystem"""
39
+ self.files = deque() # clean up after previous failed completions
40
+ self.fs._intrans = True
41
+
42
+ def complete(self, commit=True):
43
+ """Finish transaction: commit or discard all deferred files"""
44
+ f = None
45
+ try:
46
+ while self.files:
47
+ f = self.files.popleft()
48
+ if commit:
49
+ f.commit()
50
+ else:
51
+ f.discard()
52
+ f = None
53
+ finally:
54
+ # the file being processed when the error was raised is already
55
+ # off the queue; put it back so its temporary file is cleaned up
56
+ if f is not None:
57
+ self.files.appendleft(f)
58
+ # A failed commit or discard must still end the transaction.
59
+ # Leaving _intrans set would defer every later write on this
60
+ # filesystem into a temporary file that nothing ever commits,
61
+ # and instances are cached, so that would persist process-wide.
62
+ while self.files:
63
+ try:
64
+ self.files.popleft().discard()
65
+ except Exception:
66
+ logger.debug("Discarding deferred file failed", exc_info=True)
67
+ self.fs._intrans = False
68
+ self.fs._transaction = None
69
+ self.fs = None
70
+
71
+
72
+ class FileActor:
73
+ def __init__(self):
74
+ self.files = []
75
+
76
+ def commit(self):
77
+ for f in self.files:
78
+ f.commit()
79
+ self.files.clear()
80
+
81
+ def discard(self):
82
+ for f in self.files:
83
+ f.discard()
84
+ self.files.clear()
85
+
86
+ def append(self, f):
87
+ self.files.append(f)
88
+
89
+
90
+ class DaskTransaction(Transaction):
91
+ def __init__(self, fs):
92
+ """
93
+ Parameters
94
+ ----------
95
+ fs: FileSystem instance
96
+ """
97
+ import distributed
98
+
99
+ super().__init__(fs)
100
+ client = distributed.default_client()
101
+ self.files = client.submit(FileActor, actor=True).result()
102
+
103
+ def complete(self, commit=True):
104
+ """Finish transaction: commit or discard all deferred files"""
105
+ try:
106
+ if commit:
107
+ self.files.commit().result()
108
+ else:
109
+ self.files.discard().result()
110
+ finally:
111
+ self.fs._intrans = False
112
+ self.fs._transaction = None
113
+ self.fs = None