Ahmad2005 commited on
Commit
9a5496d
·
verified ·
1 Parent(s): adbd942

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec-2026.6.0.dist-info/METADATA +257 -0
  2. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec-2026.6.0.dist-info/RECORD +61 -0
  3. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec-2026.6.0.dist-info/WHEEL +4 -0
  4. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec-2026.6.0.dist-info/licenses/LICENSE +29 -0
  5. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/__init__.py +71 -0
  6. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/_version.py +24 -0
  7. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/archive.py +75 -0
  8. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/asyn.py +1158 -0
  9. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/caching.py +1004 -0
  10. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/callbacks.py +324 -0
  11. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/compression.py +185 -0
  12. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/config.py +131 -0
  13. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/conftest.py +125 -0
  14. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/core.py +760 -0
  15. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/dircache.py +98 -0
  16. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/exceptions.py +18 -0
  17. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/fuse.py +324 -0
  18. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/generic.py +396 -0
  19. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/gui.py +417 -0
  20. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/__init__.py +0 -0
  21. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/arrow.py +312 -0
  22. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/asyn_wrapper.py +124 -0
  23. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/cache_mapper.py +75 -0
  24. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/cache_metadata.py +217 -0
  25. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/cached.py +1024 -0
  26. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/chained.py +23 -0
  27. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/dask.py +152 -0
  28. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/data.py +71 -0
  29. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/dbfs.py +497 -0
  30. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/dirfs.py +404 -0
  31. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/ftp.py +442 -0
  32. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/gist.py +241 -0
  33. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/git.py +114 -0
  34. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/github.py +333 -0
  35. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/http.py +902 -0
  36. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/http_sync.py +937 -0
  37. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/jupyter.py +129 -0
  38. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/libarchive.py +213 -0
  39. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/local.py +517 -0
  40. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/memory.py +311 -0
  41. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/reference.py +1339 -0
  42. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/sftp.py +187 -0
  43. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/smb.py +416 -0
  44. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/tar.py +135 -0
  45. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/webhdfs.py +503 -0
  46. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/zip.py +183 -0
  47. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/json.py +112 -0
  48. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/mapping.py +251 -0
  49. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/parquet.py +572 -0
  50. .cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/registry.py +337 -0
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec-2026.6.0.dist-info/METADATA ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: fsspec
3
+ Version: 2026.6.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>2024.2.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>2024.2.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>2024.2.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; 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>2024.2.0; extra == 's3'
85
+ Provides-Extra: sftp
86
+ Requires-Dist: paramiko; extra == 'sftp'
87
+ Provides-Extra: smb
88
+ Requires-Dist: smbprotocol; extra == 'smb'
89
+ Provides-Extra: ssh
90
+ Requires-Dist: paramiko; extra == 'ssh'
91
+ Provides-Extra: test
92
+ Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test'
93
+ Requires-Dist: numpy; extra == 'test'
94
+ Requires-Dist: pytest; extra == 'test'
95
+ Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test'
96
+ Requires-Dist: pytest-benchmark; extra == 'test'
97
+ Requires-Dist: pytest-cov; extra == 'test'
98
+ Requires-Dist: pytest-mock; extra == 'test'
99
+ Requires-Dist: pytest-recording; extra == 'test'
100
+ Requires-Dist: pytest-rerunfailures; extra == 'test'
101
+ Requires-Dist: requests; extra == 'test'
102
+ Provides-Extra: test-downstream
103
+ Requires-Dist: aiobotocore<3.0.0,>=2.5.4; extra == 'test-downstream'
104
+ Requires-Dist: dask[dataframe,test]; extra == 'test-downstream'
105
+ Requires-Dist: moto[server]<5,>4; extra == 'test-downstream'
106
+ Requires-Dist: pytest-timeout; extra == 'test-downstream'
107
+ Requires-Dist: xarray; extra == 'test-downstream'
108
+ Provides-Extra: test-full
109
+ Requires-Dist: adlfs; extra == 'test-full'
110
+ Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test-full'
111
+ Requires-Dist: backports-zstd; (python_version < '3.14') and extra == 'test-full'
112
+ Requires-Dist: cloudpickle; extra == 'test-full'
113
+ Requires-Dist: dask; extra == 'test-full'
114
+ Requires-Dist: distributed; extra == 'test-full'
115
+ Requires-Dist: dropbox; extra == 'test-full'
116
+ Requires-Dist: dropboxdrivefs; extra == 'test-full'
117
+ Requires-Dist: fastparquet; extra == 'test-full'
118
+ Requires-Dist: fusepy; extra == 'test-full'
119
+ Requires-Dist: gcsfs; extra == 'test-full'
120
+ Requires-Dist: jinja2; extra == 'test-full'
121
+ Requires-Dist: kerchunk; extra == 'test-full'
122
+ Requires-Dist: libarchive-c; extra == 'test-full'
123
+ Requires-Dist: lz4; extra == 'test-full'
124
+ Requires-Dist: notebook; extra == 'test-full'
125
+ Requires-Dist: numpy; extra == 'test-full'
126
+ Requires-Dist: ocifs; extra == 'test-full'
127
+ Requires-Dist: pandas<3.0.0; extra == 'test-full'
128
+ Requires-Dist: panel; extra == 'test-full'
129
+ Requires-Dist: paramiko; extra == 'test-full'
130
+ Requires-Dist: pyarrow; 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: smbprotocol; extra == 'test-full'
144
+ Requires-Dist: tqdm; extra == 'test-full'
145
+ Requires-Dist: urllib3; extra == 'test-full'
146
+ Requires-Dist: zarr<3.2.0; extra == 'test-full'
147
+ Requires-Dist: zstandard; (python_version < '3.14') and extra == 'test-full'
148
+ Provides-Extra: tqdm
149
+ Requires-Dist: tqdm; extra == 'tqdm'
150
+ Description-Content-Type: text/markdown
151
+
152
+ # filesystem_spec
153
+
154
+ [![PyPI version](https://badge.fury.io/py/fsspec.svg)](https://pypi.python.org/pypi/fsspec/)
155
+ [![Anaconda-Server Badge](https://anaconda.org/conda-forge/fsspec/badges/version.svg)](https://anaconda.org/conda-forge/fsspec)
156
+ ![Build](https://github.com/fsspec/filesystem_spec/workflows/CI/badge.svg)
157
+ [![Docs](https://readthedocs.org/projects/filesystem-spec/badge/?version=latest)](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest)
158
+
159
+ A specification for pythonic filesystems.
160
+
161
+ ## Install
162
+
163
+ ```bash
164
+ pip install fsspec
165
+ ```
166
+
167
+ would install the base fsspec. Various optionally supported features might require specification of custom
168
+ extra require, e.g. `pip install fsspec[ssh]` will install dependencies for `ssh` backends support.
169
+ Use `pip install fsspec[full]` for installation of all known extra dependencies.
170
+
171
+ Up-to-date package also provided through conda-forge distribution:
172
+
173
+ ```bash
174
+ conda install -c conda-forge fsspec
175
+ ```
176
+
177
+
178
+ ## Purpose
179
+
180
+ To produce a template or specification for a file-system interface, that specific implementations should follow,
181
+ so that applications making use of them can rely on a common behaviour and not have to worry about the specific
182
+ internal implementation decisions with any given backend. Many such implementations are included in this package,
183
+ or in sister projects such as `s3fs` and `gcsfs`.
184
+
185
+ In addition, if this is well-designed, then additional functionality, such as a key-value store or FUSE
186
+ mounting of the file-system implementation may be available for all implementations "for free".
187
+
188
+ ## Documentation
189
+
190
+ Please refer to [RTD](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest)
191
+
192
+ ## Develop
193
+
194
+ fsspec uses GitHub Actions for CI. Environment files can be found
195
+ in the "ci/" directory. Note that the main environment is called "py38",
196
+ but it is expected that the version of python installed be adjustable at
197
+ CI runtime. For local use, pick a version suitable for you.
198
+
199
+ ```bash
200
+ # For a new environment (mamba / conda).
201
+ mamba create -n fsspec -c conda-forge python=3.10 -y
202
+ conda activate fsspec
203
+
204
+ # Standard dev install with docs and tests.
205
+ pip install -e ".[dev,doc,test]"
206
+
207
+ # Full tests except for downstream
208
+ pip install s3fs
209
+ pip uninstall s3fs
210
+ pip install -e .[dev,doc,test_full]
211
+ pip install s3fs --no-deps
212
+ pytest -v
213
+
214
+ # Downstream tests.
215
+ sh install_s3fs.sh
216
+ # Windows powershell.
217
+ install_s3fs.sh
218
+ ```
219
+
220
+ ### Testing
221
+
222
+ Tests can be run in the dev environment, if activated, via ``pytest fsspec``.
223
+
224
+ The full fsspec suite requires a system-level docker, docker-compose, and fuse
225
+ installation. If only making changes to one backend implementation, it is
226
+ not generally necessary to run all tests locally.
227
+
228
+ It is expected that contributors ensure that any change to fsspec does not
229
+ cause issues or regressions for either other fsspec-related packages such
230
+ as gcsfs and s3fs, nor for downstream users of fsspec. The "downstream" CI
231
+ run and corresponding environment file run a set of tests from the dask
232
+ test suite, and very minimal tests against pandas and zarr from the
233
+ test_downstream.py module in this repo.
234
+
235
+ ### Code Formatting
236
+
237
+ fsspec uses [Black](https://black.readthedocs.io/en/stable) to ensure
238
+ a consistent code format throughout the project.
239
+ Run ``black fsspec`` from the root of the filesystem_spec repository to
240
+ auto-format your code. Additionally, many editors have plugins that will apply
241
+ ``black`` as you edit files. ``black`` is included in the ``tox`` environments.
242
+
243
+ Optionally, you may wish to setup [pre-commit hooks](https://pre-commit.com) to
244
+ automatically run ``black`` when you make a git commit.
245
+ Run ``pre-commit install --install-hooks`` from the root of the
246
+ filesystem_spec repository to setup pre-commit hooks. ``black`` will now be run
247
+ before you commit, reformatting any changed files. You can format without
248
+ committing via ``pre-commit run`` or skip these checks with ``git commit
249
+ --no-verify``.
250
+
251
+ ## Support
252
+
253
+ Work on this repository is supported in part by:
254
+
255
+ "Anaconda, Inc. - Advancing AI through open source."
256
+
257
+ <a href="https://anaconda.com/"><img src="https://camo.githubusercontent.com/b8555ef2222598ed37ce38ac86955febbd25de7619931bb7dd3c58432181d3b6/68747470733a2f2f626565776172652e6f72672f636f6d6d756e6974792f6d656d626572732f616e61636f6e64612f616e61636f6e64612d6c617267652e706e67" alt="anaconda logo" width="40%"/></a>
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec-2026.6.0.dist-info/RECORD ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fsspec/__init__.py,sha256=L7qwNBU1iMNQd8Of87HYSNFT9gWlNMSESaJC8fY0AaQ,2053
2
+ fsspec/_version.py,sha256=UvxfmLfdYeeNmxMYI29CuetrWuGdmBzeCcZ6C6RpX24,526
3
+ fsspec/archive.py,sha256=vM6t_lgV6lBWbBYwpm3S4ofBQFQxUPr5KkDQrrQcQro,2411
4
+ fsspec/asyn.py,sha256=i2pfNovARPVnV4pg93gMUZnnkMT_sCQGF0RKPCVZP5w,38733
5
+ fsspec/caching.py,sha256=YJm7SjQTxOgyavKvAE0CST_GR0mpnEjnIIWCdE1QbLk,34024
6
+ fsspec/callbacks.py,sha256=BDIwLzK6rr_0V5ch557fSzsivCElpdqhXr5dZ9Te-EE,9210
7
+ fsspec/compression.py,sha256=3v_Fe39gzRRWfaeXpzNjAGPqgTzmETYRCo3qHVqD3po,5132
8
+ fsspec/config.py,sha256=mHKzAgjXa_LwqtO_VoTJJ568VqwYkbK3gUp4J6JZJp4,4238
9
+ fsspec/conftest.py,sha256=uWfm_Qs5alPRxOhRpDfQ0-1jqSJ54pni4y96IxOREXM,3446
10
+ fsspec/core.py,sha256=lc7XSnZU6_C6xljp7Z_xEGN3V7704hbeQLkxvPP0wds,24173
11
+ fsspec/dircache.py,sha256=YzogWJrhEastHU7vWz-cJiJ7sdtLXFXhEpInGKd4EcM,2717
12
+ fsspec/exceptions.py,sha256=pauSLDMxzTJMOjvX1WEUK0cMyFkrFxpWJsyFywav7A8,331
13
+ fsspec/fuse.py,sha256=Q-3NOOyLqBfYa4Db5E19z_ZY36zzYHtIs1mOUasItBQ,10177
14
+ fsspec/generic.py,sha256=9QHQYMNb-8w8-eYuIqShcTjO_LeHXFoQTyt8J5oEq5Q,13482
15
+ fsspec/gui.py,sha256=CQ7QsrTpaDlWSLNOpwNoJc7khOcYXIZxmrAJN9bHWQU,14002
16
+ fsspec/json.py,sha256=4EBZ-xOmRiyxmIqPIwxmDImosRQ7io7qBM2xjJPsEE4,3768
17
+ fsspec/mapping.py,sha256=m2ndB_gtRBXYmNJg0Ie1-BVR75TFleHmIQBzC-yWhjU,8343
18
+ fsspec/parquet.py,sha256=0SzfswUTc2k5nAj7xZNYPPyvUkFNXznFRXXtBRhr-iE,20506
19
+ fsspec/registry.py,sha256=KeDNL9HOyHX_D4D4qQGAI-Y3DQhiLeUC1VK2I81NZaE,12344
20
+ fsspec/spec.py,sha256=7G8EFQn3gMSMP6PxaFgM9Vf93DhFc_-1ABivc_069fo,78097
21
+ fsspec/transaction.py,sha256=xliRG6U2Zf3khG4xcw9WiB-yAoqJSHEGK_VjHOdtgo0,2398
22
+ fsspec/utils.py,sha256=E24ji0XLWC6n3bw2sHA28OYxrGU9Wy_al2XydsRgrRk,23623
23
+ fsspec/implementations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
+ fsspec/implementations/arrow.py,sha256=8FhvcvOYLZNMMegCYFFCEHgEqig8AkOU7Ehb8XfcgnA,8890
25
+ fsspec/implementations/asyn_wrapper.py,sha256=3lfJkGs6D_AwRBdxTSYlL-RCVdaXBZ9Itys2P5o5Si0,3738
26
+ fsspec/implementations/cache_mapper.py,sha256=W4wlxyPxZbSp9ItJ0pYRVBMh6bw9eFypgP6kUYuuiI4,2421
27
+ fsspec/implementations/cache_metadata.py,sha256=EPhQV27lgPlYREYprDET1vcMed15pVNMit-Ta1ljoyE,7942
28
+ fsspec/implementations/cached.py,sha256=38B4qVDDXRh65Zb_JXy2-lJOxtdgUdBgNdy-oBe6jGw,36375
29
+ fsspec/implementations/chained.py,sha256=iGivpNaHUFjB_ea0-HAPhcmm6CL8qnDf270PSj7JwuE,680
30
+ fsspec/implementations/dask.py,sha256=CXZbJzIVOhKV8ILcxuy3bTvcacCueAbyQxmvAkbPkrk,4466
31
+ fsspec/implementations/data.py,sha256=9tMcy1fyX1auvzFX2aANPK9CfPoarnxTCDLhX12usvs,2131
32
+ fsspec/implementations/dbfs.py,sha256=yHuLUGNmQd5pUCt9vpXleQNpjOpIZZwVZA08YauQU4U,16249
33
+ fsspec/implementations/dirfs.py,sha256=5JAp_nn9v1OjKY3MwuRkLrqeZ8gGYlILSQRqkQQdz7k,12624
34
+ fsspec/implementations/ftp.py,sha256=XkD7MiHczFllZZQWndpz9sHBJkzFfRcfkKAfey6KnSI,13465
35
+ fsspec/implementations/gist.py,sha256=Y6jTDrE-wuTwvpPyAQDuuOMBGxlajafKWoB1_yX6jdY,8528
36
+ fsspec/implementations/git.py,sha256=qBDWMz5LNllPqVjr5jf_1FuNha4P5lyQI3IlhYg-wUE,3731
37
+ fsspec/implementations/github.py,sha256=aCsZL8UvXZgdkcB1RUs3DdLeNrjLKcFsFYeQFDWbBFo,11653
38
+ fsspec/implementations/http.py,sha256=1uWwxllOjPe8mQD54IrCYQJHU1YaAXh_cDmXBk-AoQ8,30894
39
+ fsspec/implementations/http_sync.py,sha256=UmBqd938ebwVjYgVtzg-ysG3ZoGhIJw0wFtQAfxV3Aw,30332
40
+ fsspec/implementations/jupyter.py,sha256=q1PlQ66AAswGFyr8MFKWyobaV2YekMWRtqENBDQtD28,4002
41
+ fsspec/implementations/libarchive.py,sha256=SpIA1F-zf7kb2-VYUVuhMrXTBOhBxUXKgEW1RaAdDoA,7098
42
+ fsspec/implementations/local.py,sha256=aVEUnAB2hkxmweXLCiB4XD_KPwDL-gMX4dN9Fz-pk7k,17161
43
+ fsspec/implementations/memory.py,sha256=TDdLtSPWXxZKrrVGwmc3uS3oK_2mlcVTk2BiqR8IeII,10507
44
+ fsspec/implementations/reference.py,sha256=YKLzPBF6bLpOnHY9iM0MR5JLGRi5CB6x1cWIgMb6Ahg,49974
45
+ fsspec/implementations/sftp.py,sha256=v7t-LpD4hEycHnw1kbepyoNgrhClshXQXitFuY4mBWE,5951
46
+ fsspec/implementations/smb.py,sha256=5fhu8h06nOLBPh2c48aT7WBRqh9cEcbIwtyu06wTjec,15236
47
+ fsspec/implementations/tar.py,sha256=0gqTHdwmwQI1Ia8rNQjuAVjNgrEFKPbdPkmndR9vpmk,4451
48
+ fsspec/implementations/webhdfs.py,sha256=osF2m0nhDil6sbMzYW_4DZzhxF4ygtb59XDiybd9Fyg,17589
49
+ fsspec/implementations/zip.py,sha256=GPDJh4UtUNJmaqijUQ0eiEZIGpwusQjkIcbhsrmLSi0,6263
50
+ fsspec/tests/abstract/__init__.py,sha256=4xUJrv7gDgc85xAOz1p-V_K1hrsdMWTSa0rviALlJk8,10181
51
+ fsspec/tests/abstract/common.py,sha256=1GQwNo5AONzAnzZj0fWgn8NJPLXALehbsuGxS3FzWVU,4973
52
+ fsspec/tests/abstract/copy.py,sha256=gU5-d97U3RSde35Vp4RxPY4rWwL744HiSrJ8IBOp9-8,19967
53
+ fsspec/tests/abstract/get.py,sha256=vNR4HztvTR7Cj56AMo7_tx7TeYz1Jgr_2Wb8Lv-UiBY,20755
54
+ fsspec/tests/abstract/mv.py,sha256=k8eUEBIrRrGMsBY5OOaDXdGnQUKGwDIfQyduB6YD3Ns,1982
55
+ fsspec/tests/abstract/open.py,sha256=Fi2PBPYLbRqysF8cFm0rwnB41kMdQVYjq8cGyDXp3BU,329
56
+ fsspec/tests/abstract/pipe.py,sha256=LFzIrLCB5GLXf9rzFKJmE8AdG7LQ_h4bJo70r8FLPqM,402
57
+ fsspec/tests/abstract/put.py,sha256=7aih17OKB_IZZh1Mkq1eBDIjobhtMQmI8x-Pw-S_aZk,21201
58
+ fsspec-2026.6.0.dist-info/METADATA,sha256=IMhcAkppoFkjfDp5hdOBo3RQF64dY0xVSwxZAd3oEJU,10530
59
+ fsspec-2026.6.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
60
+ fsspec-2026.6.0.dist-info/licenses/LICENSE,sha256=LcNUls5TpzB5FcAIqESq1T53K0mzTN0ARFBnaRQH7JQ,1513
61
+ fsspec-2026.6.0.dist-info/RECORD,,
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec-2026.6.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec-2026.6.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.
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/__init__.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import caching
2
+ from ._version import __version__ # noqa: F401
3
+ from .callbacks import Callback
4
+ from .compression import available_compressions
5
+ from .core import get_fs_token_paths, open, open_files, open_local, url_to_fs
6
+ from .exceptions import FSTimeoutError
7
+ from .mapping import FSMap, get_mapper
8
+ from .registry import (
9
+ available_protocols,
10
+ filesystem,
11
+ get_filesystem_class,
12
+ register_implementation,
13
+ registry,
14
+ )
15
+ from .spec import AbstractFileSystem
16
+
17
+ __all__ = [
18
+ "AbstractFileSystem",
19
+ "FSTimeoutError",
20
+ "FSMap",
21
+ "filesystem",
22
+ "register_implementation",
23
+ "get_filesystem_class",
24
+ "get_fs_token_paths",
25
+ "get_mapper",
26
+ "open",
27
+ "open_files",
28
+ "open_local",
29
+ "registry",
30
+ "caching",
31
+ "Callback",
32
+ "available_protocols",
33
+ "available_compressions",
34
+ "url_to_fs",
35
+ ]
36
+
37
+
38
+ def process_entries():
39
+ try:
40
+ from importlib.metadata import entry_points
41
+ except ImportError:
42
+ return
43
+ if entry_points is not None:
44
+ try:
45
+ eps = entry_points()
46
+ except TypeError:
47
+ pass # importlib-metadata < 0.8
48
+ else:
49
+ if hasattr(eps, "select"): # Python 3.10+ / importlib_metadata >= 3.9.0
50
+ specs = eps.select(group="fsspec.specs")
51
+ else:
52
+ specs = eps.get("fsspec.specs", [])
53
+ registered_names = {}
54
+ for spec in specs:
55
+ err_msg = f"Unable to load filesystem from {spec}"
56
+ name = spec.name
57
+ if name in registered_names:
58
+ continue
59
+ registered_names[name] = True
60
+ register_implementation(
61
+ name,
62
+ spec.value.replace(":", "."),
63
+ errtxt=err_msg,
64
+ # We take our implementations as the ones to overload with if
65
+ # for some reason we encounter some, may be the same, already
66
+ # registered
67
+ clobber=True,
68
+ )
69
+
70
+
71
+ process_entries()
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/_version.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '2026.6.0'
22
+ __version_tuple__ = version_tuple = (2026, 6, 0)
23
+
24
+ __commit_id__ = commit_id = None
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/archive.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+
3
+ from fsspec import AbstractFileSystem
4
+ from fsspec.utils import tokenize
5
+
6
+
7
+ class AbstractArchiveFileSystem(AbstractFileSystem):
8
+ """
9
+ A generic superclass for implementing Archive-based filesystems.
10
+
11
+ Currently, it is shared amongst
12
+ :class:`~fsspec.implementations.zip.ZipFileSystem`,
13
+ :class:`~fsspec.implementations.libarchive.LibArchiveFileSystem` and
14
+ :class:`~fsspec.implementations.tar.TarFileSystem`.
15
+ """
16
+
17
+ def __str__(self):
18
+ return f"<Archive-like object {type(self).__name__} at {id(self)}>"
19
+
20
+ __repr__ = __str__
21
+
22
+ def ukey(self, path):
23
+ return tokenize(path, self.fo, self.protocol)
24
+
25
+ def _all_dirnames(self, paths):
26
+ """Returns *all* directory names for each path in paths, including intermediate
27
+ ones.
28
+
29
+ Parameters
30
+ ----------
31
+ paths: Iterable of path strings
32
+ """
33
+ if len(paths) == 0:
34
+ return set()
35
+
36
+ dirnames = {self._parent(path) for path in paths} - {self.root_marker}
37
+ return dirnames | self._all_dirnames(dirnames)
38
+
39
+ def info(self, path, **kwargs):
40
+ self._get_dirs()
41
+ path = self._strip_protocol(path)
42
+ if path in {"", "/"} and self.dir_cache:
43
+ return {"name": "", "type": "directory", "size": 0}
44
+ if path in self.dir_cache:
45
+ return self.dir_cache[path]
46
+ elif path + "/" in self.dir_cache:
47
+ return self.dir_cache[path + "/"]
48
+ else:
49
+ raise FileNotFoundError(path)
50
+
51
+ def ls(self, path, detail=True, **kwargs):
52
+ self._get_dirs()
53
+ paths = {}
54
+ for p, f in self.dir_cache.items():
55
+ p = p.rstrip("/")
56
+ if "/" in p:
57
+ root = p.rsplit("/", 1)[0]
58
+ else:
59
+ root = ""
60
+ if root == path.rstrip("/"):
61
+ paths[p] = f
62
+ elif all(
63
+ (a == b)
64
+ for a, b in zip(path.split("/"), [""] + p.strip("/").split("/"))
65
+ ):
66
+ # root directory entry
67
+ ppath = p.rstrip("/").split("/", 1)[0]
68
+ if ppath not in paths:
69
+ out = {"name": ppath, "size": 0, "type": "directory"}
70
+ paths[ppath] = out
71
+ if detail:
72
+ out = sorted(paths.values(), key=operator.itemgetter("name"))
73
+ return out
74
+ else:
75
+ return sorted(paths)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/asyn.py ADDED
@@ -0,0 +1,1158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import asyncio.events
3
+ import functools
4
+ import inspect
5
+ import io
6
+ import numbers
7
+ import os
8
+ import re
9
+ import threading
10
+ from collections.abc import Iterable
11
+ from glob import has_magic
12
+ from typing import TYPE_CHECKING
13
+
14
+ from .callbacks import DEFAULT_CALLBACK
15
+ from .exceptions import FSTimeoutError
16
+ from .implementations.local import LocalFileSystem, make_path_posix, trailing_sep
17
+ from .spec import AbstractBufferedFile, AbstractFileSystem
18
+ from .utils import glob_translate, is_exception, other_paths
19
+
20
+ private = re.compile("_[^_]")
21
+ iothread = [None] # dedicated fsspec IO thread
22
+ loop = [None] # global event loop for any non-async instance
23
+ _lock = None # global lock placeholder
24
+ get_running_loop = asyncio.get_running_loop
25
+
26
+
27
+ def get_lock():
28
+ """Allocate or return a threading lock.
29
+
30
+ The lock is allocated on first use to allow setting one lock per forked process.
31
+ """
32
+ global _lock
33
+ if not _lock:
34
+ _lock = threading.Lock()
35
+ return _lock
36
+
37
+
38
+ def reset_lock():
39
+ """Reset the global lock.
40
+
41
+ This should be called only on the init of a forked process to reset the lock to
42
+ None, enabling the new forked process to get a new lock.
43
+ """
44
+ global _lock
45
+
46
+ iothread[0] = None
47
+ loop[0] = None
48
+ _lock = None
49
+
50
+
51
+ async def _runner(event, coro, result, timeout=None):
52
+ timeout = timeout if timeout else None # convert 0 or 0.0 to None
53
+ if timeout is not None:
54
+ coro = asyncio.wait_for(coro, timeout=timeout)
55
+ try:
56
+ result[0] = await coro
57
+ except Exception as ex:
58
+ result[0] = ex
59
+ finally:
60
+ event.set()
61
+
62
+
63
+ def sync(loop, func, *args, timeout=None, **kwargs):
64
+ """
65
+ Make loop run coroutine until it returns. Runs in other thread
66
+
67
+ Examples
68
+ --------
69
+ >>> fsspec.asyn.sync(fsspec.asyn.get_loop(), func, *args,
70
+ timeout=timeout, **kwargs)
71
+ """
72
+ timeout = timeout if timeout else None # convert 0 or 0.0 to None
73
+ # NB: if the loop is not running *yet*, it is OK to submit work
74
+ # and we will wait for it
75
+ if loop is None or loop.is_closed():
76
+ raise RuntimeError("Loop is not running")
77
+ try:
78
+ loop0 = asyncio.events.get_running_loop()
79
+ if loop0 is loop:
80
+ raise NotImplementedError("Calling sync() from within a running loop")
81
+ except NotImplementedError:
82
+ raise
83
+ except RuntimeError:
84
+ pass
85
+ coro = func(*args, **kwargs)
86
+ result = [None]
87
+ event = threading.Event()
88
+ asyncio.run_coroutine_threadsafe(_runner(event, coro, result, timeout), loop)
89
+ while True:
90
+ # this loops allows thread to get interrupted
91
+ if event.wait(1):
92
+ break
93
+ if timeout is not None:
94
+ timeout -= 1
95
+ if timeout < 0:
96
+ raise FSTimeoutError
97
+
98
+ return_result = result[0]
99
+ if isinstance(return_result, asyncio.TimeoutError):
100
+ # suppress asyncio.TimeoutError, raise FSTimeoutError
101
+ raise FSTimeoutError from return_result
102
+ elif isinstance(return_result, BaseException):
103
+ raise return_result
104
+ else:
105
+ return return_result
106
+
107
+
108
+ def sync_wrapper(func, obj=None):
109
+ """Given a function, make so can be called in blocking contexts
110
+
111
+ Leave obj=None if defining within a class. Pass the instance if attaching
112
+ as an attribute of the instance.
113
+ """
114
+
115
+ @functools.wraps(func)
116
+ def wrapper(*args, **kwargs):
117
+ self = obj or args[0]
118
+ return sync(self.loop, func, *args, **kwargs)
119
+
120
+ return wrapper
121
+
122
+
123
+ def async_gen_wrapper(func, obj=None):
124
+ """Given a async generator, make so can be called in blocking contexts"""
125
+
126
+ @functools.wraps(func)
127
+ def wrapper(*args, **kwargs):
128
+ self = obj or args[0]
129
+ gen = func(*args, **kwargs)
130
+ while True:
131
+ try:
132
+ yield sync(self.loop, gen.__anext__)
133
+ except StopAsyncIteration:
134
+ break
135
+
136
+ return wrapper
137
+
138
+
139
+ def get_loop():
140
+ """Create or return the default fsspec IO loop
141
+
142
+ The loop will be running on a separate thread.
143
+ """
144
+ if loop[0] is None:
145
+ with get_lock():
146
+ # repeat the check just in case the loop got filled between the
147
+ # previous two calls from another thread
148
+ if loop[0] is None:
149
+ loop[0] = asyncio.new_event_loop()
150
+ th = threading.Thread(target=loop[0].run_forever, name="fsspecIO")
151
+ th.daemon = True
152
+ th.start()
153
+ iothread[0] = th
154
+ return loop[0]
155
+
156
+
157
+ def reset_after_fork():
158
+ global lock
159
+ loop[0] = None
160
+ iothread[0] = None
161
+ lock = None
162
+
163
+
164
+ if hasattr(os, "register_at_fork"):
165
+ # should be posix; this will do nothing for spawn or forkserver subprocesses
166
+ os.register_at_fork(after_in_child=reset_after_fork)
167
+
168
+
169
+ if TYPE_CHECKING:
170
+ import resource
171
+
172
+ ResourceError = resource.error
173
+ else:
174
+ try:
175
+ import resource
176
+ except ImportError:
177
+ resource = None
178
+ ResourceError = OSError
179
+ else:
180
+ ResourceError = getattr(resource, "error", OSError)
181
+
182
+ _DEFAULT_BATCH_SIZE = 128
183
+ _NOFILES_DEFAULT_BATCH_SIZE = 1280
184
+
185
+
186
+ def _get_batch_size(nofiles=False):
187
+ from fsspec.config import conf
188
+
189
+ if nofiles:
190
+ if "nofiles_gather_batch_size" in conf:
191
+ return conf["nofiles_gather_batch_size"]
192
+ else:
193
+ if "gather_batch_size" in conf:
194
+ return conf["gather_batch_size"]
195
+ if nofiles:
196
+ return _NOFILES_DEFAULT_BATCH_SIZE
197
+ if resource is None:
198
+ return _DEFAULT_BATCH_SIZE
199
+
200
+ try:
201
+ soft_limit, _ = resource.getrlimit(resource.RLIMIT_NOFILE)
202
+ except (ImportError, ValueError, ResourceError):
203
+ return _DEFAULT_BATCH_SIZE
204
+
205
+ if soft_limit == resource.RLIM_INFINITY:
206
+ return -1
207
+ else:
208
+ return soft_limit // 8
209
+
210
+
211
+ def running_async() -> bool:
212
+ """Being executed by an event loop?"""
213
+ try:
214
+ asyncio.get_running_loop()
215
+ return True
216
+ except RuntimeError:
217
+ return False
218
+
219
+
220
+ async def _run_coros_in_chunks(
221
+ coros,
222
+ batch_size=None,
223
+ callback=DEFAULT_CALLBACK,
224
+ timeout=None,
225
+ return_exceptions=False,
226
+ nofiles=False,
227
+ ):
228
+ """Run the given coroutines in chunks.
229
+
230
+ Parameters
231
+ ----------
232
+ coros: list of coroutines to run
233
+ batch_size: int or None
234
+ Number of coroutines to submit/wait on simultaneously.
235
+ If -1, then it will not be any throttling. If
236
+ None, it will be inferred from _get_batch_size()
237
+ callback: fsspec.callbacks.Callback instance
238
+ Gets a relative_update when each coroutine completes
239
+ timeout: number or None
240
+ If given, each coroutine times out after this time. Note that, since
241
+ there are multiple batches, the total run time of this function will in
242
+ general be longer
243
+ return_exceptions: bool
244
+ Same meaning as in asyncio.gather
245
+ nofiles: bool
246
+ If inferring the batch_size, does this operation involve local files?
247
+ If yes, you normally expect smaller batches.
248
+ """
249
+
250
+ if batch_size is None:
251
+ batch_size = _get_batch_size(nofiles=nofiles)
252
+
253
+ if batch_size == -1:
254
+ batch_size = len(coros)
255
+ elif batch_size <= 0:
256
+ raise ValueError
257
+
258
+ async def _run_coro(coro, i):
259
+ try:
260
+ return await asyncio.wait_for(coro, timeout=timeout), i
261
+ except Exception as e:
262
+ if not return_exceptions:
263
+ raise
264
+ return e, i
265
+ finally:
266
+ callback.relative_update(1)
267
+
268
+ i = 0
269
+ n = len(coros)
270
+ results = [None] * n
271
+ pending = set()
272
+
273
+ while pending or i < n:
274
+ while len(pending) < batch_size and i < n:
275
+ pending.add(asyncio.ensure_future(_run_coro(coros[i], i)))
276
+ i += 1
277
+
278
+ if not pending:
279
+ break
280
+
281
+ done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
282
+ first_exc = None
283
+ while done:
284
+ task = done.pop()
285
+ try:
286
+ result, k = await task
287
+ results[k] = result
288
+ except Exception as exc:
289
+ if first_exc is None:
290
+ first_exc = exc
291
+
292
+ if first_exc is not None:
293
+ for task in pending:
294
+ task.cancel()
295
+ if pending:
296
+ await asyncio.gather(*pending, return_exceptions=True)
297
+ raise first_exc
298
+
299
+ return results
300
+
301
+
302
+ # these methods should be implemented as async by any async-able backend
303
+ async_methods = [
304
+ "_ls",
305
+ "_cat_file",
306
+ "_get_file",
307
+ "_put_file",
308
+ "_rm_file",
309
+ "_cp_file",
310
+ "_pipe_file",
311
+ "_expand_path",
312
+ "_info",
313
+ "_isfile",
314
+ "_isdir",
315
+ "_exists",
316
+ "_walk",
317
+ "_glob",
318
+ "_find",
319
+ "_du",
320
+ "_size",
321
+ "_mkdir",
322
+ "_makedirs",
323
+ ]
324
+
325
+
326
+ class AsyncFileSystem(AbstractFileSystem):
327
+ """Async file operations, default implementations
328
+
329
+ Passes bulk operations to asyncio.gather for concurrent operation.
330
+
331
+ Implementations that have concurrent batch operations and/or async methods
332
+ should inherit from this class instead of AbstractFileSystem. Docstrings are
333
+ copied from the un-underscored method in AbstractFileSystem, if not given.
334
+ """
335
+
336
+ # note that methods do not have docstring here; they will be copied
337
+ # for _* methods and inferred for overridden methods.
338
+
339
+ async_impl = True
340
+ mirror_sync_methods = True
341
+ disable_throttling = False
342
+
343
+ def __init__(self, *args, asynchronous=False, loop=None, batch_size=None, **kwargs):
344
+ self.asynchronous = asynchronous
345
+ self._pid = os.getpid()
346
+ if not asynchronous:
347
+ self._loop = loop or get_loop()
348
+ else:
349
+ self._loop = None
350
+ self.batch_size = batch_size
351
+ super().__init__(*args, **kwargs)
352
+
353
+ @property
354
+ def loop(self):
355
+ if self._pid != os.getpid():
356
+ raise RuntimeError("This class is not fork-safe")
357
+ return self._loop
358
+
359
+ async def _rm_file(self, path, **kwargs):
360
+ if (
361
+ inspect.iscoroutinefunction(self._rm)
362
+ and type(self)._rm is not AsyncFileSystem._rm
363
+ ):
364
+ return await self._rm(path, recursive=False, batch_size=1, **kwargs)
365
+ raise NotImplementedError
366
+
367
+ async def _rm(self, path, recursive=False, batch_size=None, **kwargs):
368
+ # TODO: implement on_error
369
+ batch_size = batch_size or self.batch_size
370
+ path = await self._expand_path(path, recursive=recursive)
371
+ return await _run_coros_in_chunks(
372
+ [self._rm_file(p, **kwargs) for p in reversed(path)],
373
+ batch_size=batch_size,
374
+ nofiles=True,
375
+ )
376
+
377
+ async def _cp_file(self, path1, path2, **kwargs):
378
+ raise NotImplementedError
379
+
380
+ async def _mv_file(self, path1, path2):
381
+ await self._cp_file(path1, path2)
382
+ await self._rm_file(path1)
383
+
384
+ async def _copy(
385
+ self,
386
+ path1,
387
+ path2,
388
+ recursive=False,
389
+ on_error=None,
390
+ maxdepth=None,
391
+ batch_size=None,
392
+ **kwargs,
393
+ ):
394
+ if on_error is None and recursive:
395
+ on_error = "ignore"
396
+ elif on_error is None:
397
+ on_error = "raise"
398
+
399
+ if isinstance(path1, list) and isinstance(path2, list):
400
+ # No need to expand paths when both source and destination
401
+ # are provided as lists
402
+ paths1 = path1
403
+ paths2 = path2
404
+ else:
405
+ source_is_str = isinstance(path1, str)
406
+ paths1 = await self._expand_path(
407
+ path1, maxdepth=maxdepth, recursive=recursive
408
+ )
409
+ if source_is_str and (not recursive or maxdepth is not None):
410
+ # Non-recursive glob does not copy directories
411
+ paths1 = [
412
+ p for p in paths1 if not (trailing_sep(p) or await self._isdir(p))
413
+ ]
414
+ if not paths1:
415
+ return
416
+
417
+ source_is_file = len(paths1) == 1
418
+ dest_is_dir = isinstance(path2, str) and (
419
+ trailing_sep(path2) or await self._isdir(path2)
420
+ )
421
+
422
+ exists = source_is_str and (
423
+ (has_magic(path1) and source_is_file)
424
+ or (not has_magic(path1) and dest_is_dir and not trailing_sep(path1))
425
+ )
426
+ paths2 = other_paths(
427
+ paths1,
428
+ path2,
429
+ exists=exists,
430
+ flatten=not source_is_str,
431
+ )
432
+
433
+ batch_size = batch_size or self.batch_size
434
+ coros = [self._cp_file(p1, p2, **kwargs) for p1, p2 in zip(paths1, paths2)]
435
+ result = await _run_coros_in_chunks(
436
+ coros, batch_size=batch_size, return_exceptions=True, nofiles=True
437
+ )
438
+
439
+ for ex in filter(is_exception, result):
440
+ if on_error == "ignore" and isinstance(ex, FileNotFoundError):
441
+ continue
442
+ raise ex
443
+
444
+ async def _pipe_file(self, path, value, mode="overwrite", **kwargs):
445
+ raise NotImplementedError
446
+
447
+ async def _pipe(self, path, value=None, batch_size=None, **kwargs):
448
+ if isinstance(path, str):
449
+ path = {path: value}
450
+ batch_size = batch_size or self.batch_size
451
+ return await _run_coros_in_chunks(
452
+ [self._pipe_file(k, v, **kwargs) for k, v in path.items()],
453
+ batch_size=batch_size,
454
+ nofiles=True,
455
+ )
456
+
457
+ async def _process_limits(self, url, start, end):
458
+ """Helper for "Range"-based _cat_file"""
459
+ size = None
460
+ suff = False
461
+ if start is not None and start < 0:
462
+ # if start is negative and end None, end is the "suffix length"
463
+ if end is None:
464
+ end = -start
465
+ start = ""
466
+ suff = True
467
+ else:
468
+ size = size or (await self._info(url))["size"]
469
+ start = size + start
470
+ elif start is None:
471
+ start = 0
472
+ if not suff:
473
+ if end is not None and end < 0:
474
+ if start is not None:
475
+ size = size or (await self._info(url))["size"]
476
+ end = size + end
477
+ elif end is None:
478
+ end = ""
479
+ if isinstance(end, numbers.Integral):
480
+ end -= 1 # bytes range is inclusive
481
+ return f"bytes={start}-{end}"
482
+
483
+ async def _cat_file(self, path, start=None, end=None, **kwargs):
484
+ raise NotImplementedError
485
+
486
+ async def _cat(
487
+ self, path, recursive=False, on_error="raise", batch_size=None, **kwargs
488
+ ):
489
+ paths = await self._expand_path(path, recursive=recursive)
490
+ coros = [self._cat_file(path, **kwargs) for path in paths]
491
+ batch_size = batch_size or self.batch_size
492
+ out = await _run_coros_in_chunks(
493
+ coros, batch_size=batch_size, nofiles=True, return_exceptions=True
494
+ )
495
+ if on_error == "raise":
496
+ ex = next(filter(is_exception, out), False)
497
+ if ex:
498
+ raise ex
499
+ if (
500
+ len(paths) > 1
501
+ or isinstance(path, list)
502
+ or paths[0] != self._strip_protocol(path)
503
+ ):
504
+ return {
505
+ k: v
506
+ for k, v in zip(paths, out)
507
+ if on_error != "omit" or not is_exception(v)
508
+ }
509
+ else:
510
+ return out[0]
511
+
512
+ async def _cat_ranges(
513
+ self,
514
+ paths,
515
+ starts,
516
+ ends,
517
+ max_gap=None,
518
+ batch_size=None,
519
+ on_error="return",
520
+ **kwargs,
521
+ ):
522
+ """Get the contents of byte ranges from one or more files
523
+
524
+ Parameters
525
+ ----------
526
+ paths: list
527
+ A list of of filepaths on this filesystems
528
+ starts, ends: int or list
529
+ Bytes limits of the read. If using a single int, the same value will be
530
+ used to read all the specified files.
531
+ on_error: "return" or "raise"
532
+ If "return" (default), any per-range exception is placed in the output
533
+ list at the corresponding position. Otherwise the first such exception
534
+ is raised. Matches ``AbstractFileSystem.cat_ranges``.
535
+ """
536
+ if max_gap is not None:
537
+ # use utils.merge_offset_ranges
538
+ raise NotImplementedError
539
+ if not isinstance(paths, list):
540
+ raise TypeError
541
+ if not isinstance(starts, Iterable):
542
+ starts = [starts] * len(paths)
543
+ if not isinstance(ends, Iterable):
544
+ ends = [ends] * len(paths)
545
+ if len(starts) != len(paths) or len(ends) != len(paths):
546
+ raise ValueError
547
+ coros = [
548
+ self._cat_file(p, start=s, end=e, **kwargs)
549
+ for p, s, e in zip(paths, starts, ends)
550
+ ]
551
+ batch_size = batch_size or self.batch_size
552
+ out = await _run_coros_in_chunks(
553
+ coros, batch_size=batch_size, nofiles=True, return_exceptions=True
554
+ )
555
+ if on_error != "return":
556
+ ex = next(filter(is_exception, out), None)
557
+ if ex is not None:
558
+ raise ex
559
+ return out
560
+
561
+ async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs):
562
+ raise NotImplementedError
563
+
564
+ async def _put(
565
+ self,
566
+ lpath,
567
+ rpath,
568
+ recursive=False,
569
+ callback=DEFAULT_CALLBACK,
570
+ batch_size=None,
571
+ maxdepth=None,
572
+ **kwargs,
573
+ ):
574
+ """Copy file(s) from local.
575
+
576
+ Copies a specific file or tree of files (if recursive=True). If rpath
577
+ ends with a "/", it will be assumed to be a directory, and target files
578
+ will go within.
579
+
580
+ The put_file method will be called concurrently on a batch of files. The
581
+ batch_size option can configure the amount of futures that can be executed
582
+ at the same time. If it is -1, then all the files will be uploaded concurrently.
583
+ The default can be set for this instance by passing "batch_size" in the
584
+ constructor, or for all instances by setting the "gather_batch_size" key
585
+ in ``fsspec.config.conf``, falling back to 1/8th of the system limit .
586
+ """
587
+ if isinstance(lpath, list) and isinstance(rpath, list):
588
+ # No need to expand paths when both source and destination
589
+ # are provided as lists
590
+ rpaths = rpath
591
+ lpaths = lpath
592
+ else:
593
+ source_is_str = isinstance(lpath, str)
594
+ if source_is_str:
595
+ lpath = make_path_posix(lpath)
596
+ fs = LocalFileSystem()
597
+ lpaths = fs.expand_path(lpath, recursive=recursive, maxdepth=maxdepth)
598
+ if source_is_str and (not recursive or maxdepth is not None):
599
+ # Non-recursive glob does not copy directories
600
+ lpaths = [p for p in lpaths if not (trailing_sep(p) or fs.isdir(p))]
601
+ if not lpaths:
602
+ return
603
+
604
+ source_is_file = len(lpaths) == 1
605
+ dest_is_dir = isinstance(rpath, str) and (
606
+ trailing_sep(rpath) or await self._isdir(rpath)
607
+ )
608
+
609
+ rpath = self._strip_protocol(rpath)
610
+ exists = source_is_str and (
611
+ (has_magic(lpath) and source_is_file)
612
+ or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath))
613
+ )
614
+ rpaths = other_paths(
615
+ lpaths,
616
+ rpath,
617
+ exists=exists,
618
+ flatten=not source_is_str,
619
+ )
620
+
621
+ is_dir = {l: os.path.isdir(l) for l in lpaths}
622
+ rdirs = [r for l, r in zip(lpaths, rpaths) if is_dir[l]]
623
+ file_pairs = [(l, r) for l, r in zip(lpaths, rpaths) if not is_dir[l]]
624
+
625
+ await asyncio.gather(*[self._makedirs(d, exist_ok=True) for d in rdirs])
626
+ batch_size = batch_size or self.batch_size
627
+
628
+ coros = []
629
+ callback.set_size(len(file_pairs))
630
+ for lfile, rfile in file_pairs:
631
+ put_file = callback.branch_coro(self._put_file)
632
+ coros.append(put_file(lfile, rfile, **kwargs))
633
+
634
+ return await _run_coros_in_chunks(
635
+ coros, batch_size=batch_size, callback=callback
636
+ )
637
+
638
+ async def _get_file(self, rpath, lpath, **kwargs):
639
+ raise NotImplementedError
640
+
641
+ async def _get(
642
+ self,
643
+ rpath,
644
+ lpath,
645
+ recursive=False,
646
+ callback=DEFAULT_CALLBACK,
647
+ maxdepth=None,
648
+ **kwargs,
649
+ ):
650
+ """Copy file(s) to local.
651
+
652
+ Copies a specific file or tree of files (if recursive=True). If lpath
653
+ ends with a "/", it will be assumed to be a directory, and target files
654
+ will go within. Can submit a list of paths, which may be glob-patterns
655
+ and will be expanded.
656
+
657
+ The get_file method will be called concurrently on a batch of files. The
658
+ batch_size option can configure the amount of futures that can be executed
659
+ at the same time. If it is -1, then all the files will be uploaded concurrently.
660
+ The default can be set for this instance by passing "batch_size" in the
661
+ constructor, or for all instances by setting the "gather_batch_size" key
662
+ in ``fsspec.config.conf``, falling back to 1/8th of the system limit .
663
+ """
664
+ if isinstance(lpath, list) and isinstance(rpath, list):
665
+ # No need to expand paths when both source and destination
666
+ # are provided as lists
667
+ rpaths = rpath
668
+ lpaths = lpath
669
+ else:
670
+ source_is_str = isinstance(rpath, str)
671
+ # First check for rpath trailing slash as _strip_protocol removes it.
672
+ source_not_trailing_sep = source_is_str and not trailing_sep(rpath)
673
+ rpath = self._strip_protocol(rpath)
674
+ rpaths = await self._expand_path(
675
+ rpath, recursive=recursive, maxdepth=maxdepth
676
+ )
677
+ if source_is_str and (not recursive or maxdepth is not None):
678
+ # Non-recursive glob does not copy directories
679
+ rpaths = [
680
+ p for p in rpaths if not (trailing_sep(p) or await self._isdir(p))
681
+ ]
682
+ if not rpaths:
683
+ return
684
+
685
+ lpath = make_path_posix(lpath)
686
+ source_is_file = len(rpaths) == 1
687
+ dest_is_dir = isinstance(lpath, str) and (
688
+ trailing_sep(lpath) or LocalFileSystem().isdir(lpath)
689
+ )
690
+
691
+ exists = source_is_str and (
692
+ (has_magic(rpath) and source_is_file)
693
+ or (not has_magic(rpath) and dest_is_dir and source_not_trailing_sep)
694
+ )
695
+ lpaths = other_paths(
696
+ rpaths,
697
+ lpath,
698
+ exists=exists,
699
+ flatten=not source_is_str,
700
+ )
701
+
702
+ [os.makedirs(os.path.dirname(lp), exist_ok=True) for lp in lpaths]
703
+ batch_size = kwargs.pop("batch_size", self.batch_size)
704
+
705
+ coros = []
706
+ callback.set_size(len(lpaths))
707
+ for lpath, rpath in zip(lpaths, rpaths):
708
+ get_file = callback.branch_coro(self._get_file)
709
+ coros.append(get_file(rpath, lpath, **kwargs))
710
+ return await _run_coros_in_chunks(
711
+ coros, batch_size=batch_size, callback=callback
712
+ )
713
+
714
+ async def _isfile(self, path):
715
+ try:
716
+ return (await self._info(path))["type"] == "file"
717
+ except: # noqa: E722
718
+ return False
719
+
720
+ async def _isdir(self, path):
721
+ try:
722
+ return (await self._info(path))["type"] == "directory"
723
+ except OSError:
724
+ return False
725
+
726
+ async def _size(self, path):
727
+ return (await self._info(path)).get("size", None)
728
+
729
+ async def _sizes(self, paths, batch_size=None):
730
+ batch_size = batch_size or self.batch_size
731
+ return await _run_coros_in_chunks(
732
+ [self._size(p) for p in paths], batch_size=batch_size
733
+ )
734
+
735
+ async def _exists(self, path, **kwargs):
736
+ try:
737
+ await self._info(path, **kwargs)
738
+ return True
739
+ except FileNotFoundError:
740
+ return False
741
+
742
+ async def _info(self, path, **kwargs):
743
+ raise NotImplementedError
744
+
745
+ async def _ls(self, path, detail=True, **kwargs):
746
+ raise NotImplementedError
747
+
748
+ async def _walk(self, path, maxdepth=None, on_error="omit", **kwargs):
749
+ if maxdepth is not None and maxdepth < 1:
750
+ raise ValueError("maxdepth must be at least 1")
751
+
752
+ path = self._strip_protocol(path)
753
+ full_dirs = {}
754
+ dirs = {}
755
+ files = {}
756
+
757
+ detail = kwargs.pop("detail", False)
758
+ try:
759
+ listing = await self._ls(path, detail=True, **kwargs)
760
+ except (FileNotFoundError, OSError) as e:
761
+ if on_error == "raise":
762
+ raise
763
+ elif callable(on_error):
764
+ on_error(e)
765
+ if detail:
766
+ yield path, {}, {}
767
+ else:
768
+ yield path, [], []
769
+ return
770
+
771
+ for info in listing:
772
+ # each info name must be at least [path]/part , but here
773
+ # we check also for names like [path]/part/
774
+ pathname = info["name"].rstrip("/")
775
+ name = pathname.rsplit("/", 1)[-1]
776
+ if info["type"] == "directory" and pathname != path:
777
+ # do not include "self" path
778
+ full_dirs[name] = pathname
779
+ dirs[name] = info
780
+ elif pathname == path:
781
+ # file-like with same name as give path
782
+ files[""] = info
783
+ else:
784
+ files[name] = info
785
+
786
+ if detail:
787
+ yield path, dirs, files
788
+ else:
789
+ yield path, list(dirs), list(files)
790
+
791
+ if maxdepth is not None:
792
+ maxdepth -= 1
793
+ if maxdepth < 1:
794
+ return
795
+
796
+ for d in dirs:
797
+ async for _ in self._walk(
798
+ full_dirs[d], maxdepth=maxdepth, detail=detail, **kwargs
799
+ ):
800
+ yield _
801
+
802
+ async def _glob(self, path, maxdepth=None, **kwargs):
803
+ if maxdepth is not None and maxdepth < 1:
804
+ raise ValueError("maxdepth must be at least 1")
805
+
806
+ import re
807
+
808
+ seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,)
809
+ ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash
810
+ path = self._strip_protocol(path)
811
+ append_slash_to_dirname = ends_with_sep or path.endswith(
812
+ tuple(sep + "**" for sep in seps)
813
+ )
814
+ idx_star = path.find("*") if path.find("*") >= 0 else len(path)
815
+ idx_qmark = path.find("?") if path.find("?") >= 0 else len(path)
816
+ idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
817
+
818
+ min_idx = min(idx_star, idx_qmark, idx_brace)
819
+
820
+ detail = kwargs.pop("detail", False)
821
+ withdirs = kwargs.pop("withdirs", True)
822
+
823
+ if not has_magic(path):
824
+ if await self._exists(path, **kwargs):
825
+ if not detail:
826
+ return [path]
827
+ else:
828
+ return {path: await self._info(path, **kwargs)}
829
+ else:
830
+ if not detail:
831
+ return [] # glob of non-existent returns empty
832
+ else:
833
+ return {}
834
+ elif "/" in path[:min_idx]:
835
+ first_wildcard_idx = min_idx
836
+ min_idx = path[:min_idx].rindex("/")
837
+ root = path[
838
+ : min_idx + 1
839
+ ] # everything up to the last / before the first wildcard
840
+ prefix = path[
841
+ min_idx + 1 : first_wildcard_idx
842
+ ] # stem between last "/" and first wildcard
843
+ depth = path[min_idx + 1 :].count("/") + 1
844
+ else:
845
+ root = ""
846
+ prefix = path[:min_idx] # stem up to the first wildcard
847
+ depth = path[min_idx + 1 :].count("/") + 1
848
+
849
+ if "**" in path:
850
+ if maxdepth is not None:
851
+ idx_double_stars = path.find("**")
852
+ depth_double_stars = path[idx_double_stars:].count("/") + 1
853
+ depth = depth - depth_double_stars + maxdepth
854
+ else:
855
+ depth = None
856
+
857
+ # Pass the filename stem as prefix= so backends that support it such as
858
+ # gcsfs, s3fs and adlfs can filter server-side up to the first wildcard.
859
+ if prefix:
860
+ kwargs["prefix"] = prefix
861
+ allpaths = await self._find(
862
+ root, maxdepth=depth, withdirs=withdirs, detail=True, **kwargs
863
+ )
864
+
865
+ pattern = glob_translate(path + ("/" if ends_with_sep else ""))
866
+ pattern = re.compile(pattern)
867
+
868
+ out = {
869
+ p: info
870
+ for p, info in sorted(allpaths.items())
871
+ if pattern.match(
872
+ p + "/"
873
+ if append_slash_to_dirname and info["type"] == "directory"
874
+ else p
875
+ )
876
+ }
877
+
878
+ if detail:
879
+ return out
880
+ else:
881
+ return list(out)
882
+
883
+ async def _du(self, path, total=True, maxdepth=None, **kwargs):
884
+ sizes = {}
885
+ # async for?
886
+ for f in await self._find(path, maxdepth=maxdepth, **kwargs):
887
+ info = await self._info(f)
888
+ sizes[info["name"]] = info["size"]
889
+ if total:
890
+ return sum(sizes.values())
891
+ else:
892
+ return sizes
893
+
894
+ async def _find(self, path, maxdepth=None, withdirs=False, **kwargs):
895
+ path = self._strip_protocol(path)
896
+ out = {}
897
+ detail = kwargs.pop("detail", False)
898
+
899
+ # Add the root directory if withdirs is requested
900
+ # This is needed for posix glob compliance
901
+ if withdirs and path != "" and await self._isdir(path):
902
+ out[path] = await self._info(path)
903
+
904
+ # async for?
905
+ async for _, dirs, files in self._walk(path, maxdepth, detail=True, **kwargs):
906
+ if withdirs:
907
+ files.update(dirs)
908
+ out.update({info["name"]: info for name, info in files.items()})
909
+ if not out and (await self._isfile(path)):
910
+ # walk works on directories, but find should also return [path]
911
+ # when path happens to be a file
912
+ out[path] = {}
913
+ names = sorted(out)
914
+ if not detail:
915
+ return names
916
+ else:
917
+ return {name: out[name] for name in names}
918
+
919
+ async def _expand_path(
920
+ self, path, recursive=False, maxdepth=None, assume_literal=False
921
+ ):
922
+ if maxdepth is not None and maxdepth < 1:
923
+ raise ValueError("maxdepth must be at least 1")
924
+
925
+ if isinstance(path, str):
926
+ out = await self._expand_path([path], recursive, maxdepth)
927
+ else:
928
+ out = set()
929
+ path = [self._strip_protocol(p) for p in path]
930
+ for p in path: # can gather here
931
+ if not assume_literal and has_magic(p):
932
+ bit = set(await self._glob(p, maxdepth=maxdepth))
933
+ out |= bit
934
+ if recursive:
935
+ # glob call above expanded one depth so if maxdepth is defined
936
+ # then decrement it in expand_path call below. If it is zero
937
+ # after decrementing then avoid expand_path call.
938
+ if maxdepth is not None and maxdepth <= 1:
939
+ continue
940
+ out |= set(
941
+ await self._expand_path(
942
+ list(bit),
943
+ recursive=recursive,
944
+ maxdepth=maxdepth - 1 if maxdepth is not None else None,
945
+ assume_literal=True,
946
+ )
947
+ )
948
+ continue
949
+ elif recursive:
950
+ rec = set(await self._find(p, maxdepth=maxdepth, withdirs=True))
951
+ out |= rec
952
+ if p not in out and (recursive is False or (await self._exists(p))):
953
+ # should only check once, for the root
954
+ out.add(p)
955
+ if not out:
956
+ raise FileNotFoundError(path)
957
+ return sorted(out)
958
+
959
+ async def _mkdir(self, path, create_parents=True, **kwargs):
960
+ pass # not necessary to implement, may not have directories
961
+
962
+ async def _makedirs(self, path, exist_ok=False):
963
+ pass # not necessary to implement, may not have directories
964
+
965
+ async def open_async(self, path, mode="rb", **kwargs):
966
+ if "b" not in mode or kwargs.get("compression"):
967
+ raise ValueError
968
+ raise NotImplementedError
969
+
970
+
971
+ def mirror_sync_methods(obj):
972
+ """Populate sync and async methods for obj
973
+
974
+ For each method will create a sync version if the name refers to an async method
975
+ (coroutine) and there is no override in the child class; will create an async
976
+ method for the corresponding sync method if there is no implementation.
977
+
978
+ Uses the methods specified in
979
+ - async_methods: the set that an implementation is expected to provide
980
+ - default_async_methods: that can be derived from their sync version in
981
+ AbstractFileSystem
982
+ - AsyncFileSystem: async-specific default coroutines
983
+ """
984
+ from fsspec import AbstractFileSystem
985
+
986
+ for method in set(async_methods + dir(AsyncFileSystem)):
987
+ if not method.startswith("_"):
988
+ continue
989
+ smethod = method[1:]
990
+ if private.match(method):
991
+ isco = inspect.iscoroutinefunction(getattr(obj, method, None))
992
+ unsync = getattr(getattr(obj, smethod, False), "__func__", None)
993
+ is_default = unsync is getattr(AbstractFileSystem, smethod, "")
994
+ if isco and is_default:
995
+ mth = sync_wrapper(getattr(obj, method), obj=obj)
996
+ elif inspect.isasyncgenfunction(getattr(obj, method, None)) and is_default:
997
+ mth = async_gen_wrapper(getattr(obj, method), obj=obj)
998
+ else:
999
+ continue
1000
+ setattr(obj, smethod, mth)
1001
+ if not mth.__doc__:
1002
+ mth.__doc__ = getattr(
1003
+ getattr(AbstractFileSystem, smethod, None), "__doc__", ""
1004
+ )
1005
+
1006
+
1007
+ class FSSpecCoroutineCancel(Exception):
1008
+ pass
1009
+
1010
+
1011
+ def _dump_running_tasks(
1012
+ printout=True, cancel=True, exc=FSSpecCoroutineCancel, with_task=False
1013
+ ):
1014
+ import traceback
1015
+
1016
+ tasks = [t for t in asyncio.tasks.all_tasks(loop[0]) if not t.done()]
1017
+ if printout:
1018
+ [task.print_stack() for task in tasks]
1019
+ out = [
1020
+ {
1021
+ "locals": task._coro.cr_frame.f_locals,
1022
+ "file": task._coro.cr_frame.f_code.co_filename,
1023
+ "firstline": task._coro.cr_frame.f_code.co_firstlineno,
1024
+ "linelo": task._coro.cr_frame.f_lineno,
1025
+ "stack": traceback.format_stack(task._coro.cr_frame),
1026
+ "task": task if with_task else None,
1027
+ }
1028
+ for task in tasks
1029
+ ]
1030
+ if cancel:
1031
+ for t in tasks:
1032
+ cbs = t._callbacks
1033
+ t.cancel()
1034
+ asyncio.futures.Future.set_exception(t, exc)
1035
+ asyncio.futures.Future.cancel(t)
1036
+ [cb[0](t) for cb in cbs] # cancels any dependent concurrent.futures
1037
+ try:
1038
+ t._coro.throw(exc) # exits coro, unless explicitly handled
1039
+ except exc:
1040
+ pass
1041
+ return out
1042
+
1043
+
1044
+ class AbstractAsyncStreamedFile(AbstractBufferedFile):
1045
+ # no read buffering, and always auto-commit
1046
+ # TODO: readahead might still be useful here, but needs async version
1047
+
1048
+ async def read(self, length=-1):
1049
+ """
1050
+ Return data from cache, or fetch pieces as necessary
1051
+
1052
+ Parameters
1053
+ ----------
1054
+ length: int (-1)
1055
+ Number of bytes to read; if <0, all remaining bytes.
1056
+ """
1057
+ length = -1 if length is None else int(length)
1058
+ if self.mode != "rb":
1059
+ raise ValueError("File not in read mode")
1060
+ if length < 0:
1061
+ length = self.size - self.loc
1062
+ if self.closed:
1063
+ raise ValueError("I/O operation on closed file.")
1064
+ if length == 0:
1065
+ # don't even bother calling fetch
1066
+ return b""
1067
+ out = await self._fetch_range(self.loc, self.loc + length)
1068
+ self.loc += len(out)
1069
+ return out
1070
+
1071
+ async def write(self, data):
1072
+ """
1073
+ Write data to buffer.
1074
+
1075
+ Buffer only sent on flush() or if buffer is greater than
1076
+ or equal to blocksize.
1077
+
1078
+ Parameters
1079
+ ----------
1080
+ data: bytes
1081
+ Set of bytes to be written.
1082
+ """
1083
+ if self.mode not in {"wb", "ab"}:
1084
+ raise ValueError("File not in write mode")
1085
+ if self.closed:
1086
+ raise ValueError("I/O operation on closed file.")
1087
+ if self.forced:
1088
+ raise ValueError("This file has been force-flushed, can only close")
1089
+ out = self.buffer.write(data)
1090
+ self.loc += out
1091
+ if self.buffer.tell() >= self.blocksize:
1092
+ await self.flush()
1093
+ return out
1094
+
1095
+ async def close(self):
1096
+ """Close file
1097
+
1098
+ Finalizes writes, discards cache
1099
+ """
1100
+ if getattr(self, "_unclosable", False):
1101
+ return
1102
+ if self.closed:
1103
+ return
1104
+ if self.mode == "rb":
1105
+ self.cache = None
1106
+ else:
1107
+ if not self.forced:
1108
+ await self.flush(force=True)
1109
+
1110
+ if self.fs is not None:
1111
+ self.fs.invalidate_cache(self.path)
1112
+ self.fs.invalidate_cache(self.fs._parent(self.path))
1113
+
1114
+ self.closed = True
1115
+
1116
+ async def flush(self, force=False):
1117
+ if self.closed:
1118
+ raise ValueError("Flush on closed file")
1119
+ if force and self.forced:
1120
+ raise ValueError("Force flush cannot be called more than once")
1121
+ if force:
1122
+ self.forced = True
1123
+
1124
+ if self.mode not in {"wb", "ab"}:
1125
+ # no-op to flush on read-mode
1126
+ return
1127
+
1128
+ if not force and self.buffer.tell() < self.blocksize:
1129
+ # Defer write on small block
1130
+ return
1131
+
1132
+ if self.offset is None:
1133
+ # Initialize a multipart upload
1134
+ self.offset = 0
1135
+ try:
1136
+ await self._initiate_upload()
1137
+ except:
1138
+ self.closed = True
1139
+ raise
1140
+
1141
+ if await self._upload_chunk(final=force) is not False:
1142
+ self.offset += self.buffer.seek(0, 2)
1143
+ self.buffer = io.BytesIO()
1144
+
1145
+ async def __aenter__(self):
1146
+ return self
1147
+
1148
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
1149
+ await self.close()
1150
+
1151
+ async def _fetch_range(self, start, end):
1152
+ raise NotImplementedError
1153
+
1154
+ async def _initiate_upload(self):
1155
+ pass
1156
+
1157
+ async def _upload_chunk(self, final=False):
1158
+ raise NotImplementedError
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/caching.py ADDED
@@ -0,0 +1,1004 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections
4
+ import functools
5
+ import logging
6
+ import math
7
+ import os
8
+ import threading
9
+ from collections import OrderedDict
10
+ from collections.abc import Callable
11
+ from concurrent.futures import Future, ThreadPoolExecutor
12
+ from itertools import groupby
13
+ from operator import itemgetter
14
+ from typing import TYPE_CHECKING, Any, ClassVar, Generic, NamedTuple, TypeVar
15
+
16
+ if TYPE_CHECKING:
17
+ import mmap
18
+
19
+ from typing_extensions import ParamSpec
20
+
21
+ P = ParamSpec("P")
22
+ else:
23
+ P = TypeVar("P")
24
+
25
+ T = TypeVar("T")
26
+
27
+
28
+ logger = logging.getLogger("fsspec.caching")
29
+
30
+ Fetcher = Callable[[int, int], bytes] # Maps (start, end) to bytes
31
+ MultiFetcher = Callable[[list[int, int]], bytes] # Maps [(start, end)] to bytes
32
+
33
+
34
+ class BaseCache:
35
+ """Pass-though cache: doesn't keep anything, calls every time
36
+
37
+ Acts as base class for other cachers
38
+
39
+ Parameters
40
+ ----------
41
+ blocksize: int
42
+ How far to read ahead in numbers of bytes
43
+ fetcher: func
44
+ Function of the form f(start, end) which gets bytes from remote as
45
+ specified
46
+ size: int
47
+ How big this file is
48
+ """
49
+
50
+ name: ClassVar[str] = "none"
51
+
52
+ def __init__(self, blocksize: int, fetcher: Fetcher, size: int) -> None:
53
+ self.blocksize = blocksize
54
+ self.nblocks = 0
55
+ self.fetcher = fetcher
56
+ self.size = size
57
+ self.hit_count = 0
58
+ self.miss_count = 0
59
+ # the bytes that we actually requested
60
+ self.total_requested_bytes = 0
61
+
62
+ def _fetch(self, start: int | None, stop: int | None) -> bytes:
63
+ if start is None:
64
+ start = 0
65
+ if stop is None:
66
+ stop = self.size
67
+ if start >= self.size or start >= stop:
68
+ return b""
69
+ return self.fetcher(start, stop)
70
+
71
+ def _reset_stats(self) -> None:
72
+ """Reset hit and miss counts for a more ganular report e.g. by file."""
73
+ self.hit_count = 0
74
+ self.miss_count = 0
75
+ self.total_requested_bytes = 0
76
+
77
+ def _log_stats(self) -> str:
78
+ """Return a formatted string of the cache statistics."""
79
+ if self.hit_count == 0 and self.miss_count == 0:
80
+ # a cache that does nothing, this is for logs only
81
+ return ""
82
+ return f" , {self.name}: {self.hit_count} hits, {self.miss_count} misses, {self.total_requested_bytes} total requested bytes"
83
+
84
+ def __repr__(self) -> str:
85
+ # TODO: use rich for better formatting
86
+ return f"""
87
+ <{self.__class__.__name__}:
88
+ block size : {self.blocksize}
89
+ block count : {self.nblocks}
90
+ file size : {self.size}
91
+ cache hits : {self.hit_count}
92
+ cache misses: {self.miss_count}
93
+ total requested bytes: {self.total_requested_bytes}>
94
+ """
95
+
96
+
97
+ class MMapCache(BaseCache):
98
+ """memory-mapped sparse file cache
99
+
100
+ Opens temporary file, which is filled blocks-wise when data is requested.
101
+ Ensure there is enough disc space in the temporary location.
102
+
103
+ This cache method might only work on posix
104
+
105
+ Parameters
106
+ ----------
107
+ blocksize: int
108
+ How far to read ahead in numbers of bytes
109
+ fetcher: Fetcher
110
+ Function of the form f(start, end) which gets bytes from remote as
111
+ specified
112
+ size: int
113
+ How big this file is
114
+ location: str
115
+ Where to create the temporary file. If None, a temporary file is
116
+ created using tempfile.TemporaryFile().
117
+ blocks: set[int]
118
+ Set of block numbers that have already been fetched. If None, an empty
119
+ set is created.
120
+ multi_fetcher: MultiFetcher
121
+ Function of the form f([(start, end)]) which gets bytes from remote
122
+ as specified. This function is used to fetch multiple blocks at once.
123
+ If not specified, the fetcher function is used instead.
124
+ """
125
+
126
+ name = "mmap"
127
+
128
+ def __init__(
129
+ self,
130
+ blocksize: int,
131
+ fetcher: Fetcher,
132
+ size: int,
133
+ location: str | None = None,
134
+ blocks: set[int] | None = None,
135
+ multi_fetcher: MultiFetcher | None = None,
136
+ ) -> None:
137
+ super().__init__(blocksize, fetcher, size)
138
+ self.blocks = set() if blocks is None else blocks
139
+ self.location = location
140
+ self.multi_fetcher = multi_fetcher
141
+ self.cache = self._makefile()
142
+
143
+ def _makefile(self) -> mmap.mmap | bytearray:
144
+ import mmap
145
+ import tempfile
146
+
147
+ if self.size == 0:
148
+ return bytearray()
149
+
150
+ # posix version
151
+ if self.location is None or not os.path.exists(self.location):
152
+ if self.location is None:
153
+ fd = tempfile.TemporaryFile()
154
+ self.blocks = set()
155
+ else:
156
+ fd = open(self.location, "wb+")
157
+ fd.seek(self.size - 1)
158
+ fd.write(b"1")
159
+ fd.flush()
160
+ else:
161
+ fd = open(self.location, "r+b")
162
+
163
+ return mmap.mmap(fd.fileno(), self.size)
164
+
165
+ def _fetch(self, start: int | None, end: int | None) -> bytes:
166
+ logger.debug(f"MMap cache fetching {start}-{end}")
167
+ if start is None:
168
+ start = 0
169
+ if end is None:
170
+ end = self.size
171
+ if start >= self.size or start >= end:
172
+ return b""
173
+ start_block = start // self.blocksize
174
+ end_block = end // self.blocksize
175
+ block_range = range(start_block, end_block + 1)
176
+ # Determine which blocks need to be fetched. This sequence is sorted by construction.
177
+ need = (i for i in block_range if i not in self.blocks)
178
+ # Count the number of blocks already cached
179
+ self.hit_count += sum(1 for i in block_range if i in self.blocks)
180
+
181
+ ranges = []
182
+
183
+ # Consolidate needed blocks.
184
+ # Algorithm adapted from Python 2.x itertools documentation.
185
+ # We are grouping an enumerated sequence of blocks. By comparing when the difference
186
+ # between an ascending range (provided by enumerate) and the needed block numbers
187
+ # we can detect when the block number skips values. The key computes this difference.
188
+ # Whenever the difference changes, we know that we have previously cached block(s),
189
+ # and a new group is started. In other words, this algorithm neatly groups
190
+ # runs of consecutive block numbers so they can be fetched together.
191
+ for _, _blocks in groupby(enumerate(need), key=lambda x: x[0] - x[1]):
192
+ # Extract the blocks from the enumerated sequence
193
+ _blocks = tuple(map(itemgetter(1), _blocks))
194
+ # Compute start of first block
195
+ sstart = _blocks[0] * self.blocksize
196
+ # Compute the end of the last block. Last block may not be full size.
197
+ send = min(_blocks[-1] * self.blocksize + self.blocksize, self.size)
198
+
199
+ # Fetch bytes (could be multiple consecutive blocks)
200
+ self.total_requested_bytes += send - sstart
201
+ logger.debug(
202
+ f"MMap get blocks {_blocks[0]}-{_blocks[-1]} ({sstart}-{send})"
203
+ )
204
+ ranges.append((sstart, send))
205
+
206
+ # Update set of cached blocks
207
+ self.blocks.update(_blocks)
208
+ # Update cache statistics with number of blocks we had to cache
209
+ self.miss_count += len(_blocks)
210
+
211
+ if not ranges:
212
+ return self.cache[start:end]
213
+
214
+ if self.multi_fetcher:
215
+ logger.debug(f"MMap get blocks {ranges}")
216
+ for idx, r in enumerate(self.multi_fetcher(ranges)):
217
+ sstart, send = ranges[idx]
218
+ logger.debug(f"MMap copy block ({sstart}-{send}")
219
+ self.cache[sstart:send] = r
220
+ else:
221
+ for sstart, send in ranges:
222
+ logger.debug(f"MMap get block ({sstart}-{send}")
223
+ self.cache[sstart:send] = self.fetcher(sstart, send)
224
+
225
+ return self.cache[start:end]
226
+
227
+ def __getstate__(self) -> dict[str, Any]:
228
+ state = self.__dict__.copy()
229
+ # Remove the unpicklable entries.
230
+ del state["cache"]
231
+ return state
232
+
233
+ def __setstate__(self, state: dict[str, Any]) -> None:
234
+ # Restore instance attributes
235
+ self.__dict__.update(state)
236
+ self.cache = self._makefile()
237
+
238
+
239
+ class ReadAheadCache(BaseCache):
240
+ """Cache which reads only when we get beyond a block of data
241
+
242
+ This is a much simpler version of BytesCache, and does not attempt to
243
+ fill holes in the cache or keep fragments alive. It is best suited to
244
+ many small reads in a sequential order (e.g., reading lines from a file).
245
+ """
246
+
247
+ name = "readahead"
248
+
249
+ def __init__(self, blocksize: int, fetcher: Fetcher, size: int) -> None:
250
+ super().__init__(blocksize, fetcher, size)
251
+ self.cache = b""
252
+ self.start = 0
253
+ self.end = 0
254
+
255
+ def _fetch(self, start: int | None, end: int | None) -> bytes:
256
+ if start is None:
257
+ start = 0
258
+ if end is None or end > self.size:
259
+ end = self.size
260
+ if start >= self.size or start >= end:
261
+ return b""
262
+ l = end - start
263
+ if start >= self.start and end <= self.end:
264
+ # cache hit
265
+ self.hit_count += 1
266
+ return self.cache[start - self.start : end - self.start]
267
+ elif self.start <= start < self.end:
268
+ # partial hit
269
+ self.miss_count += 1
270
+ part = self.cache[start - self.start :]
271
+ l -= len(part)
272
+ start = self.end
273
+ else:
274
+ # miss
275
+ self.miss_count += 1
276
+ part = b""
277
+ end = min(self.size, end + self.blocksize)
278
+ self.total_requested_bytes += end - start
279
+ self.cache = self.fetcher(start, end) # new block replaces old
280
+ self.start = start
281
+ self.end = self.start + len(self.cache)
282
+ return part + self.cache[:l]
283
+
284
+
285
+ class FirstChunkCache(BaseCache):
286
+ """Caches the first block of a file only
287
+
288
+ This may be useful for file types where the metadata is stored in the header,
289
+ but is randomly accessed.
290
+ """
291
+
292
+ name = "first"
293
+
294
+ def __init__(self, blocksize: int, fetcher: Fetcher, size: int) -> None:
295
+ if blocksize > size:
296
+ # this will buffer the whole thing
297
+ blocksize = size
298
+ super().__init__(blocksize, fetcher, size)
299
+ self.cache: bytes | None = None
300
+
301
+ def _fetch(self, start: int | None, end: int | None) -> bytes:
302
+ start = start or 0
303
+ if start > self.size:
304
+ logger.debug("FirstChunkCache: requested start > file size")
305
+ return b""
306
+
307
+ end = min(end, self.size)
308
+
309
+ if start < self.blocksize:
310
+ if self.cache is None:
311
+ self.miss_count += 1
312
+ if end > self.blocksize:
313
+ self.total_requested_bytes += end
314
+ data = self.fetcher(0, end)
315
+ self.cache = data[: self.blocksize]
316
+ return data[start:]
317
+ self.cache = self.fetcher(0, self.blocksize)
318
+ self.total_requested_bytes += self.blocksize
319
+ part = self.cache[start:end]
320
+ if end > self.blocksize:
321
+ self.total_requested_bytes += end - self.blocksize
322
+ part += self.fetcher(self.blocksize, end)
323
+ self.hit_count += 1
324
+ return part
325
+ else:
326
+ self.miss_count += 1
327
+ self.total_requested_bytes += end - start
328
+ return self.fetcher(start, end)
329
+
330
+
331
+ class BlockCache(BaseCache):
332
+ """
333
+ Cache holding memory as a set of blocks.
334
+
335
+ Requests are only ever made ``blocksize`` at a time, and are
336
+ stored in an LRU cache. The least recently accessed block is
337
+ discarded when more than ``maxblocks`` are stored.
338
+
339
+ Parameters
340
+ ----------
341
+ blocksize : int
342
+ The number of bytes to store in each block.
343
+ Requests are only ever made for ``blocksize``, so this
344
+ should balance the overhead of making a request against
345
+ the granularity of the blocks.
346
+ fetcher : Callable
347
+ size : int
348
+ The total size of the file being cached.
349
+ maxblocks : int
350
+ The maximum number of blocks to cache for. The maximum memory
351
+ use for this cache is then ``blocksize * maxblocks``.
352
+ """
353
+
354
+ name = "blockcache"
355
+
356
+ def __init__(
357
+ self, blocksize: int, fetcher: Fetcher, size: int, maxblocks: int = 32
358
+ ) -> None:
359
+ super().__init__(blocksize, fetcher, size)
360
+ self.nblocks = math.ceil(size / blocksize)
361
+ self.maxblocks = maxblocks
362
+ self._fetch_block_cached = functools.lru_cache(maxblocks)(self._fetch_block)
363
+
364
+ def cache_info(self):
365
+ """
366
+ The statistics on the block cache.
367
+
368
+ Returns
369
+ -------
370
+ NamedTuple
371
+ Returned directly from the LRU Cache used internally.
372
+ """
373
+ return self._fetch_block_cached.cache_info()
374
+
375
+ def __getstate__(self) -> dict[str, Any]:
376
+ state = self.__dict__
377
+ del state["_fetch_block_cached"]
378
+ return state
379
+
380
+ def __setstate__(self, state: dict[str, Any]) -> None:
381
+ self.__dict__.update(state)
382
+ self._fetch_block_cached = functools.lru_cache(state["maxblocks"])(
383
+ self._fetch_block
384
+ )
385
+
386
+ def _fetch(self, start: int | None, end: int | None) -> bytes:
387
+ if start is None:
388
+ start = 0
389
+ if end is None:
390
+ end = self.size
391
+ if start >= self.size or start >= end:
392
+ return b""
393
+
394
+ return self._read_cache(
395
+ start, end, start // self.blocksize, (end - 1) // self.blocksize
396
+ )
397
+
398
+ def _fetch_block(self, block_number: int) -> bytes:
399
+ """
400
+ Fetch the block of data for `block_number`.
401
+ """
402
+ if block_number > self.nblocks:
403
+ raise ValueError(
404
+ f"'block_number={block_number}' is greater than "
405
+ f"the number of blocks ({self.nblocks})"
406
+ )
407
+
408
+ start = block_number * self.blocksize
409
+ end = start + self.blocksize
410
+ self.total_requested_bytes += end - start
411
+ self.miss_count += 1
412
+ logger.info("BlockCache fetching block %d", block_number)
413
+ block_contents = super()._fetch(start, end)
414
+ return block_contents
415
+
416
+ def _read_cache(
417
+ self, start: int, end: int, start_block_number: int, end_block_number: int
418
+ ) -> bytes:
419
+ """
420
+ Read from our block cache.
421
+
422
+ Parameters
423
+ ----------
424
+ start, end : int
425
+ The start and end byte positions.
426
+ start_block_number, end_block_number : int
427
+ The start and end block numbers.
428
+ """
429
+ start_pos = start % self.blocksize
430
+ end_pos = end % self.blocksize
431
+ if end_pos == 0:
432
+ end_pos = self.blocksize
433
+
434
+ self.hit_count += 1
435
+ if start_block_number == end_block_number:
436
+ block: bytes = self._fetch_block_cached(start_block_number)
437
+ return block[start_pos:end_pos]
438
+
439
+ else:
440
+ # read from the initial
441
+ out = [self._fetch_block_cached(start_block_number)[start_pos:]]
442
+
443
+ # intermediate blocks
444
+ # Note: it'd be nice to combine these into one big request. However
445
+ # that doesn't play nicely with our LRU cache.
446
+ out.extend(
447
+ map(
448
+ self._fetch_block_cached,
449
+ range(start_block_number + 1, end_block_number),
450
+ )
451
+ )
452
+
453
+ # final block
454
+ out.append(self._fetch_block_cached(end_block_number)[:end_pos])
455
+
456
+ return b"".join(out)
457
+
458
+
459
+ class BytesCache(BaseCache):
460
+ """Cache which holds data in a in-memory bytes object
461
+
462
+ Implements read-ahead by the block size, for semi-random reads progressing
463
+ through the file.
464
+
465
+ Parameters
466
+ ----------
467
+ trim: bool
468
+ As we read more data, whether to discard the start of the buffer when
469
+ we are more than a blocksize ahead of it.
470
+ """
471
+
472
+ name: ClassVar[str] = "bytes"
473
+
474
+ def __init__(
475
+ self, blocksize: int, fetcher: Fetcher, size: int, trim: bool = True
476
+ ) -> None:
477
+ super().__init__(blocksize, fetcher, size)
478
+ self.cache = b""
479
+ self.start: int | None = None
480
+ self.end: int | None = None
481
+ self.trim = trim
482
+
483
+ def _fetch(self, start: int | None, end: int | None) -> bytes:
484
+ # TODO: only set start/end after fetch, in case it fails?
485
+ # is this where retry logic might go?
486
+ if start is None:
487
+ start = 0
488
+ if end is None:
489
+ end = self.size
490
+ if start >= self.size or start >= end:
491
+ return b""
492
+ if (
493
+ self.start is not None
494
+ and start >= self.start
495
+ and self.end is not None
496
+ and end < self.end
497
+ ):
498
+ # cache hit: we have all the required data
499
+ offset = start - self.start
500
+ self.hit_count += 1
501
+ return self.cache[offset : offset + end - start]
502
+
503
+ if self.blocksize:
504
+ bend = min(self.size, end + self.blocksize)
505
+ else:
506
+ bend = end
507
+
508
+ if bend == start or start > self.size:
509
+ return b""
510
+
511
+ if (self.start is None or start < self.start) and (
512
+ self.end is None or end > self.end
513
+ ):
514
+ # First read, or extending both before and after
515
+ self.total_requested_bytes += bend - start
516
+ self.miss_count += 1
517
+ self.cache = self.fetcher(start, bend)
518
+ self.start = start
519
+ else:
520
+ assert self.start is not None
521
+ assert self.end is not None
522
+ self.miss_count += 1
523
+
524
+ if start < self.start:
525
+ if self.end is None or self.end - end > self.blocksize:
526
+ self.total_requested_bytes += bend - start
527
+ self.cache = self.fetcher(start, bend)
528
+ self.start = start
529
+ else:
530
+ self.total_requested_bytes += self.start - start
531
+ new = self.fetcher(start, self.start)
532
+ self.start = start
533
+ self.cache = new + self.cache
534
+ elif self.end is not None and bend > self.end:
535
+ if self.end > self.size:
536
+ pass
537
+ elif end - self.end > self.blocksize:
538
+ self.total_requested_bytes += bend - start
539
+ self.cache = self.fetcher(start, bend)
540
+ self.start = start
541
+ else:
542
+ self.total_requested_bytes += bend - self.end
543
+ new = self.fetcher(self.end, bend)
544
+ self.cache = self.cache + new
545
+
546
+ self.end = self.start + len(self.cache)
547
+ offset = start - self.start
548
+ out = self.cache[offset : offset + end - start]
549
+ if self.trim:
550
+ num = (self.end - self.start) // (self.blocksize + 1)
551
+ if num > 1:
552
+ self.start += self.blocksize * num
553
+ self.cache = self.cache[self.blocksize * num :]
554
+ return out
555
+
556
+ def __len__(self) -> int:
557
+ return len(self.cache)
558
+
559
+
560
+ class AllBytes(BaseCache):
561
+ """Cache entire contents of the file"""
562
+
563
+ name: ClassVar[str] = "all"
564
+
565
+ def __init__(
566
+ self,
567
+ blocksize: int | None = None,
568
+ fetcher: Fetcher | None = None,
569
+ size: int | None = None,
570
+ data: bytes | None = None,
571
+ ) -> None:
572
+ super().__init__(blocksize, fetcher, size) # type: ignore[arg-type]
573
+ if data is None:
574
+ self.miss_count += 1
575
+ self.total_requested_bytes += self.size
576
+ data = self.fetcher(0, self.size)
577
+ self.data = data
578
+
579
+ def _fetch(self, start: int | None, stop: int | None) -> bytes:
580
+ self.hit_count += 1
581
+ return self.data[start:stop]
582
+
583
+
584
+ class KnownPartsOfAFile(BaseCache):
585
+ """
586
+ Cache holding known file parts.
587
+
588
+ Parameters
589
+ ----------
590
+ blocksize: int
591
+ How far to read ahead in numbers of bytes
592
+ fetcher: func
593
+ Function of the form f(start, end) which gets bytes from remote as
594
+ specified
595
+ size: int
596
+ How big this file is
597
+ data: dict
598
+ A dictionary mapping explicit `(start, stop)` file-offset tuples
599
+ with known bytes.
600
+ strict: bool, default True
601
+ Whether to fetch reads that go beyond a known byte-range boundary.
602
+ If `False`, any read that ends outside a known part will be zero
603
+ padded. Note that zero padding will not be used for reads that
604
+ begin outside a known byte-range.
605
+ """
606
+
607
+ name: ClassVar[str] = "parts"
608
+
609
+ def __init__(
610
+ self,
611
+ blocksize: int,
612
+ fetcher: Fetcher,
613
+ size: int,
614
+ data: dict[tuple[int, int], bytes] | None = None,
615
+ strict: bool = False,
616
+ **_: Any,
617
+ ):
618
+ super().__init__(blocksize, fetcher, size)
619
+ self.strict = strict
620
+
621
+ # simple consolidation of contiguous blocks
622
+ if data:
623
+ old_offsets = sorted(data.keys())
624
+ offsets = [old_offsets[0]]
625
+ blocks = [data.pop(old_offsets[0])]
626
+ for start, stop in old_offsets[1:]:
627
+ start0, stop0 = offsets[-1]
628
+ if start == stop0:
629
+ offsets[-1] = (start0, stop)
630
+ blocks[-1] += data.pop((start, stop))
631
+ else:
632
+ offsets.append((start, stop))
633
+ blocks.append(data.pop((start, stop)))
634
+
635
+ self.data = dict(zip(offsets, blocks))
636
+ else:
637
+ self.data = {}
638
+
639
+ @property
640
+ def size(self):
641
+ return sum(_[1] - _[0] for _ in self.data)
642
+
643
+ @size.setter
644
+ def size(self, value):
645
+ pass
646
+
647
+ @property
648
+ def nblocks(self):
649
+ return len(self.data)
650
+
651
+ @nblocks.setter
652
+ def nblocks(self, value):
653
+ pass
654
+
655
+ def _fetch(self, start: int | None, stop: int | None) -> bytes:
656
+ logger.debug("Known parts request %s %s", start, stop)
657
+ if start is None:
658
+ start = 0
659
+ if stop is None:
660
+ stop = self.size
661
+ self.total_requested_bytes += stop - start
662
+ out = b""
663
+ started = False
664
+ loc_old = 0
665
+ for loc0, loc1 in sorted(self.data):
666
+ if (loc0 <= start < loc1) and (loc0 <= stop <= loc1):
667
+ # entirely within the block
668
+ off = start - loc0
669
+ self.hit_count += 1
670
+ return self.data[(loc0, loc1)][off : off + stop - start]
671
+ if stop <= loc0:
672
+ break
673
+ if started and loc0 > loc_old:
674
+ # a gap where we need data
675
+ self.miss_count += 1
676
+ if self.strict:
677
+ raise ValueError
678
+ out += b"\x00" * (loc0 - loc_old)
679
+ if loc0 <= start < loc1:
680
+ # found the start
681
+ self.hit_count += 1
682
+ off = start - loc0
683
+ out = self.data[(loc0, loc1)][off : off + stop - start]
684
+ started = True
685
+ elif start < loc0 and stop > loc1:
686
+ # the whole block
687
+ self.hit_count += 1
688
+ out += self.data[(loc0, loc1)]
689
+ elif loc0 <= stop <= loc1:
690
+ # end block
691
+ self.hit_count += 1
692
+ out = out + self.data[(loc0, loc1)][: stop - loc0]
693
+ return out
694
+ loc_old = loc1
695
+ self.miss_count += 1
696
+ if started and not self.strict:
697
+ out = out + b"\x00" * (stop - loc_old)
698
+ return out
699
+ raise ValueError
700
+
701
+
702
+ class UpdatableLRU(Generic[P, T]):
703
+ """
704
+ Custom implementation of LRU cache that allows updating keys
705
+
706
+ Used by BackgroundBlockCache
707
+ """
708
+
709
+ class CacheInfo(NamedTuple):
710
+ hits: int
711
+ misses: int
712
+ maxsize: int
713
+ currsize: int
714
+
715
+ def __init__(self, func: Callable[P, T], max_size: int = 128) -> None:
716
+ self._cache: OrderedDict[Any, T] = collections.OrderedDict()
717
+ self._func = func
718
+ self._max_size = max_size
719
+ self._hits = 0
720
+ self._misses = 0
721
+ self._lock = threading.Lock()
722
+
723
+ def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T:
724
+ if kwargs:
725
+ raise TypeError(f"Got unexpected keyword argument {kwargs.keys()}")
726
+ with self._lock:
727
+ if args in self._cache:
728
+ self._cache.move_to_end(args)
729
+ self._hits += 1
730
+ return self._cache[args]
731
+
732
+ result = self._func(*args, **kwargs)
733
+
734
+ with self._lock:
735
+ self._cache[args] = result
736
+ self._misses += 1
737
+ if len(self._cache) > self._max_size:
738
+ self._cache.popitem(last=False)
739
+
740
+ return result
741
+
742
+ def is_key_cached(self, *args: Any) -> bool:
743
+ with self._lock:
744
+ return args in self._cache
745
+
746
+ def add_key(self, result: T, *args: Any) -> None:
747
+ with self._lock:
748
+ self._cache[args] = result
749
+ if len(self._cache) > self._max_size:
750
+ self._cache.popitem(last=False)
751
+
752
+ def cache_info(self) -> UpdatableLRU.CacheInfo:
753
+ with self._lock:
754
+ return self.CacheInfo(
755
+ maxsize=self._max_size,
756
+ currsize=len(self._cache),
757
+ hits=self._hits,
758
+ misses=self._misses,
759
+ )
760
+
761
+
762
+ class BackgroundBlockCache(BaseCache):
763
+ """
764
+ Cache holding memory as a set of blocks with pre-loading of
765
+ the next block in the background.
766
+
767
+ Requests are only ever made ``blocksize`` at a time, and are
768
+ stored in an LRU cache. The least recently accessed block is
769
+ discarded when more than ``maxblocks`` are stored. If the
770
+ next block is not in cache, it is loaded in a separate thread
771
+ in non-blocking way.
772
+
773
+ Parameters
774
+ ----------
775
+ blocksize : int
776
+ The number of bytes to store in each block.
777
+ Requests are only ever made for ``blocksize``, so this
778
+ should balance the overhead of making a request against
779
+ the granularity of the blocks.
780
+ fetcher : Callable
781
+ size : int
782
+ The total size of the file being cached.
783
+ maxblocks : int
784
+ The maximum number of blocks to cache for. The maximum memory
785
+ use for this cache is then ``blocksize * maxblocks``.
786
+ """
787
+
788
+ name: ClassVar[str] = "background"
789
+
790
+ def __init__(
791
+ self, blocksize: int, fetcher: Fetcher, size: int, maxblocks: int = 32
792
+ ) -> None:
793
+ super().__init__(blocksize, fetcher, size)
794
+ self.nblocks = math.ceil(size / blocksize)
795
+ self.maxblocks = maxblocks
796
+ self._fetch_block_cached = UpdatableLRU(self._fetch_block, maxblocks)
797
+
798
+ self._thread_executor = ThreadPoolExecutor(max_workers=1)
799
+ self._fetch_future_block_number: int | None = None
800
+ self._fetch_future: Future[bytes] | None = None
801
+ self._fetch_future_lock = threading.Lock()
802
+
803
+ def cache_info(self) -> UpdatableLRU.CacheInfo:
804
+ """
805
+ The statistics on the block cache.
806
+
807
+ Returns
808
+ -------
809
+ NamedTuple
810
+ Returned directly from the LRU Cache used internally.
811
+ """
812
+ return self._fetch_block_cached.cache_info()
813
+
814
+ def __getstate__(self) -> dict[str, Any]:
815
+ state = self.__dict__
816
+ del state["_fetch_block_cached"]
817
+ del state["_thread_executor"]
818
+ del state["_fetch_future_block_number"]
819
+ del state["_fetch_future"]
820
+ del state["_fetch_future_lock"]
821
+ return state
822
+
823
+ def __setstate__(self, state) -> None:
824
+ self.__dict__.update(state)
825
+ self._fetch_block_cached = UpdatableLRU(self._fetch_block, state["maxblocks"])
826
+ self._thread_executor = ThreadPoolExecutor(max_workers=1)
827
+ self._fetch_future_block_number = None
828
+ self._fetch_future = None
829
+ self._fetch_future_lock = threading.Lock()
830
+
831
+ def _fetch(self, start: int | None, end: int | None) -> bytes:
832
+ if start is None:
833
+ start = 0
834
+ if end is None:
835
+ end = self.size
836
+ if start >= self.size or start >= end:
837
+ return b""
838
+
839
+ # byte position -> block numbers
840
+ start_block_number = start // self.blocksize
841
+ end_block_number = end // self.blocksize
842
+
843
+ fetch_future_block_number = None
844
+ fetch_future = None
845
+ with self._fetch_future_lock:
846
+ # Background thread is running. Check we we can or must join it.
847
+ if self._fetch_future is not None:
848
+ assert self._fetch_future_block_number is not None
849
+ if self._fetch_future.done():
850
+ logger.info("BlockCache joined background fetch without waiting.")
851
+ self._fetch_block_cached.add_key(
852
+ self._fetch_future.result(), self._fetch_future_block_number
853
+ )
854
+ # Cleanup the fetch variables. Done with fetching the block.
855
+ self._fetch_future_block_number = None
856
+ self._fetch_future = None
857
+ else:
858
+ # Must join if we need the block for the current fetch
859
+ must_join = bool(
860
+ start_block_number
861
+ <= self._fetch_future_block_number
862
+ <= end_block_number
863
+ )
864
+ if must_join:
865
+ # Copy to the local variables to release lock
866
+ # before waiting for result
867
+ fetch_future_block_number = self._fetch_future_block_number
868
+ fetch_future = self._fetch_future
869
+
870
+ # Cleanup the fetch variables. Have a local copy.
871
+ self._fetch_future_block_number = None
872
+ self._fetch_future = None
873
+
874
+ # Need to wait for the future for the current read
875
+ if fetch_future is not None:
876
+ logger.info("BlockCache waiting for background fetch.")
877
+ # Wait until result and put it in cache
878
+ self._fetch_block_cached.add_key(
879
+ fetch_future.result(), fetch_future_block_number
880
+ )
881
+
882
+ # these are cached, so safe to do multiple calls for the same start and end.
883
+ for block_number in range(start_block_number, end_block_number + 1):
884
+ self._fetch_block_cached(block_number)
885
+
886
+ # fetch next block in the background if nothing is running in the background,
887
+ # the block is within file and it is not already cached
888
+ end_block_plus_1 = end_block_number + 1
889
+ with self._fetch_future_lock:
890
+ if (
891
+ self._fetch_future is None
892
+ and end_block_plus_1 <= self.nblocks
893
+ and not self._fetch_block_cached.is_key_cached(end_block_plus_1)
894
+ ):
895
+ self._fetch_future_block_number = end_block_plus_1
896
+ self._fetch_future = self._thread_executor.submit(
897
+ self._fetch_block, end_block_plus_1, "async"
898
+ )
899
+
900
+ return self._read_cache(
901
+ start,
902
+ end,
903
+ start_block_number=start_block_number,
904
+ end_block_number=end_block_number,
905
+ )
906
+
907
+ def _fetch_block(self, block_number: int, log_info: str = "sync") -> bytes:
908
+ """
909
+ Fetch the block of data for `block_number`.
910
+ """
911
+ if block_number > self.nblocks:
912
+ raise ValueError(
913
+ f"'block_number={block_number}' is greater than "
914
+ f"the number of blocks ({self.nblocks})"
915
+ )
916
+
917
+ start = block_number * self.blocksize
918
+ end = start + self.blocksize
919
+ logger.info("BlockCache fetching block (%s) %d", log_info, block_number)
920
+ self.total_requested_bytes += end - start
921
+ self.miss_count += 1
922
+ block_contents = super()._fetch(start, end)
923
+ return block_contents
924
+
925
+ def _read_cache(
926
+ self, start: int, end: int, start_block_number: int, end_block_number: int
927
+ ) -> bytes:
928
+ """
929
+ Read from our block cache.
930
+
931
+ Parameters
932
+ ----------
933
+ start, end : int
934
+ The start and end byte positions.
935
+ start_block_number, end_block_number : int
936
+ The start and end block numbers.
937
+ """
938
+ start_pos = start % self.blocksize
939
+ end_pos = end % self.blocksize
940
+
941
+ # kind of pointless to count this as a hit, but it is
942
+ self.hit_count += 1
943
+
944
+ if start_block_number == end_block_number:
945
+ block = self._fetch_block_cached(start_block_number)
946
+ return block[start_pos:end_pos]
947
+
948
+ else:
949
+ # read from the initial
950
+ out = [self._fetch_block_cached(start_block_number)[start_pos:]]
951
+
952
+ # intermediate blocks
953
+ # Note: it'd be nice to combine these into one big request. However
954
+ # that doesn't play nicely with our LRU cache.
955
+ out.extend(
956
+ map(
957
+ self._fetch_block_cached,
958
+ range(start_block_number + 1, end_block_number),
959
+ )
960
+ )
961
+
962
+ # final block
963
+ out.append(self._fetch_block_cached(end_block_number)[:end_pos])
964
+
965
+ return b"".join(out)
966
+
967
+
968
+ caches: dict[str | None, type[BaseCache]] = {
969
+ # one custom case
970
+ None: BaseCache,
971
+ }
972
+
973
+
974
+ def register_cache(cls: type[BaseCache], clobber: bool = False) -> None:
975
+ """'Register' cache implementation.
976
+
977
+ Parameters
978
+ ----------
979
+ clobber: bool, optional
980
+ If set to True (default is False) - allow to overwrite existing
981
+ entry.
982
+
983
+ Raises
984
+ ------
985
+ ValueError
986
+ """
987
+ name = cls.name
988
+ if not clobber and name in caches:
989
+ raise ValueError(f"Cache with name {name!r} is already known: {caches[name]}")
990
+ caches[name] = cls
991
+
992
+
993
+ for c in (
994
+ BaseCache,
995
+ MMapCache,
996
+ BytesCache,
997
+ ReadAheadCache,
998
+ BlockCache,
999
+ FirstChunkCache,
1000
+ AllBytes,
1001
+ KnownPartsOfAFile,
1002
+ BackgroundBlockCache,
1003
+ ):
1004
+ register_cache(c)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/callbacks.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import wraps
2
+
3
+
4
+ class Callback:
5
+ """
6
+ Base class and interface for callback mechanism
7
+
8
+ This class can be used directly for monitoring file transfers by
9
+ providing ``callback=Callback(hooks=...)`` (see the ``hooks`` argument,
10
+ below), or subclassed for more specialised behaviour.
11
+
12
+ Parameters
13
+ ----------
14
+ size: int (optional)
15
+ Nominal quantity for the value that corresponds to a complete
16
+ transfer, e.g., total number of tiles or total number of
17
+ bytes
18
+ value: int (0)
19
+ Starting internal counter value
20
+ hooks: dict or None
21
+ A dict of named functions to be called on each update. The signature
22
+ of these must be ``f(size, value, **kwargs)``
23
+ """
24
+
25
+ def __init__(self, size=None, value=0, hooks=None, **kwargs):
26
+ self.size = size
27
+ self.value = value
28
+ self.hooks = hooks or {}
29
+ self.kw = kwargs
30
+
31
+ def __enter__(self):
32
+ return self
33
+
34
+ def __exit__(self, *exc_args):
35
+ self.close()
36
+
37
+ def close(self):
38
+ """Close callback."""
39
+
40
+ def branched(self, path_1, path_2, **kwargs):
41
+ """
42
+ Return callback for child transfers
43
+
44
+ If this callback is operating at a higher level, e.g., put, which may
45
+ trigger transfers that can also be monitored. The function returns a callback
46
+ that has to be passed to the child method, e.g., put_file,
47
+ as `callback=` argument.
48
+
49
+ The implementation uses `callback.branch` for compatibility.
50
+ When implementing callbacks, it is recommended to override this function instead
51
+ of `branch` and avoid calling `super().branched(...)`.
52
+
53
+ Prefer using this function over `branch`.
54
+
55
+ Parameters
56
+ ----------
57
+ path_1: str
58
+ Child's source path
59
+ path_2: str
60
+ Child's destination path
61
+ **kwargs:
62
+ Arbitrary keyword arguments
63
+
64
+ Returns
65
+ -------
66
+ callback: Callback
67
+ A callback instance to be passed to the child method
68
+ """
69
+ self.branch(path_1, path_2, kwargs)
70
+ # mutate kwargs so that we can force the caller to pass "callback=" explicitly
71
+ return kwargs.pop("callback", DEFAULT_CALLBACK)
72
+
73
+ def branch_coro(self, fn):
74
+ """
75
+ Wraps a coroutine, and pass a new child callback to it.
76
+ """
77
+
78
+ @wraps(fn)
79
+ async def func(path1, path2: str, **kwargs):
80
+ with self.branched(path1, path2, **kwargs) as child:
81
+ return await fn(path1, path2, callback=child, **kwargs)
82
+
83
+ return func
84
+
85
+ def set_size(self, size):
86
+ """
87
+ Set the internal maximum size attribute
88
+
89
+ Usually called if not initially set at instantiation. Note that this
90
+ triggers a ``call()``.
91
+
92
+ Parameters
93
+ ----------
94
+ size: int
95
+ """
96
+ self.size = size
97
+ self.call()
98
+
99
+ def absolute_update(self, value):
100
+ """
101
+ Set the internal value state
102
+
103
+ Triggers ``call()``
104
+
105
+ Parameters
106
+ ----------
107
+ value: int
108
+ """
109
+ self.value = value
110
+ self.call()
111
+
112
+ def relative_update(self, inc=1):
113
+ """
114
+ Delta increment the internal counter
115
+
116
+ Triggers ``call()``
117
+
118
+ Parameters
119
+ ----------
120
+ inc: int
121
+ """
122
+ self.value += inc
123
+ self.call()
124
+
125
+ def call(self, hook_name=None, **kwargs):
126
+ """
127
+ Execute hook(s) with current state
128
+
129
+ Each function is passed the internal size and current value
130
+
131
+ Parameters
132
+ ----------
133
+ hook_name: str or None
134
+ If given, execute on this hook
135
+ kwargs: passed on to (all) hook(s)
136
+ """
137
+ if not self.hooks:
138
+ return
139
+ kw = self.kw.copy()
140
+ kw.update(kwargs)
141
+ if hook_name:
142
+ if hook_name not in self.hooks:
143
+ return
144
+ return self.hooks[hook_name](self.size, self.value, **kw)
145
+ for hook in self.hooks.values() or []:
146
+ hook(self.size, self.value, **kw)
147
+
148
+ def wrap(self, iterable):
149
+ """
150
+ Wrap an iterable to call ``relative_update`` on each iterations
151
+
152
+ Parameters
153
+ ----------
154
+ iterable: Iterable
155
+ The iterable that is being wrapped
156
+ """
157
+ for item in iterable:
158
+ self.relative_update()
159
+ yield item
160
+
161
+ def branch(self, path_1, path_2, kwargs):
162
+ """
163
+ Set callbacks for child transfers
164
+
165
+ If this callback is operating at a higher level, e.g., put, which may
166
+ trigger transfers that can also be monitored. The passed kwargs are
167
+ to be *mutated* to add ``callback=``, if this class supports branching
168
+ to children.
169
+
170
+ Parameters
171
+ ----------
172
+ path_1: str
173
+ Child's source path
174
+ path_2: str
175
+ Child's destination path
176
+ kwargs: dict
177
+ arguments passed to child method, e.g., put_file.
178
+
179
+ Returns
180
+ -------
181
+
182
+ """
183
+ return None
184
+
185
+ def no_op(self, *_, **__):
186
+ pass
187
+
188
+ def __getattr__(self, item):
189
+ """
190
+ If undefined methods are called on this class, nothing happens
191
+ """
192
+ return self.no_op
193
+
194
+ @classmethod
195
+ def as_callback(cls, maybe_callback=None):
196
+ """Transform callback=... into Callback instance
197
+
198
+ For the special value of ``None``, return the global instance of
199
+ ``NoOpCallback``. This is an alternative to including
200
+ ``callback=DEFAULT_CALLBACK`` directly in a method signature.
201
+ """
202
+ if maybe_callback is None:
203
+ return DEFAULT_CALLBACK
204
+ return maybe_callback
205
+
206
+
207
+ class NoOpCallback(Callback):
208
+ """
209
+ This implementation of Callback does exactly nothing
210
+ """
211
+
212
+ def call(self, *args, **kwargs):
213
+ return None
214
+
215
+
216
+ class DotPrinterCallback(Callback):
217
+ """
218
+ Simple example Callback implementation
219
+
220
+ Almost identical to Callback with a hook that prints a char; here we
221
+ demonstrate how the outer layer may print "#" and the inner layer "."
222
+ """
223
+
224
+ def __init__(self, chr_to_print="#", **kwargs):
225
+ self.chr = chr_to_print
226
+ super().__init__(**kwargs)
227
+
228
+ def branch(self, path_1, path_2, kwargs):
229
+ """Mutate kwargs to add new instance with different print char"""
230
+ kwargs["callback"] = DotPrinterCallback(".")
231
+
232
+ def call(self, **kwargs):
233
+ """Just outputs a character"""
234
+ print(self.chr, end="")
235
+
236
+
237
+ class TqdmCallback(Callback):
238
+ """
239
+ A callback to display a progress bar using tqdm
240
+
241
+ Parameters
242
+ ----------
243
+ tqdm_kwargs : dict, (optional)
244
+ Any argument accepted by the tqdm constructor.
245
+ See the `tqdm doc <https://tqdm.github.io/docs/tqdm/#__init__>`_.
246
+ Will be forwarded to `tqdm_cls`.
247
+ tqdm_cls: (optional)
248
+ subclass of `tqdm.tqdm`. If not passed, it will default to `tqdm.tqdm`.
249
+
250
+ Examples
251
+ --------
252
+ >>> import fsspec
253
+ >>> from fsspec.callbacks import TqdmCallback
254
+ >>> fs = fsspec.filesystem("memory")
255
+ >>> path2distant_data = "/your-path"
256
+ >>> fs.upload(
257
+ ".",
258
+ path2distant_data,
259
+ recursive=True,
260
+ callback=TqdmCallback(),
261
+ )
262
+
263
+ You can forward args to tqdm using the ``tqdm_kwargs`` parameter.
264
+
265
+ >>> fs.upload(
266
+ ".",
267
+ path2distant_data,
268
+ recursive=True,
269
+ callback=TqdmCallback(tqdm_kwargs={"desc": "Your tqdm description"}),
270
+ )
271
+
272
+ You can also customize the progress bar by passing a subclass of `tqdm`.
273
+
274
+ .. code-block:: python
275
+
276
+ class TqdmFormat(tqdm):
277
+ '''Provides a `total_time` format parameter'''
278
+ @property
279
+ def format_dict(self):
280
+ d = super().format_dict
281
+ total_time = d["elapsed"] * (d["total"] or 0) / max(d["n"], 1)
282
+ d.update(total_time=self.format_interval(total_time) + " in total")
283
+ return d
284
+
285
+ >>> with TqdmCallback(
286
+ tqdm_kwargs={
287
+ "desc": "desc",
288
+ "bar_format": "{total_time}: {percentage:.0f}%|{bar}{r_bar}",
289
+ },
290
+ tqdm_cls=TqdmFormat,
291
+ ) as callback:
292
+ fs.upload(".", path2distant_data, recursive=True, callback=callback)
293
+ """
294
+
295
+ def __init__(self, tqdm_kwargs=None, *args, **kwargs):
296
+ try:
297
+ from tqdm import tqdm
298
+
299
+ except ImportError as exce:
300
+ raise ImportError(
301
+ "Using TqdmCallback requires tqdm to be installed"
302
+ ) from exce
303
+
304
+ self._tqdm_cls = kwargs.pop("tqdm_cls", tqdm)
305
+ self._tqdm_kwargs = tqdm_kwargs or {}
306
+ self.tqdm = None
307
+ super().__init__(*args, **kwargs)
308
+
309
+ def call(self, *args, **kwargs):
310
+ if self.tqdm is None:
311
+ self.tqdm = self._tqdm_cls(total=self.size, **self._tqdm_kwargs)
312
+ self.tqdm.total = self.size
313
+ self.tqdm.update(self.value - self.tqdm.n)
314
+
315
+ def close(self):
316
+ if self.tqdm is not None:
317
+ self.tqdm.close()
318
+ self.tqdm = None
319
+
320
+ def __del__(self):
321
+ return self.close()
322
+
323
+
324
+ DEFAULT_CALLBACK = _DEFAULT_CALLBACK = NoOpCallback()
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/compression.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helper functions for a standard streaming compression API"""
2
+
3
+ import sys
4
+ from zipfile import ZipFile
5
+
6
+ import fsspec.utils
7
+ from fsspec.spec import AbstractBufferedFile
8
+
9
+
10
+ def noop_file(file, mode, **kwargs):
11
+ return file
12
+
13
+
14
+ # TODO: files should also be available as contexts
15
+ # should be functions of the form func(infile, mode=, **kwargs) -> file-like
16
+ compr = {None: noop_file}
17
+
18
+
19
+ def register_compression(name, callback, extensions, force=False):
20
+ """Register an "inferable" file compression type.
21
+
22
+ Registers transparent file compression type for use with fsspec.open.
23
+ Compression can be specified by name in open, or "infer"-ed for any files
24
+ ending with the given extensions.
25
+
26
+ Args:
27
+ name: (str) The compression type name. Eg. "gzip".
28
+ callback: A callable of form (infile, mode, **kwargs) -> file-like.
29
+ Accepts an input file-like object, the target mode and kwargs.
30
+ Returns a wrapped file-like object.
31
+ extensions: (str, Iterable[str]) A file extension, or list of file
32
+ extensions for which to infer this compression scheme. Eg. "gz".
33
+ force: (bool) Force re-registration of compression type or extensions.
34
+
35
+ Raises:
36
+ ValueError: If name or extensions already registered, and not force.
37
+
38
+ """
39
+ if isinstance(extensions, str):
40
+ extensions = [extensions]
41
+
42
+ # Validate registration
43
+ if name in compr and not force:
44
+ raise ValueError(f"Duplicate compression registration: {name}")
45
+
46
+ for ext in extensions:
47
+ if ext in fsspec.utils.compressions and not force:
48
+ raise ValueError(f"Duplicate compression file extension: {ext} ({name})")
49
+
50
+ compr[name] = callback
51
+
52
+ for ext in extensions:
53
+ fsspec.utils.compressions[ext] = name
54
+
55
+
56
+ def unzip(infile, mode="rb", filename=None, **kwargs):
57
+ if "r" not in mode:
58
+ filename = filename or "file"
59
+ z = ZipFile(infile, mode="w", **kwargs)
60
+ fo = z.open(filename, mode="w")
61
+ fo.close = lambda closer=fo.close: closer() or z.close()
62
+ return fo
63
+ z = ZipFile(infile)
64
+ if filename is None:
65
+ filename = z.namelist()[0]
66
+ return z.open(filename, mode="r", **kwargs)
67
+
68
+
69
+ register_compression("zip", unzip, "zip")
70
+
71
+ try:
72
+ from bz2 import BZ2File
73
+ except ImportError:
74
+ pass
75
+ else:
76
+ register_compression("bz2", BZ2File, "bz2")
77
+
78
+ try: # pragma: no cover
79
+ from isal import igzip
80
+
81
+ def isal(infile, mode="rb", **kwargs):
82
+ return igzip.IGzipFile(fileobj=infile, mode=mode, **kwargs)
83
+
84
+ register_compression("gzip", isal, "gz")
85
+ except ImportError:
86
+ from gzip import GzipFile
87
+
88
+ register_compression(
89
+ "gzip", lambda f, **kwargs: GzipFile(fileobj=f, **kwargs), "gz"
90
+ )
91
+
92
+ try:
93
+ from lzma import LZMAFile
94
+
95
+ register_compression("lzma", LZMAFile, "lzma")
96
+ register_compression("xz", LZMAFile, "xz")
97
+ except ImportError:
98
+ pass
99
+
100
+ try:
101
+ import lzmaffi
102
+
103
+ register_compression("lzma", lzmaffi.LZMAFile, "lzma", force=True)
104
+ register_compression("xz", lzmaffi.LZMAFile, "xz", force=True)
105
+ except ImportError:
106
+ pass
107
+
108
+
109
+ class SnappyFile(AbstractBufferedFile):
110
+ def __init__(self, infile, mode, **kwargs):
111
+ import snappy
112
+
113
+ super().__init__(
114
+ fs=None, path="snappy", mode=mode.strip("b") + "b", size=999999999, **kwargs
115
+ )
116
+ self.infile = infile
117
+ if "r" in mode:
118
+ self.codec = snappy.StreamDecompressor()
119
+ else:
120
+ self.codec = snappy.StreamCompressor()
121
+
122
+ def _upload_chunk(self, final=False):
123
+ self.buffer.seek(0)
124
+ out = self.codec.add_chunk(self.buffer.read())
125
+ self.infile.write(out)
126
+ return True
127
+
128
+ def seek(self, loc, whence=0):
129
+ raise NotImplementedError("SnappyFile is not seekable")
130
+
131
+ def seekable(self):
132
+ return False
133
+
134
+ def _fetch_range(self, start, end):
135
+ """Get the specified set of bytes from remote"""
136
+ data = self.infile.read(end - start)
137
+ return self.codec.decompress(data)
138
+
139
+
140
+ try:
141
+ import snappy
142
+
143
+ snappy.compress(b"")
144
+ # Snappy may use the .sz file extension, but this is not part of the
145
+ # standard implementation.
146
+ register_compression("snappy", SnappyFile, [])
147
+
148
+ except (ImportError, NameError, AttributeError):
149
+ pass
150
+
151
+ try:
152
+ import lz4.frame
153
+
154
+ register_compression("lz4", lz4.frame.open, "lz4")
155
+ except ImportError:
156
+ pass
157
+
158
+ try:
159
+ if sys.version_info >= (3, 14):
160
+ from compression import zstd
161
+ else:
162
+ from backports import zstd
163
+
164
+ register_compression("zstd", zstd.ZstdFile, "zst")
165
+ except ImportError:
166
+ try:
167
+ import zstandard as zstd
168
+
169
+ def zstandard_file(infile, mode="rb"):
170
+ if "r" in mode:
171
+ cctx = zstd.ZstdDecompressor()
172
+ return cctx.stream_reader(infile)
173
+ else:
174
+ cctx = zstd.ZstdCompressor(level=10)
175
+ return cctx.stream_writer(infile)
176
+
177
+ register_compression("zstd", zstandard_file, "zst")
178
+ except ImportError:
179
+ pass
180
+ pass
181
+
182
+
183
+ def available_compressions():
184
+ """Return a list of the implemented compressions."""
185
+ return list(compr)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/config.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import configparser
4
+ import json
5
+ import os
6
+ import warnings
7
+ from typing import Any
8
+
9
+ conf: dict[str, dict[str, Any]] = {}
10
+ default_conf_dir = os.path.join(os.path.expanduser("~"), ".config/fsspec")
11
+ conf_dir = os.environ.get("FSSPEC_CONFIG_DIR", default_conf_dir)
12
+
13
+
14
+ def set_conf_env(conf_dict, envdict=os.environ):
15
+ """Set config values from environment variables
16
+
17
+ Looks for variables of the form ``FSSPEC_<protocol>`` and
18
+ ``FSSPEC_<protocol>_<kwarg>``. For ``FSSPEC_<protocol>`` the value is parsed
19
+ as a json dictionary and used to ``update`` the config of the
20
+ corresponding protocol. For ``FSSPEC_<protocol>_<kwarg>`` there is no
21
+ attempt to convert the string value, but the kwarg keys will be lower-cased.
22
+
23
+ The ``FSSPEC_<protocol>_<kwarg>`` variables are applied after the
24
+ ``FSSPEC_<protocol>`` ones.
25
+
26
+ Parameters
27
+ ----------
28
+ conf_dict : dict(str, dict)
29
+ This dict will be mutated
30
+ envdict : dict-like(str, str)
31
+ Source for the values - usually the real environment
32
+ """
33
+ envdict = dict(envdict)
34
+ kwarg_keys = []
35
+ for key in envdict:
36
+ if key.startswith("FSSPEC_") and len(key) > 7 and key[7] != "_":
37
+ try:
38
+ value = json.loads(envdict[key])
39
+ envdict[key] = value
40
+ except json.decoder.JSONDecodeError:
41
+ value = envdict[key]
42
+ if key.count("_") > 1:
43
+ kwarg_keys.append(key)
44
+ continue
45
+ else:
46
+ if isinstance(value, dict):
47
+ _, proto = key.split("_", 1)
48
+ conf_dict.setdefault(proto.lower(), {}).update(value)
49
+ else:
50
+ warnings.warn(
51
+ f"Ignoring environment variable {key} due to not being a dict:"
52
+ f" {type(value)}"
53
+ )
54
+ elif key.startswith("FSSPEC"):
55
+ warnings.warn(
56
+ f"Ignoring environment variable {key} due to having an unexpected name"
57
+ )
58
+
59
+ for key in kwarg_keys:
60
+ _, proto, kwarg = key.split("_", 2)
61
+ conf_dict.setdefault(proto.lower(), {})[kwarg.lower()] = envdict[key]
62
+
63
+
64
+ def set_conf_files(cdir, conf_dict):
65
+ """Set config values from files
66
+
67
+ Scans for INI and JSON files in the given dictionary, and uses their
68
+ contents to set the config. In case of repeated values, later values
69
+ win.
70
+
71
+ In the case of INI files, all values are strings, and these will not
72
+ be converted.
73
+
74
+ Parameters
75
+ ----------
76
+ cdir : str
77
+ Directory to search
78
+ conf_dict : dict(str, dict)
79
+ This dict will be mutated
80
+ """
81
+ if not os.path.isdir(cdir):
82
+ return
83
+ allfiles = sorted(os.listdir(cdir))
84
+ for fn in allfiles:
85
+ if fn.endswith(".ini"):
86
+ ini = configparser.ConfigParser()
87
+ ini.read(os.path.join(cdir, fn))
88
+ for key in ini:
89
+ if key == "DEFAULT":
90
+ continue
91
+ conf_dict.setdefault(key, {}).update(dict(ini[key]))
92
+ if fn.endswith(".json"):
93
+ with open(os.path.join(cdir, fn)) as f:
94
+ js = json.load(f)
95
+ for key in js:
96
+ conf_dict.setdefault(key, {}).update(dict(js[key]))
97
+
98
+
99
+ def apply_config(cls, kwargs, conf_dict=None):
100
+ """Supply default values for kwargs when instantiating class
101
+
102
+ Augments the passed kwargs, by finding entries in the config dict
103
+ which match the classes ``.protocol`` attribute (one or more str)
104
+
105
+ Parameters
106
+ ----------
107
+ cls : file system implementation
108
+ kwargs : dict
109
+ conf_dict : dict of dict
110
+ Typically this is the global configuration
111
+
112
+ Returns
113
+ -------
114
+ dict : the modified set of kwargs
115
+ """
116
+ if conf_dict is None:
117
+ conf_dict = conf
118
+ protos = cls.protocol if isinstance(cls.protocol, (tuple, list)) else [cls.protocol]
119
+ kw = {}
120
+ for proto in protos:
121
+ # default kwargs from the current state of the config
122
+ if proto in conf_dict:
123
+ kw.update(conf_dict[proto])
124
+ # explicit kwargs always win
125
+ kw.update(**kwargs)
126
+ kwargs = kw
127
+ return kwargs
128
+
129
+
130
+ set_conf_files(conf_dir, conf)
131
+ set_conf_env(conf)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/conftest.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import subprocess
4
+ import sys
5
+ import time
6
+ from collections import deque
7
+ from collections.abc import Generator, Sequence
8
+
9
+ import pytest
10
+
11
+ import fsspec
12
+
13
+
14
+ @pytest.fixture()
15
+ def m():
16
+ """
17
+ Fixture providing a memory filesystem.
18
+ """
19
+ m = fsspec.filesystem("memory")
20
+ m.store.clear()
21
+ m.pseudo_dirs.clear()
22
+ m.pseudo_dirs.append("")
23
+ try:
24
+ yield m
25
+ finally:
26
+ m.store.clear()
27
+ m.pseudo_dirs.clear()
28
+ m.pseudo_dirs.append("")
29
+
30
+
31
+ class InstanceCacheInspector:
32
+ """
33
+ Helper class to inspect instance caches of filesystem classes in tests.
34
+ """
35
+
36
+ def clear(self) -> None:
37
+ """
38
+ Clear instance caches of all currently imported filesystem classes.
39
+ """
40
+ classes = deque([fsspec.spec.AbstractFileSystem])
41
+ while classes:
42
+ cls = classes.popleft()
43
+ cls.clear_instance_cache()
44
+ classes.extend(cls.__subclasses__())
45
+
46
+ def gather_counts(self, *, omit_zero: bool = True) -> dict[str, int]:
47
+ """
48
+ Gather counts of filesystem instances in the instance caches
49
+ of all currently imported filesystem classes.
50
+
51
+ Parameters
52
+ ----------
53
+ omit_zero:
54
+ Whether to omit instance types with no cached instances.
55
+ """
56
+ out: dict[str, int] = {}
57
+ classes = deque([fsspec.spec.AbstractFileSystem])
58
+ while classes:
59
+ cls = classes.popleft()
60
+ count = len(cls._cache) # there is no public interface for the cache
61
+ # note: skip intermediate AbstractFileSystem subclasses
62
+ # if they proxy the protocol attribute via a property.
63
+ if isinstance(cls.protocol, (Sequence, str)):
64
+ key = cls.protocol if isinstance(cls.protocol, str) else cls.protocol[0]
65
+ if count or not omit_zero:
66
+ out[key] = count
67
+ classes.extend(cls.__subclasses__())
68
+ return out
69
+
70
+
71
+ @pytest.fixture(scope="function", autouse=True)
72
+ def instance_caches() -> Generator[InstanceCacheInspector, None, None]:
73
+ """
74
+ Fixture to ensure empty filesystem instance caches before and after a test.
75
+
76
+ Used by default for all tests.
77
+ Clears caches of all imported filesystem classes.
78
+ Can be used to write test assertions about instance caches.
79
+
80
+ Usage:
81
+
82
+ def test_something(instance_caches):
83
+ # Test code here
84
+ fsspec.open("file://abc")
85
+ fsspec.open("memory://foo/bar")
86
+
87
+ # Test assertion
88
+ assert instance_caches.gather_counts() == {"file": 1, "memory": 1}
89
+
90
+ Returns
91
+ -------
92
+ instance_caches: An instance cache inspector for clearing and inspecting caches.
93
+ """
94
+ ic = InstanceCacheInspector()
95
+
96
+ ic.clear()
97
+ try:
98
+ yield ic
99
+ finally:
100
+ ic.clear()
101
+
102
+
103
+ @pytest.fixture(scope="function")
104
+ def ftp_writable(tmpdir):
105
+ """
106
+ Fixture providing a writable FTP filesystem.
107
+ """
108
+ pytest.importorskip("pyftpdlib")
109
+
110
+ d = str(tmpdir)
111
+ with open(os.path.join(d, "out"), "wb") as f:
112
+ f.write(b"hello" * 10000)
113
+ P = subprocess.Popen(
114
+ [sys.executable, "-m", "pyftpdlib", "-d", d, "-u", "user", "-P", "pass", "-w"]
115
+ )
116
+ try:
117
+ time.sleep(1)
118
+ yield "localhost", 2121, "user", "pass"
119
+ finally:
120
+ P.terminate()
121
+ P.wait()
122
+ try:
123
+ shutil.rmtree(tmpdir)
124
+ except Exception:
125
+ pass
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/core.py ADDED
@@ -0,0 +1,760 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import logging
5
+ import os
6
+ import re
7
+ from glob import has_magic
8
+ from pathlib import Path
9
+
10
+ # for backwards compat, we export cache things from here too
11
+ from fsspec.caching import ( # noqa: F401
12
+ BaseCache,
13
+ BlockCache,
14
+ BytesCache,
15
+ MMapCache,
16
+ ReadAheadCache,
17
+ caches,
18
+ )
19
+ from fsspec.compression import compr
20
+ from fsspec.config import conf
21
+ from fsspec.registry import available_protocols, filesystem, get_filesystem_class
22
+ from fsspec.utils import (
23
+ _unstrip_protocol,
24
+ build_name_function,
25
+ infer_compression,
26
+ stringify_path,
27
+ )
28
+
29
+ logger = logging.getLogger("fsspec")
30
+
31
+
32
+ class OpenFile:
33
+ """
34
+ File-like object to be used in a context
35
+
36
+ Can layer (buffered) text-mode and compression over any file-system, which
37
+ are typically binary-only.
38
+
39
+ These instances are safe to serialize, as the low-level file object
40
+ is not created until invoked using ``with``.
41
+
42
+ Parameters
43
+ ----------
44
+ fs: FileSystem
45
+ The file system to use for opening the file. Should be a subclass or duck-type
46
+ with ``fsspec.spec.AbstractFileSystem``
47
+ path: str
48
+ Location to open
49
+ mode: str like 'rb', optional
50
+ Mode of the opened file
51
+ compression: str or None, optional
52
+ Compression to apply
53
+ encoding: str or None, optional
54
+ The encoding to use if opened in text mode.
55
+ errors: str or None, optional
56
+ How to handle encoding errors if opened in text mode.
57
+ newline: None or str
58
+ Passed to TextIOWrapper in text mode, how to handle line endings.
59
+ autoopen: bool
60
+ If True, calls open() immediately. Mostly used by pickle
61
+ pos: int
62
+ If given and autoopen is True, seek to this location immediately
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ fs,
68
+ path,
69
+ mode="rb",
70
+ compression=None,
71
+ encoding=None,
72
+ errors=None,
73
+ newline=None,
74
+ ):
75
+ self.fs = fs
76
+ self.path = path
77
+ self.mode = mode
78
+ self.compression = get_compression(path, compression)
79
+ self.encoding = encoding
80
+ self.errors = errors
81
+ self.newline = newline
82
+ self.fobjects = []
83
+
84
+ def __reduce__(self):
85
+ return (
86
+ OpenFile,
87
+ (
88
+ self.fs,
89
+ self.path,
90
+ self.mode,
91
+ self.compression,
92
+ self.encoding,
93
+ self.errors,
94
+ self.newline,
95
+ ),
96
+ )
97
+
98
+ def __repr__(self):
99
+ return f"<OpenFile '{self.path}'>"
100
+
101
+ def __enter__(self):
102
+ mode = self.mode.replace("t", "").replace("b", "") + "b"
103
+
104
+ try:
105
+ f = self.fs.open(self.path, mode=mode)
106
+ except FileNotFoundError as e:
107
+ if has_magic(self.path):
108
+ raise FileNotFoundError(
109
+ "%s not found. The URL contains glob characters: you maybe needed\n"
110
+ "to pass expand=True in fsspec.open() or the storage_options of \n"
111
+ "your library. You can also set the config value 'open_expand'\n"
112
+ "before import, or fsspec.core.DEFAULT_EXPAND at runtime, to True.",
113
+ self.path,
114
+ ) from e
115
+ raise
116
+
117
+ self.fobjects = [f]
118
+
119
+ if self.compression is not None:
120
+ compress = compr[self.compression]
121
+ f = compress(f, mode=mode[0])
122
+ self.fobjects.append(f)
123
+
124
+ if "b" not in self.mode:
125
+ # assume, for example, that 'r' is equivalent to 'rt' as in builtin
126
+ f = PickleableTextIOWrapper(
127
+ f, encoding=self.encoding, errors=self.errors, newline=self.newline
128
+ )
129
+ self.fobjects.append(f)
130
+
131
+ return self.fobjects[-1]
132
+
133
+ def __exit__(self, *args):
134
+ self.close()
135
+
136
+ @property
137
+ def full_name(self):
138
+ return _unstrip_protocol(self.path, self.fs)
139
+
140
+ def open(self):
141
+ """Materialise this as a real open file without context
142
+
143
+ The OpenFile object should be explicitly closed to avoid enclosed file
144
+ instances persisting. You must, therefore, keep a reference to the OpenFile
145
+ during the life of the file-like it generates.
146
+ """
147
+ return self.__enter__()
148
+
149
+ def close(self):
150
+ """Close all encapsulated file objects"""
151
+ for f in reversed(self.fobjects):
152
+ if "r" not in self.mode and not f.closed:
153
+ f.flush()
154
+ f.close()
155
+ self.fobjects.clear()
156
+
157
+
158
+ class OpenFiles(list):
159
+ """List of OpenFile instances
160
+
161
+ Can be used in a single context, which opens and closes all of the
162
+ contained files. Normal list access to get the elements works as
163
+ normal.
164
+
165
+ A special case is made for caching filesystems - the files will
166
+ be down/uploaded together at the start or end of the context, and
167
+ this may happen concurrently, if the target filesystem supports it.
168
+ """
169
+
170
+ def __init__(self, *args, mode="rb", fs=None):
171
+ self.mode = mode
172
+ self.fs = fs
173
+ self.files = []
174
+ super().__init__(*args)
175
+
176
+ def __enter__(self):
177
+ if self.fs is None:
178
+ raise ValueError("Context has already been used")
179
+
180
+ fs = self.fs
181
+ while True:
182
+ if hasattr(fs, "open_many"):
183
+ # check for concurrent cache download; or set up for upload
184
+ self.files = fs.open_many(self)
185
+ return self.files
186
+ if hasattr(fs, "fs") and fs.fs is not None:
187
+ fs = fs.fs
188
+ else:
189
+ break
190
+ return [s.__enter__() for s in self]
191
+
192
+ def __exit__(self, *args):
193
+ fs = self.fs
194
+ [s.__exit__(*args) for s in self]
195
+ if "r" not in self.mode:
196
+ while True:
197
+ if hasattr(fs, "open_many"):
198
+ # check for concurrent cache upload
199
+ fs.commit_many(self.files)
200
+ return
201
+ if hasattr(fs, "fs") and fs.fs is not None:
202
+ fs = fs.fs
203
+ else:
204
+ break
205
+
206
+ def __getitem__(self, item):
207
+ out = super().__getitem__(item)
208
+ if isinstance(item, slice):
209
+ return OpenFiles(out, mode=self.mode, fs=self.fs)
210
+ return out
211
+
212
+ def __repr__(self):
213
+ return f"<List of {len(self)} OpenFile instances>"
214
+
215
+
216
+ def open_files(
217
+ urlpath,
218
+ mode="rb",
219
+ compression=None,
220
+ encoding="utf8",
221
+ errors=None,
222
+ name_function=None,
223
+ num=1,
224
+ protocol=None,
225
+ newline=None,
226
+ auto_mkdir=True,
227
+ expand=True,
228
+ **kwargs,
229
+ ):
230
+ """Given a path or paths, return a list of ``OpenFile`` objects.
231
+
232
+ For writing, a str path must contain the "*" character, which will be filled
233
+ in by increasing numbers, e.g., "part*" -> "part1", "part2" if num=2.
234
+
235
+ For either reading or writing, can instead provide explicit list of paths.
236
+
237
+ Parameters
238
+ ----------
239
+ urlpath: string or list
240
+ Absolute or relative filepath(s). Prefix with a protocol like ``s3://``
241
+ to read from alternative filesystems. To read from multiple files you
242
+ can pass a globstring or a list of paths, with the caveat that they
243
+ must all have the same protocol.
244
+ mode: 'rb', 'wt', etc.
245
+ compression: string or None
246
+ If given, open file using compression codec. Can either be a compression
247
+ name (a key in ``fsspec.compression.compr``) or "infer" to guess the
248
+ compression from the filename suffix.
249
+ encoding: str
250
+ For text mode only
251
+ errors: None or str
252
+ Passed to TextIOWrapper in text mode
253
+ name_function: function or None
254
+ if opening a set of files for writing, those files do not yet exist,
255
+ so we need to generate their names by formatting the urlpath for
256
+ each sequence number
257
+ num: int [1]
258
+ if writing mode, number of files we expect to create (passed to
259
+ name+function)
260
+ protocol: str or None
261
+ If given, overrides the protocol found in the URL.
262
+ newline: bytes or None
263
+ Used for line terminator in text mode. If None, uses system default;
264
+ if blank, uses no translation.
265
+ auto_mkdir: bool (True)
266
+ If in write mode, this will ensure the target directory exists before
267
+ writing, by calling ``fs.mkdirs(exist_ok=True)``.
268
+ expand: bool
269
+ **kwargs: dict
270
+ Extra options that make sense to a particular storage connection, e.g.
271
+ host, port, username, password, etc.
272
+
273
+ Examples
274
+ --------
275
+ >>> files = open_files('2015-*-*.csv') # doctest: +SKIP
276
+ >>> files = open_files(
277
+ ... 's3://bucket/2015-*-*.csv.gz', compression='gzip'
278
+ ... ) # doctest: +SKIP
279
+
280
+ Returns
281
+ -------
282
+ An ``OpenFiles`` instance, which is a list of ``OpenFile`` objects that can
283
+ be used as a single context
284
+
285
+ Notes
286
+ -----
287
+ For a full list of the available protocols and the implementations that
288
+ they map across to see the latest online documentation:
289
+
290
+ - For implementations built into ``fsspec`` see
291
+ https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations
292
+ - For implementations in separate packages see
293
+ https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations
294
+ """
295
+ fs, fs_token, paths = get_fs_token_paths(
296
+ urlpath,
297
+ mode,
298
+ num=num,
299
+ name_function=name_function,
300
+ storage_options=kwargs,
301
+ protocol=protocol,
302
+ expand=expand,
303
+ )
304
+ if fs.protocol == "file":
305
+ fs.auto_mkdir = auto_mkdir
306
+ elif "r" not in mode and auto_mkdir:
307
+ parents = {fs._parent(path) for path in paths}
308
+ for parent in parents:
309
+ try:
310
+ fs.makedirs(parent, exist_ok=True)
311
+ except PermissionError:
312
+ pass
313
+ return OpenFiles(
314
+ [
315
+ OpenFile(
316
+ fs,
317
+ path,
318
+ mode=mode,
319
+ compression=compression,
320
+ encoding=encoding,
321
+ errors=errors,
322
+ newline=newline,
323
+ )
324
+ for path in paths
325
+ ],
326
+ mode=mode,
327
+ fs=fs,
328
+ )
329
+
330
+
331
+ def _un_chain(path, kwargs):
332
+ # Avoid a circular import
333
+ from fsspec.implementations.chained import ChainedFileSystem
334
+
335
+ if "::" in path:
336
+ x = re.compile(".*[^a-z]+.*") # test for non protocol-like single word
337
+ known_protocols = set(available_protocols())
338
+ bits = []
339
+
340
+ # split on '::', then ensure each bit has a protocol
341
+ for p in path.split("::"):
342
+ if p in known_protocols:
343
+ bits.append(p + "://")
344
+ elif "://" in p or x.match(p):
345
+ bits.append(p)
346
+ else:
347
+ bits.append(p + "://")
348
+ else:
349
+ bits = [path]
350
+
351
+ # [[url, protocol, kwargs], ...]
352
+ out = []
353
+ previous_bit = None
354
+ kwargs = kwargs.copy()
355
+
356
+ for bit in reversed(bits):
357
+ protocol = kwargs.pop("protocol", None) or split_protocol(bit)[0] or "file"
358
+ cls = get_filesystem_class(protocol)
359
+ extra_kwargs = cls._get_kwargs_from_urls(bit)
360
+ kws = kwargs.pop(protocol, {})
361
+
362
+ if bit is bits[0]:
363
+ kws.update(kwargs)
364
+
365
+ kw = dict(
366
+ **{k: v for k, v in extra_kwargs.items() if k not in kws or v != kws[k]},
367
+ **kws,
368
+ )
369
+ bit = cls._strip_protocol(bit)
370
+
371
+ if (
372
+ "target_protocol" not in kw
373
+ and issubclass(cls, ChainedFileSystem)
374
+ and not bit
375
+ ):
376
+ # replace bit if we are chaining and no path given
377
+ bit = previous_bit
378
+
379
+ out.append((bit, protocol, kw))
380
+ previous_bit = bit
381
+
382
+ out.reverse()
383
+ return out
384
+
385
+
386
+ def url_to_fs(url, **kwargs):
387
+ """
388
+ Turn fully-qualified and potentially chained URL into filesystem instance
389
+
390
+ Parameters
391
+ ----------
392
+ url : str
393
+ The fsspec-compatible URL
394
+ **kwargs: dict
395
+ Extra options that make sense to a particular storage connection, e.g.
396
+ host, port, username, password, etc.
397
+
398
+ Returns
399
+ -------
400
+ filesystem : FileSystem
401
+ The new filesystem discovered from ``url`` and created with
402
+ ``**kwargs``.
403
+ urlpath : str
404
+ The file-systems-specific URL for ``url``.
405
+ """
406
+ url = stringify_path(url)
407
+ # non-FS arguments that appear in fsspec.open()
408
+ # inspect could keep this in sync with open()'s signature
409
+ known_kwargs = {
410
+ "compression",
411
+ "encoding",
412
+ "errors",
413
+ "expand",
414
+ "mode",
415
+ "name_function",
416
+ "newline",
417
+ "num",
418
+ }
419
+ kwargs = {k: v for k, v in kwargs.items() if k not in known_kwargs}
420
+ chain = _un_chain(url, kwargs)
421
+ inkwargs = {}
422
+ # Reverse iterate the chain, creating a nested target_* structure
423
+ for i, ch in enumerate(reversed(chain)):
424
+ urls, protocol, kw = ch
425
+ if i == len(chain) - 1:
426
+ inkwargs = dict(**kw, **inkwargs)
427
+ continue
428
+ inkwargs["target_options"] = dict(**kw, **inkwargs)
429
+ inkwargs["target_protocol"] = protocol
430
+ inkwargs["fo"] = urls
431
+ urlpath, protocol, _ = chain[0]
432
+ fs = filesystem(protocol, **inkwargs)
433
+ return fs, urlpath
434
+
435
+
436
+ DEFAULT_EXPAND = conf.get("open_expand", False)
437
+
438
+
439
+ def open(
440
+ urlpath,
441
+ mode="rb",
442
+ compression=None,
443
+ encoding="utf8",
444
+ errors=None,
445
+ protocol=None,
446
+ newline=None,
447
+ expand=None,
448
+ **kwargs,
449
+ ):
450
+ """Given a path or paths, return one ``OpenFile`` object.
451
+
452
+ Parameters
453
+ ----------
454
+ urlpath: string or list
455
+ Absolute or relative filepath. Prefix with a protocol like ``s3://``
456
+ to read from alternative filesystems. Should not include glob
457
+ character(s).
458
+ mode: 'rb', 'wt', etc.
459
+ compression: string or None
460
+ If given, open file using compression codec. Can either be a compression
461
+ name (a key in ``fsspec.compression.compr``) or "infer" to guess the
462
+ compression from the filename suffix.
463
+ encoding: str
464
+ For text mode only
465
+ errors: None or str
466
+ Passed to TextIOWrapper in text mode
467
+ protocol: str or None
468
+ If given, overrides the protocol found in the URL.
469
+ newline: bytes or None
470
+ Used for line terminator in text mode. If None, uses system default;
471
+ if blank, uses no translation.
472
+ expand: bool or None
473
+ Whether to regard file paths containing special glob characters as needing
474
+ expansion (finding the first match) or absolute. Setting False allows using
475
+ paths which do embed such characters. If None (default), this argument
476
+ takes its value from the DEFAULT_EXPAND module variable, which takes
477
+ its initial value from the "open_expand" config value at startup, which will
478
+ be False if not set.
479
+ **kwargs: dict
480
+ Extra options that make sense to a particular storage connection, e.g.
481
+ host, port, username, password, etc.
482
+
483
+ Examples
484
+ --------
485
+ >>> openfile = open('2015-01-01.csv') # doctest: +SKIP
486
+ >>> openfile = open(
487
+ ... 's3://bucket/2015-01-01.csv.gz', compression='gzip'
488
+ ... ) # doctest: +SKIP
489
+ >>> with openfile as f:
490
+ ... df = pd.read_csv(f) # doctest: +SKIP
491
+ ...
492
+
493
+ Returns
494
+ -------
495
+ ``OpenFile`` object.
496
+
497
+ Notes
498
+ -----
499
+ For a full list of the available protocols and the implementations that
500
+ they map across to see the latest online documentation:
501
+
502
+ - For implementations built into ``fsspec`` see
503
+ https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations
504
+ - For implementations in separate packages see
505
+ https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations
506
+ """
507
+ expand = DEFAULT_EXPAND if expand is None else expand
508
+ out = open_files(
509
+ urlpath=[urlpath],
510
+ mode=mode,
511
+ compression=compression,
512
+ encoding=encoding,
513
+ errors=errors,
514
+ protocol=protocol,
515
+ newline=newline,
516
+ expand=expand,
517
+ **kwargs,
518
+ )
519
+ if not out:
520
+ raise FileNotFoundError(urlpath)
521
+ return out[0]
522
+
523
+
524
+ def open_local(
525
+ url: str | list[str] | Path | list[Path],
526
+ mode: str = "rb",
527
+ **storage_options: dict,
528
+ ) -> str | list[str]:
529
+ """Open file(s) which can be resolved to local
530
+
531
+ For files which either are local, or get downloaded upon open
532
+ (e.g., by file caching)
533
+
534
+ Parameters
535
+ ----------
536
+ url: str or list(str)
537
+ mode: str
538
+ Must be read mode
539
+ storage_options:
540
+ passed on to FS for or used by open_files (e.g., compression)
541
+ """
542
+ if "r" not in mode:
543
+ raise ValueError("Can only ensure local files when reading")
544
+ of = open_files(url, mode=mode, **storage_options)
545
+ if not getattr(of[0].fs, "local_file", False):
546
+ raise ValueError(
547
+ "open_local can only be used on a filesystem which"
548
+ " has attribute local_file=True"
549
+ )
550
+ with of as files:
551
+ paths = [f.name for f in files]
552
+ if (isinstance(url, str) and not has_magic(url)) or isinstance(url, Path):
553
+ return paths[0]
554
+ return paths
555
+
556
+
557
+ def get_compression(urlpath, compression):
558
+ if compression == "infer":
559
+ compression = infer_compression(urlpath)
560
+ if compression is not None and compression not in compr:
561
+ raise ValueError(f"Compression type {compression} not supported")
562
+ return compression
563
+
564
+
565
+ def split_protocol(urlpath):
566
+ """Return protocol, path pair"""
567
+ urlpath = stringify_path(urlpath)
568
+ if "://" in urlpath:
569
+ protocol, path = urlpath.split("://", 1)
570
+ if len(protocol) > 1:
571
+ # excludes Windows paths
572
+ return protocol, path
573
+ if urlpath.startswith("data:"):
574
+ return urlpath.split(":", 1)
575
+ return None, urlpath
576
+
577
+
578
+ def strip_protocol(urlpath):
579
+ """Return only path part of full URL, according to appropriate backend"""
580
+ protocol, _ = split_protocol(urlpath)
581
+ cls = get_filesystem_class(protocol)
582
+ return cls._strip_protocol(urlpath)
583
+
584
+
585
+ def expand_paths_if_needed(paths, mode, num, fs, name_function):
586
+ """Expand paths if they have a ``*`` in them (write mode) or any of ``*?[]``
587
+ in them (read mode).
588
+
589
+ :param paths: list of paths
590
+ mode: str
591
+ Mode in which to open files.
592
+ num: int
593
+ If opening in writing mode, number of files we expect to create.
594
+ fs: filesystem object
595
+ name_function: callable
596
+ If opening in writing mode, this callable is used to generate path
597
+ names. Names are generated for each partition by
598
+ ``urlpath.replace('*', name_function(partition_index))``.
599
+ :return: list of paths
600
+ """
601
+ expanded_paths = []
602
+ paths = list(paths)
603
+
604
+ if "w" in mode: # read mode
605
+ if sum(1 for p in paths if "*" in p) > 1:
606
+ raise ValueError(
607
+ "When writing data, only one filename mask can be specified."
608
+ )
609
+ num = max(num, len(paths))
610
+
611
+ for curr_path in paths:
612
+ if "*" in curr_path:
613
+ # expand using name_function
614
+ expanded_paths.extend(_expand_paths(curr_path, name_function, num))
615
+ else:
616
+ expanded_paths.append(curr_path)
617
+ # if we generated more paths that asked for, trim the list
618
+ if len(expanded_paths) > num:
619
+ expanded_paths = expanded_paths[:num]
620
+
621
+ else: # read mode
622
+ for curr_path in paths:
623
+ if has_magic(curr_path):
624
+ # expand using glob
625
+ expanded_paths.extend(fs.glob(curr_path))
626
+ else:
627
+ expanded_paths.append(curr_path)
628
+
629
+ return expanded_paths
630
+
631
+
632
+ def get_fs_token_paths(
633
+ urlpath,
634
+ mode="rb",
635
+ num=1,
636
+ name_function=None,
637
+ storage_options=None,
638
+ protocol=None,
639
+ expand=True,
640
+ ):
641
+ """Filesystem, deterministic token, and paths from a urlpath and options.
642
+
643
+ Parameters
644
+ ----------
645
+ urlpath: string or iterable
646
+ Absolute or relative filepath, URL (may include protocols like
647
+ ``s3://``), or globstring pointing to data.
648
+ mode: str, optional
649
+ Mode in which to open files.
650
+ num: int, optional
651
+ If opening in writing mode, number of files we expect to create.
652
+ name_function: callable, optional
653
+ If opening in writing mode, this callable is used to generate path
654
+ names. Names are generated for each partition by
655
+ ``urlpath.replace('*', name_function(partition_index))``.
656
+ storage_options: dict, optional
657
+ Additional keywords to pass to the filesystem class.
658
+ protocol: str or None
659
+ To override the protocol specifier in the URL
660
+ expand: bool
661
+ Expand string paths for writing, assuming the path is a directory
662
+ """
663
+ if isinstance(urlpath, (list, tuple, set)):
664
+ if not urlpath:
665
+ raise ValueError("empty urlpath sequence")
666
+ urlpath0 = stringify_path(next(iter(urlpath)))
667
+ else:
668
+ urlpath0 = stringify_path(urlpath)
669
+ storage_options = storage_options or {}
670
+ if protocol:
671
+ storage_options["protocol"] = protocol
672
+ chain = _un_chain(urlpath0, storage_options or {})
673
+ inkwargs = {}
674
+ # Reverse iterate the chain, creating a nested target_* structure
675
+ for i, ch in enumerate(reversed(chain)):
676
+ urls, nested_protocol, kw = ch
677
+ if i == len(chain) - 1:
678
+ inkwargs = dict(**kw, **inkwargs)
679
+ continue
680
+ inkwargs["target_options"] = dict(**kw, **inkwargs)
681
+ inkwargs["target_protocol"] = nested_protocol
682
+ inkwargs["fo"] = urls
683
+ paths, protocol, _ = chain[0]
684
+ fs = filesystem(protocol, **inkwargs)
685
+ if isinstance(urlpath, (list, tuple, set)):
686
+ pchains = [
687
+ _un_chain(stringify_path(u), storage_options or {})[0] for u in urlpath
688
+ ]
689
+ if len({pc[1] for pc in pchains}) > 1:
690
+ raise ValueError("Protocol mismatch getting fs from %s", urlpath)
691
+ paths = [pc[0] for pc in pchains]
692
+ else:
693
+ paths = fs._strip_protocol(paths)
694
+ if isinstance(paths, (list, tuple, set)):
695
+ if expand:
696
+ paths = expand_paths_if_needed(paths, mode, num, fs, name_function)
697
+ elif not isinstance(paths, list):
698
+ paths = list(paths)
699
+ else:
700
+ if ("w" in mode or "x" in mode) and expand:
701
+ paths = _expand_paths(paths, name_function, num)
702
+ elif "*" in paths:
703
+ paths = [f for f in sorted(fs.glob(paths)) if not fs.isdir(f)]
704
+ else:
705
+ paths = [paths]
706
+
707
+ return fs, fs._fs_token, paths
708
+
709
+
710
+ def _expand_paths(path, name_function, num):
711
+ if isinstance(path, str):
712
+ if path.count("*") > 1:
713
+ raise ValueError("Output path spec must contain exactly one '*'.")
714
+ elif "*" not in path:
715
+ path = os.path.join(path, "*.part")
716
+
717
+ if name_function is None:
718
+ name_function = build_name_function(num - 1)
719
+
720
+ paths = [path.replace("*", name_function(i)) for i in range(num)]
721
+ if paths != sorted(paths):
722
+ logger.warning(
723
+ "In order to preserve order between partitions"
724
+ " paths created with ``name_function`` should "
725
+ "sort to partition order"
726
+ )
727
+ elif isinstance(path, (tuple, list)):
728
+ assert len(path) == num
729
+ paths = list(path)
730
+ else:
731
+ raise ValueError(
732
+ "Path should be either\n"
733
+ "1. A list of paths: ['foo.json', 'bar.json', ...]\n"
734
+ "2. A directory: 'foo/\n"
735
+ "3. A path with a '*' in it: 'foo.*.json'"
736
+ )
737
+ return paths
738
+
739
+
740
+ class PickleableTextIOWrapper(io.TextIOWrapper):
741
+ """TextIOWrapper cannot be pickled. This solves it.
742
+
743
+ Requires that ``buffer`` be pickleable, which all instances of
744
+ AbstractBufferedFile are.
745
+ """
746
+
747
+ def __init__(
748
+ self,
749
+ buffer,
750
+ encoding=None,
751
+ errors=None,
752
+ newline=None,
753
+ line_buffering=False,
754
+ write_through=False,
755
+ ):
756
+ self.args = buffer, encoding, errors, newline, line_buffering, write_through
757
+ super().__init__(*self.args)
758
+
759
+ def __reduce__(self):
760
+ return PickleableTextIOWrapper, self.args
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/dircache.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from collections.abc import MutableMapping
3
+ from functools import lru_cache
4
+
5
+
6
+ class DirCache(MutableMapping):
7
+ """
8
+ Caching of directory listings, in a structure like::
9
+
10
+ {"path0": [
11
+ {"name": "path0/file0",
12
+ "size": 123,
13
+ "type": "file",
14
+ ...
15
+ },
16
+ {"name": "path0/file1",
17
+ },
18
+ ...
19
+ ],
20
+ "path1": [...]
21
+ }
22
+
23
+ Parameters to this class control listing expiry or indeed turn
24
+ caching off
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ use_listings_cache=True,
30
+ listings_expiry_time=None,
31
+ max_paths=None,
32
+ **kwargs,
33
+ ):
34
+ """
35
+
36
+ Parameters
37
+ ----------
38
+ use_listings_cache: bool
39
+ If False, this cache never returns items, but always reports KeyError,
40
+ and setting items has no effect
41
+ listings_expiry_time: int or float (optional)
42
+ Time in seconds that a listing is considered valid. If None,
43
+ listings do not expire.
44
+ max_paths: int (optional)
45
+ The number of most recent listings that are considered valid; 'recent'
46
+ refers to when the entry was set.
47
+ """
48
+ self._cache = {}
49
+ self._times = {}
50
+ if max_paths:
51
+ self._q = lru_cache(max_paths + 1)(lambda key: self._cache.pop(key, None))
52
+ self.use_listings_cache = use_listings_cache
53
+ self.listings_expiry_time = listings_expiry_time
54
+ self.max_paths = max_paths
55
+
56
+ def __getitem__(self, item):
57
+ if self.listings_expiry_time is not None:
58
+ if self._times.get(item, 0) - time.time() < -self.listings_expiry_time:
59
+ del self._cache[item]
60
+ if self.max_paths:
61
+ self._q(item)
62
+ return self._cache[item] # maybe raises KeyError
63
+
64
+ def clear(self):
65
+ self._cache.clear()
66
+
67
+ def __len__(self):
68
+ return len(self._cache)
69
+
70
+ def __contains__(self, item):
71
+ try:
72
+ self[item]
73
+ return True
74
+ except KeyError:
75
+ return False
76
+
77
+ def __setitem__(self, key, value):
78
+ if not self.use_listings_cache:
79
+ return
80
+ if self.max_paths:
81
+ self._q(key)
82
+ self._cache[key] = value
83
+ if self.listings_expiry_time is not None:
84
+ self._times[key] = time.time()
85
+
86
+ def __delitem__(self, key):
87
+ del self._cache[key]
88
+
89
+ def __iter__(self):
90
+ entries = list(self._cache)
91
+
92
+ return (k for k in entries if k in self)
93
+
94
+ def __reduce__(self):
95
+ return (
96
+ DirCache,
97
+ (self.use_listings_cache, self.listings_expiry_time, self.max_paths),
98
+ )
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/exceptions.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ fsspec user-defined exception classes
3
+ """
4
+
5
+ import asyncio
6
+
7
+
8
+ class BlocksizeMismatchError(ValueError):
9
+ """
10
+ Raised when a cached file is opened with a different blocksize than it was
11
+ written with
12
+ """
13
+
14
+
15
+ class FSTimeoutError(asyncio.TimeoutError):
16
+ """
17
+ Raised when a fsspec function timed out occurs
18
+ """
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/fuse.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import os
4
+ import stat
5
+ import threading
6
+ import time
7
+ from errno import EIO, ENOENT
8
+
9
+ from fuse import FUSE, FuseOSError, LoggingMixIn, Operations
10
+
11
+ from fsspec import __version__
12
+ from fsspec.core import url_to_fs
13
+
14
+ logger = logging.getLogger("fsspec.fuse")
15
+
16
+
17
+ class FUSEr(Operations):
18
+ def __init__(self, fs, path, ready_file=False):
19
+ self.fs = fs
20
+ self.cache = {}
21
+ self.root = path.rstrip("/") + "/"
22
+ self.counter = 0
23
+ logger.info("Starting FUSE at %s", path)
24
+ self._ready_file = ready_file
25
+
26
+ def getattr(self, path, fh=None):
27
+ logger.debug("getattr %s", path)
28
+ if self._ready_file and path in ["/.fuse_ready", ".fuse_ready"]:
29
+ return {"type": "file", "st_size": 5}
30
+
31
+ path = "".join([self.root, path.lstrip("/")]).rstrip("/")
32
+ try:
33
+ info = self.fs.info(path)
34
+ except FileNotFoundError as exc:
35
+ raise FuseOSError(ENOENT) from exc
36
+
37
+ data = {"st_uid": info.get("uid", 1000), "st_gid": info.get("gid", 1000)}
38
+ perm = info.get("mode", 0o777)
39
+
40
+ if info["type"] != "file":
41
+ data["st_mode"] = stat.S_IFDIR | perm
42
+ data["st_size"] = 0
43
+ data["st_blksize"] = 0
44
+ else:
45
+ data["st_mode"] = stat.S_IFREG | perm
46
+ data["st_size"] = info["size"]
47
+ data["st_blksize"] = 5 * 2**20
48
+ data["st_nlink"] = 1
49
+ data["st_atime"] = info["atime"] if "atime" in info else time.time()
50
+ data["st_ctime"] = info["ctime"] if "ctime" in info else time.time()
51
+ data["st_mtime"] = info["mtime"] if "mtime" in info else time.time()
52
+ return data
53
+
54
+ def readdir(self, path, fh):
55
+ logger.debug("readdir %s", path)
56
+ path = "".join([self.root, path.lstrip("/")])
57
+ files = self.fs.ls(path, False)
58
+ files = [os.path.basename(f.rstrip("/")) for f in files]
59
+ return [".", ".."] + files
60
+
61
+ def mkdir(self, path, mode):
62
+ path = "".join([self.root, path.lstrip("/")])
63
+ self.fs.mkdir(path)
64
+ return 0
65
+
66
+ def rmdir(self, path):
67
+ path = "".join([self.root, path.lstrip("/")])
68
+ self.fs.rmdir(path)
69
+ return 0
70
+
71
+ def read(self, path, size, offset, fh):
72
+ logger.debug("read %s", (path, size, offset))
73
+ if self._ready_file and path in ["/.fuse_ready", ".fuse_ready"]:
74
+ # status indicator
75
+ return b"ready"
76
+
77
+ f = self.cache[fh]
78
+ f.seek(offset)
79
+ out = f.read(size)
80
+ return out
81
+
82
+ def write(self, path, data, offset, fh):
83
+ logger.debug("write %s", (path, offset))
84
+ f = self.cache[fh]
85
+ f.seek(offset)
86
+ f.write(data)
87
+ return len(data)
88
+
89
+ def create(self, path, flags, fi=None):
90
+ logger.debug("create %s", (path, flags))
91
+ fn = "".join([self.root, path.lstrip("/")])
92
+ self.fs.touch(fn) # OS will want to get attributes immediately
93
+ f = self.fs.open(fn, "wb")
94
+ self.cache[self.counter] = f
95
+ self.counter += 1
96
+ return self.counter - 1
97
+
98
+ def open(self, path, flags):
99
+ logger.debug("open %s", (path, flags))
100
+ fn = "".join([self.root, path.lstrip("/")])
101
+ if flags % 2 == 0:
102
+ # read
103
+ mode = "rb"
104
+ else:
105
+ # write/create
106
+ mode = "wb"
107
+ self.cache[self.counter] = self.fs.open(fn, mode)
108
+ self.counter += 1
109
+ return self.counter - 1
110
+
111
+ def truncate(self, path, length, fh=None):
112
+ fn = "".join([self.root, path.lstrip("/")])
113
+ if length != 0:
114
+ raise NotImplementedError
115
+ # maybe should be no-op since open with write sets size to zero anyway
116
+ self.fs.touch(fn)
117
+
118
+ def unlink(self, path):
119
+ fn = "".join([self.root, path.lstrip("/")])
120
+ try:
121
+ self.fs.rm(fn, False)
122
+ except (OSError, FileNotFoundError) as exc:
123
+ raise FuseOSError(EIO) from exc
124
+
125
+ def release(self, path, fh):
126
+ try:
127
+ if fh in self.cache:
128
+ f = self.cache[fh]
129
+ f.close()
130
+ self.cache.pop(fh)
131
+ except Exception as e:
132
+ print(e)
133
+ return 0
134
+
135
+ def chmod(self, path, mode):
136
+ if hasattr(self.fs, "chmod"):
137
+ path = "".join([self.root, path.lstrip("/")])
138
+ return self.fs.chmod(path, mode)
139
+ raise NotImplementedError
140
+
141
+
142
+ def run(
143
+ fs,
144
+ path,
145
+ mount_point,
146
+ foreground=True,
147
+ threads=False,
148
+ ready_file=False,
149
+ ops_class=FUSEr,
150
+ ):
151
+ """Mount stuff in a local directory
152
+
153
+ This uses fusepy to make it appear as if a given path on an fsspec
154
+ instance is in fact resident within the local file-system.
155
+
156
+ This requires that fusepy by installed, and that FUSE be available on
157
+ the system (typically requiring a package to be installed with
158
+ apt, yum, brew, etc.).
159
+
160
+ Parameters
161
+ ----------
162
+ fs: file-system instance
163
+ From one of the compatible implementations
164
+ path: str
165
+ Location on that file-system to regard as the root directory to
166
+ mount. Note that you typically should include the terminating "/"
167
+ character.
168
+ mount_point: str
169
+ An empty directory on the local file-system where the contents of
170
+ the remote path will appear.
171
+ foreground: bool
172
+ Whether or not calling this function will block. Operation will
173
+ typically be more stable if True.
174
+ threads: bool
175
+ Whether or not to create threads when responding to file operations
176
+ within the mounter directory. Operation will typically be more
177
+ stable if False.
178
+ ready_file: bool
179
+ Whether the FUSE process is ready. The ``.fuse_ready`` file will
180
+ exist in the ``mount_point`` directory if True. Debugging purpose.
181
+ ops_class: FUSEr or Subclass of FUSEr
182
+ To override the default behavior of FUSEr. For Example, logging
183
+ to file.
184
+
185
+ """
186
+ func = lambda: FUSE(
187
+ ops_class(fs, path, ready_file=ready_file),
188
+ mount_point,
189
+ nothreads=not threads,
190
+ foreground=foreground,
191
+ )
192
+ if not foreground:
193
+ th = threading.Thread(target=func)
194
+ th.daemon = True
195
+ th.start()
196
+ return th
197
+ else: # pragma: no cover
198
+ try:
199
+ func()
200
+ except KeyboardInterrupt:
201
+ pass
202
+
203
+
204
+ def main(args):
205
+ """Mount filesystem from chained URL to MOUNT_POINT.
206
+
207
+ Examples:
208
+
209
+ python3 -m fsspec.fuse memory /usr/share /tmp/mem
210
+
211
+ python3 -m fsspec.fuse local /tmp/source /tmp/local \\
212
+ -l /tmp/fsspecfuse.log
213
+
214
+ You can also mount chained-URLs and use special settings:
215
+
216
+ python3 -m fsspec.fuse 'filecache::zip::file://data.zip' \\
217
+ / /tmp/zip \\
218
+ -o 'filecache-cache_storage=/tmp/simplecache'
219
+
220
+ You can specify the type of the setting by using `[int]` or `[bool]`,
221
+ (`true`, `yes`, `1` represents the Boolean value `True`):
222
+
223
+ python3 -m fsspec.fuse 'simplecache::ftp://ftp1.at.proftpd.org' \\
224
+ /historic/packages/RPMS /tmp/ftp \\
225
+ -o 'simplecache-cache_storage=/tmp/simplecache' \\
226
+ -o 'simplecache-check_files=false[bool]' \\
227
+ -o 'ftp-listings_expiry_time=60[int]' \\
228
+ -o 'ftp-username=anonymous' \\
229
+ -o 'ftp-password=xieyanbo'
230
+ """
231
+
232
+ class RawDescriptionArgumentParser(argparse.ArgumentParser):
233
+ def format_help(self):
234
+ usage = super().format_help()
235
+ parts = usage.split("\n\n")
236
+ parts[1] = self.description.rstrip()
237
+ return "\n\n".join(parts)
238
+
239
+ parser = RawDescriptionArgumentParser(prog="fsspec.fuse", description=main.__doc__)
240
+ parser.add_argument("--version", action="version", version=__version__)
241
+ parser.add_argument("url", type=str, help="fs url")
242
+ parser.add_argument("source_path", type=str, help="source directory in fs")
243
+ parser.add_argument("mount_point", type=str, help="local directory")
244
+ parser.add_argument(
245
+ "-o",
246
+ "--option",
247
+ action="append",
248
+ help="Any options of protocol included in the chained URL",
249
+ )
250
+ parser.add_argument(
251
+ "-l", "--log-file", type=str, help="Logging FUSE debug info (Default: '')"
252
+ )
253
+ parser.add_argument(
254
+ "-f",
255
+ "--foreground",
256
+ action="store_false",
257
+ help="Running in foreground or not (Default: False)",
258
+ )
259
+ parser.add_argument(
260
+ "-t",
261
+ "--threads",
262
+ action="store_false",
263
+ help="Running with threads support (Default: False)",
264
+ )
265
+ parser.add_argument(
266
+ "-r",
267
+ "--ready-file",
268
+ action="store_false",
269
+ help="The `.fuse_ready` file will exist after FUSE is ready. "
270
+ "(Debugging purpose, Default: False)",
271
+ )
272
+ args = parser.parse_args(args)
273
+
274
+ kwargs = {}
275
+ for item in args.option or []:
276
+ key, sep, value = item.partition("=")
277
+ if not sep:
278
+ parser.error(message=f"Wrong option: {item!r}")
279
+ val = value.lower()
280
+ if val.endswith("[int]"):
281
+ value = int(value[: -len("[int]")])
282
+ elif val.endswith("[bool]"):
283
+ value = val[: -len("[bool]")] in ["1", "yes", "true"]
284
+
285
+ if "-" in key:
286
+ fs_name, setting_name = key.split("-", 1)
287
+ if fs_name in kwargs:
288
+ kwargs[fs_name][setting_name] = value
289
+ else:
290
+ kwargs[fs_name] = {setting_name: value}
291
+ else:
292
+ kwargs[key] = value
293
+
294
+ if args.log_file:
295
+ logging.basicConfig(
296
+ level=logging.DEBUG,
297
+ filename=args.log_file,
298
+ format="%(asctime)s %(message)s",
299
+ )
300
+
301
+ class LoggingFUSEr(FUSEr, LoggingMixIn):
302
+ pass
303
+
304
+ fuser = LoggingFUSEr
305
+ else:
306
+ fuser = FUSEr
307
+
308
+ fs, url_path = url_to_fs(args.url, **kwargs)
309
+ logger.debug("Mounting %s to %s", url_path, str(args.mount_point))
310
+ run(
311
+ fs,
312
+ args.source_path,
313
+ args.mount_point,
314
+ foreground=args.foreground,
315
+ threads=args.threads,
316
+ ready_file=args.ready_file,
317
+ ops_class=fuser,
318
+ )
319
+
320
+
321
+ if __name__ == "__main__":
322
+ import sys
323
+
324
+ main(sys.argv[1:])
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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)
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)
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)
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)
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)
297
+ fs2 = _resolve_fs(url2, self.method)
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)
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)
336
+ fs2 = _resolve_fs(path2, self.method)
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
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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()
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/__init__.py ADDED
File without changes
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/arrow.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
39
+
40
+ class ArrowFSWrapper(AbstractFileSystem):
41
+ """FSSpec-compatible wrapper of pyarrow.fs.FileSystem.
42
+
43
+ Parameters
44
+ ----------
45
+ fs : pyarrow.fs.FileSystem
46
+
47
+ """
48
+
49
+ root_marker = "/"
50
+
51
+ def __init__(self, fs, **kwargs):
52
+ global PYARROW_VERSION
53
+ PYARROW_VERSION = get_package_version_without_import("pyarrow")
54
+ self.fs = fs
55
+ super().__init__(**kwargs)
56
+
57
+ @property
58
+ def protocol(self):
59
+ return self.fs.type_name
60
+
61
+ @cached_property
62
+ def fsid(self):
63
+ return "hdfs_" + tokenize(self.fs.host, self.fs.port)
64
+
65
+ @classmethod
66
+ def _strip_protocol(cls, path):
67
+ ops = infer_storage_options(path)
68
+ path = ops["path"]
69
+ if path.startswith("//"):
70
+ # special case for "hdfs://path" (without the triple slash)
71
+ path = path[1:]
72
+ return path
73
+
74
+ def ls(self, path, detail=False, **kwargs):
75
+ path = self._strip_protocol(path)
76
+ from pyarrow.fs import FileSelector
77
+
78
+ try:
79
+ entries = [
80
+ self._make_entry(entry)
81
+ for entry in self.fs.get_file_info(FileSelector(path))
82
+ ]
83
+ except (FileNotFoundError, NotADirectoryError):
84
+ entries = [self.info(path, **kwargs)]
85
+ if detail:
86
+ return entries
87
+ else:
88
+ return [entry["name"] for entry in entries]
89
+
90
+ def info(self, path, **kwargs):
91
+ path = self._strip_protocol(path)
92
+ [info] = self.fs.get_file_info([path])
93
+ return self._make_entry(info)
94
+
95
+ def exists(self, path):
96
+ path = self._strip_protocol(path)
97
+ try:
98
+ self.info(path)
99
+ except FileNotFoundError:
100
+ return False
101
+ else:
102
+ return True
103
+
104
+ def _make_entry(self, info):
105
+ from pyarrow.fs import FileType
106
+
107
+ if info.type is FileType.Directory:
108
+ kind = "directory"
109
+ elif info.type is FileType.File:
110
+ kind = "file"
111
+ elif info.type is FileType.NotFound:
112
+ raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), info.path)
113
+ else:
114
+ kind = "other"
115
+
116
+ return {
117
+ "name": info.path,
118
+ "size": info.size,
119
+ "type": kind,
120
+ "mtime": info.mtime,
121
+ }
122
+
123
+ @wrap_exceptions
124
+ def cp_file(self, path1, path2, **kwargs):
125
+ path1 = self._strip_protocol(path1).rstrip("/")
126
+ path2 = self._strip_protocol(path2).rstrip("/")
127
+
128
+ with self._open(path1, "rb") as lstream:
129
+ tmp_fname = f"{path2}.tmp.{secrets.token_hex(6)}"
130
+ try:
131
+ with self.open(tmp_fname, "wb") as rstream:
132
+ shutil.copyfileobj(lstream, rstream)
133
+ self.fs.move(tmp_fname, path2)
134
+ except BaseException:
135
+ with suppress(FileNotFoundError):
136
+ self.fs.delete_file(tmp_fname)
137
+ raise
138
+
139
+ @wrap_exceptions
140
+ def mv(self, path1, path2, **kwargs):
141
+ path1 = self._strip_protocol(path1).rstrip("/")
142
+ path2 = self._strip_protocol(path2).rstrip("/")
143
+ self.fs.move(path1, path2)
144
+
145
+ @wrap_exceptions
146
+ def rm_file(self, path):
147
+ path = self._strip_protocol(path)
148
+ self.fs.delete_file(path)
149
+
150
+ @wrap_exceptions
151
+ def rm(self, path, recursive=False, maxdepth=None):
152
+ path = self._strip_protocol(path).rstrip("/")
153
+ if self.isdir(path):
154
+ if recursive:
155
+ self.fs.delete_dir(path)
156
+ else:
157
+ raise ValueError("Can't delete directories without recursive=False")
158
+ else:
159
+ self.fs.delete_file(path)
160
+
161
+ @wrap_exceptions
162
+ def _open(self, path, mode="rb", block_size=None, seekable=True, **kwargs):
163
+ if mode == "rb":
164
+ if seekable:
165
+ method = self.fs.open_input_file
166
+ else:
167
+ method = self.fs.open_input_stream
168
+ elif mode == "wb":
169
+ method = self.fs.open_output_stream
170
+ elif mode == "ab":
171
+ method = self.fs.open_append_stream
172
+ else:
173
+ raise ValueError(f"unsupported mode for Arrow filesystem: {mode!r}")
174
+
175
+ _kwargs = {}
176
+ if mode != "rb" or not seekable:
177
+ if int(PYARROW_VERSION.split(".")[0]) >= 4:
178
+ # disable compression auto-detection
179
+ _kwargs["compression"] = None
180
+ stream = method(path, **_kwargs)
181
+
182
+ return ArrowFile(self, stream, path, mode, block_size, **kwargs)
183
+
184
+ @wrap_exceptions
185
+ def mkdir(self, path, create_parents=True, **kwargs):
186
+ path = self._strip_protocol(path)
187
+ if create_parents:
188
+ self.makedirs(path, exist_ok=True)
189
+ else:
190
+ self.fs.create_dir(path, recursive=False)
191
+
192
+ @wrap_exceptions
193
+ def makedirs(self, path, exist_ok=False):
194
+ path = self._strip_protocol(path)
195
+ self.fs.create_dir(path, recursive=True)
196
+
197
+ @wrap_exceptions
198
+ def rmdir(self, path):
199
+ path = self._strip_protocol(path)
200
+ self.fs.delete_dir(path)
201
+
202
+ @wrap_exceptions
203
+ def modified(self, path):
204
+ path = self._strip_protocol(path)
205
+ return self.fs.get_file_info(path).mtime
206
+
207
+ def cat_file(self, path, start=None, end=None, **kwargs):
208
+ kwargs.setdefault("seekable", start not in [None, 0])
209
+ return super().cat_file(path, start=None, end=None, **kwargs)
210
+
211
+ def get_file(self, rpath, lpath, **kwargs):
212
+ kwargs.setdefault("seekable", False)
213
+ super().get_file(rpath, lpath, **kwargs)
214
+
215
+
216
+ @mirror_from(
217
+ "stream",
218
+ [
219
+ "read",
220
+ "seek",
221
+ "tell",
222
+ "write",
223
+ "readable",
224
+ "writable",
225
+ "close",
226
+ "seekable",
227
+ ],
228
+ )
229
+ class ArrowFile(io.IOBase):
230
+ def __init__(self, fs, stream, path, mode, block_size=None, **kwargs):
231
+ self.path = path
232
+ self.mode = mode
233
+
234
+ self.fs = fs
235
+ self.stream = stream
236
+
237
+ self.blocksize = self.block_size = block_size
238
+ self.kwargs = kwargs
239
+
240
+ def __enter__(self):
241
+ return self
242
+
243
+ @property
244
+ def size(self):
245
+ if self.stream.seekable():
246
+ return self.stream.size()
247
+ return None
248
+
249
+ def __exit__(self, *args):
250
+ return self.close()
251
+
252
+
253
+ class HadoopFileSystem(ArrowFSWrapper):
254
+ """A wrapper on top of the pyarrow.fs.HadoopFileSystem
255
+ to connect it's interface with fsspec"""
256
+
257
+ protocol = "hdfs"
258
+
259
+ def __init__(
260
+ self,
261
+ host="default",
262
+ port=0,
263
+ user=None,
264
+ kerb_ticket=None,
265
+ replication=3,
266
+ extra_conf=None,
267
+ **kwargs,
268
+ ):
269
+ """
270
+
271
+ Parameters
272
+ ----------
273
+ host: str
274
+ Hostname, IP or "default" to try to read from Hadoop config
275
+ port: int
276
+ Port to connect on, or default from Hadoop config if 0
277
+ user: str or None
278
+ If given, connect as this username
279
+ kerb_ticket: str or None
280
+ If given, use this ticket for authentication
281
+ replication: int
282
+ set replication factor of file for write operations. default value is 3.
283
+ extra_conf: None or dict
284
+ Passed on to HadoopFileSystem
285
+ """
286
+ from pyarrow.fs import HadoopFileSystem
287
+
288
+ fs = HadoopFileSystem(
289
+ host=host,
290
+ port=port,
291
+ user=user,
292
+ kerb_ticket=kerb_ticket,
293
+ replication=replication,
294
+ extra_conf=extra_conf,
295
+ )
296
+ super().__init__(fs=fs, **kwargs)
297
+
298
+ @staticmethod
299
+ def _get_kwargs_from_urls(path):
300
+ ops = infer_storage_options(path)
301
+ out = {}
302
+ if ops.get("host", None):
303
+ out["host"] = ops["host"]
304
+ if ops.get("username", None):
305
+ out["user"] = ops["username"]
306
+ if ops.get("port", None):
307
+ out["port"] = ops["port"]
308
+ if ops.get("url_query", None):
309
+ queries = parse_qs(ops["url_query"])
310
+ if queries.get("replication", None):
311
+ out["replication"] = int(queries["replication"][0])
312
+ return out
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/asyn_wrapper.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import functools
3
+ import inspect
4
+
5
+ import fsspec
6
+ from fsspec.asyn import AsyncFileSystem, running_async
7
+
8
+ from .chained import ChainedFileSystem
9
+
10
+
11
+ def async_wrapper(func, obj=None, semaphore=None):
12
+ """
13
+ Wraps a synchronous function to make it awaitable.
14
+
15
+ Parameters
16
+ ----------
17
+ func : callable
18
+ The synchronous function to wrap.
19
+ obj : object, optional
20
+ The instance to bind the function to, if applicable.
21
+ semaphore : asyncio.Semaphore, optional
22
+ A semaphore to limit concurrent calls.
23
+
24
+ Returns
25
+ -------
26
+ coroutine
27
+ An awaitable version of the function.
28
+ """
29
+
30
+ @functools.wraps(func)
31
+ async def wrapper(*args, **kwargs):
32
+ if semaphore:
33
+ async with semaphore:
34
+ return await asyncio.to_thread(func, *args, **kwargs)
35
+ return await asyncio.to_thread(func, *args, **kwargs)
36
+
37
+ return wrapper
38
+
39
+
40
+ class AsyncFileSystemWrapper(AsyncFileSystem, ChainedFileSystem):
41
+ """
42
+ A wrapper class to convert a synchronous filesystem into an asynchronous one.
43
+
44
+ This class takes an existing synchronous filesystem implementation and wraps all
45
+ its methods to provide an asynchronous interface.
46
+
47
+ Parameters
48
+ ----------
49
+ sync_fs : AbstractFileSystem
50
+ The synchronous filesystem instance to wrap.
51
+ """
52
+
53
+ protocol = "asyncwrapper", "async_wrapper"
54
+ cachable = False
55
+
56
+ def __init__(
57
+ self,
58
+ fs=None,
59
+ asynchronous=None,
60
+ target_protocol=None,
61
+ target_options=None,
62
+ semaphore=None,
63
+ max_concurrent_tasks=None,
64
+ **kwargs,
65
+ ):
66
+ if asynchronous is None:
67
+ asynchronous = running_async()
68
+ super().__init__(asynchronous=asynchronous, **kwargs)
69
+ if fs is not None:
70
+ self.sync_fs = fs
71
+ else:
72
+ self.sync_fs = fsspec.filesystem(target_protocol, **target_options)
73
+ self.protocol = self.sync_fs.protocol
74
+ self.semaphore = semaphore
75
+ self._wrap_all_sync_methods()
76
+
77
+ @property
78
+ def fsid(self):
79
+ return f"async_{self.sync_fs.fsid}"
80
+
81
+ def _wrap_all_sync_methods(self):
82
+ """
83
+ Wrap all synchronous methods of the underlying filesystem with asynchronous versions.
84
+ """
85
+ excluded_methods = {"open"}
86
+ for method_name in dir(self.sync_fs):
87
+ if method_name.startswith("_") or method_name in excluded_methods:
88
+ continue
89
+
90
+ attr = inspect.getattr_static(self.sync_fs, method_name)
91
+ if isinstance(attr, property):
92
+ continue
93
+
94
+ method = getattr(self.sync_fs, method_name)
95
+ if callable(method) and not inspect.iscoroutinefunction(method):
96
+ async_method = async_wrapper(method, obj=self, semaphore=self.semaphore)
97
+ setattr(self, f"_{method_name}", async_method)
98
+
99
+ @classmethod
100
+ def wrap_class(cls, sync_fs_class):
101
+ """
102
+ Create a new class that can be used to instantiate an AsyncFileSystemWrapper
103
+ with lazy instantiation of the underlying synchronous filesystem.
104
+
105
+ Parameters
106
+ ----------
107
+ sync_fs_class : type
108
+ The class of the synchronous filesystem to wrap.
109
+
110
+ Returns
111
+ -------
112
+ type
113
+ A new class that wraps the provided synchronous filesystem class.
114
+ """
115
+
116
+ class GeneratedAsyncFileSystemWrapper(cls):
117
+ def __init__(self, *args, **kwargs):
118
+ sync_fs = sync_fs_class(*args, **kwargs)
119
+ super().__init__(sync_fs)
120
+
121
+ GeneratedAsyncFileSystemWrapper.__name__ = (
122
+ f"Async{sync_fs_class.__name__}Wrapper"
123
+ )
124
+ return GeneratedAsyncFileSystemWrapper
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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()
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/cached.py ADDED
@@ -0,0 +1,1024 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ **kwargs,
80
+ ):
81
+ """
82
+
83
+ Parameters
84
+ ----------
85
+ target_protocol: str (optional)
86
+ Target filesystem protocol. Provide either this or ``fs``.
87
+ cache_storage: str or list(str)
88
+ Location to store files. If "TMP", this is a temporary directory,
89
+ and will be cleaned up by the OS when this process ends (or later).
90
+ If a list, each location will be tried in the order given, but
91
+ only the last will be considered writable.
92
+ cache_check: int
93
+ Number of seconds between reload of cache metadata
94
+ check_files: bool
95
+ Whether to explicitly see if the UID of the remote file matches
96
+ the stored one before using. Warning: some file systems such as
97
+ HTTP cannot reliably give a unique hash of the contents of some
98
+ path, so be sure to set this option to False.
99
+ expiry_time: int
100
+ The time in seconds after which a local copy is considered useless.
101
+ Set to falsy to prevent expiry. The default is equivalent to one
102
+ week.
103
+ target_options: dict or None
104
+ Passed to the instantiation of the FS, if fs is None.
105
+ fs: filesystem instance
106
+ The target filesystem to run against. Provide this or ``protocol``.
107
+ same_names: bool (optional)
108
+ By default, target URLs are hashed using a ``HashCacheMapper`` so
109
+ that files from different backends with the same basename do not
110
+ conflict. If this argument is ``true``, a ``BasenameCacheMapper``
111
+ is used instead. Other cache mapper options are available by using
112
+ the ``cache_mapper`` keyword argument. Only one of this and
113
+ ``cache_mapper`` should be specified.
114
+ compression: str (optional)
115
+ To decompress on download. Can be 'infer' (guess from the URL name),
116
+ one of the entries in ``fsspec.compression.compr``, or None for no
117
+ decompression.
118
+ cache_mapper: AbstractCacheMapper (optional)
119
+ The object use to map from original filenames to cached filenames.
120
+ Only one of this and ``same_names`` should be specified.
121
+ """
122
+ super().__init__(**kwargs)
123
+ if fs is None and target_protocol is None:
124
+ raise ValueError(
125
+ "Please provide filesystem instance(fs) or target_protocol"
126
+ )
127
+ if not (fs is None) ^ (target_protocol is None):
128
+ raise ValueError(
129
+ "Both filesystems (fs) and target_protocol may not be both given."
130
+ )
131
+ if cache_storage == "TMP":
132
+ tempdir = tempfile.mkdtemp()
133
+ storage = [tempdir]
134
+ weakref.finalize(self, self._remove_tempdir, tempdir)
135
+ else:
136
+ if isinstance(cache_storage, str):
137
+ storage = [cache_storage]
138
+ else:
139
+ storage = cache_storage
140
+ os.makedirs(storage[-1], exist_ok=True)
141
+ self.storage = storage
142
+ self.kwargs = target_options or {}
143
+ self.cache_check = cache_check
144
+ self.check_files = check_files
145
+ self.expiry = expiry_time
146
+ self.compression = compression
147
+
148
+ # Size of cache in bytes. If None then the size is unknown and will be
149
+ # recalculated the next time cache_size() is called. On writes to the
150
+ # cache this is reset to None.
151
+ self._cache_size = None
152
+
153
+ if same_names is not None and cache_mapper is not None:
154
+ raise ValueError(
155
+ "Cannot specify both same_names and cache_mapper in "
156
+ "CachingFileSystem.__init__"
157
+ )
158
+ if cache_mapper is not None:
159
+ self._mapper = cache_mapper
160
+ else:
161
+ self._mapper = create_cache_mapper(
162
+ same_names if same_names is not None else False
163
+ )
164
+
165
+ self.target_protocol = (
166
+ target_protocol
167
+ if isinstance(target_protocol, str)
168
+ else (fs.protocol if isinstance(fs.protocol, str) else fs.protocol[0])
169
+ )
170
+ self._metadata = CacheMetadata(self.storage)
171
+ self.load_cache()
172
+ self.fs = fs if fs is not None else filesystem(target_protocol, **self.kwargs)
173
+
174
+ def _strip_protocol(path):
175
+ # acts as a method, since each instance has a difference target
176
+ return self.fs._strip_protocol(type(self)._strip_protocol(path))
177
+
178
+ self._strip_protocol: Callable = _strip_protocol
179
+
180
+ @staticmethod
181
+ def _remove_tempdir(tempdir):
182
+ try:
183
+ rmtree(tempdir)
184
+ except Exception:
185
+ pass
186
+
187
+ def _mkcache(self):
188
+ os.makedirs(self.storage[-1], exist_ok=True)
189
+
190
+ def cache_size(self):
191
+ """Return size of cache in bytes.
192
+
193
+ If more than one cache directory is in use, only the size of the last
194
+ one (the writable cache directory) is returned.
195
+ """
196
+ if self._cache_size is None:
197
+ cache_dir = self.storage[-1]
198
+ self._cache_size = filesystem("file").du(cache_dir, withdirs=True)
199
+ return self._cache_size
200
+
201
+ def load_cache(self):
202
+ """Read set of stored blocks from file"""
203
+ self._metadata.load()
204
+ self._mkcache()
205
+ self.last_cache = time.time()
206
+
207
+ def save_cache(self):
208
+ """Save set of stored blocks from file"""
209
+ self._mkcache()
210
+ self._metadata.save()
211
+ self.last_cache = time.time()
212
+ self._cache_size = None
213
+
214
+ def _check_cache(self):
215
+ """Reload caches if time elapsed or any disappeared"""
216
+ self._mkcache()
217
+ if not self.cache_check:
218
+ # explicitly told not to bother checking
219
+ return
220
+ timecond = time.time() - self.last_cache > self.cache_check
221
+ existcond = all(os.path.exists(storage) for storage in self.storage)
222
+ if timecond or not existcond:
223
+ self.load_cache()
224
+
225
+ def _check_file(self, path):
226
+ """Is path in cache and still valid"""
227
+ path = self._strip_protocol(path)
228
+ self._check_cache()
229
+ return self._metadata.check_file(path, self)
230
+
231
+ def clear_cache(self):
232
+ """Remove all files and metadata from the cache
233
+
234
+ In the case of multiple cache locations, this clears only the last one,
235
+ which is assumed to be the read/write one.
236
+ """
237
+ rmtree(self.storage[-1])
238
+ self.load_cache()
239
+ self._cache_size = None
240
+
241
+ def clear_expired_cache(self, expiry_time=None):
242
+ """Remove all expired files and metadata from the cache
243
+
244
+ In the case of multiple cache locations, this clears only the last one,
245
+ which is assumed to be the read/write one.
246
+
247
+ Parameters
248
+ ----------
249
+ expiry_time: int
250
+ The time in seconds after which a local copy is considered useless.
251
+ If not defined the default is equivalent to the attribute from the
252
+ file caching instantiation.
253
+ """
254
+
255
+ if not expiry_time:
256
+ expiry_time = self.expiry
257
+
258
+ self._check_cache()
259
+
260
+ expired_files, writable_cache_empty = self._metadata.clear_expired(expiry_time)
261
+ for fn in expired_files:
262
+ if os.path.exists(fn):
263
+ os.remove(fn)
264
+
265
+ if writable_cache_empty:
266
+ rmtree(self.storage[-1])
267
+ self.load_cache()
268
+
269
+ self._cache_size = None
270
+
271
+ def pop_from_cache(self, path):
272
+ """Remove cached version of given file
273
+
274
+ Deletes local copy of the given (remote) path. If it is found in a cache
275
+ location which is not the last, it is assumed to be read-only, and
276
+ raises PermissionError
277
+ """
278
+ path = self._strip_protocol(path)
279
+ fn = self._metadata.pop_file(path)
280
+ if fn is not None:
281
+ os.remove(fn)
282
+ self._cache_size = None
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
+ """Wrap the target _open
294
+
295
+ If the whole file exists in the cache, just open it locally and
296
+ return that.
297
+
298
+ Otherwise, open the file on the target FS, and make it have a mmap
299
+ cache pointing to the location which we determine, in our cache.
300
+ The ``blocks`` instance is shared, so as the mmap cache instance
301
+ updates, so does the entry in our ``cached_files`` attribute.
302
+ We monkey-patch this file, so that when it closes, we call
303
+ ``close_and_update`` to save the state of the blocks.
304
+ """
305
+ path = self._strip_protocol(path)
306
+
307
+ path = self.fs._strip_protocol(path)
308
+ if "r" not in mode:
309
+ return self.fs._open(
310
+ path,
311
+ mode=mode,
312
+ block_size=block_size,
313
+ autocommit=autocommit,
314
+ cache_options=cache_options,
315
+ **kwargs,
316
+ )
317
+ detail = self._check_file(path)
318
+ if detail:
319
+ # file is in cache
320
+ detail, fn = detail
321
+ hash, blocks = detail["fn"], detail["blocks"]
322
+ if blocks is True:
323
+ # stored file is complete
324
+ logger.debug("Opening local copy of %s", path)
325
+ return open(fn, mode)
326
+ # TODO: action where partial file exists in read-only cache
327
+ logger.debug("Opening partially cached copy of %s", path)
328
+ else:
329
+ hash = self._mapper(path)
330
+ fn = os.path.join(self.storage[-1], hash)
331
+ blocks = set()
332
+ detail = {
333
+ "original": path,
334
+ "fn": hash,
335
+ "blocks": blocks,
336
+ "time": time.time(),
337
+ "uid": self.fs.ukey(path),
338
+ }
339
+ self._metadata.update_file(path, detail)
340
+ logger.debug("Creating local sparse file for %s", path)
341
+
342
+ # explicitly submitting the size to the open call will avoid extra
343
+ # operations when opening. This is particularly relevant
344
+ # for any file that is read over a network, e.g. S3.
345
+ size = detail.get("size")
346
+
347
+ # call target filesystems open
348
+ self._mkcache()
349
+ f = self.fs._open(
350
+ path,
351
+ mode=mode,
352
+ block_size=block_size,
353
+ autocommit=autocommit,
354
+ cache_options=cache_options,
355
+ cache_type="none",
356
+ size=size,
357
+ **kwargs,
358
+ )
359
+
360
+ # set size if not already set
361
+ if size is None:
362
+ detail["size"] = f.size
363
+ self._metadata.update_file(path, detail)
364
+
365
+ if self.compression:
366
+ comp = (
367
+ infer_compression(path)
368
+ if self.compression == "infer"
369
+ else self.compression
370
+ )
371
+ f = compr[comp](f, mode="rb")
372
+ if "blocksize" in detail:
373
+ if detail["blocksize"] != f.blocksize:
374
+ raise BlocksizeMismatchError(
375
+ f"Cached file must be reopened with same block"
376
+ f" size as original (old: {detail['blocksize']},"
377
+ f" new {f.blocksize})"
378
+ )
379
+ else:
380
+ detail["blocksize"] = f.blocksize
381
+
382
+ def _fetch_ranges(ranges):
383
+ return self.fs.cat_ranges(
384
+ [path] * len(ranges),
385
+ [r[0] for r in ranges],
386
+ [r[1] for r in ranges],
387
+ **kwargs,
388
+ )
389
+
390
+ multi_fetcher = None if self.compression else _fetch_ranges
391
+ f.cache = MMapCache(
392
+ f.blocksize, f._fetch_range, f.size, fn, blocks, multi_fetcher=multi_fetcher
393
+ )
394
+ close = f.close
395
+ f.close = lambda: self.close_and_update(f, close)
396
+ self.save_cache()
397
+ return f
398
+
399
+ def _parent(self, path):
400
+ return self.fs._parent(path)
401
+
402
+ def hash_name(self, path: str, *args: Any) -> str:
403
+ # Kept for backward compatibility with downstream libraries.
404
+ # Ignores extra arguments, previously same_name boolean.
405
+ return self._mapper(path)
406
+
407
+ def close_and_update(self, f, close):
408
+ """Called when a file is closing, so store the set of blocks"""
409
+ if f.closed:
410
+ return
411
+ path = self._strip_protocol(f.path)
412
+ self._metadata.on_close_cached_file(f, path)
413
+ try:
414
+ logger.debug("going to save")
415
+ self.save_cache()
416
+ logger.debug("saved")
417
+ except OSError:
418
+ logger.debug("Cache saving failed while closing file")
419
+ except NameError:
420
+ logger.debug("Cache save failed due to interpreter shutdown")
421
+ close()
422
+ f.closed = True
423
+
424
+ def ls(self, path, detail=True):
425
+ return self.fs.ls(path, detail)
426
+
427
+ def __getattribute__(self, item):
428
+ if item in {
429
+ "load_cache",
430
+ "_get_cached_file_before_open",
431
+ "_open",
432
+ "save_cache",
433
+ "close_and_update",
434
+ "__init__",
435
+ "__getattribute__",
436
+ "__reduce__",
437
+ "_make_local_details",
438
+ "open",
439
+ "cat",
440
+ "cat_file",
441
+ "_cat_file",
442
+ "cat_ranges",
443
+ "_cat_ranges",
444
+ "get",
445
+ "read_block",
446
+ "tail",
447
+ "head",
448
+ "info",
449
+ "ls",
450
+ "exists",
451
+ "isfile",
452
+ "isdir",
453
+ "_check_file",
454
+ "_check_cache",
455
+ "_mkcache",
456
+ "clear_cache",
457
+ "clear_expired_cache",
458
+ "pop_from_cache",
459
+ "local_file",
460
+ "_paths_from_path",
461
+ "get_mapper",
462
+ "open_many",
463
+ "commit_many",
464
+ "hash_name",
465
+ "__hash__",
466
+ "__eq__",
467
+ "to_json",
468
+ "to_dict",
469
+ "cache_size",
470
+ "pipe_file",
471
+ "pipe",
472
+ "start_transaction",
473
+ "end_transaction",
474
+ }:
475
+ # all the methods defined in this class. Note `open` here, since
476
+ # it calls `_open`, but is actually in superclass
477
+ if hasattr(type(self), item):
478
+ return lambda *args, **kw: getattr(type(self), item).__get__(self)(
479
+ *args, **kw
480
+ )
481
+ # method is in the whitelist but not defined on this subclass;
482
+ # fall through to delegate to the wrapped filesystem below
483
+ if item in ["__reduce_ex__"]:
484
+ raise AttributeError
485
+ if item in ["transaction"]:
486
+ # property
487
+ return type(self).transaction.__get__(self)
488
+ if item in {"_cache", "transaction_type", "protocol"}:
489
+ # class attributes
490
+ return getattr(type(self), item)
491
+ if item == "__class__":
492
+ return type(self)
493
+ d = object.__getattribute__(self, "__dict__")
494
+ fs = d.get("fs", None) # fs is not immediately defined
495
+ if item in d:
496
+ return d[item]
497
+ elif fs is not None:
498
+ if item in fs.__dict__:
499
+ # attribute of instance
500
+ return fs.__dict__[item]
501
+ # attributed belonging to the target filesystem
502
+ cls = type(fs)
503
+ m = getattr(cls, item)
504
+ if (inspect.isfunction(m) or inspect.isdatadescriptor(m)) and (
505
+ not hasattr(m, "__self__") or m.__self__ is None
506
+ ):
507
+ # instance method
508
+ return m.__get__(fs, cls)
509
+ return m # class method or attribute
510
+ else:
511
+ # attributes of the superclass, while target is being set up
512
+ return super().__getattribute__(item)
513
+
514
+ def __eq__(self, other):
515
+ """Test for equality."""
516
+ if self is other:
517
+ return True
518
+ if not isinstance(other, type(self)):
519
+ return False
520
+ return (
521
+ self.storage == other.storage
522
+ and self.kwargs == other.kwargs
523
+ and self.cache_check == other.cache_check
524
+ and self.check_files == other.check_files
525
+ and self.expiry == other.expiry
526
+ and self.compression == other.compression
527
+ and self._mapper == other._mapper
528
+ and self.target_protocol == other.target_protocol
529
+ )
530
+
531
+ def __hash__(self):
532
+ """Calculate hash."""
533
+ return (
534
+ hash(tuple(self.storage))
535
+ ^ hash(str(self.kwargs))
536
+ ^ hash(self.cache_check)
537
+ ^ hash(self.check_files)
538
+ ^ hash(self.expiry)
539
+ ^ hash(self.compression)
540
+ ^ hash(self._mapper)
541
+ ^ hash(self.target_protocol)
542
+ )
543
+
544
+
545
+ class WholeFileCacheFileSystem(CachingFileSystem):
546
+ """Caches whole remote files on first access
547
+
548
+ This class is intended as a layer over any other file system, and
549
+ will make a local copy of each file accessed, so that all subsequent
550
+ reads are local. This is similar to ``CachingFileSystem``, but without
551
+ the block-wise functionality and so can work even when sparse files
552
+ are not allowed. See its docstring for definition of the init
553
+ arguments.
554
+
555
+ The class still needs access to the remote store for listing files,
556
+ and may refresh cached files.
557
+ """
558
+
559
+ protocol = "filecache"
560
+ local_file = True
561
+
562
+ def open_many(self, open_files, **kwargs):
563
+ paths = [of.path for of in open_files]
564
+ if "r" in open_files.mode:
565
+ self._mkcache()
566
+ else:
567
+ return [
568
+ LocalTempFile(
569
+ self.fs,
570
+ path,
571
+ mode=open_files.mode,
572
+ fn=os.path.join(self.storage[-1], self._mapper(path)),
573
+ **kwargs,
574
+ )
575
+ for path in paths
576
+ ]
577
+
578
+ if self.compression:
579
+ raise NotImplementedError
580
+ details = [self._check_file(sp) for sp in paths]
581
+ downpath = [p for p, d in zip(paths, details) if not d]
582
+ downfn0 = [
583
+ os.path.join(self.storage[-1], self._mapper(p))
584
+ for p, d in zip(paths, details)
585
+ ] # keep these path names for opening later
586
+ downfn = [fn for fn, d in zip(downfn0, details) if not d]
587
+ if downpath:
588
+ # skip if all files are already cached and up to date
589
+ self.fs.get(downpath, downfn)
590
+
591
+ # update metadata - only happens when downloads are successful
592
+ newdetail = [
593
+ {
594
+ "original": path,
595
+ "fn": self._mapper(path),
596
+ "blocks": True,
597
+ "time": time.time(),
598
+ "uid": self.fs.ukey(path),
599
+ }
600
+ for path in downpath
601
+ ]
602
+ for path, detail in zip(downpath, newdetail):
603
+ self._metadata.update_file(path, detail)
604
+ self.save_cache()
605
+
606
+ def firstpart(fn):
607
+ # helper to adapt both whole-file and simple-cache
608
+ return fn[1] if isinstance(fn, tuple) else fn
609
+
610
+ return [
611
+ open(firstpart(fn0) if fn0 else fn1, mode=open_files.mode)
612
+ for fn0, fn1 in zip(details, downfn0)
613
+ ]
614
+
615
+ def commit_many(self, open_files):
616
+ self.fs.put([f.fn for f in open_files], [f.path for f in open_files])
617
+ [f.close() for f in open_files]
618
+ for f in open_files:
619
+ # in case autocommit is off, and so close did not already delete
620
+ try:
621
+ os.remove(f.name)
622
+ except FileNotFoundError:
623
+ pass
624
+ self._cache_size = None
625
+
626
+ def _make_local_details(self, path):
627
+ hash = self._mapper(path)
628
+ fn = os.path.join(self.storage[-1], hash)
629
+ detail = {
630
+ "original": path,
631
+ "fn": hash,
632
+ "blocks": True,
633
+ "time": time.time(),
634
+ "uid": self.fs.ukey(path),
635
+ }
636
+ self._metadata.update_file(path, detail)
637
+ logger.debug("Copying %s to local cache", path)
638
+ return fn
639
+
640
+ def cat(
641
+ self,
642
+ path,
643
+ recursive=False,
644
+ on_error="raise",
645
+ callback=DEFAULT_CALLBACK,
646
+ **kwargs,
647
+ ):
648
+ paths = self.expand_path(
649
+ path, recursive=recursive, maxdepth=kwargs.get("maxdepth")
650
+ )
651
+ getpaths = []
652
+ storepaths = []
653
+ fns = []
654
+ out = {}
655
+ for p in paths.copy():
656
+ try:
657
+ detail = self._check_file(p)
658
+ if not detail:
659
+ fn = self._make_local_details(p)
660
+ getpaths.append(p)
661
+ storepaths.append(fn)
662
+ else:
663
+ detail, fn = detail if isinstance(detail, tuple) else (None, detail)
664
+ fns.append(fn)
665
+ except Exception as e:
666
+ if on_error == "raise":
667
+ raise
668
+ if on_error == "return":
669
+ out[p] = e
670
+ paths.remove(p)
671
+
672
+ if getpaths:
673
+ self.fs.get(getpaths, storepaths)
674
+ self.save_cache()
675
+
676
+ callback.set_size(len(paths))
677
+ for p, fn in zip(paths, fns):
678
+ with open(fn, "rb") as f:
679
+ out[p] = f.read()
680
+ callback.relative_update(1)
681
+ if isinstance(path, str) and len(paths) == 1 and recursive is False:
682
+ out = out[paths[0]]
683
+ return out
684
+
685
+ def _get_cached_file_before_open(self, path, **kwargs):
686
+ fn = self._make_local_details(path)
687
+ # call target filesystems open
688
+ self._mkcache()
689
+ if self.compression:
690
+ with self.fs._open(path, mode="rb", **kwargs) as f, open(fn, "wb") as f2:
691
+ if isinstance(f, AbstractBufferedFile):
692
+ # want no type of caching if just downloading whole thing
693
+ f.cache = BaseCache(0, f.cache.fetcher, f.size)
694
+ comp = (
695
+ infer_compression(path)
696
+ if self.compression == "infer"
697
+ else self.compression
698
+ )
699
+ f = compr[comp](f, mode="rb")
700
+ data = True
701
+ while data:
702
+ block = getattr(f, "blocksize", 5 * 2**20)
703
+ data = f.read(block)
704
+ f2.write(data)
705
+ else:
706
+ self.fs.get_file(path, fn)
707
+ self.save_cache()
708
+
709
+ def _open(self, path, mode="rb", **kwargs):
710
+ path = self._strip_protocol(path)
711
+ # For read (or append), (try) download from remote
712
+ if "r" in mode or "a" in mode:
713
+ if not self._check_file(path):
714
+ if self.fs.exists(path):
715
+ self._get_cached_file_before_open(path, **kwargs)
716
+ elif "r" in mode:
717
+ raise FileNotFoundError(path)
718
+
719
+ detail, fn = self._check_file(path)
720
+ _, blocks = detail["fn"], detail["blocks"]
721
+ if blocks is True:
722
+ logger.debug("Opening local copy of %s", path)
723
+ else:
724
+ raise ValueError(
725
+ f"Attempt to open partially cached file {path}"
726
+ f" as a wholly cached file"
727
+ )
728
+
729
+ # Just reading does not need special file handling
730
+ if "r" in mode and "+" not in mode:
731
+ # In order to support downstream filesystems to be able to
732
+ # infer the compression from the original filename, like
733
+ # the `TarFileSystem`, let's extend the `io.BufferedReader`
734
+ # fileobject protocol by adding a dedicated attribute
735
+ # `original`.
736
+ f = open(fn, mode)
737
+ f.original = detail.get("original")
738
+ return f
739
+
740
+ hash = self._mapper(path)
741
+ fn = os.path.join(self.storage[-1], hash)
742
+ user_specified_kwargs = {
743
+ k: v
744
+ for k, v in kwargs.items()
745
+ # those kwargs were added by open(), we don't want them
746
+ if k not in ["autocommit", "block_size", "cache_options"]
747
+ }
748
+ return LocalTempFile(self, path, mode=mode, fn=fn, **user_specified_kwargs)
749
+
750
+ async def _cat_file(self, path, start=None, end=None, **kwargs):
751
+ logger.debug("async cat_file %s", path)
752
+ path = self._strip_protocol(path)
753
+ sha = self._mapper(path)
754
+ fn = self._check_file(path)
755
+
756
+ if not fn:
757
+ fn = os.path.join(self.storage[-1], sha)
758
+ await self.fs._get_file(path, fn, **kwargs)
759
+
760
+ with open(fn, "rb") as f: # noqa ASYNC230
761
+ if start:
762
+ f.seek(start)
763
+ size = -1 if end is None else end - f.tell()
764
+ return f.read(size)
765
+
766
+ async def _cat_ranges(
767
+ self, paths, starts, ends, max_gap=None, on_error="return", **kwargs
768
+ ):
769
+ logger.debug("async cat ranges %s", paths)
770
+ lpaths = []
771
+ rset = set()
772
+ download = []
773
+ rpaths = []
774
+ for p in paths:
775
+ fn = self._check_file(p)
776
+ if fn is None and p not in rset:
777
+ sha = self._mapper(p)
778
+ fn = os.path.join(self.storage[-1], sha)
779
+ download.append(fn)
780
+ rset.add(p)
781
+ rpaths.append(p)
782
+ lpaths.append(fn)
783
+ if download:
784
+ await self.fs._get(rpaths, download, on_error=on_error)
785
+
786
+ return LocalFileSystem().cat_ranges(
787
+ lpaths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs
788
+ )
789
+
790
+
791
+ class SimpleCacheFileSystem(WholeFileCacheFileSystem):
792
+ """Caches whole remote files on first access
793
+
794
+ This class is intended as a layer over any other file system, and
795
+ will make a local copy of each file accessed, so that all subsequent
796
+ reads are local. This implementation only copies whole files, and
797
+ does not keep any metadata about the download time or file details.
798
+ It is therefore safer to use in multi-threaded/concurrent situations.
799
+
800
+ This is the only of the caching filesystems that supports write: you will
801
+ be given a real local open file, and upon close and commit, it will be
802
+ uploaded to the target filesystem; the writability or the target URL is
803
+ not checked until that time.
804
+
805
+ """
806
+
807
+ protocol = "simplecache"
808
+ local_file = True
809
+ transaction_type = WriteCachedTransaction
810
+
811
+ def __init__(self, **kwargs):
812
+ kw = kwargs.copy()
813
+ for key in ["cache_check", "expiry_time", "check_files"]:
814
+ kw[key] = False
815
+ super().__init__(**kw)
816
+ for storage in self.storage:
817
+ if not os.path.exists(storage):
818
+ os.makedirs(storage, exist_ok=True)
819
+
820
+ def _check_file(self, path):
821
+ self._check_cache()
822
+ sha = self._mapper(path)
823
+ for storage in self.storage:
824
+ fn = os.path.join(storage, sha)
825
+ if os.path.exists(fn):
826
+ return fn
827
+
828
+ def save_cache(self):
829
+ pass
830
+
831
+ def load_cache(self):
832
+ pass
833
+
834
+ def pipe_file(self, path, value=None, **kwargs):
835
+ if self._intrans:
836
+ with self.open(path, "wb") as f:
837
+ f.write(value)
838
+ else:
839
+ super().pipe_file(path, value)
840
+
841
+ def ls(self, path, detail=True, **kwargs):
842
+ path = self._strip_protocol(path)
843
+ details = []
844
+ try:
845
+ details = self.fs.ls(
846
+ path, detail=True, **kwargs
847
+ ).copy() # don't edit original!
848
+ except FileNotFoundError as e:
849
+ ex = e
850
+ else:
851
+ ex = None
852
+ if self._intrans:
853
+ path1 = path.rstrip("/") + "/"
854
+ for f in self.transaction.files:
855
+ if f.path == path:
856
+ details.append(
857
+ {"name": path, "size": f.size or f.tell(), "type": "file"}
858
+ )
859
+ elif f.path.startswith(path1):
860
+ if f.path.count("/") == path1.count("/"):
861
+ details.append(
862
+ {"name": f.path, "size": f.size or f.tell(), "type": "file"}
863
+ )
864
+ else:
865
+ dname = "/".join(f.path.split("/")[: path1.count("/") + 1])
866
+ details.append({"name": dname, "size": 0, "type": "directory"})
867
+ if ex is not None and not details:
868
+ raise ex
869
+ if detail:
870
+ return details
871
+ return sorted(_["name"] for _ in details)
872
+
873
+ def info(self, path, **kwargs):
874
+ path = self._strip_protocol(path)
875
+ if self._intrans:
876
+ f = [_ for _ in self.transaction.files if _.path == path]
877
+ if f:
878
+ size = os.path.getsize(f[0].fn) if f[0].closed else f[0].tell()
879
+ return {"name": path, "size": size, "type": "file"}
880
+ f = any(_.path.startswith(path + "/") for _ in self.transaction.files)
881
+ if f:
882
+ return {"name": path, "size": 0, "type": "directory"}
883
+ return self.fs.info(path, **kwargs)
884
+
885
+ def pipe(self, path, value=None, **kwargs):
886
+ if isinstance(path, str):
887
+ self.pipe_file(self._strip_protocol(path), value, **kwargs)
888
+ elif isinstance(path, dict):
889
+ for k, v in path.items():
890
+ self.pipe_file(self._strip_protocol(k), v, **kwargs)
891
+ else:
892
+ raise ValueError("path must be str or dict")
893
+
894
+ def cat_ranges(
895
+ self, paths, starts, ends, max_gap=None, on_error="return", **kwargs
896
+ ):
897
+ logger.debug("cat ranges %s", paths)
898
+ lpaths = [self._check_file(p) for p in paths]
899
+ rpaths = [p for l, p in zip(lpaths, paths) if l is False]
900
+ lpaths = [l for l, p in zip(lpaths, paths) if l is False]
901
+ self.fs.get(rpaths, lpaths)
902
+ paths = [self._check_file(p) for p in paths]
903
+ return LocalFileSystem().cat_ranges(
904
+ paths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs
905
+ )
906
+
907
+ def _get_cached_file_before_open(self, path, **kwargs):
908
+ sha = self._mapper(path)
909
+ fn = os.path.join(self.storage[-1], sha)
910
+ logger.debug("Copying %s to local cache", path)
911
+
912
+ self._mkcache()
913
+ self._cache_size = None
914
+
915
+ if self.compression:
916
+ with self.fs._open(path, mode="rb", **kwargs) as f, open(fn, "wb") as f2:
917
+ if isinstance(f, AbstractBufferedFile):
918
+ # want no type of caching if just downloading whole thing
919
+ f.cache = BaseCache(0, f.cache.fetcher, f.size)
920
+ comp = (
921
+ infer_compression(path)
922
+ if self.compression == "infer"
923
+ else self.compression
924
+ )
925
+ f = compr[comp](f, mode="rb")
926
+ data = True
927
+ while data:
928
+ block = getattr(f, "blocksize", 5 * 2**20)
929
+ data = f.read(block)
930
+ f2.write(data)
931
+ else:
932
+ self.fs.get_file(path, fn)
933
+
934
+ def _open(self, path, mode="rb", **kwargs):
935
+ path = self._strip_protocol(path)
936
+ sha = self._mapper(path)
937
+
938
+ # For read (or append), (try) download from remote
939
+ if "r" in mode or "a" in mode:
940
+ if not self._check_file(path):
941
+ # append does not require an existing file but read does
942
+ if self.fs.exists(path):
943
+ self._get_cached_file_before_open(path, **kwargs)
944
+ elif "r" in mode:
945
+ raise FileNotFoundError(path)
946
+
947
+ fn = self._check_file(path)
948
+ # Just reading does not need special file handling
949
+ if "r" in mode and "+" not in mode:
950
+ return open(fn, mode)
951
+
952
+ fn = os.path.join(self.storage[-1], sha)
953
+ user_specified_kwargs = {
954
+ k: v
955
+ for k, v in kwargs.items()
956
+ if k not in ["autocommit", "block_size", "cache_options"]
957
+ } # those were added by open()
958
+ return LocalTempFile(
959
+ self,
960
+ path,
961
+ mode=mode,
962
+ autocommit=not self._intrans,
963
+ fn=fn,
964
+ **user_specified_kwargs,
965
+ )
966
+
967
+
968
+ class LocalTempFile:
969
+ """A temporary local file, which will be uploaded on commit"""
970
+
971
+ def __init__(self, fs, path, fn, mode="wb", autocommit=True, seek=0, **kwargs):
972
+ self.fn = fn
973
+ self.fh = open(fn, mode)
974
+ self.mode = mode
975
+ if seek:
976
+ self.fh.seek(seek)
977
+ self.path = path
978
+ self.size = None
979
+ self.fs = fs
980
+ self.closed = False
981
+ self.autocommit = autocommit
982
+ self.kwargs = kwargs
983
+
984
+ def __reduce__(self):
985
+ # always open in r+b to allow continuing writing at a location
986
+ return (
987
+ LocalTempFile,
988
+ (self.fs, self.path, self.fn, "r+b", self.autocommit, self.tell()),
989
+ )
990
+
991
+ def __enter__(self):
992
+ return self.fh
993
+
994
+ def __exit__(self, exc_type, exc_val, exc_tb):
995
+ self.close()
996
+
997
+ def close(self):
998
+ # self.size = self.fh.tell()
999
+ if self.closed:
1000
+ return
1001
+ self.fh.close()
1002
+ self.closed = True
1003
+ if self.autocommit:
1004
+ self.commit()
1005
+
1006
+ def discard(self):
1007
+ self.fh.close()
1008
+ os.remove(self.fn)
1009
+
1010
+ def commit(self):
1011
+ # calling put() with list arguments avoids path expansion and additional operations
1012
+ # like isdir()
1013
+ self.fs.put([self.fn], [self.path], **self.kwargs)
1014
+ # we do not delete the local copy, it's still in the cache.
1015
+
1016
+ @property
1017
+ def name(self):
1018
+ return self.fn
1019
+
1020
+ def __repr__(self) -> str:
1021
+ return f"LocalTempFile: {self.path}"
1022
+
1023
+ def __getattr__(self, item):
1024
+ return getattr(self.fh, item)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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"
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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()}"
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/dirfs.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .. import filesystem
2
+ from ..asyn import AsyncFileSystem
3
+ from .chained import ChainedFileSystem
4
+
5
+
6
+ class DirFileSystem(AsyncFileSystem, ChainedFileSystem):
7
+ """Directory prefix filesystem
8
+
9
+ The DirFileSystem is a filesystem-wrapper. It assumes every path it is dealing with
10
+ is relative to the `path`. After performing the necessary paths operation it
11
+ delegates everything to the wrapped filesystem.
12
+ """
13
+
14
+ protocol = "dir"
15
+
16
+ def __init__(
17
+ self,
18
+ path=None,
19
+ fs=None,
20
+ fo=None,
21
+ target_protocol=None,
22
+ target_options=None,
23
+ **storage_options,
24
+ ):
25
+ """
26
+ Parameters
27
+ ----------
28
+ path: str
29
+ Path to the directory.
30
+ fs: AbstractFileSystem
31
+ An instantiated filesystem to wrap.
32
+ target_protocol, target_options:
33
+ if fs is none, construct it from these
34
+ fo: str
35
+ Alternate for path; do not provide both
36
+ """
37
+ super().__init__(**storage_options)
38
+ if fs is None:
39
+ fs = filesystem(protocol=target_protocol, **(target_options or {}))
40
+ path = path or fo
41
+
42
+ if self.asynchronous and not fs.async_impl:
43
+ raise ValueError("can't use asynchronous with non-async fs")
44
+
45
+ if fs.async_impl and self.asynchronous != fs.asynchronous:
46
+ raise ValueError("both dirfs and fs should be in the same sync/async mode")
47
+
48
+ self.path = fs._strip_protocol(path)
49
+ self.fs = fs
50
+
51
+ def _join(self, path):
52
+ if isinstance(path, str):
53
+ if not self.path:
54
+ return path
55
+ if not path:
56
+ return self.path
57
+ return self.fs.sep.join((self.path, self._strip_protocol(path)))
58
+ if isinstance(path, dict):
59
+ return {self._join(_path): value for _path, value in path.items()}
60
+ return [self._join(_path) for _path in path]
61
+
62
+ def _relpath(self, path):
63
+ if isinstance(path, str):
64
+ if not self.path:
65
+ return path
66
+ # We need to account for S3FileSystem returning paths that do not
67
+ # start with a '/'
68
+ if path == self.path or (
69
+ self.path.startswith(self.fs.sep) and path == self.path[1:]
70
+ ):
71
+ return ""
72
+ prefix = self.path + self.fs.sep
73
+ if self.path.startswith(self.fs.sep) and not path.startswith(self.fs.sep):
74
+ prefix = prefix[1:]
75
+ assert path.startswith(prefix)
76
+ return path[len(prefix) :]
77
+ return [self._relpath(_path) for _path in path]
78
+
79
+ # Wrappers below
80
+
81
+ @property
82
+ def sep(self):
83
+ return self.fs.sep
84
+
85
+ async def set_session(self, *args, **kwargs):
86
+ return await self.fs.set_session(*args, **kwargs)
87
+
88
+ async def _rm_file(self, path, **kwargs):
89
+ return await self.fs._rm_file(self._join(path), **kwargs)
90
+
91
+ def rm_file(self, path, **kwargs):
92
+ return self.fs.rm_file(self._join(path), **kwargs)
93
+
94
+ async def _rm(self, path, *args, **kwargs):
95
+ return await self.fs._rm(self._join(path), *args, **kwargs)
96
+
97
+ def rm(self, path, *args, **kwargs):
98
+ return self.fs.rm(self._join(path), *args, **kwargs)
99
+
100
+ def delete(self, path, recursive=False, maxdepth=None):
101
+ return self.fs.delete(self._join(path), recursive=recursive, maxdepth=maxdepth)
102
+
103
+ async def _cp_file(self, path1, path2, **kwargs):
104
+ return await self.fs._cp_file(self._join(path1), self._join(path2), **kwargs)
105
+
106
+ def cp_file(self, path1, path2, **kwargs):
107
+ return self.fs.cp_file(self._join(path1), self._join(path2), **kwargs)
108
+
109
+ async def _copy(
110
+ self,
111
+ path1,
112
+ path2,
113
+ *args,
114
+ **kwargs,
115
+ ):
116
+ return await self.fs._copy(
117
+ self._join(path1),
118
+ self._join(path2),
119
+ *args,
120
+ **kwargs,
121
+ )
122
+
123
+ def copy(self, path1, path2, *args, **kwargs):
124
+ return self.fs.copy(
125
+ self._join(path1),
126
+ self._join(path2),
127
+ *args,
128
+ **kwargs,
129
+ )
130
+
131
+ async def _pipe(self, path, *args, **kwargs):
132
+ return await self.fs._pipe(self._join(path), *args, **kwargs)
133
+
134
+ def pipe(self, path, *args, **kwargs):
135
+ return self.fs.pipe(self._join(path), *args, **kwargs)
136
+
137
+ async def _pipe_file(self, path, *args, **kwargs):
138
+ return await self.fs._pipe_file(self._join(path), *args, **kwargs)
139
+
140
+ def pipe_file(self, path, *args, **kwargs):
141
+ return self.fs.pipe_file(self._join(path), *args, **kwargs)
142
+
143
+ def write_text(
144
+ self, path, value, encoding=None, errors=None, newline=None, **kwargs
145
+ ):
146
+ return self.fs.write_text(
147
+ self._join(path),
148
+ value,
149
+ encoding=encoding,
150
+ errors=errors,
151
+ newline=newline,
152
+ **kwargs,
153
+ )
154
+
155
+ async def _cat_file(self, path, *args, **kwargs):
156
+ return await self.fs._cat_file(self._join(path), *args, **kwargs)
157
+
158
+ def cat_file(self, path, *args, **kwargs):
159
+ return self.fs.cat_file(self._join(path), *args, **kwargs)
160
+
161
+ async def _cat(self, path, *args, **kwargs):
162
+ ret = await self.fs._cat(
163
+ self._join(path),
164
+ *args,
165
+ **kwargs,
166
+ )
167
+
168
+ if isinstance(ret, dict):
169
+ return {self._relpath(key): value for key, value in ret.items()}
170
+
171
+ return ret
172
+
173
+ def cat(self, path, *args, **kwargs):
174
+ ret = self.fs.cat(
175
+ self._join(path),
176
+ *args,
177
+ **kwargs,
178
+ )
179
+
180
+ if isinstance(ret, dict):
181
+ return {self._relpath(key): value for key, value in ret.items()}
182
+
183
+ return ret
184
+
185
+ async def _put_file(self, lpath, rpath, **kwargs):
186
+ return await self.fs._put_file(lpath, self._join(rpath), **kwargs)
187
+
188
+ def put_file(self, lpath, rpath, **kwargs):
189
+ return self.fs.put_file(lpath, self._join(rpath), **kwargs)
190
+
191
+ async def _put(
192
+ self,
193
+ lpath,
194
+ rpath,
195
+ *args,
196
+ **kwargs,
197
+ ):
198
+ return await self.fs._put(
199
+ lpath,
200
+ self._join(rpath),
201
+ *args,
202
+ **kwargs,
203
+ )
204
+
205
+ def put(self, lpath, rpath, *args, **kwargs):
206
+ return self.fs.put(
207
+ lpath,
208
+ self._join(rpath),
209
+ *args,
210
+ **kwargs,
211
+ )
212
+
213
+ async def _get_file(self, rpath, lpath, **kwargs):
214
+ return await self.fs._get_file(self._join(rpath), lpath, **kwargs)
215
+
216
+ def get_file(self, rpath, lpath, **kwargs):
217
+ return self.fs.get_file(self._join(rpath), lpath, **kwargs)
218
+
219
+ async def _get(self, rpath, *args, **kwargs):
220
+ return await self.fs._get(self._join(rpath), *args, **kwargs)
221
+
222
+ def get(self, rpath, *args, **kwargs):
223
+ return self.fs.get(self._join(rpath), *args, **kwargs)
224
+
225
+ async def _isfile(self, path):
226
+ return await self.fs._isfile(self._join(path))
227
+
228
+ def isfile(self, path):
229
+ return self.fs.isfile(self._join(path))
230
+
231
+ async def _isdir(self, path):
232
+ return await self.fs._isdir(self._join(path))
233
+
234
+ def isdir(self, path):
235
+ return self.fs.isdir(self._join(path))
236
+
237
+ async def _size(self, path):
238
+ return await self.fs._size(self._join(path))
239
+
240
+ def size(self, path):
241
+ return self.fs.size(self._join(path))
242
+
243
+ async def _exists(self, path):
244
+ return await self.fs._exists(self._join(path))
245
+
246
+ def exists(self, path):
247
+ return self.fs.exists(self._join(path))
248
+
249
+ async def _info(self, path, **kwargs):
250
+ info = await self.fs._info(self._join(path), **kwargs)
251
+ info = info.copy()
252
+ info["name"] = self._relpath(info["name"])
253
+ return info
254
+
255
+ def info(self, path, **kwargs):
256
+ info = self.fs.info(self._join(path), **kwargs)
257
+ info = info.copy()
258
+ info["name"] = self._relpath(info["name"])
259
+ return info
260
+
261
+ async def _ls(self, path, detail=True, **kwargs):
262
+ ret = (await self.fs._ls(self._join(path), detail=detail, **kwargs)).copy()
263
+ if detail:
264
+ out = []
265
+ for entry in ret:
266
+ entry = entry.copy()
267
+ entry["name"] = self._relpath(entry["name"])
268
+ out.append(entry)
269
+ return out
270
+
271
+ return self._relpath(ret)
272
+
273
+ def ls(self, path, detail=True, **kwargs):
274
+ ret = self.fs.ls(self._join(path), detail=detail, **kwargs).copy()
275
+ if detail:
276
+ out = []
277
+ for entry in ret:
278
+ entry = entry.copy()
279
+ entry["name"] = self._relpath(entry["name"])
280
+ out.append(entry)
281
+ return out
282
+
283
+ return self._relpath(ret)
284
+
285
+ async def _walk(self, path, *args, **kwargs):
286
+ async for root, dirs, files in self.fs._walk(self._join(path), *args, **kwargs):
287
+ yield self._relpath(root), dirs, files
288
+
289
+ def walk(self, path, *args, **kwargs):
290
+ for root, dirs, files in self.fs.walk(self._join(path), *args, **kwargs):
291
+ yield self._relpath(root), dirs, files
292
+
293
+ async def _glob(self, path, **kwargs):
294
+ detail = kwargs.get("detail", False)
295
+ ret = await self.fs._glob(self._join(path), **kwargs)
296
+ if detail:
297
+ return {self._relpath(path): info for path, info in ret.items()}
298
+ return self._relpath(ret)
299
+
300
+ def glob(self, path, **kwargs):
301
+ detail = kwargs.get("detail", False)
302
+ ret = self.fs.glob(self._join(path), **kwargs)
303
+ if detail:
304
+ return {self._relpath(path): info for path, info in ret.items()}
305
+ return self._relpath(ret)
306
+
307
+ async def _du(self, path, *args, **kwargs):
308
+ total = kwargs.get("total", True)
309
+ ret = await self.fs._du(self._join(path), *args, **kwargs)
310
+ if total:
311
+ return ret
312
+
313
+ return {self._relpath(path): size for path, size in ret.items()}
314
+
315
+ def du(self, path, *args, **kwargs):
316
+ total = kwargs.get("total", True)
317
+ ret = self.fs.du(self._join(path), *args, **kwargs)
318
+ if total:
319
+ return ret
320
+
321
+ return {self._relpath(path): size for path, size in ret.items()}
322
+
323
+ async def _find(self, path, *args, **kwargs):
324
+ detail = kwargs.get("detail", False)
325
+ ret = await self.fs._find(self._join(path), *args, **kwargs)
326
+ if detail:
327
+ return {self._relpath(path): info for path, info in ret.items()}
328
+ return self._relpath(ret)
329
+
330
+ def find(self, path, *args, **kwargs):
331
+ detail = kwargs.get("detail", False)
332
+ ret = self.fs.find(self._join(path), *args, **kwargs)
333
+ if detail:
334
+ return {self._relpath(path): info for path, info in ret.items()}
335
+ return self._relpath(ret)
336
+
337
+ async def _expand_path(self, path, *args, **kwargs):
338
+ return self._relpath(
339
+ await self.fs._expand_path(self._join(path), *args, **kwargs)
340
+ )
341
+
342
+ def expand_path(self, path, *args, **kwargs):
343
+ return self._relpath(self.fs.expand_path(self._join(path), *args, **kwargs))
344
+
345
+ async def _mkdir(self, path, *args, **kwargs):
346
+ return await self.fs._mkdir(self._join(path), *args, **kwargs)
347
+
348
+ def mkdir(self, path, *args, **kwargs):
349
+ return self.fs.mkdir(self._join(path), *args, **kwargs)
350
+
351
+ async def _makedirs(self, path, *args, **kwargs):
352
+ return await self.fs._makedirs(self._join(path), *args, **kwargs)
353
+
354
+ def makedirs(self, path, *args, **kwargs):
355
+ return self.fs.makedirs(self._join(path), *args, **kwargs)
356
+
357
+ def rmdir(self, path):
358
+ return self.fs.rmdir(self._join(path))
359
+
360
+ def mv(self, path1, path2, **kwargs):
361
+ return self.fs.mv(
362
+ self._join(path1),
363
+ self._join(path2),
364
+ **kwargs,
365
+ )
366
+
367
+ def touch(self, path, **kwargs):
368
+ return self.fs.touch(self._join(path), **kwargs)
369
+
370
+ def created(self, path):
371
+ return self.fs.created(self._join(path))
372
+
373
+ def modified(self, path):
374
+ return self.fs.modified(self._join(path))
375
+
376
+ def sign(self, path, *args, **kwargs):
377
+ return self.fs.sign(self._join(path), *args, **kwargs)
378
+
379
+ def __repr__(self):
380
+ return f"{self.__class__.__qualname__}(path='{self.path}', fs={self.fs})"
381
+
382
+ def open(
383
+ self,
384
+ path,
385
+ *args,
386
+ **kwargs,
387
+ ):
388
+ return self.fs.open(
389
+ self._join(path),
390
+ *args,
391
+ **kwargs,
392
+ )
393
+
394
+ async def open_async(
395
+ self,
396
+ path,
397
+ *args,
398
+ **kwargs,
399
+ ):
400
+ return await self.fs.open_async(
401
+ self._join(path),
402
+ *args,
403
+ **kwargs,
404
+ )
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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
+ "tlsv1": ssl.PROTOCOL_TLSv1,
13
+ "tlsv1_1": ssl.PROTOCOL_TLSv1_1,
14
+ "tlsv1_2": ssl.PROTOCOL_TLSv1_2,
15
+ "sslv23": ssl.PROTOCOL_SSLv23,
16
+ }
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
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/local.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import io
3
+ import logging
4
+ import os
5
+ import os.path as osp
6
+ import shutil
7
+ import stat
8
+ import tempfile
9
+ from functools import lru_cache
10
+
11
+ from fsspec import AbstractFileSystem
12
+ from fsspec.compression import compr
13
+ from fsspec.core import get_compression
14
+ from fsspec.utils import isfilelike, stringify_path
15
+
16
+ logger = logging.getLogger("fsspec.local")
17
+
18
+
19
+ class LocalFileSystem(AbstractFileSystem):
20
+ """Interface to files on local storage
21
+
22
+ Parameters
23
+ ----------
24
+ auto_mkdir: bool
25
+ Whether, when opening a file, the directory containing it should
26
+ be created (if it doesn't already exist). This is assumed by pyarrow
27
+ code.
28
+ """
29
+
30
+ root_marker = "/"
31
+ protocol = "file", "local"
32
+ local_file = True
33
+
34
+ def __init__(self, auto_mkdir=False, **kwargs):
35
+ super().__init__(**kwargs)
36
+ self.auto_mkdir = auto_mkdir
37
+
38
+ @property
39
+ def fsid(self):
40
+ return "local"
41
+
42
+ def mkdir(self, path, create_parents=True, **kwargs):
43
+ path = self._strip_protocol(path)
44
+ if self.exists(path):
45
+ raise FileExistsError(path)
46
+ if create_parents:
47
+ self.makedirs(path, exist_ok=True)
48
+ else:
49
+ os.mkdir(path, **kwargs)
50
+
51
+ def makedirs(self, path, exist_ok=False):
52
+ path = self._strip_protocol(path)
53
+ os.makedirs(path, exist_ok=exist_ok)
54
+
55
+ def rmdir(self, path):
56
+ path = self._strip_protocol(path)
57
+ os.rmdir(path)
58
+
59
+ def ls(self, path, detail=False, **kwargs):
60
+ path = self._strip_protocol(path)
61
+ path_info = self.info(path)
62
+ infos = []
63
+ if path_info["type"] == "directory":
64
+ with os.scandir(path) as it:
65
+ for f in it:
66
+ try:
67
+ # Only get the info if requested since it is a bit expensive (the stat call inside)
68
+ # The strip_protocol is also used in info() and calls make_path_posix to always return posix paths
69
+ info = self.info(f) if detail else self._strip_protocol(f.path)
70
+ infos.append(info)
71
+ except FileNotFoundError:
72
+ pass
73
+ else:
74
+ infos = [path_info] if detail else [path_info["name"]]
75
+
76
+ return infos
77
+
78
+ def info(self, path, **kwargs):
79
+ if isinstance(path, os.DirEntry):
80
+ # scandir DirEntry
81
+ out = path.stat(follow_symlinks=False)
82
+ link = path.is_symlink()
83
+ if path.is_dir(follow_symlinks=False):
84
+ t = "directory"
85
+ elif path.is_file(follow_symlinks=False):
86
+ t = "file"
87
+ else:
88
+ t = "other"
89
+
90
+ size = out.st_size
91
+ if link:
92
+ try:
93
+ out2 = path.stat(follow_symlinks=True)
94
+ size = out2.st_size
95
+ except OSError:
96
+ size = 0
97
+ path = self._strip_protocol(path.path)
98
+ else:
99
+ # str or path-like
100
+ path = self._strip_protocol(path)
101
+ out = os.stat(path, follow_symlinks=False)
102
+ link = stat.S_ISLNK(out.st_mode)
103
+ if link:
104
+ out = os.stat(path, follow_symlinks=True)
105
+ size = out.st_size
106
+ if stat.S_ISDIR(out.st_mode):
107
+ t = "directory"
108
+ elif stat.S_ISREG(out.st_mode):
109
+ t = "file"
110
+ else:
111
+ t = "other"
112
+
113
+ # Check for the 'st_birthtime' attribute, which is not always present; fallback to st_ctime
114
+ created_time = getattr(out, "st_birthtime", out.st_ctime)
115
+
116
+ result = {
117
+ "name": path,
118
+ "size": size,
119
+ "type": t,
120
+ "created": created_time,
121
+ "islink": link,
122
+ }
123
+ for field in ["mode", "uid", "gid", "mtime", "ino", "nlink"]:
124
+ result[field] = getattr(out, f"st_{field}")
125
+ if link:
126
+ result["destination"] = os.readlink(path)
127
+ return result
128
+
129
+ def lexists(self, path, **kwargs):
130
+ return osp.lexists(path)
131
+
132
+ def cp_file(self, path1, path2, **kwargs):
133
+ path1 = self._strip_protocol(path1)
134
+ path2 = self._strip_protocol(path2)
135
+ if self.auto_mkdir:
136
+ self.makedirs(self._parent(path2), exist_ok=True)
137
+ if self.isfile(path1):
138
+ shutil.copyfile(path1, path2)
139
+ elif self.isdir(path1):
140
+ self.mkdirs(path2, exist_ok=True)
141
+ else:
142
+ raise FileNotFoundError(path1)
143
+
144
+ def isfile(self, path):
145
+ path = self._strip_protocol(path)
146
+ return os.path.isfile(path)
147
+
148
+ def isdir(self, path):
149
+ path = self._strip_protocol(path)
150
+ return os.path.isdir(path)
151
+
152
+ def get_file(self, path1, path2, callback=None, **kwargs):
153
+ if isfilelike(path2):
154
+ with open(path1, "rb") as f:
155
+ shutil.copyfileobj(f, path2)
156
+ else:
157
+ return self.cp_file(path1, path2, **kwargs)
158
+
159
+ def put_file(self, path1, path2, callback=None, **kwargs):
160
+ return self.cp_file(path1, path2, **kwargs)
161
+
162
+ def mv(self, path1, path2, recursive: bool = True, **kwargs):
163
+ """Move files/directories
164
+ For the specific case of local, all ops on directories are recursive and
165
+ the recursive= kwarg is ignored.
166
+ """
167
+ path1 = self._strip_protocol(path1)
168
+ path2 = self._strip_protocol(path2)
169
+
170
+ if self.auto_mkdir:
171
+ self.makedirs(self._parent(path2), exist_ok=True)
172
+
173
+ shutil.move(path1, path2)
174
+
175
+ def link(self, src, dst, **kwargs):
176
+ src = self._strip_protocol(src)
177
+ dst = self._strip_protocol(dst)
178
+ os.link(src, dst, **kwargs)
179
+
180
+ def symlink(self, src, dst, **kwargs):
181
+ src = self._strip_protocol(src)
182
+ dst = self._strip_protocol(dst)
183
+ os.symlink(src, dst, **kwargs)
184
+
185
+ def islink(self, path) -> bool:
186
+ return os.path.islink(self._strip_protocol(path))
187
+
188
+ def rm_file(self, path):
189
+ os.remove(self._strip_protocol(path))
190
+
191
+ def rm(self, path, recursive=False, maxdepth=None):
192
+ if not isinstance(path, list):
193
+ path = [path]
194
+
195
+ for p in path:
196
+ p = self._strip_protocol(p)
197
+ if self.isdir(p):
198
+ if not recursive:
199
+ raise ValueError("Cannot delete directory, set recursive=True")
200
+ if osp.abspath(p) == os.getcwd():
201
+ raise ValueError("Cannot delete current working directory")
202
+ shutil.rmtree(p)
203
+ else:
204
+ os.remove(p)
205
+
206
+ def unstrip_protocol(self, name):
207
+ protocol = self.protocol if isinstance(self.protocol, str) else self.protocol[0]
208
+ name = self._strip_protocol(name) # normalise for local/win/...
209
+ return f"{protocol}://{name}"
210
+
211
+ def _open(self, path, mode="rb", block_size=None, **kwargs):
212
+ path = self._strip_protocol(path)
213
+ if self.auto_mkdir and "w" in mode:
214
+ self.makedirs(self._parent(path), exist_ok=True)
215
+ return LocalFileOpener(path, mode, fs=self, **kwargs)
216
+
217
+ def touch(self, path, truncate=True, **kwargs):
218
+ path = self._strip_protocol(path)
219
+ if self.auto_mkdir:
220
+ self.makedirs(self._parent(path), exist_ok=True)
221
+ if self.exists(path):
222
+ os.utime(path, None)
223
+ else:
224
+ open(path, "a").close()
225
+ if truncate:
226
+ os.truncate(path, 0)
227
+
228
+ def created(self, path):
229
+ info = self.info(path=path)
230
+ return datetime.datetime.fromtimestamp(
231
+ info["created"], tz=datetime.timezone.utc
232
+ )
233
+
234
+ def modified(self, path):
235
+ info = self.info(path=path)
236
+ return datetime.datetime.fromtimestamp(info["mtime"], tz=datetime.timezone.utc)
237
+
238
+ @classmethod
239
+ def _parent(cls, path):
240
+ path = cls._strip_protocol(path)
241
+ if os.sep == "/":
242
+ # posix native
243
+ return path.rsplit("/", 1)[0] or "/"
244
+ else:
245
+ # NT
246
+ path_ = path.rsplit("/", 1)[0]
247
+ if len(path_) <= 3:
248
+ if path_[1:2] == ":":
249
+ # nt root (something like c:/)
250
+ return path_[0] + ":/"
251
+ # More cases may be required here
252
+ return path_
253
+
254
+ @classmethod
255
+ def _strip_protocol(cls, path):
256
+ path = stringify_path(path)
257
+ protos = (cls.protocol,) if isinstance(cls.protocol, str) else cls.protocol
258
+ prefixes = (protocol + sep for protocol in protos for sep in ("://", ":"))
259
+ for prefix in prefixes:
260
+ if path.startswith(prefix):
261
+ path = path.removeprefix(prefix)
262
+ break
263
+
264
+ path = make_path_posix(path)
265
+ if os.sep != "/":
266
+ # This code-path is a stripped down version of
267
+ # > drive, path = ntpath.splitdrive(path)
268
+ if path[1:2] == ":":
269
+ # Absolute drive-letter path, e.g. X:\Windows
270
+ # Relative path with drive, e.g. X:Windows
271
+ drive, path = path[:2], path[2:]
272
+ elif path[:2] == "//":
273
+ # UNC drives, e.g. \\server\share or \\?\UNC\server\share
274
+ # Device drives, e.g. \\.\device or \\?\device
275
+ if (index1 := path.find("/", 2)) == -1 or (
276
+ index2 := path.find("/", index1 + 1)
277
+ ) == -1:
278
+ drive, path = path, ""
279
+ else:
280
+ drive, path = path[:index2], path[index2:]
281
+ else:
282
+ # Relative path, e.g. Windows
283
+ drive = ""
284
+
285
+ path = path.rstrip("/") or cls.root_marker
286
+ return drive + path
287
+
288
+ else:
289
+ return path.rstrip("/") or cls.root_marker
290
+
291
+ def _isfilestore(self):
292
+ # Inheriting from DaskFileSystem makes this False (S3, etc. were)
293
+ # the original motivation. But we are a posix-like file system.
294
+ # See https://github.com/dask/dask/issues/5526
295
+ return True
296
+
297
+ def chmod(self, path, mode):
298
+ path = stringify_path(path)
299
+ return os.chmod(path, mode)
300
+
301
+
302
+ def make_path_posix(path):
303
+ """Make path generic and absolute for current OS"""
304
+ if not isinstance(path, str):
305
+ if isinstance(path, (list, set, tuple)):
306
+ return type(path)(make_path_posix(p) for p in path)
307
+ else:
308
+ path = stringify_path(path)
309
+ if not isinstance(path, str):
310
+ raise TypeError(f"could not convert {path!r} to string")
311
+ if os.sep == "/":
312
+ # Native posix
313
+ if path.startswith("/"):
314
+ # most common fast case for posix
315
+ return path
316
+ elif path.startswith("~"):
317
+ return osp.expanduser(path)
318
+ elif path.startswith("./"):
319
+ path = path[2:]
320
+ elif path == ".":
321
+ path = ""
322
+ return f"{os.getcwd()}/{path}"
323
+ else:
324
+ # NT handling
325
+ if path[0:1] == "/" and path[2:3] == ":":
326
+ # path is like "/c:/local/path"
327
+ path = path[1:]
328
+ if path[1:2] == ":":
329
+ # windows full path like "C:\\local\\path"
330
+ if len(path) <= 3:
331
+ # nt root (something like c:/)
332
+ return path[0] + ":/"
333
+ path = path.replace("\\", "/")
334
+ return path
335
+ elif path[0:1] == "~":
336
+ return make_path_posix(osp.expanduser(path))
337
+ elif path.startswith(("\\\\", "//")):
338
+ # windows UNC/DFS-style paths
339
+ return "//" + path[2:].replace("\\", "/")
340
+ elif path.startswith(("\\", "/")):
341
+ # windows relative path with root
342
+ path = path.replace("\\", "/")
343
+ return f"{osp.splitdrive(os.getcwd())[0]}{path}"
344
+ else:
345
+ path = path.replace("\\", "/")
346
+ if path.startswith("./"):
347
+ path = path[2:]
348
+ elif path == ".":
349
+ path = ""
350
+ return f"{make_path_posix(os.getcwd())}/{path}"
351
+
352
+
353
+ def trailing_sep(path):
354
+ """Return True if the path ends with a path separator.
355
+
356
+ A forward slash is always considered a path separator, even on Operating
357
+ Systems that normally use a backslash.
358
+ """
359
+ # TODO: if all incoming paths were posix-compliant then separator would
360
+ # always be a forward slash, simplifying this function.
361
+ # See https://github.com/fsspec/filesystem_spec/pull/1250
362
+ return path.endswith(os.sep) or (os.altsep is not None and path.endswith(os.altsep))
363
+
364
+
365
+ @lru_cache(maxsize=1)
366
+ def get_umask(mask: int = 0o666) -> int:
367
+ """Get the current umask.
368
+
369
+ Follows https://stackoverflow.com/a/44130549 to get the umask.
370
+ Temporarily sets the umask to the given value, and then resets it to the
371
+ original value.
372
+ """
373
+ value = os.umask(mask)
374
+ os.umask(value)
375
+ return value
376
+
377
+
378
+ class LocalFileOpener(io.IOBase):
379
+ def __init__(
380
+ self, path, mode, autocommit=True, fs=None, compression=None, **kwargs
381
+ ):
382
+ logger.debug("open file: %s", path)
383
+ self.path = path
384
+ self.mode = mode
385
+ self.fs = fs
386
+ self.f = None
387
+ self.autocommit = autocommit
388
+ self.compression = get_compression(path, compression)
389
+ self.blocksize = io.DEFAULT_BUFFER_SIZE
390
+ self._open()
391
+
392
+ def _open(self):
393
+ if self.f is None or self.f.closed:
394
+ if self.autocommit or "w" not in self.mode:
395
+ self.f = open(self.path, mode=self.mode)
396
+ if self.compression:
397
+ compress = compr[self.compression]
398
+ self.f = compress(self.f, mode=self.mode)
399
+ else:
400
+ # TODO: check if path is writable?
401
+ i, name = tempfile.mkstemp()
402
+ os.close(i) # we want normal open and normal buffered file
403
+ self.temp = name
404
+ self.f = open(name, mode=self.mode)
405
+ if "w" not in self.mode:
406
+ self.size = self.f.seek(0, 2)
407
+ self.f.seek(0)
408
+ self.f.size = self.size
409
+
410
+ def _fetch_range(self, start, end):
411
+ # probably only used by cached FS
412
+ if "r" not in self.mode:
413
+ raise ValueError
414
+ self._open()
415
+ self.f.seek(start)
416
+ return self.f.read(end - start)
417
+
418
+ def __setstate__(self, state):
419
+ self.f = None
420
+ loc = state.pop("loc", None)
421
+ self.__dict__.update(state)
422
+ if "r" in state["mode"]:
423
+ self.f = None
424
+ self._open()
425
+ self.f.seek(loc)
426
+
427
+ def __getstate__(self):
428
+ d = self.__dict__.copy()
429
+ d.pop("f")
430
+ if "r" in self.mode:
431
+ d["loc"] = self.f.tell()
432
+ else:
433
+ if not self.f.closed:
434
+ raise ValueError("Cannot serialise open write-mode local file")
435
+ return d
436
+
437
+ def commit(self):
438
+ if self.autocommit:
439
+ raise RuntimeError("Can only commit if not already set to autocommit")
440
+ try:
441
+ shutil.move(self.temp, self.path)
442
+ except PermissionError as e:
443
+ # shutil.move raises PermissionError if os.rename
444
+ # and the default copy2 fallback with shutil.copystats fail.
445
+ # The file should be there nonetheless, but without copied permissions.
446
+ # If it doesn't exist, there was no permission to create the file.
447
+ if not os.path.exists(self.path):
448
+ raise e
449
+ else:
450
+ # If PermissionError is not raised, permissions can be set.
451
+ try:
452
+ mask = 0o666
453
+ os.chmod(self.path, mask & ~get_umask(mask))
454
+ except RuntimeError:
455
+ pass
456
+
457
+ def discard(self):
458
+ if self.autocommit:
459
+ raise RuntimeError("Cannot discard if set to autocommit")
460
+ os.remove(self.temp)
461
+
462
+ def readable(self) -> bool:
463
+ return True
464
+
465
+ def writable(self) -> bool:
466
+ return "r" not in self.mode
467
+
468
+ def read(self, *args, **kwargs):
469
+ return self.f.read(*args, **kwargs)
470
+
471
+ def write(self, *args, **kwargs):
472
+ return self.f.write(*args, **kwargs)
473
+
474
+ def tell(self, *args, **kwargs):
475
+ return self.f.tell(*args, **kwargs)
476
+
477
+ def seek(self, *args, **kwargs):
478
+ return self.f.seek(*args, **kwargs)
479
+
480
+ def seekable(self, *args, **kwargs):
481
+ return self.f.seekable(*args, **kwargs)
482
+
483
+ def readline(self, *args, **kwargs):
484
+ return self.f.readline(*args, **kwargs)
485
+
486
+ def readlines(self, *args, **kwargs):
487
+ return self.f.readlines(*args, **kwargs)
488
+
489
+ def close(self):
490
+ return self.f.close()
491
+
492
+ def truncate(self, size=None) -> int:
493
+ return self.f.truncate(size)
494
+
495
+ @property
496
+ def closed(self):
497
+ return self.f.closed
498
+
499
+ def fileno(self):
500
+ return self.raw.fileno()
501
+
502
+ def flush(self) -> None:
503
+ self.f.flush()
504
+
505
+ def __iter__(self):
506
+ return self.f.__iter__()
507
+
508
+ def __getattr__(self, item):
509
+ return getattr(self.f, item)
510
+
511
+ def __enter__(self):
512
+ self._incontext = True
513
+ return self
514
+
515
+ def __exit__(self, exc_type, exc_value, traceback):
516
+ self._incontext = False
517
+ self.f.__exit__(exc_type, exc_value, traceback)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/memory.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from datetime import datetime, timezone
5
+ from errno import ENOTEMPTY
6
+ from io import BytesIO
7
+ from pathlib import PurePath, PureWindowsPath
8
+ from typing import Any, ClassVar
9
+
10
+ from fsspec import AbstractFileSystem
11
+ from fsspec.implementations.local import LocalFileSystem
12
+ from fsspec.utils import stringify_path
13
+
14
+ logger = logging.getLogger("fsspec.memoryfs")
15
+
16
+
17
+ class MemoryFileSystem(AbstractFileSystem):
18
+ """A filesystem based on a dict of BytesIO objects
19
+
20
+ This is a global filesystem so instances of this class all point to the same
21
+ in memory filesystem.
22
+ """
23
+
24
+ store: ClassVar[dict[str, Any]] = {} # global, do not overwrite!
25
+ pseudo_dirs = [""] # global, do not overwrite!
26
+ protocol = "memory"
27
+ root_marker = "/"
28
+
29
+ @classmethod
30
+ def _strip_protocol(cls, path):
31
+ if isinstance(path, PurePath):
32
+ if isinstance(path, PureWindowsPath):
33
+ return LocalFileSystem._strip_protocol(path)
34
+ else:
35
+ path = stringify_path(path)
36
+
37
+ path = path.removeprefix("memory://")
38
+ if "::" in path or "://" in path:
39
+ return path.rstrip("/")
40
+ path = path.lstrip("/").rstrip("/")
41
+ return "/" + path if path else ""
42
+
43
+ def ls(self, path, detail=True, **kwargs):
44
+ path = self._strip_protocol(path)
45
+ if path in self.store:
46
+ # there is a key with this exact name
47
+ if not detail:
48
+ return [path]
49
+ return [
50
+ {
51
+ "name": path,
52
+ "size": self.store[path].size,
53
+ "type": "file",
54
+ "created": self.store[path].created.timestamp(),
55
+ }
56
+ ]
57
+ paths = set()
58
+ starter = path + "/"
59
+ out = []
60
+ for p2 in tuple(self.store):
61
+ if p2.startswith(starter):
62
+ if "/" not in p2[len(starter) :]:
63
+ # exact child
64
+ out.append(
65
+ {
66
+ "name": p2,
67
+ "size": self.store[p2].size,
68
+ "type": "file",
69
+ "created": self.store[p2].created.timestamp(),
70
+ }
71
+ )
72
+ elif len(p2) > len(starter):
73
+ # implied child directory
74
+ ppath = starter + p2[len(starter) :].split("/", 1)[0]
75
+ if ppath not in paths:
76
+ out = out or []
77
+ out.append(
78
+ {
79
+ "name": ppath,
80
+ "size": 0,
81
+ "type": "directory",
82
+ }
83
+ )
84
+ paths.add(ppath)
85
+ for p2 in self.pseudo_dirs:
86
+ if p2.startswith(starter):
87
+ if "/" not in p2[len(starter) :]:
88
+ # exact child pdir
89
+ if p2 not in paths:
90
+ out.append({"name": p2, "size": 0, "type": "directory"})
91
+ paths.add(p2)
92
+ else:
93
+ # directory implied by deeper pdir
94
+ ppath = starter + p2[len(starter) :].split("/", 1)[0]
95
+ if ppath not in paths:
96
+ out.append({"name": ppath, "size": 0, "type": "directory"})
97
+ paths.add(ppath)
98
+ if not out:
99
+ if path in self.pseudo_dirs:
100
+ # empty dir
101
+ return []
102
+ raise FileNotFoundError(path)
103
+ if detail:
104
+ return out
105
+ return sorted([f["name"] for f in out])
106
+
107
+ def mkdir(self, path, create_parents=True, **kwargs):
108
+ path = self._strip_protocol(path)
109
+ if path in self.store or path in self.pseudo_dirs:
110
+ raise FileExistsError(path)
111
+ if self._parent(path).strip("/") and self.isfile(self._parent(path)):
112
+ raise NotADirectoryError(self._parent(path))
113
+ if create_parents and self._parent(path).strip("/"):
114
+ try:
115
+ self.mkdir(self._parent(path), create_parents, **kwargs)
116
+ except FileExistsError:
117
+ pass
118
+ if path and path not in self.pseudo_dirs:
119
+ self.pseudo_dirs.append(path)
120
+
121
+ def makedirs(self, path, exist_ok=False):
122
+ try:
123
+ self.mkdir(path, create_parents=True)
124
+ except FileExistsError:
125
+ if not exist_ok:
126
+ raise
127
+
128
+ def pipe_file(self, path, value, mode="overwrite", **kwargs):
129
+ """Set the bytes of given file
130
+
131
+ Avoids copies of the data if possible
132
+ """
133
+ mode = "xb" if mode == "create" else "wb"
134
+ self.open(path, mode=mode, data=value)
135
+
136
+ def rmdir(self, path):
137
+ path = self._strip_protocol(path)
138
+ if path == "":
139
+ # silently avoid deleting FS root
140
+ return
141
+ if path in self.pseudo_dirs:
142
+ if not self.ls(path):
143
+ self.pseudo_dirs.remove(path)
144
+ else:
145
+ raise OSError(ENOTEMPTY, "Directory not empty", path)
146
+ else:
147
+ raise FileNotFoundError(path)
148
+
149
+ def info(self, path, **kwargs):
150
+ logger.debug("info: %s", path)
151
+ path = self._strip_protocol(path)
152
+ if path in self.pseudo_dirs or any(
153
+ p.startswith(path + "/") for p in list(self.store) + self.pseudo_dirs
154
+ ):
155
+ return {
156
+ "name": path,
157
+ "size": 0,
158
+ "type": "directory",
159
+ }
160
+ elif path in self.store:
161
+ filelike = self.store[path]
162
+ return {
163
+ "name": path,
164
+ "size": filelike.size,
165
+ "type": "file",
166
+ "created": getattr(filelike, "created", None),
167
+ }
168
+ else:
169
+ raise FileNotFoundError(path)
170
+
171
+ def _open(
172
+ self,
173
+ path,
174
+ mode="rb",
175
+ block_size=None,
176
+ autocommit=True,
177
+ cache_options=None,
178
+ **kwargs,
179
+ ):
180
+ path = self._strip_protocol(path)
181
+ if "x" in mode and self.exists(path):
182
+ raise FileExistsError
183
+ if path in self.pseudo_dirs:
184
+ raise IsADirectoryError(path)
185
+ parent = path
186
+ while len(parent) > 1:
187
+ parent = self._parent(parent)
188
+ if self.isfile(parent):
189
+ raise FileExistsError(parent)
190
+ if mode in ["rb", "ab", "r+b", "a+b"]:
191
+ if path in self.store:
192
+ f = self.store[path]
193
+ if "a" in mode:
194
+ # position at the end of file
195
+ f.seek(0, 2)
196
+ else:
197
+ # position at the beginning of file
198
+ f.seek(0)
199
+ return f
200
+ else:
201
+ raise FileNotFoundError(path)
202
+ elif mode in {"wb", "w+b", "xb", "x+b"}:
203
+ if "x" in mode and self.exists(path):
204
+ raise FileExistsError
205
+ m = MemoryFile(self, path, kwargs.get("data"))
206
+ if not self._intrans:
207
+ m.commit()
208
+ return m
209
+ else:
210
+ name = self.__class__.__name__
211
+ raise ValueError(f"unsupported file mode for {name}: {mode!r}")
212
+
213
+ def cp_file(self, path1, path2, **kwargs):
214
+ path1 = self._strip_protocol(path1)
215
+ path2 = self._strip_protocol(path2)
216
+ if self.isfile(path1):
217
+ self.store[path2] = MemoryFile(
218
+ self, path2, self.store[path1].getvalue()
219
+ ) # implicit copy
220
+ elif self.isdir(path1):
221
+ if path2 not in self.pseudo_dirs:
222
+ self.pseudo_dirs.append(path2)
223
+ else:
224
+ raise FileNotFoundError(path1)
225
+
226
+ def cat_file(self, path, start=None, end=None, **kwargs):
227
+ logger.debug("cat: %s", path)
228
+ path = self._strip_protocol(path)
229
+ try:
230
+ return bytes(self.store[path].getbuffer()[start:end])
231
+ except KeyError as e:
232
+ raise FileNotFoundError(path) from e
233
+
234
+ def _rm(self, path):
235
+ path = self._strip_protocol(path)
236
+ try:
237
+ del self.store[path]
238
+ except KeyError as e:
239
+ raise FileNotFoundError(path) from e
240
+
241
+ def modified(self, path):
242
+ path = self._strip_protocol(path)
243
+ try:
244
+ return self.store[path].modified
245
+ except KeyError as e:
246
+ raise FileNotFoundError(path) from e
247
+
248
+ def created(self, path):
249
+ path = self._strip_protocol(path)
250
+ try:
251
+ return self.store[path].created
252
+ except KeyError as e:
253
+ raise FileNotFoundError(path) from e
254
+
255
+ def isfile(self, path):
256
+ path = self._strip_protocol(path)
257
+ return path in self.store
258
+
259
+ def rm(self, path, recursive=False, maxdepth=None):
260
+ if isinstance(path, str):
261
+ path = self._strip_protocol(path)
262
+ else:
263
+ path = [self._strip_protocol(p) for p in path]
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
+ # If the expanded path doesn't exist, it is only because the expanded
269
+ # path was a directory that does not exist in self.pseudo_dirs. This
270
+ # is possible if you directly create files without making the
271
+ # directories first.
272
+ elif not self.exists(p):
273
+ continue
274
+ else:
275
+ self.rmdir(p)
276
+
277
+
278
+ class MemoryFile(BytesIO):
279
+ """A BytesIO which can't close and works as a context manager
280
+
281
+ Can initialise with data. Each path should only be active once at any moment.
282
+
283
+ No need to provide fs, path if auto-committing (default)
284
+ """
285
+
286
+ def __init__(self, fs=None, path=None, data=None):
287
+ logger.debug("open file %s", path)
288
+ self.fs = fs
289
+ self.path = path
290
+ self.created = datetime.now(tz=timezone.utc)
291
+ self.modified = datetime.now(tz=timezone.utc)
292
+ if data:
293
+ super().__init__(data)
294
+ self.seek(0)
295
+
296
+ @property
297
+ def size(self):
298
+ return self.getbuffer().nbytes
299
+
300
+ def __enter__(self):
301
+ return self
302
+
303
+ def close(self):
304
+ pass
305
+
306
+ def discard(self):
307
+ pass
308
+
309
+ def commit(self):
310
+ self.fs.store[self.path] = self
311
+ self.modified = datetime.now(tz=timezone.utc)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/reference.py ADDED
@@ -0,0 +1,1339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import collections
3
+ import io
4
+ import itertools
5
+ import logging
6
+ import math
7
+ import os
8
+ from functools import lru_cache
9
+ from itertools import chain
10
+ from typing import TYPE_CHECKING, Literal
11
+
12
+ import fsspec.core
13
+ from fsspec.spec import AbstractBufferedFile
14
+
15
+ try:
16
+ import ujson as json
17
+ except ImportError:
18
+ if not TYPE_CHECKING:
19
+ import json
20
+
21
+ from fsspec.asyn import AsyncFileSystem
22
+ from fsspec.callbacks import DEFAULT_CALLBACK
23
+ from fsspec.core import filesystem, open, split_protocol
24
+ from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper
25
+ from fsspec.utils import (
26
+ isfilelike,
27
+ merge_offset_ranges,
28
+ other_paths,
29
+ )
30
+
31
+ logger = logging.getLogger("fsspec.reference")
32
+
33
+
34
+ class ReferenceNotReachable(RuntimeError):
35
+ def __init__(self, reference, target, *args):
36
+ super().__init__(*args)
37
+ self.reference = reference
38
+ self.target = target
39
+
40
+ def __str__(self):
41
+ return f'Reference "{self.reference}" failed to fetch target {self.target}'
42
+
43
+
44
+ def _first(d):
45
+ return next(iter(d.values()))
46
+
47
+
48
+ def _prot_in_references(path, references):
49
+ ref = references.get(path)
50
+ if isinstance(ref, (list, tuple)) and isinstance(ref[0], str):
51
+ return split_protocol(ref[0])[0] if ref[0] else ref[0]
52
+
53
+
54
+ def _protocol_groups(paths, references):
55
+ if isinstance(paths, str):
56
+ return {_prot_in_references(paths, references): [paths]}
57
+ out = {}
58
+ for path in paths:
59
+ protocol = _prot_in_references(path, references)
60
+ out.setdefault(protocol, []).append(path)
61
+ return out
62
+
63
+
64
+ class RefsValuesView(collections.abc.ValuesView):
65
+ def __iter__(self):
66
+ for val in self._mapping.zmetadata.values():
67
+ yield json.dumps(val).encode()
68
+ yield from self._mapping._items.values()
69
+ for field in self._mapping.listdir():
70
+ chunk_sizes = self._mapping._get_chunk_sizes(field)
71
+ if len(chunk_sizes) == 0:
72
+ yield self._mapping[field + "/0"]
73
+ continue
74
+ yield from self._mapping._generate_all_records(field)
75
+
76
+
77
+ class RefsItemsView(collections.abc.ItemsView):
78
+ def __iter__(self):
79
+ return zip(self._mapping.keys(), self._mapping.values())
80
+
81
+
82
+ def ravel_multi_index(idx, sizes):
83
+ val = 0
84
+ mult = 1
85
+ for i, s in zip(idx[::-1], sizes[::-1]):
86
+ val += i * mult
87
+ mult *= s
88
+ return val
89
+
90
+
91
+ class LazyReferenceMapper(collections.abc.MutableMapping):
92
+ """This interface can be used to read/write references from Parquet stores.
93
+ It is not intended for other types of references.
94
+ It can be used with Kerchunk's MultiZarrToZarr method to combine
95
+ references into a parquet store.
96
+ Examples of this use-case can be found here:
97
+ https://fsspec.github.io/kerchunk/advanced.html?highlight=parquet#parquet-storage"""
98
+
99
+ # import is class level to prevent numpy dep requirement for fsspec
100
+ @property
101
+ def np(self):
102
+ import numpy as np
103
+
104
+ return np
105
+
106
+ @property
107
+ def pd(self):
108
+ import pandas as pd
109
+
110
+ return pd
111
+
112
+ def __init__(
113
+ self,
114
+ root,
115
+ fs=None,
116
+ out_root=None,
117
+ cache_size=128,
118
+ categorical_threshold=10,
119
+ engine: Literal["fastparquet", "pyarrow"] = "fastparquet",
120
+ ):
121
+ """
122
+
123
+ This instance will be writable, storing changes in memory until full partitions
124
+ are accumulated or .flush() is called.
125
+
126
+ To create an empty lazy store, use .create()
127
+
128
+ Parameters
129
+ ----------
130
+ root : str
131
+ Root of parquet store
132
+ fs : fsspec.AbstractFileSystem
133
+ fsspec filesystem object, default is local filesystem.
134
+ cache_size : int, default=128
135
+ Maximum size of LRU cache, where cache_size*record_size denotes
136
+ the total number of references that can be loaded in memory at once.
137
+ categorical_threshold : int
138
+ Encode urls as pandas.Categorical to reduce memory footprint if the ratio
139
+ of the number of unique urls to total number of refs for each variable
140
+ is greater than or equal to this number. (default 10)
141
+ engine: Literal["fastparquet","pyarrow"]
142
+ Engine choice for reading parquet files. (default is "fastparquet")
143
+ """
144
+
145
+ self.root = root
146
+ self.chunk_sizes = {}
147
+ self.cat_thresh = categorical_threshold
148
+ self.engine = engine
149
+ self.cache_size = cache_size
150
+ self.url = self.root + "/{field}/refs.{record}.parq"
151
+ # TODO: derive fs from `root`
152
+ self.fs = fsspec.filesystem("file") if fs is None else fs
153
+ self.out_root = self.fs.unstrip_protocol(out_root or self.root)
154
+
155
+ from importlib.util import find_spec
156
+
157
+ if self.engine == "pyarrow" and find_spec("pyarrow") is None:
158
+ raise ImportError("engine choice `pyarrow` is not installed.")
159
+
160
+ # Apply `lru_cache` decorator manually per instance.
161
+ # This way `self` reference is not held on class level.
162
+ # WARNING: However, this means that self and its members are not reflected
163
+ # in the cache key, so we expect they won't be mutated once a value is cached.
164
+ self.listdir = lru_cache()(self.listdir)
165
+ self._key_to_record = lru_cache(maxsize=4096)(self._key_to_record)
166
+
167
+ def __getattr__(self, item):
168
+ if item in ("_items", "record_size", "zmetadata"):
169
+ self.setup()
170
+ # avoid possible recursion if setup fails somehow
171
+ return self.__dict__[item]
172
+ raise AttributeError(item)
173
+
174
+ def setup(self):
175
+ self._items = {}
176
+ self._items[".zmetadata"] = self.fs.cat_file(
177
+ "/".join([self.root, ".zmetadata"])
178
+ )
179
+ met = json.loads(self._items[".zmetadata"])
180
+ self.record_size = met["record_size"]
181
+ self.zmetadata = met["metadata"]
182
+
183
+ # Define function to open and decompress refs
184
+ @lru_cache(maxsize=self.cache_size)
185
+ def open_refs(field, record):
186
+ """cached parquet file loader"""
187
+ path = self.url.format(field=field, record=record)
188
+ data = io.BytesIO(self.fs.cat_file(path))
189
+ try:
190
+ df = self.pd.read_parquet(data, engine=self.engine)
191
+ refs = {c: df[c].to_numpy(copy=True) for c in df.columns}
192
+ except OSError:
193
+ refs = None
194
+ return refs
195
+
196
+ self.open_refs = open_refs
197
+
198
+ @staticmethod
199
+ def create(root, storage_options=None, fs=None, record_size=10000, **kwargs):
200
+ """Make empty parquet reference set
201
+
202
+ First deletes the contents of the given directory, if it exists.
203
+
204
+ Parameters
205
+ ----------
206
+ root: str
207
+ Directory to contain the output; will be created
208
+ storage_options: dict | None
209
+ For making the filesystem to use for writing is fs is None
210
+ fs: FileSystem | None
211
+ Filesystem for writing
212
+ record_size: int
213
+ Number of references per parquet file
214
+ kwargs: passed to __init__
215
+
216
+ Returns
217
+ -------
218
+ LazyReferenceMapper instance
219
+ """
220
+ met = {"metadata": {}, "record_size": record_size}
221
+ if fs is None:
222
+ fs, root = fsspec.core.url_to_fs(root, **(storage_options or {}))
223
+ if fs.exists(root):
224
+ fs.rm(root, recursive=True)
225
+ fs.makedirs(root, exist_ok=True)
226
+ fs.pipe("/".join([root, ".zmetadata"]), json.dumps(met).encode())
227
+ return LazyReferenceMapper(root, fs, **kwargs)
228
+
229
+ def listdir(self):
230
+ """List top-level directories"""
231
+ dirs = (p.rsplit("/", 1)[0] for p in self.zmetadata if not p.startswith(".z"))
232
+ return set(dirs)
233
+
234
+ def ls(self, path="", detail=True):
235
+ """Shortcut file listings"""
236
+ path = path.rstrip("/")
237
+ pathdash = path + "/" if path else ""
238
+ dirnames = self.listdir()
239
+ dirs = [
240
+ d
241
+ for d in dirnames
242
+ if d.startswith(pathdash) and "/" not in d.lstrip(pathdash)
243
+ ]
244
+ if dirs:
245
+ others = {
246
+ f
247
+ for f in chain(
248
+ [".zmetadata"],
249
+ (name for name in self.zmetadata),
250
+ (name for name in self._items),
251
+ )
252
+ if f.startswith(pathdash) and "/" not in f.lstrip(pathdash)
253
+ }
254
+ if detail is False:
255
+ others.update(dirs)
256
+ return sorted(others)
257
+ dirinfo = [{"name": name, "type": "directory", "size": 0} for name in dirs]
258
+ fileinfo = [
259
+ {
260
+ "name": name,
261
+ "type": "file",
262
+ "size": len(
263
+ json.dumps(self.zmetadata[name])
264
+ if name in self.zmetadata
265
+ else self._items[name]
266
+ ),
267
+ }
268
+ for name in others
269
+ ]
270
+ return sorted(dirinfo + fileinfo, key=lambda s: s["name"])
271
+ field = path
272
+ others = set(
273
+ [name for name in self.zmetadata if name.startswith(f"{path}/")]
274
+ + [name for name in self._items if name.startswith(f"{path}/")]
275
+ )
276
+ fileinfo = [
277
+ {
278
+ "name": name,
279
+ "type": "file",
280
+ "size": len(
281
+ json.dumps(self.zmetadata[name])
282
+ if name in self.zmetadata
283
+ else self._items[name]
284
+ ),
285
+ }
286
+ for name in others
287
+ ]
288
+ keys = self._keys_in_field(field)
289
+
290
+ if detail is False:
291
+ return list(others) + list(keys)
292
+ recs = self._generate_all_records(field)
293
+ recinfo = [
294
+ {"name": name, "type": "file", "size": rec[-1]}
295
+ for name, rec in zip(keys, recs)
296
+ if rec[0] # filters out path==None, deleted/missing
297
+ ]
298
+ return fileinfo + recinfo
299
+
300
+ def _load_one_key(self, key):
301
+ """Get the reference for one key
302
+
303
+ Returns bytes, one-element list or three-element list.
304
+ """
305
+ if key in self._items:
306
+ return self._items[key]
307
+ elif key in self.zmetadata:
308
+ return json.dumps(self.zmetadata[key]).encode()
309
+ elif "/" not in key or self._is_meta(key):
310
+ raise KeyError(key)
311
+ field, _ = key.rsplit("/", 1)
312
+ record, ri, chunk_size = self._key_to_record(key)
313
+ maybe = self._items.get((field, record), {}).get(ri, False)
314
+ if maybe is None:
315
+ # explicitly deleted
316
+ raise KeyError
317
+ elif maybe:
318
+ return maybe
319
+ elif chunk_size == 0:
320
+ return b""
321
+
322
+ # Chunk keys can be loaded from row group and cached in LRU cache
323
+ try:
324
+ refs = self.open_refs(field, record)
325
+ except (ValueError, TypeError, FileNotFoundError) as exc:
326
+ raise KeyError(key) from exc
327
+ columns = ["path", "offset", "size", "raw"]
328
+ selection = [refs[c][ri] if c in refs else None for c in columns]
329
+ raw = selection[-1]
330
+ if raw is not None:
331
+ return raw
332
+ if selection[0] is None:
333
+ raise KeyError("This reference does not exist or has been deleted")
334
+ if selection[1:3] == [0, 0]:
335
+ # URL only
336
+ return selection[:1]
337
+ # URL, offset, size
338
+ return selection[:3]
339
+
340
+ def _key_to_record(self, key):
341
+ """Details needed to construct a reference for one key"""
342
+ field, chunk = key.rsplit("/", 1)
343
+ chunk_sizes = self._get_chunk_sizes(field)
344
+ if len(chunk_sizes) == 0:
345
+ return 0, 0, 0
346
+ chunk_idx = [int(c) for c in chunk.split(".")]
347
+ chunk_number = ravel_multi_index(chunk_idx, chunk_sizes)
348
+ record = chunk_number // self.record_size
349
+ ri = chunk_number % self.record_size
350
+ return record, ri, len(chunk_sizes)
351
+
352
+ def _get_chunk_sizes(self, field):
353
+ """The number of chunks along each axis for a given field"""
354
+ if field not in self.chunk_sizes:
355
+ zarray = self.zmetadata[f"{field}/.zarray"]
356
+ size_ratio = [
357
+ math.ceil(s / c) for s, c in zip(zarray["shape"], zarray["chunks"])
358
+ ]
359
+ self.chunk_sizes[field] = size_ratio or [1]
360
+ return self.chunk_sizes[field]
361
+
362
+ def _generate_record(self, field, record):
363
+ """The references for a given parquet file of a given field"""
364
+ refs = self.open_refs(field, record)
365
+ it = iter(zip(*refs.values()))
366
+ if len(refs) == 3:
367
+ # All urls
368
+ return (list(t) for t in it)
369
+ elif len(refs) == 1:
370
+ # All raws
371
+ return refs["raw"]
372
+ else:
373
+ # Mix of urls and raws
374
+ return (list(t[:3]) if not t[3] else t[3] for t in it)
375
+
376
+ def _generate_all_records(self, field):
377
+ """Load all the references within a field by iterating over the parquet files"""
378
+ nrec = 1
379
+ for ch in self._get_chunk_sizes(field):
380
+ nrec *= ch
381
+ nrec = math.ceil(nrec / self.record_size)
382
+ for record in range(nrec):
383
+ yield from self._generate_record(field, record)
384
+
385
+ def values(self):
386
+ return RefsValuesView(self)
387
+
388
+ def items(self):
389
+ return RefsItemsView(self)
390
+
391
+ def __hash__(self):
392
+ return id(self)
393
+
394
+ def __getitem__(self, key):
395
+ return self._load_one_key(key)
396
+
397
+ def __setitem__(self, key, value):
398
+ if "/" in key and not self._is_meta(key):
399
+ field, chunk = key.rsplit("/", 1)
400
+ record, i, _ = self._key_to_record(key)
401
+ subdict = self._items.setdefault((field, record), {})
402
+ subdict[i] = value
403
+ if len(subdict) == self.record_size:
404
+ self.write(field, record)
405
+ else:
406
+ # metadata or top-level
407
+ if hasattr(value, "to_bytes"):
408
+ val = value.to_bytes().decode()
409
+ elif isinstance(value, bytes):
410
+ val = value.decode()
411
+ else:
412
+ val = value
413
+ self._items[key] = val
414
+ new_value = json.loads(val)
415
+ self.zmetadata[key] = {**self.zmetadata.get(key, {}), **new_value}
416
+
417
+ @staticmethod
418
+ def _is_meta(key):
419
+ return key.startswith(".z") or "/.z" in key
420
+
421
+ def __delitem__(self, key):
422
+ if key in self._items:
423
+ del self._items[key]
424
+ elif key in self.zmetadata:
425
+ del self.zmetadata[key]
426
+ else:
427
+ if "/" in key and not self._is_meta(key):
428
+ field, _ = key.rsplit("/", 1)
429
+ record, i, _ = self._key_to_record(key)
430
+ subdict = self._items.setdefault((field, record), {})
431
+ subdict[i] = None
432
+ if len(subdict) == self.record_size:
433
+ self.write(field, record)
434
+ else:
435
+ # metadata or top-level
436
+ self._items[key] = None
437
+
438
+ def write(self, field, record, base_url=None, storage_options=None):
439
+ # extra requirements if writing
440
+ import kerchunk.df
441
+ import numpy as np
442
+ import pandas as pd
443
+
444
+ partition = self._items[(field, record)]
445
+ original = False
446
+ if len(partition) < self.record_size:
447
+ try:
448
+ original = self.open_refs(field, record)
449
+ except OSError:
450
+ pass
451
+
452
+ if original:
453
+ paths = original["path"]
454
+ offsets = original["offset"]
455
+ sizes = original["size"]
456
+ raws = original["raw"]
457
+ else:
458
+ paths = np.full(self.record_size, np.nan, dtype="O")
459
+ offsets = np.zeros(self.record_size, dtype="int64")
460
+ sizes = np.zeros(self.record_size, dtype="int64")
461
+ raws = np.full(self.record_size, np.nan, dtype="O")
462
+ for j, data in partition.items():
463
+ if isinstance(data, list):
464
+ if (
465
+ str(paths.dtype) == "category"
466
+ and data[0] not in paths.dtype.categories
467
+ ):
468
+ paths = paths.add_categories(data[0])
469
+ paths[j] = data[0]
470
+ if len(data) > 1:
471
+ offsets[j] = data[1]
472
+ sizes[j] = data[2]
473
+ elif data is None:
474
+ # delete
475
+ paths[j] = None
476
+ offsets[j] = 0
477
+ sizes[j] = 0
478
+ raws[j] = None
479
+ else:
480
+ # this is the only call into kerchunk, could remove
481
+ raws[j] = kerchunk.df._proc_raw(data)
482
+ # TODO: only save needed columns
483
+ df = pd.DataFrame(
484
+ {
485
+ "path": paths,
486
+ "offset": offsets,
487
+ "size": sizes,
488
+ "raw": raws,
489
+ },
490
+ copy=False,
491
+ )
492
+ if df.path.count() / (df.path.nunique() or 1) > self.cat_thresh:
493
+ df["path"] = df["path"].astype("category")
494
+ object_encoding = {"raw": "bytes", "path": "utf8"}
495
+ has_nulls = ["path", "raw"]
496
+
497
+ fn = f"{base_url or self.out_root}/{field}/refs.{record}.parq"
498
+ self.fs.mkdirs(f"{base_url or self.out_root}/{field}", exist_ok=True)
499
+
500
+ if self.engine == "pyarrow":
501
+ df_backend_kwargs = {"write_statistics": False}
502
+ elif self.engine == "fastparquet":
503
+ df_backend_kwargs = {
504
+ "stats": False,
505
+ "object_encoding": object_encoding,
506
+ "has_nulls": has_nulls,
507
+ }
508
+ else:
509
+ raise NotImplementedError(f"{self.engine} not supported")
510
+ df.to_parquet(
511
+ fn,
512
+ engine=self.engine,
513
+ storage_options=storage_options
514
+ or getattr(self.fs, "storage_options", None),
515
+ compression="zstd",
516
+ index=False,
517
+ **df_backend_kwargs,
518
+ )
519
+
520
+ partition.clear()
521
+ self._items.pop((field, record))
522
+
523
+ def flush(self, base_url=None, storage_options=None):
524
+ """Output any modified or deleted keys
525
+
526
+ Parameters
527
+ ----------
528
+ base_url: str
529
+ Location of the output
530
+ """
531
+
532
+ # write what we have so far and clear sub chunks
533
+ for thing in list(self._items):
534
+ if isinstance(thing, tuple):
535
+ field, record = thing
536
+ self.write(
537
+ field,
538
+ record,
539
+ base_url=base_url,
540
+ storage_options=storage_options,
541
+ )
542
+
543
+ # gather .zmetadata from self._items and write that too
544
+ for k in list(self._items):
545
+ if k != ".zmetadata" and ".z" in k:
546
+ self.zmetadata[k] = json.loads(self._items.pop(k))
547
+ met = {"metadata": self.zmetadata, "record_size": self.record_size}
548
+ self._items.clear()
549
+ self._items[".zmetadata"] = json.dumps(met).encode()
550
+ self.fs.pipe(
551
+ "/".join([base_url or self.out_root, ".zmetadata"]),
552
+ self._items[".zmetadata"],
553
+ )
554
+
555
+ # TODO: only clear those that we wrote to?
556
+ self.open_refs.cache_clear()
557
+
558
+ def __len__(self):
559
+ # Caveat: This counts expected references, not actual - but is fast
560
+ count = 0
561
+ for field in self.listdir():
562
+ if field.startswith("."):
563
+ count += 1
564
+ else:
565
+ count += math.prod(self._get_chunk_sizes(field))
566
+ count += len(self.zmetadata) # all metadata keys
567
+ # any other files not in reference partitions
568
+ count += sum(1 for _ in self._items if not isinstance(_, tuple))
569
+ return count
570
+
571
+ def __iter__(self):
572
+ # Caveat: returns only existing keys, so the number of these does not
573
+ # match len(self)
574
+ metas = set(self.zmetadata)
575
+ metas.update(self._items)
576
+ for bit in metas:
577
+ if isinstance(bit, str):
578
+ yield bit
579
+ for field in self.listdir():
580
+ for k in self._keys_in_field(field):
581
+ if k in self:
582
+ yield k
583
+
584
+ def __contains__(self, item):
585
+ try:
586
+ self._load_one_key(item)
587
+ return True
588
+ except KeyError:
589
+ return False
590
+
591
+ def _keys_in_field(self, field):
592
+ """List key names in given field
593
+
594
+ Produces strings like "field/x.y" appropriate from the chunking of the array
595
+ """
596
+ chunk_sizes = self._get_chunk_sizes(field)
597
+ if len(chunk_sizes) == 0:
598
+ yield field + "/0"
599
+ return
600
+ inds = itertools.product(*(range(i) for i in chunk_sizes))
601
+ for ind in inds:
602
+ yield field + "/" + ".".join([str(c) for c in ind])
603
+
604
+
605
+ class ReferenceFileSystem(AsyncFileSystem):
606
+ """View byte ranges of some other file as a file system
607
+ Initial version: single file system target, which must support
608
+ async, and must allow start and end args in _cat_file. Later versions
609
+ may allow multiple arbitrary URLs for the targets.
610
+ This FileSystem is read-only. It is designed to be used with async
611
+ targets (for now). We do not get original file details from the target FS.
612
+ Configuration is by passing a dict of references at init, or a URL to
613
+ a JSON file containing the same; this dict
614
+ can also contain concrete data for some set of paths.
615
+ Reference dict format:
616
+ {path0: bytes_data, path1: (target_url, offset, size)}
617
+ https://github.com/fsspec/kerchunk/blob/main/README.md
618
+
619
+ simple_references: if True (default), no jinja interpreting is done,
620
+ which is the safe option.
621
+ """
622
+
623
+ protocol = "reference"
624
+ cachable = False
625
+
626
+ def __init__(
627
+ self,
628
+ fo,
629
+ target=None,
630
+ ref_storage_args=None,
631
+ target_protocol=None,
632
+ target_options=None,
633
+ remote_protocol=None,
634
+ remote_options=None,
635
+ fs=None,
636
+ template_overrides=None,
637
+ simple_templates=True,
638
+ max_gap=64_000,
639
+ max_block=256_000_000,
640
+ cache_size=128,
641
+ **kwargs,
642
+ ):
643
+ """
644
+ Parameters
645
+ ----------
646
+ fo : dict or str
647
+ The set of references to use for this instance, with a structure as above.
648
+ If str referencing a JSON file, will use fsspec.open, in conjunction
649
+ with target_options and target_protocol to open and parse JSON at this
650
+ location. If a directory, then assume references are a set of parquet
651
+ files to be loaded lazily.
652
+ target : str
653
+ For any references having target_url as None, this is the default file
654
+ target to use
655
+ ref_storage_args : dict
656
+ If references is a str, use these kwargs for loading the JSON file.
657
+ Deprecated: use target_options instead.
658
+ target_protocol : str
659
+ Used for loading the reference file, if it is a path. If None, protocol
660
+ will be derived from the given path
661
+ target_options : dict
662
+ Extra FS options for loading the reference file ``fo``, if given as a path
663
+ remote_protocol : str
664
+ The protocol of the filesystem on which the references will be evaluated
665
+ (unless fs is provided). If not given, will be derived from the first
666
+ URL that has a protocol in the templates or in the references, in that
667
+ order.
668
+ remote_options : dict
669
+ kwargs to go with remote_protocol
670
+ fs : AbstractFileSystem | dict(str, (AbstractFileSystem | dict))
671
+ Directly provide a file system(s):
672
+ - a single filesystem instance
673
+ - a dict of protocol:filesystem, where each value is either a filesystem
674
+ instance, or a dict of kwargs that can be used to create in
675
+ instance for the given protocol
676
+
677
+ If this is given, remote_options and remote_protocol are ignored.
678
+ template_overrides : dict
679
+ Swap out any templates in the references file with these - useful for
680
+ testing.
681
+ simple_templates: bool
682
+ Whether templates can be processed with simple replace (True) or if
683
+ jinja is needed (False, much slower). All reference sets produced by
684
+ ``kerchunk`` are simple in this sense, but the spec allows for complex.
685
+ max_gap, max_block: int
686
+ For merging multiple concurrent requests to the same remote file.
687
+ Neighboring byte ranges will only be merged when their
688
+ inter-range gap is <= ``max_gap``. Default is 64KB. Set to 0
689
+ to only merge when it requires no extra bytes. Pass a negative
690
+ number to disable merging, appropriate for local target files.
691
+ Neighboring byte ranges will only be merged when the size of
692
+ the aggregated range is <= ``max_block``. Default is 256MB.
693
+ cache_size : int
694
+ Maximum size of LRU cache, where cache_size*record_size denotes
695
+ the total number of references that can be loaded in memory at once.
696
+ Only used for lazily loaded references.
697
+ kwargs : passed to parent class
698
+ """
699
+ super().__init__(**kwargs)
700
+ self.target = target
701
+ self.template_overrides = template_overrides
702
+ self.simple_templates = simple_templates
703
+ self.templates = {}
704
+ self.fss = {}
705
+ self._dircache = {}
706
+ self.max_gap = max_gap
707
+ self.max_block = max_block
708
+ if isinstance(fo, str):
709
+ dic = dict(
710
+ **(ref_storage_args or target_options or {}), protocol=target_protocol
711
+ )
712
+ ref_fs, fo2 = fsspec.core.url_to_fs(fo, **dic)
713
+ if ".json" not in fo2 and (
714
+ fo.endswith(("parq", "parquet", "/")) or ref_fs.isdir(fo2)
715
+ ):
716
+ # Lazy parquet refs
717
+ logger.info("Open lazy reference dict from URL %s", fo)
718
+ self.references = LazyReferenceMapper(
719
+ fo2,
720
+ fs=ref_fs,
721
+ cache_size=cache_size,
722
+ )
723
+ else:
724
+ # text JSON
725
+ with fsspec.open(fo, "rb", **dic) as f:
726
+ logger.info("Read reference from URL %s", fo)
727
+ text = json.load(f)
728
+ self._process_references(text, template_overrides)
729
+ else:
730
+ # dictionaries
731
+ self._process_references(fo, template_overrides)
732
+ if isinstance(fs, dict):
733
+ self.fss = {
734
+ k: (
735
+ fsspec.filesystem(k.split(":", 1)[0], **opts)
736
+ if isinstance(opts, dict)
737
+ else opts
738
+ )
739
+ for k, opts in fs.items()
740
+ }
741
+ if None not in self.fss:
742
+ self.fss[None] = filesystem("file")
743
+ return
744
+ if fs is not None:
745
+ # single remote FS
746
+ remote_protocol = (
747
+ fs.protocol[0] if isinstance(fs.protocol, tuple) else fs.protocol
748
+ )
749
+ self.fss[remote_protocol] = fs
750
+
751
+ if remote_protocol is None:
752
+ # get single protocol from any templates
753
+ for ref in self.templates.values():
754
+ if callable(ref):
755
+ ref = ref()
756
+ protocol, _ = fsspec.core.split_protocol(ref)
757
+ if protocol and protocol not in self.fss:
758
+ fs = filesystem(protocol, **(remote_options or {}))
759
+ self.fss[protocol] = fs
760
+ if remote_protocol is None:
761
+ # get single protocol from references
762
+ # TODO: warning here, since this can be very expensive?
763
+ for ref in self.references.values():
764
+ if callable(ref):
765
+ ref = ref()
766
+ if isinstance(ref, list) and ref[0]:
767
+ protocol, _ = fsspec.core.split_protocol(ref[0])
768
+ if protocol not in self.fss:
769
+ fs = filesystem(protocol, **(remote_options or {}))
770
+ self.fss[protocol] = fs
771
+ # only use first remote URL
772
+ break
773
+
774
+ if remote_protocol and remote_protocol not in self.fss:
775
+ fs = filesystem(remote_protocol, **(remote_options or {}))
776
+ self.fss[remote_protocol] = fs
777
+
778
+ self.fss[None] = fs or filesystem("file") # default one
779
+ # Wrap any non-async filesystems to ensure async methods are available below
780
+ for k, f in self.fss.items():
781
+ if not f.async_impl:
782
+ self.fss[k] = AsyncFileSystemWrapper(f, asynchronous=self.asynchronous)
783
+ elif self.asynchronous ^ f.asynchronous:
784
+ raise ValueError(
785
+ "Reference-FS's target filesystem must have same value "
786
+ "of asynchronous"
787
+ )
788
+
789
+ def _cat_common(self, path, start=None, end=None):
790
+ path = self._strip_protocol(path)
791
+ logger.debug(f"cat: {path}")
792
+ try:
793
+ part = self.references[path]
794
+ except KeyError as exc:
795
+ raise FileNotFoundError(path) from exc
796
+ if isinstance(part, str):
797
+ part = part.encode()
798
+ if hasattr(part, "to_bytes"):
799
+ part = part.to_bytes()
800
+ if isinstance(part, bytes):
801
+ logger.debug(f"Reference: {path}, type bytes")
802
+ if part.startswith(b"base64:"):
803
+ part = base64.b64decode(part[7:])
804
+ return part, None, None
805
+
806
+ if len(part) == 1:
807
+ logger.debug(f"Reference: {path}, whole file => {part}")
808
+ url = part[0]
809
+ start1, end1 = start, end
810
+ else:
811
+ url, start0, size = part
812
+ logger.debug(f"Reference: {path} => {url}, offset {start0}, size {size}")
813
+ end0 = start0 + size
814
+
815
+ if start is not None:
816
+ if start >= 0:
817
+ start1 = start0 + start
818
+ else:
819
+ start1 = end0 + start
820
+ else:
821
+ start1 = start0
822
+ if end is not None:
823
+ if end >= 0:
824
+ end1 = start0 + end
825
+ else:
826
+ end1 = end0 + end
827
+ else:
828
+ end1 = end0
829
+ if url is None:
830
+ url = self.target
831
+ return url, start1, end1
832
+
833
+ async def _cat_file(self, path, start=None, end=None, **kwargs):
834
+ part_or_url, start0, end0 = self._cat_common(path, start=start, end=end)
835
+ if isinstance(part_or_url, bytes):
836
+ return part_or_url[start:end]
837
+ protocol, _ = split_protocol(part_or_url)
838
+ try:
839
+ return await self.fss[protocol]._cat_file(
840
+ part_or_url, start=start0, end=end0
841
+ )
842
+ except Exception as e:
843
+ raise ReferenceNotReachable(path, part_or_url) from e
844
+
845
+ def cat_file(self, path, start=None, end=None, **kwargs):
846
+ part_or_url, start0, end0 = self._cat_common(path, start=start, end=end)
847
+ if isinstance(part_or_url, bytes):
848
+ return part_or_url[start:end]
849
+ protocol, _ = split_protocol(part_or_url)
850
+ try:
851
+ return self.fss[protocol].cat_file(part_or_url, start=start0, end=end0)
852
+ except Exception as e:
853
+ raise ReferenceNotReachable(path, part_or_url) from e
854
+
855
+ def pipe_file(self, path, value, **_):
856
+ """Temporarily add binary data or reference as a file"""
857
+ self.references[path] = value
858
+
859
+ async def _get_file(self, rpath, lpath, **kwargs):
860
+ if self.isdir(rpath):
861
+ return os.makedirs(lpath, exist_ok=True)
862
+ data = await self._cat_file(rpath)
863
+ with open(lpath, "wb") as f:
864
+ f.write(data)
865
+
866
+ def get_file(self, rpath, lpath, callback=DEFAULT_CALLBACK, **kwargs):
867
+ if self.isdir(rpath):
868
+ return os.makedirs(lpath, exist_ok=True)
869
+ data = self.cat_file(rpath, **kwargs)
870
+ callback.set_size(len(data))
871
+ if isfilelike(lpath):
872
+ lpath.write(data)
873
+ else:
874
+ with open(lpath, "wb") as f:
875
+ f.write(data)
876
+ callback.absolute_update(len(data))
877
+
878
+ def get(self, rpath, lpath, recursive=False, **kwargs):
879
+ if recursive:
880
+ # trigger directory build
881
+ self.ls("")
882
+ rpath = self.expand_path(rpath, recursive=recursive)
883
+ fs = fsspec.filesystem("file", auto_mkdir=True)
884
+ targets = other_paths(rpath, lpath)
885
+ if recursive:
886
+ data = self.cat([r for r in rpath if not self.isdir(r)])
887
+ else:
888
+ data = self.cat(rpath)
889
+ for remote, local in zip(rpath, targets):
890
+ if remote in data:
891
+ fs.pipe_file(local, data[remote])
892
+
893
+ def cat(self, path, recursive=False, on_error="raise", **kwargs):
894
+ if isinstance(path, str) and recursive:
895
+ raise NotImplementedError
896
+ if isinstance(path, list) and (recursive or any("*" in p for p in path)):
897
+ raise NotImplementedError
898
+ # TODO: if references is lazy, pre-fetch all paths in batch before access
899
+ proto_dict = _protocol_groups(path, self.references)
900
+ out = {}
901
+ for proto, paths in proto_dict.items():
902
+ fs = self.fss[proto]
903
+ urls, starts, ends, valid_paths = [], [], [], []
904
+ for p in paths:
905
+ # find references or label not-found. Early exit if any not
906
+ # found and on_error is "raise"
907
+ try:
908
+ u, s, e = self._cat_common(p)
909
+ if not isinstance(u, (bytes, str)):
910
+ # nan/None from parquet
911
+ continue
912
+ except FileNotFoundError as err:
913
+ if on_error == "raise":
914
+ raise
915
+ if on_error != "omit":
916
+ out[p] = err
917
+ else:
918
+ urls.append(u)
919
+ starts.append(s)
920
+ ends.append(e)
921
+ valid_paths.append(p)
922
+
923
+ # process references into form for merging
924
+ urls2 = []
925
+ starts2 = []
926
+ ends2 = []
927
+ paths2 = []
928
+ whole_files = set()
929
+ for u, s, e, p in zip(urls, starts, ends, valid_paths):
930
+ if isinstance(u, bytes):
931
+ # data
932
+ out[p] = u
933
+ elif s is None:
934
+ # whole file - limits are None, None, but no further
935
+ # entries take for this file
936
+ whole_files.add(u)
937
+ urls2.append(u)
938
+ starts2.append(s)
939
+ ends2.append(e)
940
+ paths2.append(p)
941
+ for u, s, e, p in zip(urls, starts, ends, valid_paths):
942
+ # second run to account for files that are to be loaded whole
943
+ if s is not None and u not in whole_files:
944
+ urls2.append(u)
945
+ starts2.append(s)
946
+ ends2.append(e)
947
+ paths2.append(p)
948
+
949
+ # merge and fetch consolidated ranges
950
+ new_paths, new_starts, new_ends = merge_offset_ranges(
951
+ list(urls2),
952
+ list(starts2),
953
+ list(ends2),
954
+ sort=True,
955
+ max_gap=self.max_gap,
956
+ max_block=self.max_block,
957
+ )
958
+ bytes_out = fs.cat_ranges(new_paths, new_starts, new_ends)
959
+
960
+ # unbundle from merged bytes - simple approach
961
+ for u, s, e, p in zip(urls, starts, ends, valid_paths):
962
+ if p in out:
963
+ continue # was bytes, already handled
964
+ for np, ns, ne, b in zip(new_paths, new_starts, new_ends, bytes_out):
965
+ if np == u and (ns is None or ne is None):
966
+ if isinstance(b, Exception):
967
+ out[p] = b
968
+ else:
969
+ out[p] = b[s:e]
970
+ elif np == u and s >= ns and e <= ne:
971
+ if isinstance(b, Exception):
972
+ out[p] = b
973
+ else:
974
+ out[p] = b[s - ns : (e - ne) or None]
975
+
976
+ for k, v in out.copy().items():
977
+ # these were valid references, but fetch failed, so transform exc
978
+ if isinstance(v, Exception) and k in self.references:
979
+ ex = out[k]
980
+ new_ex = ReferenceNotReachable(k, self.references[k])
981
+ new_ex.__cause__ = ex
982
+ if on_error == "raise":
983
+ raise new_ex
984
+ elif on_error != "omit":
985
+ out[k] = new_ex
986
+
987
+ if len(out) == 1 and isinstance(path, str) and "*" not in path:
988
+ return _first(out)
989
+ return out
990
+
991
+ def _process_references(self, references, template_overrides=None):
992
+ vers = references.get("version", None)
993
+ if vers is None:
994
+ self._process_references0(references)
995
+ elif vers == 1:
996
+ self._process_references1(references, template_overrides=template_overrides)
997
+ else:
998
+ raise ValueError(f"Unknown reference spec version: {vers}")
999
+ # TODO: we make dircache by iterating over all entries, but for Spec >= 1,
1000
+ # can replace with programmatic. Is it even needed for mapper interface?
1001
+
1002
+ def _process_references0(self, references):
1003
+ """Make reference dict for Spec Version 0"""
1004
+ if isinstance(references, dict):
1005
+ # do not do this for lazy/parquet backend, which will not make dicts,
1006
+ # but must remain writable in the original object
1007
+ references = {
1008
+ key: json.dumps(val) if isinstance(val, dict) else val
1009
+ for key, val in references.items()
1010
+ }
1011
+ self.references = references
1012
+
1013
+ def _process_references1(self, references, template_overrides=None):
1014
+ if not self.simple_templates or self.templates:
1015
+ import jinja2.sandbox
1016
+ self.references = {}
1017
+ self._process_templates(references.get("templates", {}))
1018
+
1019
+ @lru_cache(1000)
1020
+ def _render_jinja(u):
1021
+ return (
1022
+ jinja2.sandbox.SandboxedEnvironment()
1023
+ .from_string(u)
1024
+ .render(**self.templates)
1025
+ )
1026
+
1027
+ for k, v in references.get("refs", {}).items():
1028
+ if isinstance(v, str):
1029
+ if v.startswith("base64:"):
1030
+ self.references[k] = base64.b64decode(v[7:])
1031
+ self.references[k] = v
1032
+ elif isinstance(v, dict):
1033
+ self.references[k] = json.dumps(v)
1034
+ elif self.templates:
1035
+ u = v[0]
1036
+ if "{{" in u:
1037
+ if self.simple_templates:
1038
+ u = (
1039
+ u.replace("{{", "{")
1040
+ .replace("}}", "}")
1041
+ .format(**self.templates)
1042
+ )
1043
+ else:
1044
+ u = _render_jinja(u)
1045
+ self.references[k] = [u] if len(v) == 1 else [u, v[1], v[2]]
1046
+ else:
1047
+ self.references[k] = v
1048
+ self.references.update(self._process_gen(references.get("gen", [])))
1049
+
1050
+ def _process_templates(self, tmp):
1051
+ self.templates = {}
1052
+ if self.template_overrides is not None:
1053
+ tmp.update(self.template_overrides)
1054
+ for k, v in tmp.items():
1055
+ if "{{" in v:
1056
+ import jinja2.sandbox
1057
+
1058
+ self.templates[k] = (
1059
+ lambda temp=v, **kwargs: jinja2.sandbox.SandboxedEnvironment()
1060
+ .from_string(temp)
1061
+ .render(**kwargs)
1062
+ )
1063
+ else:
1064
+ self.templates[k] = v
1065
+
1066
+ def _process_gen(self, gens):
1067
+ out = {}
1068
+ if self.simple_templates:
1069
+ return out
1070
+ for gen in gens:
1071
+ dimension = {
1072
+ k: (
1073
+ v
1074
+ if isinstance(v, list)
1075
+ else range(v.get("start", 0), v["stop"], v.get("step", 1))
1076
+ )
1077
+ for k, v in gen["dimensions"].items()
1078
+ }
1079
+ products = (
1080
+ dict(zip(dimension.keys(), values))
1081
+ for values in itertools.product(*dimension.values())
1082
+ )
1083
+ for pr in products:
1084
+ import jinja2.sandbox
1085
+
1086
+ key = (
1087
+ jinja2.sandbox.SandboxedEnvironment()
1088
+ .from_string(gen["key"])
1089
+ .render(**pr, **self.templates)
1090
+ )
1091
+ url = (
1092
+ jinja2.sandbox.SandboxedEnvironment()
1093
+ .from_string(gen["url"])
1094
+ .render(**pr, **self.templates)
1095
+ )
1096
+ if ("offset" in gen) and ("length" in gen):
1097
+ offset = int(
1098
+ jinja2.sandbox.SandboxedEnvironment()
1099
+ .from_string(gen["offset"])
1100
+ .render(**pr, **self.templates)
1101
+ )
1102
+ length = int(
1103
+ jinja2.sandbox.SandboxedEnvironment()
1104
+ .from_string(gen["length"])
1105
+ .render(**pr, **self.templates)
1106
+ )
1107
+ out[key] = [url, offset, length]
1108
+ elif ("offset" in gen) ^ ("length" in gen):
1109
+ raise ValueError(
1110
+ "Both 'offset' and 'length' are required for a "
1111
+ "reference generator entry if either is provided."
1112
+ )
1113
+ else:
1114
+ out[key] = [url]
1115
+ return out
1116
+
1117
+ def _dircache_from_items(self):
1118
+ self.dircache = {"": []}
1119
+ it = self.references.items()
1120
+ for path, part in it:
1121
+ if isinstance(part, (bytes, str)) or hasattr(part, "to_bytes"):
1122
+ size = len(part)
1123
+ elif len(part) == 1:
1124
+ size = None
1125
+ else:
1126
+ _, _, size = part
1127
+ par = path.rsplit("/", 1)[0] if "/" in path else ""
1128
+ par0 = par
1129
+ subdirs = [par0]
1130
+ while par0 and par0 not in self.dircache:
1131
+ # collect parent directories
1132
+ par0 = self._parent(par0)
1133
+ subdirs.append(par0)
1134
+
1135
+ subdirs.reverse()
1136
+ for parent, child in zip(subdirs, subdirs[1:]):
1137
+ # register newly discovered directories
1138
+ assert child not in self.dircache
1139
+ assert parent in self.dircache
1140
+ self.dircache[parent].append(
1141
+ {"name": child, "type": "directory", "size": 0}
1142
+ )
1143
+ self.dircache[child] = []
1144
+
1145
+ self.dircache[par].append({"name": path, "type": "file", "size": size})
1146
+
1147
+ def _open(self, path, mode="rb", block_size=None, cache_options=None, **kwargs):
1148
+ part_or_url, start0, end0 = self._cat_common(path)
1149
+ # This logic is kept outside `ReferenceFile` to avoid unnecessary redirection.
1150
+ # That does mean `_cat_common` gets called twice if it eventually reaches `ReferenceFile`.
1151
+ if isinstance(part_or_url, bytes):
1152
+ return io.BytesIO(part_or_url[start0:end0])
1153
+
1154
+ protocol, _ = split_protocol(part_or_url)
1155
+ if start0 is None and end0 is None:
1156
+ return self.fss[protocol]._open(
1157
+ part_or_url,
1158
+ mode,
1159
+ block_size=block_size,
1160
+ cache_options=cache_options,
1161
+ **kwargs,
1162
+ )
1163
+
1164
+ return ReferenceFile(
1165
+ self,
1166
+ path,
1167
+ mode,
1168
+ block_size=block_size,
1169
+ cache_options=cache_options,
1170
+ **kwargs,
1171
+ )
1172
+
1173
+ def ls(self, path, detail=True, **kwargs):
1174
+ logger.debug("list %s", path)
1175
+ path = self._strip_protocol(path)
1176
+ if isinstance(self.references, LazyReferenceMapper):
1177
+ try:
1178
+ return self.references.ls(path, detail)
1179
+ except KeyError:
1180
+ pass
1181
+ raise FileNotFoundError(f"'{path}' is not a known key")
1182
+ if not self.dircache:
1183
+ self._dircache_from_items()
1184
+ out = self._ls_from_cache(path)
1185
+ if out is None:
1186
+ raise FileNotFoundError(path)
1187
+ if detail:
1188
+ return out
1189
+ return [o["name"] for o in out]
1190
+
1191
+ def exists(self, path, **kwargs): # overwrite auto-sync version
1192
+ return self.isdir(path) or self.isfile(path)
1193
+
1194
+ def isdir(self, path): # overwrite auto-sync version
1195
+ if self.dircache:
1196
+ return path in self.dircache
1197
+ elif isinstance(self.references, LazyReferenceMapper):
1198
+ return path in self.references.listdir()
1199
+ else:
1200
+ # this may be faster than building dircache for single calls, but
1201
+ # by looping will be slow for many calls; could cache it?
1202
+ return any(_.startswith(f"{path}/") for _ in self.references)
1203
+
1204
+ def isfile(self, path): # overwrite auto-sync version
1205
+ return path in self.references
1206
+
1207
+ async def _ls(self, path, detail=True, **kwargs): # calls fast sync code
1208
+ return self.ls(path, detail, **kwargs)
1209
+
1210
+ def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
1211
+ if withdirs:
1212
+ return super().find(
1213
+ path, maxdepth=maxdepth, withdirs=withdirs, detail=detail, **kwargs
1214
+ )
1215
+ if path:
1216
+ path = self._strip_protocol(path)
1217
+ r = sorted(k for k in self.references if k.startswith(path))
1218
+ else:
1219
+ r = sorted(self.references)
1220
+ if detail:
1221
+ if not self.dircache:
1222
+ self._dircache_from_items()
1223
+ return {k: self._ls_from_cache(k)[0] for k in r}
1224
+ else:
1225
+ return r
1226
+
1227
+ def info(self, path, **kwargs):
1228
+ out = self.references.get(path)
1229
+ if out is not None:
1230
+ if isinstance(out, (str, bytes)):
1231
+ # decode base64 here
1232
+ return {"name": path, "type": "file", "size": len(out)}
1233
+ elif len(out) > 1:
1234
+ return {"name": path, "type": "file", "size": out[2]}
1235
+ else:
1236
+ out0 = [{"name": path, "type": "file", "size": None}]
1237
+ else:
1238
+ out = self.ls(path, True)
1239
+ out0 = [o for o in out if o["name"] == path]
1240
+ if not out0:
1241
+ return {"name": path, "type": "directory", "size": 0}
1242
+ if out0[0]["size"] is None:
1243
+ # if this is a whole remote file, update size using remote FS
1244
+ prot, _ = split_protocol(self.references[path][0])
1245
+ out0[0]["size"] = self.fss[prot].size(self.references[path][0])
1246
+ return out0[0]
1247
+
1248
+ async def _info(self, path, **kwargs): # calls fast sync code
1249
+ return self.info(path)
1250
+
1251
+ async def _rm_file(self, path, **kwargs):
1252
+ self.references.pop(
1253
+ path, None
1254
+ ) # ignores FileNotFound, just as well for directories
1255
+ self.dircache.clear() # this is a bit heavy handed
1256
+
1257
+ async def _pipe_file(self, path, data, mode="overwrite", **kwargs):
1258
+ if mode == "create" and self.exists(path):
1259
+ raise FileExistsError
1260
+ # can be str or bytes
1261
+ self.references[path] = data
1262
+ self.dircache.clear() # this is a bit heavy handed
1263
+
1264
+ async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs):
1265
+ # puts binary
1266
+ if mode == "create" and self.exists(rpath):
1267
+ raise FileExistsError
1268
+ with open(lpath, "rb") as f:
1269
+ self.references[rpath] = f.read()
1270
+ self.dircache.clear() # this is a bit heavy handed
1271
+
1272
+ def save_json(self, url, **storage_options):
1273
+ """Write modified references into new location"""
1274
+ out = {}
1275
+ for k, v in self.references.items():
1276
+ if isinstance(v, bytes):
1277
+ try:
1278
+ out[k] = v.decode("ascii")
1279
+ except UnicodeDecodeError:
1280
+ out[k] = (b"base64:" + base64.b64encode(v)).decode()
1281
+ else:
1282
+ out[k] = v
1283
+ with fsspec.open(url, "wb", **storage_options) as f:
1284
+ f.write(json.dumps({"version": 1, "refs": out}).encode())
1285
+
1286
+
1287
+ class ReferenceFile(AbstractBufferedFile):
1288
+ def __init__(
1289
+ self,
1290
+ fs,
1291
+ path,
1292
+ mode="rb",
1293
+ block_size="default",
1294
+ autocommit=True,
1295
+ cache_type="readahead",
1296
+ cache_options=None,
1297
+ size=None,
1298
+ **kwargs,
1299
+ ):
1300
+ super().__init__(
1301
+ fs,
1302
+ path,
1303
+ mode=mode,
1304
+ block_size=block_size,
1305
+ autocommit=autocommit,
1306
+ size=size,
1307
+ cache_type=cache_type,
1308
+ cache_options=cache_options,
1309
+ **kwargs,
1310
+ )
1311
+ part_or_url, self.start, self.end = self.fs._cat_common(self.path)
1312
+ protocol, _ = split_protocol(part_or_url)
1313
+ self.src_fs = self.fs.fss[protocol]
1314
+ self.src_path = part_or_url
1315
+ self._f = None
1316
+
1317
+ @property
1318
+ def f(self):
1319
+ if self._f is None or self._f.closed:
1320
+ self._f = self.src_fs._open(
1321
+ self.src_path,
1322
+ mode=self.mode,
1323
+ block_size=self.blocksize,
1324
+ autocommit=self.autocommit,
1325
+ cache_type="none",
1326
+ **self.kwargs,
1327
+ )
1328
+ return self._f
1329
+
1330
+ def close(self):
1331
+ if self._f is not None:
1332
+ self._f.close()
1333
+ return super().close()
1334
+
1335
+ def _fetch_range(self, start, end):
1336
+ start = start + self.start
1337
+ end = min(end + self.start, self.end)
1338
+ self.f.seek(start)
1339
+ return self.f.read(end - start)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/sftp.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import logging
3
+ import os
4
+ import types
5
+ import uuid
6
+ from stat import S_ISDIR, S_ISLNK
7
+
8
+ import paramiko
9
+
10
+ from .. import AbstractFileSystem
11
+ from ..utils import infer_storage_options
12
+
13
+ logger = logging.getLogger("fsspec.sftp")
14
+
15
+
16
+ class SFTPFileSystem(AbstractFileSystem):
17
+ """Files over SFTP/SSH
18
+
19
+ Peer-to-peer filesystem over SSH using paramiko.
20
+
21
+ Note: if using this with the ``open`` or ``open_files``, with full URLs,
22
+ there is no way to tell if a path is relative, so all paths are assumed
23
+ to be absolute.
24
+ """
25
+
26
+ protocol = "sftp", "ssh"
27
+
28
+ def __init__(self, host, **ssh_kwargs):
29
+ """
30
+
31
+ Parameters
32
+ ----------
33
+ host: str
34
+ Hostname or IP as a string
35
+ temppath: str
36
+ Location on the server to put files, when within a transaction
37
+ ssh_kwargs: dict
38
+ Parameters passed on to connection. See details in
39
+ https://docs.paramiko.org/en/3.3/api/client.html#paramiko.client.SSHClient.connect
40
+ May include port, username, password...
41
+ """
42
+ if self._cached:
43
+ return
44
+ super().__init__(**ssh_kwargs)
45
+ self.temppath = ssh_kwargs.pop("temppath", "/tmp") # remote temp directory
46
+ self.host = host
47
+ self.ssh_kwargs = ssh_kwargs
48
+ self._connect()
49
+
50
+ def _connect(self):
51
+ logger.debug("Connecting to SFTP server %s", self.host)
52
+ self.client = paramiko.SSHClient()
53
+ self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
54
+ self.client.connect(self.host, **self.ssh_kwargs)
55
+ self.ftp = self.client.open_sftp()
56
+
57
+ @classmethod
58
+ def _strip_protocol(cls, path):
59
+ return infer_storage_options(path)["path"]
60
+
61
+ @staticmethod
62
+ def _get_kwargs_from_urls(urlpath):
63
+ out = infer_storage_options(urlpath)
64
+ out.pop("path", None)
65
+ out.pop("protocol", None)
66
+ return out
67
+
68
+ def mkdir(self, path, create_parents=True, mode=511):
69
+ path = self._strip_protocol(path)
70
+ logger.debug("Creating folder %s", path)
71
+ if self.exists(path):
72
+ raise FileExistsError(f"File exists: {path}")
73
+
74
+ if create_parents:
75
+ self.makedirs(path)
76
+ else:
77
+ self.ftp.mkdir(path, mode)
78
+
79
+ def makedirs(self, path, exist_ok=False, mode=511):
80
+ if self.exists(path) and not exist_ok:
81
+ raise FileExistsError(f"File exists: {path}")
82
+
83
+ parts = path.split("/")
84
+ new_path = "/" if path[:1] == "/" else ""
85
+
86
+ for part in parts:
87
+ if part:
88
+ new_path = f"{new_path}/{part}" if new_path else part
89
+ if not self.exists(new_path):
90
+ self.ftp.mkdir(new_path, mode)
91
+
92
+ def rmdir(self, path):
93
+ path = self._strip_protocol(path)
94
+ logger.debug("Removing folder %s", path)
95
+ self.ftp.rmdir(path)
96
+
97
+ def info(self, path):
98
+ path = self._strip_protocol(path)
99
+ stat = self._decode_stat(self.ftp.stat(path))
100
+ stat["name"] = path
101
+ return stat
102
+
103
+ @staticmethod
104
+ def _decode_stat(stat, parent_path=None):
105
+ if S_ISDIR(stat.st_mode):
106
+ t = "directory"
107
+ elif S_ISLNK(stat.st_mode):
108
+ t = "link"
109
+ else:
110
+ t = "file"
111
+ out = {
112
+ "name": "",
113
+ "size": stat.st_size,
114
+ "type": t,
115
+ "uid": stat.st_uid,
116
+ "gid": stat.st_gid,
117
+ "time": datetime.datetime.fromtimestamp(
118
+ stat.st_atime, tz=datetime.timezone.utc
119
+ ),
120
+ "mtime": datetime.datetime.fromtimestamp(
121
+ stat.st_mtime, tz=datetime.timezone.utc
122
+ ),
123
+ }
124
+ if parent_path:
125
+ out["name"] = "/".join([parent_path.rstrip("/"), stat.filename])
126
+ return out
127
+
128
+ def ls(self, path, detail=False):
129
+ path = self._strip_protocol(path)
130
+ logger.debug("Listing folder %s", path)
131
+ stats = [self._decode_stat(stat, path) for stat in self.ftp.listdir_iter(path)]
132
+ if detail:
133
+ return stats
134
+ else:
135
+ paths = [stat["name"] for stat in stats]
136
+ return sorted(paths)
137
+
138
+ def put_file(self, lpath, rpath, callback=None, **kwargs):
139
+ self.mkdirs(self._parent(os.fspath(rpath)), exist_ok=True)
140
+ logger.debug("Put file %s into %s", lpath, rpath)
141
+ self.ftp.put(lpath, rpath)
142
+
143
+ def get_file(self, rpath, lpath, **kwargs):
144
+ if self.isdir(rpath):
145
+ os.makedirs(lpath, exist_ok=True)
146
+ else:
147
+ self.ftp.get(self._strip_protocol(rpath), lpath)
148
+
149
+ def _open(self, path, mode="rb", block_size=None, **kwargs):
150
+ """
151
+ block_size: int or None
152
+ If 0, no buffering, if 1, line buffering, if >1, buffer that many
153
+ bytes, if None use default from paramiko.
154
+ """
155
+ logger.debug("Opening file %s", path)
156
+ if kwargs.get("autocommit", True) is False:
157
+ # writes to temporary file, move on commit
158
+ path2 = "/".join([self.temppath, str(uuid.uuid4())])
159
+ f = self.ftp.open(path2, mode, bufsize=block_size if block_size else -1)
160
+ f.temppath = path2
161
+ f.targetpath = path
162
+ f.fs = self
163
+ f.commit = types.MethodType(commit_a_file, f)
164
+ f.discard = types.MethodType(discard_a_file, f)
165
+ else:
166
+ f = self.ftp.open(path, mode, bufsize=block_size if block_size else -1)
167
+ return f
168
+
169
+ def _rm(self, path):
170
+ if self.isdir(path):
171
+ self.ftp.rmdir(path)
172
+ else:
173
+ self.ftp.remove(path)
174
+
175
+ def mv(self, old, new):
176
+ new = self._strip_protocol(new)
177
+ old = self._strip_protocol(old)
178
+ logger.debug("Renaming %s into %s", old, new)
179
+ self.ftp.posix_rename(old, new)
180
+
181
+
182
+ def commit_a_file(self):
183
+ self.fs.mv(self.temppath, self.targetpath)
184
+
185
+
186
+ def discard_a_file(self):
187
+ self.fs._rm(self.temppath)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/tar.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import tarfile
3
+
4
+ import fsspec
5
+ from fsspec.archive import AbstractArchiveFileSystem
6
+ from fsspec.compression import compr
7
+ from fsspec.utils import infer_compression
8
+
9
+ typemap = {b"0": "file", b"5": "directory"}
10
+
11
+ logger = logging.getLogger("tar")
12
+
13
+
14
+ class TarFileSystem(AbstractArchiveFileSystem):
15
+ """Compressed Tar archives as a file-system (read-only)
16
+
17
+ Supports the following formats:
18
+ tar.gz, tar.bz2, tar.xz
19
+ """
20
+
21
+ root_marker = ""
22
+ protocol = "tar"
23
+ cachable = False
24
+
25
+ def __init__(
26
+ self,
27
+ fo="",
28
+ index_store=None,
29
+ target_options=None,
30
+ target_protocol=None,
31
+ compression=None,
32
+ **kwargs,
33
+ ):
34
+ super().__init__(**kwargs)
35
+ target_options = target_options or {}
36
+
37
+ if isinstance(fo, str):
38
+ self.of = fsspec.open(fo, protocol=target_protocol, **target_options)
39
+ fo = self.of.open() # keep the reference
40
+
41
+ # Try to infer compression.
42
+ if compression is None:
43
+ name = None
44
+
45
+ # Try different ways to get hold of the filename. `fo` might either
46
+ # be a `fsspec.LocalFileOpener`, an `io.BufferedReader` or an
47
+ # `fsspec.AbstractFileSystem` instance.
48
+ try:
49
+ # Amended io.BufferedReader or similar.
50
+ # This uses a "protocol extension" where original filenames are
51
+ # propagated to archive-like filesystems in order to let them
52
+ # infer the right compression appropriately.
53
+ if hasattr(fo, "original"):
54
+ name = fo.original
55
+
56
+ # fsspec.LocalFileOpener
57
+ elif hasattr(fo, "path"):
58
+ name = fo.path
59
+
60
+ # io.BufferedReader
61
+ elif hasattr(fo, "name"):
62
+ name = fo.name
63
+
64
+ # fsspec.AbstractFileSystem
65
+ elif hasattr(fo, "info"):
66
+ name = fo.info()["name"]
67
+
68
+ except Exception as ex:
69
+ logger.warning(
70
+ f"Unable to determine file name, not inferring compression: {ex}"
71
+ )
72
+
73
+ if name is not None:
74
+ compression = infer_compression(name)
75
+ logger.info(f"Inferred compression {compression} from file name {name}")
76
+
77
+ if compression is not None:
78
+ # TODO: tarfile already implements compression with modes like "'r:gz'",
79
+ # but then would seek to offset in the file work?
80
+ fo = compr[compression](fo)
81
+
82
+ self._fo_ref = fo
83
+ self.fo = fo # the whole instance is a context
84
+ self.tar = tarfile.TarFile(fileobj=self.fo)
85
+ self.dir_cache = None
86
+
87
+ self.index_store = index_store
88
+ self.index = None
89
+ self._index()
90
+
91
+ def _index(self):
92
+ # TODO: load and set saved index, if exists
93
+ out = {}
94
+ for ti in self.tar:
95
+ info = ti.get_info()
96
+ info["type"] = typemap.get(info["type"], "file")
97
+ name = ti.get_info()["name"].rstrip("/")
98
+ out[name] = (info, ti.offset_data)
99
+
100
+ self.index = out
101
+ # TODO: save index to self.index_store here, if set
102
+
103
+ def _get_dirs(self):
104
+ if self.dir_cache is not None:
105
+ return
106
+
107
+ # This enables ls to get directories as children as well as files
108
+ self.dir_cache = {
109
+ dirname: {"name": dirname, "size": 0, "type": "directory"}
110
+ for dirname in self._all_dirnames(self.tar.getnames())
111
+ }
112
+ for member in self.tar.getmembers():
113
+ info = member.get_info()
114
+ info["name"] = info["name"].rstrip("/")
115
+ info["type"] = typemap.get(info["type"], "file")
116
+ self.dir_cache[info["name"]] = info
117
+
118
+ def _open(self, path, mode="rb", **kwargs):
119
+ if mode != "rb":
120
+ raise ValueError("Read-only filesystem implementation")
121
+ details, offset = self.index[path]
122
+ if details["type"] != "file":
123
+ raise ValueError("Can only handle regular files")
124
+ return self.tar.extractfile(path)
125
+
126
+ def close(self):
127
+ """Commits any write changes to the file. Done on ``del`` too."""
128
+ self.tar.close()
129
+
130
+ def __del__(self):
131
+ if hasattr(self, "tar"):
132
+ self.close()
133
+ del self.tar
134
+ if hasattr(self, "of") and hasattr(self.of, "__exit__"):
135
+ self.of.__exit__(None, None, None)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/implementations/zip.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import zipfile
3
+
4
+ import fsspec
5
+ from fsspec.archive import AbstractArchiveFileSystem
6
+
7
+
8
+ class ZipFileSystem(AbstractArchiveFileSystem):
9
+ """Read/Write contents of ZIP archive as a file-system
10
+
11
+ Keeps file object open while instance lives.
12
+
13
+ This class is pickleable, but not necessarily thread-safe
14
+ """
15
+
16
+ root_marker = ""
17
+ protocol = "zip"
18
+ cachable = False
19
+
20
+ def __init__(
21
+ self,
22
+ fo="",
23
+ mode="r",
24
+ target_protocol=None,
25
+ target_options=None,
26
+ compression=zipfile.ZIP_STORED,
27
+ allowZip64=True,
28
+ compresslevel=None,
29
+ **kwargs,
30
+ ):
31
+ """
32
+ Parameters
33
+ ----------
34
+ fo: str or file-like
35
+ Contains ZIP, and must exist. If a str, will fetch file using
36
+ :meth:`~fsspec.open_files`, which must return one file exactly.
37
+ mode: str
38
+ Accept: "r", "w", "a"
39
+ target_protocol: str (optional)
40
+ If ``fo`` is a string, this value can be used to override the
41
+ FS protocol inferred from a URL
42
+ target_options: dict (optional)
43
+ Kwargs passed when instantiating the target FS, if ``fo`` is
44
+ a string.
45
+ compression, allowZip64, compresslevel: passed to ZipFile
46
+ Only relevant when creating a ZIP
47
+ """
48
+ super().__init__(self, **kwargs)
49
+ if mode not in set("rwa"):
50
+ raise ValueError(f"mode '{mode}' no understood")
51
+ self.mode = mode
52
+ if isinstance(fo, (str, os.PathLike)):
53
+ if mode == "a":
54
+ m = "r+b"
55
+ else:
56
+ m = mode + "b"
57
+ fo = fsspec.open(
58
+ fo, mode=m, protocol=target_protocol, **(target_options or {})
59
+ )
60
+ self.force_zip_64 = allowZip64
61
+ self.of = fo
62
+ self.fo = fo.__enter__() # the whole instance is a context
63
+ self.zip = zipfile.ZipFile(
64
+ self.fo,
65
+ mode=mode,
66
+ compression=compression,
67
+ allowZip64=allowZip64,
68
+ compresslevel=compresslevel,
69
+ )
70
+ self.dir_cache = None
71
+
72
+ @classmethod
73
+ def _strip_protocol(cls, path):
74
+ # zip file paths are always relative to the archive root
75
+ return super()._strip_protocol(path).lstrip("/")
76
+
77
+ def __del__(self):
78
+ if hasattr(self, "zip"):
79
+ self.close()
80
+ del self.zip
81
+ if hasattr(self, "of") and hasattr(self.of, "__exit__"):
82
+ self.of.__exit__(None, None, None)
83
+
84
+ def close(self):
85
+ """Commits any write changes to the file. Done on ``del`` too."""
86
+ self.zip.close()
87
+
88
+ def _get_dirs(self):
89
+ if self.dir_cache is None or self.mode in set("wa"):
90
+ # when writing, dir_cache is always in the ZipFile's attributes,
91
+ # not read from the file.
92
+ files = self.zip.infolist()
93
+ self.dir_cache = {
94
+ dirname.rstrip("/"): {
95
+ "name": dirname.rstrip("/"),
96
+ "size": 0,
97
+ "type": "directory",
98
+ }
99
+ for dirname in self._all_dirnames(self.zip.namelist())
100
+ }
101
+ for z in files:
102
+ f = {s: getattr(z, s, None) for s in zipfile.ZipInfo.__slots__}
103
+ f.update(
104
+ {
105
+ "name": z.filename.rstrip("/"),
106
+ "size": z.file_size,
107
+ "type": ("directory" if z.is_dir() else "file"),
108
+ }
109
+ )
110
+ self.dir_cache[f["name"]] = f
111
+
112
+ def pipe_file(self, path, value, **kwargs):
113
+ # override upstream, because we know the exact file size in this case
114
+ self.zip.writestr(path, value, **kwargs)
115
+
116
+ def _open(
117
+ self,
118
+ path,
119
+ mode="rb",
120
+ block_size=None,
121
+ autocommit=True,
122
+ cache_options=None,
123
+ **kwargs,
124
+ ):
125
+ path = self._strip_protocol(path)
126
+ if "r" in mode and self.mode in set("wa"):
127
+ if self.exists(path):
128
+ raise OSError("ZipFS can only be open for reading or writing, not both")
129
+ raise FileNotFoundError(path)
130
+ if "r" in self.mode and "w" in mode:
131
+ raise OSError("ZipFS can only be open for reading or writing, not both")
132
+ out = self.zip.open(path, mode.strip("b"), force_zip64=self.force_zip_64)
133
+ if "r" in mode:
134
+ info = self.info(path)
135
+ out.size = info["size"]
136
+ out.name = info["name"]
137
+ return out
138
+
139
+ def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
140
+ if maxdepth is not None and maxdepth < 1:
141
+ raise ValueError("maxdepth must be at least 1")
142
+
143
+ def to_parts(_path: str):
144
+ return list(filter(None, _path.replace("\\", "/").split("/")))
145
+
146
+ if not isinstance(path, str):
147
+ path = str(path)
148
+
149
+ # Remove the leading slash, as the zip file paths are always
150
+ # given without a leading slash
151
+ path = path.lstrip("/")
152
+ path_parts = to_parts(path)
153
+ path_depth = len(path_parts)
154
+
155
+ self._get_dirs()
156
+
157
+ result = {}
158
+ # To match posix find, if an exact file name is given, we should
159
+ # return only that file
160
+ if path in self.dir_cache and self.dir_cache[path]["type"] == "file":
161
+ result[path] = self.dir_cache[path]
162
+ return result if detail else [path]
163
+
164
+ for file_path, file_info in self.dir_cache.items():
165
+ if len(file_parts := to_parts(file_path)) < path_depth or any(
166
+ a != b for a, b in zip(path_parts, file_parts)
167
+ ):
168
+ # skip parent folders and mismatching paths
169
+ continue
170
+
171
+ if file_info["type"] == "directory":
172
+ if withdirs and file_path not in result:
173
+ result[file_path.strip("/")] = file_info
174
+ continue
175
+
176
+ if file_path not in result:
177
+ result[file_path] = file_info if detail else None
178
+
179
+ if maxdepth:
180
+ result = {
181
+ k: v for k, v in result.items() if k.count("/") < maxdepth + path_depth
182
+ }
183
+ return result if detail else sorted(result)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/fsspec/mapping.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import array
2
+ import logging
3
+ import posixpath
4
+ import warnings
5
+ from collections.abc import MutableMapping
6
+ from functools import cached_property
7
+
8
+ from fsspec.core import url_to_fs
9
+
10
+ logger = logging.getLogger("fsspec.mapping")
11
+
12
+
13
+ class FSMap(MutableMapping):
14
+ """Wrap a FileSystem instance as a mutable wrapping.
15
+
16
+ The keys of the mapping become files under the given root, and the
17
+ values (which must be bytes) the contents of those files.
18
+
19
+ Parameters
20
+ ----------
21
+ root: string
22
+ prefix for all the files
23
+ fs: FileSystem instance
24
+ check: bool (=True)
25
+ performs a touch at the location, to check for write access.
26
+
27
+ Examples
28
+ --------
29
+ >>> fs = FileSystem(**parameters) # doctest: +SKIP
30
+ >>> d = FSMap('my-data/path/', fs) # doctest: +SKIP
31
+ or, more likely
32
+ >>> d = fs.get_mapper('my-data/path/')
33
+
34
+ >>> d['loc1'] = b'Hello World' # doctest: +SKIP
35
+ >>> list(d.keys()) # doctest: +SKIP
36
+ ['loc1']
37
+ >>> d['loc1'] # doctest: +SKIP
38
+ b'Hello World'
39
+ """
40
+
41
+ def __init__(self, root, fs, check=False, create=False, missing_exceptions=None):
42
+ self.fs = fs
43
+ self.root = fs._strip_protocol(root)
44
+ self._root_key_to_str = fs._strip_protocol(posixpath.join(root, "x"))[:-1]
45
+ if missing_exceptions is None:
46
+ missing_exceptions = (
47
+ FileNotFoundError,
48
+ IsADirectoryError,
49
+ NotADirectoryError,
50
+ )
51
+ self.missing_exceptions = missing_exceptions
52
+ self.check = check
53
+ self.create = create
54
+ if create:
55
+ if not self.fs.exists(root):
56
+ self.fs.mkdir(root)
57
+ if check:
58
+ if not self.fs.exists(root):
59
+ raise ValueError(
60
+ f"Path {root} does not exist. Create "
61
+ f" with the ``create=True`` keyword"
62
+ )
63
+ self.fs.touch(root + "/a")
64
+ self.fs.rm(root + "/a")
65
+
66
+ @cached_property
67
+ def dirfs(self):
68
+ """dirfs instance that can be used with the same keys as the mapper"""
69
+ from .implementations.dirfs import DirFileSystem
70
+
71
+ return DirFileSystem(path=self._root_key_to_str, fs=self.fs)
72
+
73
+ def clear(self):
74
+ """Remove all keys below root - empties out mapping"""
75
+ logger.info("Clear mapping at %s", self.root)
76
+ try:
77
+ self.fs.rm(self.root, True)
78
+ self.fs.mkdir(self.root)
79
+ except: # noqa: E722
80
+ pass
81
+
82
+ def getitems(self, keys, on_error="raise"):
83
+ """Fetch multiple items from the store
84
+
85
+ If the backend is async-able, this might proceed concurrently
86
+
87
+ Parameters
88
+ ----------
89
+ keys: list(str)
90
+ They keys to be fetched
91
+ on_error : "raise", "omit", "return"
92
+ If raise, an underlying exception will be raised (converted to KeyError
93
+ if the type is in self.missing_exceptions); if omit, keys with exception
94
+ will simply not be included in the output; if "return", all keys are
95
+ included in the output, but the value will be bytes or an exception
96
+ instance.
97
+
98
+ Returns
99
+ -------
100
+ dict(key, bytes|exception)
101
+ """
102
+ keys2 = [self._key_to_str(k) for k in keys]
103
+ oe = on_error if on_error == "raise" else "return"
104
+ try:
105
+ out = self.fs.cat(keys2, on_error=oe)
106
+ if isinstance(out, bytes):
107
+ out = {keys2[0]: out}
108
+ except self.missing_exceptions as e:
109
+ raise KeyError from e
110
+ out = {
111
+ k: (KeyError() if isinstance(v, self.missing_exceptions) else v)
112
+ for k, v in out.items()
113
+ }
114
+ return {
115
+ key: out[k2] if on_error == "raise" else out.get(k2, KeyError(k2))
116
+ for key, k2 in zip(keys, keys2)
117
+ if on_error == "return" or not isinstance(out[k2], BaseException)
118
+ }
119
+
120
+ def setitems(self, values_dict):
121
+ """Set the values of multiple items in the store
122
+
123
+ Parameters
124
+ ----------
125
+ values_dict: dict(str, bytes)
126
+ """
127
+ values = {self._key_to_str(k): maybe_convert(v) for k, v in values_dict.items()}
128
+ self.fs.pipe(values)
129
+
130
+ def delitems(self, keys):
131
+ """Remove multiple keys from the store"""
132
+ self.fs.rm([self._key_to_str(k) for k in keys])
133
+
134
+ def _key_to_str(self, key):
135
+ """Generate full path for the key"""
136
+ if not isinstance(key, str):
137
+ # raise TypeError("key must be of type `str`, got `{type(key).__name__}`"
138
+ warnings.warn(
139
+ "from fsspec 2023.5 onward FSMap non-str keys will raise TypeError",
140
+ DeprecationWarning,
141
+ )
142
+ if isinstance(key, list):
143
+ key = tuple(key)
144
+ key = str(key)
145
+ return f"{self._root_key_to_str}{key}".rstrip("/")
146
+
147
+ def _str_to_key(self, s):
148
+ """Strip path of to leave key name"""
149
+ return s[len(self.root) :].lstrip("/")
150
+
151
+ def __getitem__(self, key, default=None):
152
+ """Retrieve data"""
153
+ k = self._key_to_str(key)
154
+ try:
155
+ result = self.fs.cat(k)
156
+ except self.missing_exceptions as exc:
157
+ if default is not None:
158
+ return default
159
+ raise KeyError(key) from exc
160
+ return result
161
+
162
+ def pop(self, key, default=None):
163
+ """Pop data"""
164
+ result = self.__getitem__(key, default)
165
+ try:
166
+ del self[key]
167
+ except KeyError:
168
+ pass
169
+ return result
170
+
171
+ def __setitem__(self, key, value):
172
+ """Store value in key"""
173
+ key = self._key_to_str(key)
174
+ self.fs.mkdirs(self.fs._parent(key), exist_ok=True)
175
+ self.fs.pipe_file(key, maybe_convert(value))
176
+
177
+ def __iter__(self):
178
+ return (self._str_to_key(x) for x in self.fs.find(self.root))
179
+
180
+ def __len__(self):
181
+ return len(self.fs.find(self.root))
182
+
183
+ def __delitem__(self, key):
184
+ """Remove key"""
185
+ try:
186
+ self.fs.rm(self._key_to_str(key))
187
+ except Exception as exc:
188
+ raise KeyError from exc
189
+
190
+ def __contains__(self, key):
191
+ """Does key exist in mapping?"""
192
+ path = self._key_to_str(key)
193
+ return self.fs.isfile(path)
194
+
195
+ def __reduce__(self):
196
+ return FSMap, (self.root, self.fs, False, False, self.missing_exceptions)
197
+
198
+
199
+ def maybe_convert(value):
200
+ if isinstance(value, array.array) or hasattr(value, "__array__"):
201
+ # bytes-like things
202
+ if hasattr(value, "dtype") and value.dtype.kind in "Mm":
203
+ # The buffer interface doesn't support datetime64/timdelta64 numpy
204
+ # arrays
205
+ value = value.view("int64")
206
+ value = bytes(memoryview(value))
207
+ return value
208
+
209
+
210
+ def get_mapper(
211
+ url="",
212
+ check=False,
213
+ create=False,
214
+ missing_exceptions=None,
215
+ alternate_root=None,
216
+ **kwargs,
217
+ ):
218
+ """Create key-value interface for given URL and options
219
+
220
+ The URL will be of the form "protocol://location" and point to the root
221
+ of the mapper required. All keys will be file-names below this location,
222
+ and their values the contents of each key.
223
+
224
+ Also accepts compound URLs like zip::s3://bucket/file.zip , see ``fsspec.open``.
225
+
226
+ Parameters
227
+ ----------
228
+ url: str
229
+ Root URL of mapping
230
+ check: bool
231
+ Whether to attempt to read from the location before instantiation, to
232
+ check that the mapping does exist
233
+ create: bool
234
+ Whether to make the directory corresponding to the root before
235
+ instantiating
236
+ missing_exceptions: None or tuple
237
+ If given, these exception types will be regarded as missing keys and
238
+ return KeyError when trying to read data. By default, you get
239
+ (FileNotFoundError, IsADirectoryError, NotADirectoryError)
240
+ alternate_root: None or str
241
+ In cases of complex URLs, the parser may fail to pick the correct part
242
+ for the mapper root, so this arg can override
243
+
244
+ Returns
245
+ -------
246
+ ``FSMap`` instance, the dict-like key-value store.
247
+ """
248
+ # Removing protocol here - could defer to each open() on the backend
249
+ fs, urlpath = url_to_fs(url, **kwargs)
250
+ root = alternate_root if alternate_root is not None else urlpath
251
+ return FSMap(root, fs, check, create, missing_exceptions=missing_exceptions)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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)
.cache/uv/archive-v0/0_TkEojhKs0o0LVqFJ_vB/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)